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 |
|---|---|---|---|---|---|---|---|---|
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-codec/src/main/java/org/tinylcy/RpcDecoder.java | buddha-codec/src/main/java/org/tinylcy/RpcDecoder.java | package org.tinylcy;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
/**
* Created by chenyangli.
*/
public class RpcDecoder extends ByteToMessageDecoder {
private Class<?> clazz;
public RpcDecoder(Class<?> clazz) {
this.clazz = clazz;
}
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list)
throws Exception {
if (byteBuf.readableBytes() < 4) {
return;
}
Serializer serializer = SerializerFactory.load();
int length = byteBuf.readInt();
if (byteBuf.readableBytes() < length) {
throw new RuntimeException("Insufficient bytes to be read, expected: " + length);
}
byte[] bytes = new byte[length];
byteBuf.readBytes(bytes);
Object object = serializer.deserialize(bytes, clazz);
list.add(object);
}
public void setClass(Class<?> clazz) {
this.clazz = clazz;
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-codec/src/main/java/org/tinylcy/RpcEncoder.java | buddha-codec/src/main/java/org/tinylcy/RpcEncoder.java | package org.tinylcy;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* Created by chenyangli.
*/
public class RpcEncoder extends MessageToByteEncoder {
private Class<?> clazz;
public RpcEncoder(Class<?> clazz) {
this.clazz = clazz;
}
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, Object object, ByteBuf byteBuf)
throws Exception {
Serializer serializer = SerializerFactory.load();
byte[] bytes = serializer.serialize(object);
int len = bytes.length;
byteBuf.writeInt(len);
byteBuf.writeBytes(bytes);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-codec/src/main/java/org/tinylcy/RpcResponseCodec.java | buddha-codec/src/main/java/org/tinylcy/RpcResponseCodec.java | package org.tinylcy;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import java.util.List;
/**
* Created by chenyangli.
*/
public class RpcResponseCodec extends ByteToMessageCodec<RpcResponse> {
@Override
protected void encode(ChannelHandlerContext context, RpcResponse response, ByteBuf byteBuf)
throws Exception {
Serializer serializer = SerializerFactory.load();
byte[] bytes = serializer.serialize(response);
int len = bytes.length;
byteBuf.writeInt(len);
byteBuf.writeBytes(bytes);
}
@Override
protected void decode(ChannelHandlerContext context, ByteBuf byteBuf, List<Object> list)
throws Exception {
if (byteBuf.readableBytes() < 4) {
return;
}
int len = byteBuf.readInt();
if (byteBuf.readableBytes() < len) {
throw new RuntimeException("Insufficient bytes to be read, expected: " + len);
}
byte[] bytes = new byte[len];
byteBuf.readBytes(bytes);
Serializer serializer = SerializerFactory.load();
Object object = serializer.deserialize(bytes, RpcResponse.class);
list.add(object);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-registry/src/test/java/org/tinylcy/ZooKeeperManagerTest.java | buddha-registry/src/test/java/org/tinylcy/ZooKeeperManagerTest.java | package org.tinylcy;
import org.junit.Test;
import org.tinylcy.zookeeper.ZooKeeperManager;
import java.util.List;
/**
* Created by chenyangli.
*/
public class ZooKeeperManagerTest {
@Test
public void testCreateNode() {
ZooKeeperManager manager = new ZooKeeperManager("127.0.0.1:2181");
manager.connect();
manager.createNode("127.0.0.1:9090");
}
@Test
public void testDeleteNode() {
ZooKeeperManager manager = new ZooKeeperManager("127.0.0.1:2181");
manager.connect();
manager.deleteNode(ZooKeeperManager.ZK_REGISTRY_PATH);
}
@Test
public void testListChildren() {
ZooKeeperManager manager = new ZooKeeperManager("127.0.0.1:2181");
manager.connect();
List<String> list = manager.listChildren(ZooKeeperManager.ZK_REGISTRY_PATH);
System.out.println(list);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-registry/src/test/java/org/tinylcy/examples/MyStringCallback.java | buddha-registry/src/test/java/org/tinylcy/examples/MyStringCallback.java | package org.tinylcy.examples;
import org.apache.zookeeper.AsyncCallback;
/**
* Created by chenyangli.
*/
public class MyStringCallback implements AsyncCallback.StringCallback {
public void processResult(int i, String s, Object o, String s1) {
System.out.println("异步创建回调结果 - 状态: " + i + ", 创建路径: " + s
+ ", 传递信息: " + o + ", 实际节点名称: " + s1);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-registry/src/test/java/org/tinylcy/examples/GetChildrenExample.java | buddha-registry/src/test/java/org/tinylcy/examples/GetChildrenExample.java | package org.tinylcy.examples;
import org.apache.zookeeper.*;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
* Created by chenyangli.
*/
public class GetChildrenExample implements Watcher {
private static final CountDownLatch connectedSignal = new CountDownLatch(1);
private static ZooKeeper zk;
public static void main(String[] args) throws Exception {
zk = new ZooKeeper("127.0.0.1:2181", 5000, new GetChildrenExample());
connectedSignal.await();
// 创建父节点 /test
zk.create("/ex2", "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// 在父节点/test下创建a1节点
zk.create("/ex2/a1", "456".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// 同步获得结果
List<String> childrenList = zk.getChildren("/ex2", true);
System.out.println(childrenList);
// 异步获得结果
// zk.getChildren("/ex2", true, new MyChildren2Callback(), null);
// 在父节点/test下面创建a2节点
zk.create("/ex2/a2", "456".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
Thread.sleep(10000);
}
public void process(WatchedEvent watchedEvent) {
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
if (watchedEvent.getType() == Event.EventType.None && watchedEvent.getPath() == null) {
connectedSignal.countDown();
} else if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
try {
System.out.println("获得children,并注册监听: " + zk.getChildren(watchedEvent.getPath(), true));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-registry/src/test/java/org/tinylcy/examples/CreateNodeExample.java | buddha-registry/src/test/java/org/tinylcy/examples/CreateNodeExample.java | package org.tinylcy.examples;
import org.apache.zookeeper.*;
import java.util.concurrent.CountDownLatch;
/**
* Created by chenyangli.
*/
public class CreateNodeExample implements Watcher {
private static final CountDownLatch connectedSignal = new CountDownLatch(1);
public static void main(String[] args) throws Exception {
ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 5000, new CreateNodeExample());
connectedSignal.await();
// 同步创建临时节点
String ephemeralPath = zk.create("/zk-test-create-ephemeral-", "123".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println("同步创建临时节点成功: " + ephemeralPath);
// 同步创建临时顺序节点
String sequentialPath = zk.create("/zk-test-create-sequential-", "456".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println("同步创建临时顺序节点成功: " + sequentialPath);
// 异步创建临时节点
zk.create("/zk-test-create-async-ephemeral-", "abc".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new MyStringCallback(), "我是传递内容");
// 异步创建临时顺序节点
zk.create("/zk-test-create-async-sequential-", "def".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, new MyStringCallback(), "我是传递内容");
Thread.sleep(10000);
}
public void process(WatchedEvent watchedEvent) {
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-registry/src/test/java/org/tinylcy/examples/SessionExample.java | buddha-registry/src/test/java/org/tinylcy/examples/SessionExample.java | package org.tinylcy.examples;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.util.concurrent.CountDownLatch;
/**
* Created by chenyangli.
*/
public class SessionExample implements Watcher {
private static CountDownLatch connectedSignal = new CountDownLatch(1);
public static void main(String[] args) throws Exception {
ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 5000, new SessionExample());
connectedSignal.await();
System.out.println(zk.getState());
}
public void process(WatchedEvent watchedEvent) {
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-registry/src/test/java/org/tinylcy/examples/GetDataExample.java | buddha-registry/src/test/java/org/tinylcy/examples/GetDataExample.java | package org.tinylcy.examples;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.util.concurrent.CountDownLatch;
/**
* Created by chenyangli.
*/
public class GetDataExample implements Watcher {
private static final CountDownLatch connectedSignal = new CountDownLatch(1);
private static ZooKeeper zk;
private static Stat stat = new Stat();
public static void main(String[] args) throws Exception {
zk = new ZooKeeper("127.0.0.1:2181", 5000, new GetDataExample());
connectedSignal.await();
String path = "/test-get-data";
zk.create(path, "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println("同步读取节点内容:" + new String(zk.getData(path, true, stat)));
System.out.println("同步读取Stat:czxid=" + stat.getCzxid()
+ ";mzxid=" + stat.getMzxid() + ";version=" + stat.getVersion());
zk.setData(path, "123".getBytes(), -1);
Thread.sleep(10000);
}
public void process(WatchedEvent event) {
if (Event.KeeperState.SyncConnected == event.getState()) {
if (Event.EventType.None == event.getType() && null == event.getPath()) { // 连接时的监听事件
connectedSignal.countDown();
} else if (event.getType() == Event.EventType.NodeDataChanged) { // 子节点内容变更时的监听
try {
System.out.println("监听获得通知内容:data="
+ new String(zk.getData(event.getPath(), true, stat)));
System.out.println("监听获得通知Stat:czxid=" + stat.getCzxid()
+ ";mzxid=" + stat.getMzxid() + ";version=" + stat.getVersion());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-registry/src/test/java/org/tinylcy/examples/MyChildren2Callback.java | buddha-registry/src/test/java/org/tinylcy/examples/MyChildren2Callback.java | package org.tinylcy.examples;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.data.Stat;
import java.util.List;
/**
* Created by chenyangli.
*/
public class MyChildren2Callback implements AsyncCallback.Children2Callback {
public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
System.out.println("异步获得getChildren结果,rc=" + rc
+ ";path=" + path + ";ctx=" + ctx + ";children=" + children + ";stat=" + stat);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-registry/src/main/java/org/tinylcy/ServiceRegistry.java | buddha-registry/src/main/java/org/tinylcy/ServiceRegistry.java | package org.tinylcy;
import org.apache.log4j.Logger;
import org.tinylcy.zookeeper.ZooKeeperManager;
/**
* Created by chenyangli.
*/
public class ServiceRegistry {
private static final Logger LOGGER = Logger.getLogger(ServiceRegistry.class);
private ZooKeeperManager manager;
public ServiceRegistry(ZooKeeperManager manager) {
this.manager = manager;
}
/**
* Service format -> host:port
*
* @param host
* @param port
*/
public void register(String host, int port) {
manager.connect();
manager.createNode(host + ":" + port);
LOGGER.info("Register to " + host + ":" + port + " successfully");
}
/**
* Delete all the registered services before rpc server start.
*/
public void init() {
manager.connect();
manager.deleteNode(ZooKeeperManager.ZK_REGISTRY_PATH);
LOGGER.info("Delete Node: " + ZooKeeperManager.ZK_REGISTRY_PATH);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-registry/src/main/java/org/tinylcy/ServiceDiscovery.java | buddha-registry/src/main/java/org/tinylcy/ServiceDiscovery.java | package org.tinylcy;
import org.apache.log4j.Logger;
import org.tinylcy.zookeeper.ZooKeeperManager;
import java.util.List;
/**
* Created by chenyangli.
*/
public class ServiceDiscovery {
private static final Logger LOGGER = Logger.getLogger(ServiceDiscovery.class);
private ZooKeeperManager manager;
public ServiceDiscovery(ZooKeeperManager manager) {
this.manager = manager;
}
public String discover() {
manager.connect();
List<String> services = manager.listChildren(ZooKeeperManager.ZK_REGISTRY_PATH);
int size = services.size();
int index = RandomGenerator.randInt(0, size - 1);
String connectString = services.get(index);
LOGGER.info("Select connection [" + connectString + "] as service provider.");
return connectString;
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-registry/src/main/java/org/tinylcy/zookeeper/ZooKeeperManager.java | buddha-registry/src/main/java/org/tinylcy/zookeeper/ZooKeeperManager.java | package org.tinylcy.zookeeper;
import com.google.common.base.Strings;
import org.apache.log4j.Logger;
import org.apache.zookeeper.*;
import org.tinylcy.PropertyReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
* Created by chenyangli.
*/
public class ZooKeeperManager {
private static final Logger LOGGER = Logger.getLogger(ZooKeeperManager.class);
private static final PropertyReader READER = new PropertyReader("zookeeper.properties");
public static final int ZK_SESSION_TIMEOUT =
Integer.parseInt(READER.getProperty("ZK_SESSION_TIMEOUT"));
public static final String ZK_REGISTRY_PATH = READER.getProperty("ZK_REGISTRY_PATH");
private String zkAddress;
private ZooKeeper zk;
public ZooKeeperManager(String zkAddress) {
this.zkAddress = zkAddress;
}
public void connect() {
final CountDownLatch connectedSignal = new CountDownLatch(1);
try {
zk = new ZooKeeper(zkAddress, ZK_SESSION_TIMEOUT, new Watcher() {
public void process(WatchedEvent watchedEvent) {
connectedSignal.countDown();
}
});
connectedSignal.await();
LOGGER.info("Successfully connected to " + zkAddress);
} catch (IOException e) {
LOGGER.info("Failed to connect to " + zkAddress);
e.printStackTrace();
} catch (InterruptedException e) {
LOGGER.info("Failed to connect to " + zkAddress);
e.printStackTrace();
}
}
public void createNode(String nodePath) {
try {
if (zk.exists(ZK_REGISTRY_PATH, true) == null) {
zk.create(ZK_REGISTRY_PATH, null,
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.create(ZK_REGISTRY_PATH + "/" + nodePath, null,
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
LOGGER.info("Node " + nodePath + " have been created successfully.");
zk.close();
} catch (InterruptedException e) {
LOGGER.error("Creating node " + nodePath + " failed.");
e.printStackTrace();
} catch (KeeperException e) {
LOGGER.error("Creating node " + nodePath + " failed.");
e.printStackTrace();
}
}
public List<String> listChildren(String nodePath) {
checkGroupPath(nodePath);
List<String> result = new ArrayList<String>();
try {
List<String> children = zk.getChildren(nodePath, true);
for (String c : children) {
result.add(c);
}
zk.close();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return result;
}
public void deleteNode(String nodePath) {
checkGroupPath(nodePath);
try {
List<String> children = zk.getChildren(nodePath, true);
for (String c : children) {
zk.delete(nodePath + "/" + c, -1);
}
zk.delete(nodePath, -1);
zk.close();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void checkGroupPath(String path) {
if (Strings.isNullOrEmpty(path)) {
String msg = "group path can not be null or empty: " + path;
LOGGER.error(msg);
throw new IllegalArgumentException(msg);
}
if (!path.startsWith(ZK_REGISTRY_PATH)) {
String msg = "Illegal access to group: " + path;
LOGGER.error(msg);
throw new IllegalArgumentException(msg);
}
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-server/src/test/java/org/tinylcy/PropertyReaderTest.java | buddha-server/src/test/java/org/tinylcy/PropertyReaderTest.java | package org.tinylcy;
import org.junit.Test;
/**
* Created by chenyangli.
*/
public class PropertyReaderTest {
@Test
public void read() {
PropertyReader reader = new PropertyReader("buddha-server.properties");
String host = reader.getProperty("server.address.host");
System.out.println(host);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-server/src/test/java/org/tinylcy/ApplicationContextTest.java | buddha-server/src/test/java/org/tinylcy/ApplicationContextTest.java | package org.tinylcy;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by chenyangli.
*/
public class ApplicationContextTest {
@Test
public void testApplicationContext() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Object manager = context.getBean("zk-manager");
System.out.println(manager);
Object registry = context.getBean("buddha-registry");
System.out.println(registry);
Object server = context.getBean("buddha-rpc-server");
System.out.println(server);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-server/src/main/java/org/tinylcy/RpcServerHandler.java | buddha-server/src/main/java/org/tinylcy/RpcServerHandler.java | package org.tinylcy;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
/**
* Created by chenyangli.
*/
public class RpcServerHandler extends SimpleChannelInboundHandler<RpcRequest> {
private Map<String, Object> handlerMap;
public RpcServerHandler(Map<String, Object> handlerMap) {
this.handlerMap = handlerMap;
}
@Override
protected void channelRead0(ChannelHandlerContext context, RpcRequest request)
throws Exception {
System.out.println("RpcServerHandler request: " + request);
RpcResponse response = new RpcResponse();
response.setRequestId(request.getRequestId());
response.setError(null);
Object result = handle(request);
response.setResult(result);
context.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
}
private Object handle(RpcRequest request) {
String className = request.getClassName();
Object serviceBean = handlerMap.get(className);
if (serviceBean == null) {
}
Method[] methods = serviceBean.getClass().getDeclaredMethods();
Object result = null;
try {
for (Method method : methods) {
if (method.getName().equals(request.getMethodName())) {
result = method.invoke(serviceBean, request.getParams());
break;
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return result;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-server/src/main/java/org/tinylcy/RpcServer.java | buddha-server/src/main/java/org/tinylcy/RpcServer.java | package org.tinylcy;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.commons.collections4.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.tinylcy.annotation.RpcService;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
/**
* Created by chenyangli.
*/
public class RpcServer implements ApplicationContextAware, InitializingBean {
private static final Logger LOGGER = Logger.getLogger(RpcServer.class);
/**
* host:port
*/
private String serverAddress;
private ServiceRegistry registry;
/**
* Service handler map
* key: service Id (interface name)
* value: concrete handler (Spring bean)
*/
private Map<String, Object> handlerMap = new HashMap<String, Object>();
public RpcServer(String serverAddress, ServiceRegistry registry) {
this.serverAddress = serverAddress;
this.registry = registry;
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
Map<String, Object> serviceMap = applicationContext.getBeansWithAnnotation(RpcService.class);
if (MapUtils.isNotEmpty(serviceMap)) {
for (Object bean : serviceMap.values()) {
String interfaceName = bean.getClass().getAnnotation(RpcService.class).value().getName();
handlerMap.put(interfaceName, bean);
}
}
}
public void afterPropertiesSet() throws Exception {
registry.init();
bootstrap();
}
public void bootstrap() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new RpcEncoder(RpcResponse.class));
channel.pipeline().addLast(new RpcDecoder(RpcRequest.class));
// channel.pipeline().addLast(new RpcRequestCodec());
channel.pipeline().addLast(new RpcServerHandler(handlerMap));
// channel.pipeline().addLast(new RpcResponseCodec());
}
}).option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
String[] tokens = serverAddress.split(":");
String host = tokens[0];
int port = Integer.parseInt(tokens[1]);
ChannelFuture future = bootstrap.bind(new InetSocketAddress(port)).sync();
registry.register(host, port);
System.out.println("buddha rpc server start successfully, listening on port: " + port);
LOGGER.info("RpcServer start successfully, listening on port: " + port);
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
LOGGER.error("RpcServer bind failure.");
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
// RpcServer server = (RpcServer) context.getBean("buddha-rpc-server");
// System.out.println(server);
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-server/src/main/java/org/tinylcy/service/HelloServiceImpl.java | buddha-server/src/main/java/org/tinylcy/service/HelloServiceImpl.java | package org.tinylcy.service;
import org.tinylcy.annotation.RpcService;
/**
* Created by chenyangli.
*/
@RpcService(value = IHelloService.class)
public class HelloServiceImpl implements IHelloService {
public String hello(String name) {
return "hello! " + name;
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-server/src/main/java/org/tinylcy/service/IHelloService.java | buddha-server/src/main/java/org/tinylcy/service/IHelloService.java | package org.tinylcy.service;
/**
* Created by chenyangli.
*/
public interface IHelloService {
String hello(String name);
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-server/src/main/java/org/tinylcy/annotation/RpcService.java | buddha-server/src/main/java/org/tinylcy/annotation/RpcService.java | package org.tinylcy.annotation;
import org.springframework.stereotype.Component;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by chenyangli.
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface RpcService {
Class<?> value();
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-common/src/main/java/org/tinylcy/PropertyReader.java | buddha-common/src/main/java/org/tinylcy/PropertyReader.java | package org.tinylcy;
import com.google.common.io.ByteSource;
import com.google.common.io.Resources;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
/**
* Created by chenyangli.
* <p>
* Read a properties file and get property.
*/
public class PropertyReader {
private String path;
public PropertyReader(String path) {
this.path = path;
}
public String getProperty(String key) {
final URL url = Resources.getResource(path);
final ByteSource byteSource = Resources.asByteSource(url);
final Properties properties = new Properties();
InputStream inputStream = null;
String value = null;
try {
inputStream = byteSource.openBufferedStream();
properties.load(inputStream);
value = properties.getProperty(key);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return value;
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-common/src/main/java/org/tinylcy/RandomGenerator.java | buddha-common/src/main/java/org/tinylcy/RandomGenerator.java | package org.tinylcy;
import java.util.Random;
/**
* Created by chenyangli.
*/
public class RandomGenerator {
/**
* @param min minimum value
* @param max maximum value must be greater than min
* @return Integer between min and max, inclusive.
*/
public static int randInt(int min, int max) {
Random random = new Random();
int randomNum = random.nextInt((max - min) + 1) + min;
return randomNum;
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-client/src/test/java/org/tinylcy/HelloServiceTest.java | buddha-client/src/test/java/org/tinylcy/HelloServiceTest.java | package org.tinylcy;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.tinylcy.proxy.RpcProxy;
import org.tinylcy.service.IHelloService;
/**
* Created by chenyangli.
*/
public class HelloServiceTest {
@Test
public void helloTest() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
RpcProxy proxy = (RpcProxy) context.getBean("buddha-rpc-proxy");
IHelloService service = proxy.newProxy(IHelloService.class);
for (int i = 0; i < 100; i++) {
String result = service.hello("chenyang");
System.out.println(result);
}
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-client/src/main/java/org/tinylcy/RpcClientHandler.java | buddha-client/src/main/java/org/tinylcy/RpcClientHandler.java | package org.tinylcy;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* Created by chenyangli.
*/
public class RpcClientHandler extends SimpleChannelInboundHandler<RpcResponse> {
private RpcResponse response;
public RpcClientHandler(RpcResponse response) {
this.response = response;
}
@Override
protected void channelRead0(ChannelHandlerContext context, RpcResponse resp)
throws Exception {
System.out.println("RpcClientHandler - response: " + resp);
response.setRequestId(resp.getRequestId());
response.setError(resp.getError());
response.setResult(resp.getResult());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
public RpcResponse getResponse() {
return response;
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-client/src/main/java/org/tinylcy/RpcClient.java | buddha-client/src/main/java/org/tinylcy/RpcClient.java | package org.tinylcy;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.log4j.Logger;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
/**
* Created by chenyangli.
*/
public class RpcClient {
private static final Logger LOGGER = Logger.getLogger(RpcClient.class);
private ServiceDiscovery discovery;
public RpcClient(ServiceDiscovery discovery) {
this.discovery = discovery;
}
public Object call(final Class<?> clazz, Method method, Object[] args) {
RpcRequest request = new RpcRequest(clazz.getName(),
method.getName(), method.getParameterTypes(), args);
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
final RpcResponse response = new RpcResponse();
try {
final CountDownLatch completedSignal = new CountDownLatch(1);
bootstrap.group(group).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new RpcEncoder(RpcRequest.class));
channel.pipeline().addLast(new RpcDecoder(RpcResponse.class));
// channel.pipeline().addLast(new RpcResponseCodec());
channel.pipeline().addLast(new RpcClientHandler(response));
// channel.pipeline().addLast(new RpcRequestCodec());
}
}).option(ChannelOption.SO_KEEPALIVE, true);
String connectString = discovery.discover();
String[] tokens = connectString.split(":");
String host = tokens[0];
int port = Integer.parseInt(tokens[1]);
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)).sync();
future.channel().writeAndFlush(request).addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture channelFuture) throws Exception {
completedSignal.countDown();
}
});
// Wait until the asynchronous write return.
completedSignal.await();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
LOGGER.error("RpcClient call RPC failure.");
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
return response;
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-client/src/main/java/org/tinylcy/service/IHelloService.java | buddha-client/src/main/java/org/tinylcy/service/IHelloService.java | package org.tinylcy.service;
/**
* Created by chenyangli.
*/
public interface IHelloService {
String hello(String name);
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
tinylcy/buddha | https://github.com/tinylcy/buddha/blob/60b868ab565dcfb9f1c22e0776388bac20d8cea5/buddha-client/src/main/java/org/tinylcy/proxy/RpcProxy.java | buddha-client/src/main/java/org/tinylcy/proxy/RpcProxy.java | package org.tinylcy.proxy;
import org.apache.log4j.Logger;
import org.tinylcy.RpcClient;
import org.tinylcy.RpcResponse;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Created by chenyangli.
*/
public class RpcProxy implements InvocationHandler {
private static final Logger LOGGER = Logger.getLogger(RpcProxy.class);
private Class<?> clazz;
private RpcClient client;
public RpcProxy(RpcClient client) {
this.client = client;
}
public <T> T newProxy(Class<?> clazz) {
this.clazz = clazz;
return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{clazz}, this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
RpcResponse response = (RpcResponse) client.call(clazz, method, args);
return response.getResult();
}
}
| java | MIT | 60b868ab565dcfb9f1c22e0776388bac20d8cea5 | 2026-01-05T02:40:43.558810Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-server/src/main/java/com/webank/ai/fate/serving/Bootstrap.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/Bootstrap.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving;
import com.webank.ai.fate.serving.common.flow.JvmInfoCounter;
import com.webank.ai.fate.serving.common.rpc.core.AbstractServiceAdaptor;
import com.webank.ai.fate.serving.common.utils.HttpClientPool;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.io.*;
import java.util.Properties;
@SpringBootApplication
@ConfigurationProperties
@PropertySource(value = "classpath:serving-server.properties", ignoreResourceNotFound = false)
@EnableScheduling
public class Bootstrap {
static Logger logger = LoggerFactory.getLogger(Bootstrap.class);
private static ApplicationContext applicationContext;
public static void main(String[] args) {
try {
parseConfig();
Bootstrap bootstrap = new Bootstrap();
bootstrap.start(args);
Runtime.getRuntime().addShutdownHook(new Thread(() -> bootstrap.stop()));
} catch (Exception ex) {
logger.error("serving-server start error", ex);
System.exit(1);
}
}
public static void parseConfig() {
ClassPathResource classPathResource = new ClassPathResource("serving-server.properties");
try {
File file = classPathResource.getFile();
Properties environment = new Properties();
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
environment.load(inputStream);
} catch (FileNotFoundException e) {
logger.error("profile serving-server.properties not found");
throw e;
} catch (IOException e) {
logger.error("parse config error, {}", e.getMessage());
throw e;
}
int processors = Runtime.getRuntime().availableProcessors();
MetaInfo.PROPERTY_ROOT_PATH = new File("").getCanonicalPath();
MetaInfo.PROPERTY_PROXY_ADDRESS = environment.getProperty(Dict.PROPERTY_PROXY_ADDRESS);
MetaInfo.PROPERTY_SERVING_CORE_POOL_SIZE = environment.getProperty(Dict.PROPERTY_SERVING_CORE_POOL_SIZE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_SERVING_CORE_POOL_SIZE)) : processors;
MetaInfo.PROPERTY_SERVING_MAX_POOL_SIZE = environment.getProperty(Dict.PROPERTY_SERVING_MAX_POOL_SIZE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_SERVING_MAX_POOL_SIZE)) : processors * 2;
MetaInfo.PROPERTY_SERVING_POOL_ALIVE_TIME = environment.getProperty(Dict.PROPERTY_SERVING_POOL_ALIVE_TIME) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_SERVING_POOL_ALIVE_TIME)) : 1000;
MetaInfo.PROPERTY_SERVING_POOL_QUEUE_SIZE = environment.getProperty(Dict.PROPERTY_SERVING_POOL_QUEUE_SIZE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_SERVING_POOL_QUEUE_SIZE)) : 100;
MetaInfo.PROPERTY_FEATURE_BATCH_ADAPTOR = environment.getProperty(Dict.PROPERTY_FEATURE_BATCH_ADAPTOR);
MetaInfo.PROPERTY_FETTURE_BATCH_SINGLE_ADAPTOR = environment.getProperty(Dict.PROPERTY_FEATURE_BATCH_SINGLE_ADAPTOR);
MetaInfo.PROPERTY_BATCH_INFERENCE_MAX = environment.getProperty(Dict.PROPERTY_BATCH_INFERENCE_MAX) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_BATCH_INFERENCE_MAX)) : 300;
MetaInfo.PROPERTY_REMOTE_MODEL_INFERENCE_RESULT_CACHE_SWITCH = environment.getProperty(Dict.PROPERTY_REMOTE_MODEL_INFERENCE_RESULT_CACHE_SWITCH) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_REMOTE_MODEL_INFERENCE_RESULT_CACHE_SWITCH)) : Boolean.FALSE;
MetaInfo.PROPERTY_SINGLE_INFERENCE_RPC_TIMEOUT = environment.getProperty(Dict.PROPERTY_SINGLE_INFERENCE_RPC_TIMEOUT) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_SINGLE_INFERENCE_RPC_TIMEOUT)) : 3000;
MetaInfo.PROPERTY_BATCH_INFERENCE_RPC_TIMEOUT = environment.getProperty(Dict.PROPERTY_BATCH_INFERENCE_RPC_TIMEOUT) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_BATCH_INFERENCE_RPC_TIMEOUT)) : 3000;
MetaInfo.PROPERTY_FEATURE_SINGLE_ADAPTOR = environment.getProperty(Dict.PROPERTY_FEATURE_SINGLE_ADAPTOR);
MetaInfo.PROPERTY_USE_REGISTER = environment.getProperty(Dict.PROPERTY_USE_REGISTER) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_USE_REGISTER)) : true;
MetaInfo.PROPERTY_USE_ZK_ROUTER = environment.getProperty(Dict.PROPERTY_USE_ZK_ROUTER) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_USE_ZK_ROUTER)) : true;
MetaInfo.PROPERTY_SERVER_PORT = environment.getProperty(Dict.PORT) != null ? Integer.valueOf(environment.getProperty(Dict.PORT)) : 8000;
MetaInfo.PROPERTY_ZK_URL = environment.getProperty(Dict.PROPERTY_ZK_URL);
MetaInfo.PROPERTY_CACHE_TYPE = environment.getProperty(Dict.PROPERTY_CACHE_TYPE, "local");
MetaInfo.PROPERTY_REDIS_IP = environment.getProperty(Dict.PROPERTY_REDIS_IP);
MetaInfo.PROPERTY_REDIS_PASSWORD = environment.getProperty(Dict.PROPERTY_REDIS_PASSWORD);
MetaInfo.PROPERTY_REDIS_PORT = environment.getProperty(Dict.PROPERTY_REDIS_PORT) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_REDIS_PORT)) : 3306;
MetaInfo.PROPERTY_REDIS_TIMEOUT = environment.getProperty(Dict.PROPERTY_REDIS_TIMEOUT) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_REDIS_TIMEOUT)) : 2000;
MetaInfo.PROPERTY_REDIS_MAX_TOTAL = environment.getProperty(Dict.PROPERTY_REDIS_MAX_TOTAL) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_REDIS_MAX_TOTAL)) : 20;
MetaInfo.PROPERTY_REDIS_MAX_IDLE = environment.getProperty(Dict.PROPERTY_REDIS_MAX_IDLE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_REDIS_MAX_IDLE)) : 2;
MetaInfo.PROPERTY_REDIS_EXPIRE = environment.getProperty(Dict.PROPERTY_REDIS_EXPIRE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_REDIS_EXPIRE)) : 3000;
MetaInfo.PROPERTY_REDIS_CLUSTER_NODES = environment.getProperty(Dict.PROPERTY_REDIS_CLUSTER_NODES);
MetaInfo.PROPERTY_LOCAL_CACHE_MAXSIZE = environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_MAXSIZE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_MAXSIZE)) : 10000;
MetaInfo.PROPERTY_LOCAL_CACHE_EXPIRE = environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_EXPIRE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_EXPIRE)) : 30;
MetaInfo.PROPERTY_LOCAL_CACHE_INTERVAL = environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_INTERVAL) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_INTERVAL)) : 3;
MetaInfo.PROPERTY_BATCH_SPLIT_SIZE = environment.getProperty(Dict.PROPERTY_BATCH_SPLIT_SIZE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_BATCH_SPLIT_SIZE)) : 100;
MetaInfo.PROPERTY_LR_SPLIT_SIZE = environment.getProperty(Dict.PROPERTY_LR_SPLIT_SIZE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_LR_SPLIT_SIZE)) : 500;
MetaInfo.PROPERTY_SERVICE_ROLE_NAME = environment.getProperty(Dict.PROPERTY_SERVICE_ROLE_NAME, Dict.PROPERTY_SERVICE_ROLE_NAME_DEFAULT_VALUE);
MetaInfo.PROPERTY_MODEL_TRANSFER_URL = environment.getProperty(Dict.PROPERTY_MODEL_TRANSFER_URL);
MetaInfo.PROPERTY_MODEL_CACHE_PATH = StringUtils.isNotBlank(environment.getProperty(Dict.PROPERTY_MODEL_CACHE_PATH)) ? environment.getProperty(Dict.PROPERTY_MODEL_CACHE_PATH) : MetaInfo.PROPERTY_ROOT_PATH;
MetaInfo.PROPERTY_ACL_ENABLE = Boolean.valueOf(environment.getProperty(Dict.PROPERTY_ACL_ENABLE, "false"));
MetaInfo.PROPERTY_MODEL_SYNC = Boolean.valueOf(environment.getProperty(Dict.PROPERTY_MODEL_SYNC, "false"));
MetaInfo.PROPERTY_GRPC_TIMEOUT = Integer.valueOf(environment.getProperty(Dict.PROPERTY_GRPC_TIMEOUT, "5000"));
MetaInfo.PROPERTY_ACL_USERNAME = environment.getProperty(Dict.PROPERTY_ACL_USERNAME);
MetaInfo.PROPERTY_ACL_PASSWORD = environment.getProperty(Dict.PROPERTY_ACL_PASSWORD);
MetaInfo.PROPERTY_PRINT_INPUT_DATA = environment.getProperty(Dict.PROPERTY_PRINT_INPUT_DATA) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_PRINT_INPUT_DATA)) : false;
MetaInfo.PROPERTY_PRINT_OUTPUT_DATA = environment.getProperty(Dict.PROPERTY_PRINT_OUTPUT_DATA) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_PRINT_OUTPUT_DATA)) : false;
MetaInfo.PROPERTY_LR_USE_PARALLEL = environment.getProperty(Dict.PROPERTY_LR_USE_PARALLEL) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_LR_USE_PARALLEL)) : false;
MetaInfo.PROPERTY_ALLOW_HEALTH_CHECK = environment.getProperty(Dict.PROPERTY_ALLOW_HEALTH_CHECK) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_ALLOW_HEALTH_CHECK)) : true;
MetaInfo.HTTP_CLIENT_CONFIG_CONN_REQ_TIME_OUT = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_CONFIG_CONN_REQ_TIME_OUT,"500"));
MetaInfo.HTTP_CLIENT_CONFIG_CONN_TIME_OUT = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_CONFIG_CONN_TIME_OUT,"500"));
MetaInfo.HTTP_CLIENT_CONFIG_SOCK_TIME_OUT = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_CONFIG_SOCK_TIME_OUT,"2000"));
MetaInfo.HTTP_CLIENT_INIT_POOL_MAX_TOTAL = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_INIT_POOL_MAX_TOTAL,"500"));
MetaInfo.HTTP_CLIENT_INIT_POOL_DEF_MAX_PER_ROUTE = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_INIT_POOL_DEF_MAX_PER_ROUTE,"200"));
MetaInfo.HTTP_CLIENT_INIT_POOL_SOCK_TIME_OUT = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_INIT_POOL_SOCK_TIME_OUT,"10000"));
MetaInfo.HTTP_CLIENT_INIT_POOL_CONN_TIME_OUT = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_INIT_POOL_CONN_TIME_OUT,"10000"));
MetaInfo.HTTP_CLIENT_INIT_POOL_CONN_REQ_TIME_OUT = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_INIT_POOL_CONN_REQ_TIME_OUT,"10000"));
MetaInfo.HTTP_CLIENT_TRAN_CONN_REQ_TIME_OUT = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_TRAN_CONN_REQ_TIME_OUT,"60000"));
MetaInfo.HTTP_CLIENT_TRAN_CONN_TIME_OUT = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_TRAN_CONN_TIME_OUT,"60000"));
MetaInfo.HTTP_CLIENT_TRAN_SOCK_TIME_OUT = Integer.valueOf(environment.getProperty(Dict.HTTP_CLIENT_TRAN_SOCK_TIME_OUT,"60000"));
MetaInfo.PROPERTY_HTTP_CONNECT_REQUEST_TIMEOUT = environment.getProperty(Dict.PROPERTY_HTTP_CONNECT_REQUEST_TIMEOUT) !=null?Integer.parseInt(environment.getProperty(Dict.PROPERTY_HTTP_CONNECT_REQUEST_TIMEOUT)):10000;
MetaInfo.PROPERTY_HTTP_CONNECT_TIMEOUT = environment.getProperty(Dict.PROPERTY_HTTP_CONNECT_TIMEOUT) !=null?Integer.parseInt(environment.getProperty(Dict.PROPERTY_HTTP_CONNECT_TIMEOUT)):10000;
MetaInfo.PROPERTY_HTTP_SOCKET_TIMEOUT = environment.getProperty(Dict.PROPERTY_HTTP_SOCKET_TIMEOUT) !=null?Integer.parseInt(environment.getProperty(Dict.PROPERTY_HTTP_SOCKET_TIMEOUT)):10000;
MetaInfo.PROPERTY_HTTP_MAX_POOL_SIZE = environment.getProperty(Dict.PROPERTY_HTTP_MAX_POOL_SIZE) !=null?Integer.parseInt(environment.getProperty(Dict.PROPERTY_HTTP_MAX_POOL_SIZE)):50;
MetaInfo.PROPERTY_HTTP_ADAPTER_URL = environment.getProperty(Dict.PROPERTY_HTTP_ADAPTER_URL);
} catch (Exception e) {
e.printStackTrace();
logger.error("init metainfo error", e);
System.exit(1);
}
}
public void start(String[] args) {
HttpClientPool.initPool();
SpringApplication springApplication = new SpringApplication(Bootstrap.class);
applicationContext = springApplication.run(args);
JvmInfoCounter.start();
}
public void stop() {
logger.info("try to shutdown server ...");
AbstractServiceAdaptor.isOpen = false;
int retryCount = 0;
while (AbstractServiceAdaptor.requestInHandle.get() > 0 && retryCount < 30) {
logger.info("try to stop server, there is {} request in process, try count {}", AbstractServiceAdaptor.requestInHandle.get(), retryCount + 1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
retryCount++;
}
}
} | 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-server/src/main/java/com/webank/ai/fate/serving/ServingServer.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/ServingServer.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;
import com.webank.ai.fate.register.common.NamedThreadFactory;
import com.webank.ai.fate.register.provider.FateServer;
import com.webank.ai.fate.register.provider.FateServerBuilder;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.common.bean.BaseContext;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.grpc.service.*;
import com.webank.ai.fate.serving.model.ModelManager;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerInterceptors;
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.concurrent.*;
@Service
public class ServingServer implements InitializingBean {
Logger logger = LoggerFactory.getLogger(ServingServer.class);
@Autowired
GuestInferenceService guestInferenceService;
@Autowired
CommonService commonService;
@Autowired
ModelManager modelManager;
@Autowired
ModelService modelService;
@Autowired
HostInferenceService hostInferenceService;
@Autowired(required = false)
ZookeeperRegistry zookeeperRegistry;
private Server server;
@Override
public void afterPropertiesSet() throws Exception {
logger.info("try to star server ,meta info {}", MetaInfo.toMap());
Executor executor = new ThreadPoolExecutor(MetaInfo.PROPERTY_SERVING_CORE_POOL_SIZE, MetaInfo.PROPERTY_SERVING_MAX_POOL_SIZE, MetaInfo.PROPERTY_SERVING_POOL_ALIVE_TIME, TimeUnit.MILLISECONDS,
MetaInfo.PROPERTY_SERVING_POOL_QUEUE_SIZE == 0 ? new SynchronousQueue<Runnable>() :
(MetaInfo.PROPERTY_SERVING_POOL_QUEUE_SIZE < 0 ? new LinkedBlockingQueue<Runnable>()
: new LinkedBlockingQueue<Runnable>(MetaInfo.PROPERTY_SERVING_POOL_QUEUE_SIZE)), new NamedThreadFactory("ServingServer", true));
FateServerBuilder serverBuilder = (FateServerBuilder) ServerBuilder.forPort(MetaInfo.PROPERTY_SERVER_PORT);
serverBuilder.keepAliveTime(100, TimeUnit.MILLISECONDS);
serverBuilder.executor(executor);
serverBuilder.addService(ServerInterceptors.intercept(guestInferenceService, new ServiceExceptionHandler(), new ServiceOverloadProtectionHandle()), GuestInferenceService.class);
serverBuilder.addService(ServerInterceptors.intercept(modelService, new ServiceExceptionHandler(), new ServiceOverloadProtectionHandle()), ModelService.class);
serverBuilder.addService(ServerInterceptors.intercept(hostInferenceService, new ServiceExceptionHandler(), new ServiceOverloadProtectionHandle()), HostInferenceService.class);
serverBuilder.addService(ServerInterceptors.intercept(commonService, new ServiceExceptionHandler(), new ServiceOverloadProtectionHandle()), CommonService.class);
server = serverBuilder.build();
server.start();
boolean useRegister = MetaInfo.PROPERTY_USE_REGISTER;
if (useRegister) {
logger.info("serving-server is using register center");
zookeeperRegistry.subProject(Dict.PROPERTY_PROXY_ADDRESS);
zookeeperRegistry.subProject(Dict.PROPERTY_FLOW_ADDRESS);
zookeeperRegistry.register(FateServer.serviceSets);
} else {
logger.warn("serving-server not use register center");
}
modelManager.restore(new BaseContext());
logger.warn("serving-server start over");
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-server/src/main/java/com/webank/ai/fate/serving/FateServiceRegister.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/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;
import com.webank.ai.fate.serving.common.flow.FlowCounterManager;
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;
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
@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);
FlowCounterManager flowCounterManager = applicationContext.getBean(FlowCounterManager.class);
for (String beanName : beans) {
AbstractServiceAdaptor serviceAdaptor = applicationContext.getBean(beanName, AbstractServiceAdaptor.class);
serviceAdaptor.setFlowCounterManager(flowCounterManager);
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-server/src/main/java/com/webank/ai/fate/serving/AsyncMessageConfig.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/AsyncMessageConfig.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;
import com.webank.ai.fate.serving.common.async.AbstractAsyncMessageProcessor;
import com.webank.ai.fate.serving.common.async.AsyncSubscribeRegister;
import com.webank.ai.fate.serving.common.async.Subscribe;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
@Configuration
public class AsyncMessageConfig implements ApplicationContextAware {
Logger logger = LoggerFactory.getLogger(AsyncMessageConfig.class);
ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Bean
public ApplicationListener<ApplicationReadyEvent> asyncSubscribeRegister() {
return applicationReadyEvent -> {
String[] beans = applicationContext.getBeanNamesForType(AbstractAsyncMessageProcessor.class);
for (String beanName : beans) {
AbstractAsyncMessageProcessor eventProcessor = applicationContext.getBean(beanName, AbstractAsyncMessageProcessor.class);
Method[] methods = eventProcessor.getClass().getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(Subscribe.class)) {
Subscribe subscribe = method.getAnnotation(Subscribe.class);
if (subscribe != null) {
Set<Method> methodList = AsyncSubscribeRegister.SUBSCRIBE_METHOD_MAP.get(subscribe.value());
if (methodList == null) {
methodList = new HashSet<>();
}
methodList.add(method);
AsyncSubscribeRegister.METHOD_INSTANCE_MAP.put(method, eventProcessor);
AsyncSubscribeRegister.SUBSCRIBE_METHOD_MAP.put(subscribe.value(), methodList);
}
}
}
}
logger.info("subscribe register info {}", AsyncSubscribeRegister.SUBSCRIBE_METHOD_MAP.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-server/src/main/java/com/webank/ai/fate/serving/UseZkCondition.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/UseZkCondition.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;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class UseZkCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return MetaInfo.PROPERTY_USE_REGISTER;
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/ServingConfig.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/ServingConfig.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;
import com.google.common.base.Preconditions;
import com.webank.ai.fate.register.router.DefaultRouterService;
import com.webank.ai.fate.register.router.RouterService;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.common.cache.Cache;
import com.webank.ai.fate.serving.common.cache.ExpiringLRUCache;
import com.webank.ai.fate.serving.common.cache.RedisCache;
import com.webank.ai.fate.serving.common.cache.RedisClusterCache;
import com.webank.ai.fate.serving.common.flow.FlowCounterManager;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServingConfig {
Logger logger = LoggerFactory.getLogger(ServingConfig.class);
@Bean(destroyMethod = "destroy")
@Conditional({UseZkCondition.class})
ZookeeperRegistry getServiceRegistry() {
Preconditions.checkArgument(StringUtils.isNotEmpty(MetaInfo.PROPERTY_ZK_URL));
return ZookeeperRegistry.createRegistry(MetaInfo.PROPERTY_ZK_URL, Dict.SERVICE_SERVING, Dict.ONLINE_ENVIRONMENT, MetaInfo.PROPERTY_SERVER_PORT);
}
@Bean
@Conditional({UseZkCondition.class})
RouterService getRouterService(ZookeeperRegistry zookeeperRegistry) {
DefaultRouterService routerService = new DefaultRouterService();
routerService.setRegistry(zookeeperRegistry);
return routerService;
}
@Bean(initMethod = "initialize", destroyMethod = "destroy")
public FlowCounterManager flowCounterManager() {
FlowCounterManager flowCounterManager = new FlowCounterManager(Dict.SERVICE_SERVING, true);
flowCounterManager.startReport();
return flowCounterManager;
}
@Bean
public Cache cache() {
String cacheType = MetaInfo.PROPERTY_CACHE_TYPE;
logger.info("cache type is {},prepare to build cache", cacheType);
Cache cache = null;
switch (cacheType) {
case "redis":
String ip = MetaInfo.PROPERTY_REDIS_IP;
String password = MetaInfo.PROPERTY_REDIS_PASSWORD;
Integer port = MetaInfo.PROPERTY_REDIS_PORT;
Integer timeout = MetaInfo.PROPERTY_REDIS_TIMEOUT;
Integer maxTotal = MetaInfo.PROPERTY_REDIS_MAX_TOTAL;
Integer maxIdle = MetaInfo.PROPERTY_REDIS_MAX_IDLE;
Integer expire = MetaInfo.PROPERTY_REDIS_EXPIRE;
String clusterNodes = MetaInfo.PROPERTY_REDIS_CLUSTER_NODES;
RedisCache redisCache;
if (StringUtils.isNotBlank(clusterNodes)) {
redisCache = new RedisClusterCache(clusterNodes);
logger.info("redis cache mode: cluster");
} else {
redisCache = new RedisCache();
logger.info("redis cache mode: standalone");
}
redisCache.setExpireTime(timeout);
redisCache.setMaxTotal(maxTotal);
redisCache.setMaxIdel(maxIdle);
redisCache.setHost(ip);
redisCache.setPort(port);
redisCache.setExpireTime(expire != null ? expire : -1);
redisCache.setPassword(password);
redisCache.init();
cache = redisCache;
break;
case "local":
Integer maxSize = MetaInfo.PROPERTY_LOCAL_CACHE_MAXSIZE;
Integer expireTime = MetaInfo.PROPERTY_LOCAL_CACHE_EXPIRE;
Integer interval = MetaInfo.PROPERTY_LOCAL_CACHE_INTERVAL;
ExpiringLRUCache lruCache = new ExpiringLRUCache(maxSize, expireTime, interval);
cache = lruCache;
break;
default:
}
return cache;
}
@Bean
@Conditional(UseZkCondition.class)
@ConditionalOnBean(ZookeeperRegistry.class)
public ApplicationListener<ApplicationReadyEvent> registerComponent(ZookeeperRegistry zookeeperRegistry) {
return applicationReadyEvent -> zookeeperRegistry.registerComponent();
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/guest/provider/GuestSingleInferenceProvider.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/guest/provider/GuestSingleInferenceProvider.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.guest.provider;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListenableFuture;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.model.ModelProcessor;
import com.webank.ai.fate.serving.common.rpc.core.*;
import com.webank.ai.fate.serving.core.bean.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
@FateService(name = "singleInference", preChain = {
"requestOverloadBreaker",
"guestSingleParamInterceptor",
"guestModelInterceptor",
"federationRouterInterceptor"
}, postChain = {
})
@Service
public class GuestSingleInferenceProvider extends AbstractServingServiceProvider<InferenceRequest, ReturnResult> {
@Autowired
FederatedRpcInvoker federatedRpcInvoker;
Logger logger = LoggerFactory.getLogger(GuestSingleInferenceProvider.class);
@Override
public ReturnResult doService(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) {
Model model = ((ServingServerContext) context).getModel();
ModelProcessor modelProcessor = model.getModelProcessor();
InferenceRequest inferenceRequest = (InferenceRequest) inboundPackage.getBody();
Map<String, Future> futureMap = Maps.newHashMap();
InferenceRequest remoteInferenceRequest = new InferenceRequest();
remoteInferenceRequest.setSendToRemoteFeatureData(inferenceRequest.getSendToRemoteFeatureData());
List<FederatedRpcInvoker.RpcDataWraper> rpcList = this.buildRpcDataWraper(context, Dict.FEDERATED_INFERENCE, remoteInferenceRequest);
rpcList.forEach((rpcDataWraper -> {
ListenableFuture<ReturnResult> future = federatedRpcInvoker.singleInferenceRpcWithCache(context, rpcDataWraper, MetaInfo.PROPERTY_REMOTE_MODEL_INFERENCE_RESULT_CACHE_SWITCH);
futureMap.put(rpcDataWraper.getHostModel().getPartId(), future);
}));
ReturnResult returnResult = modelProcessor.guestInference(context, inferenceRequest, futureMap, MetaInfo.PROPERTY_SINGLE_INFERENCE_RPC_TIMEOUT);
postProcess(context, returnResult);
return returnResult;
}
@Override
protected OutboundPackage<ReturnResult> serviceFailInner(Context context, InboundPackage<InferenceRequest> data, Throwable e) {
OutboundPackage<ReturnResult> outboundPackage = new OutboundPackage<ReturnResult>();
ReturnResult returnResult = ErrorMessageUtil.handleExceptionToReturnResult(e);
postProcess(context, returnResult);
outboundPackage.setData(returnResult);
context.setReturnCode(returnResult.getRetcode());
return outboundPackage;
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/guest/provider/GuestBatchInferenceProvider.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/guest/provider/GuestBatchInferenceProvider.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.guest.provider;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListenableFuture;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.model.ModelProcessor;
import com.webank.ai.fate.serving.common.rpc.core.FateService;
import com.webank.ai.fate.serving.common.rpc.core.FederatedRpcInvoker;
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.*;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@FateService(name = "batchInference", preChain = {
"requestOverloadBreaker",
"guestBatchParamInterceptor",
"guestModelInterceptor",
"federationRouterInterceptor"
}, postChain = {
})
@Service
public class GuestBatchInferenceProvider extends AbstractServingServiceProvider<BatchInferenceRequest, BatchInferenceResult> {
@Autowired
FederatedRpcInvoker federatedRpcInvoker;
@Override
public BatchInferenceResult doService(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) {
Model model = ((ServingServerContext) context).getModel();
ModelProcessor modelProcessor = model.getModelProcessor();
BatchInferenceRequest batchInferenceRequest = (BatchInferenceRequest) inboundPackage.getBody();
Map futureMap = Maps.newHashMap();
model.getFederationModelMap().forEach((hostPartyId, remoteModel) -> {
BatchHostFederatedParams batchHostFederatedParams = buildBatchHostFederatedParams(context, batchInferenceRequest, model, remoteModel);
ListenableFuture<BatchInferenceResult> originBatchResultFuture = federatedRpcInvoker.batchInferenceRpcWithCache(context, buildRpcDataWraper(model, remoteModel, batchHostFederatedParams), MetaInfo.PROPERTY_REMOTE_MODEL_INFERENCE_RESULT_CACHE_SWITCH);
futureMap.put(hostPartyId, originBatchResultFuture);
});
BatchInferenceResult batchFederatedResult = modelProcessor.guestBatchInference(context, batchInferenceRequest, futureMap, MetaInfo.PROPERTY_BATCH_INFERENCE_RPC_TIMEOUT);
batchFederatedResult.setCaseid(context.getCaseId());
postProcess(context, batchFederatedResult);
return batchFederatedResult;
}
@Override
protected OutboundPackage<BatchInferenceResult> serviceFailInner(Context context, InboundPackage<BatchInferenceRequest> data, Throwable e) {
OutboundPackage<BatchInferenceResult> outboundPackage = new OutboundPackage<BatchInferenceResult>();
BatchInferenceResult batchInferenceResult = new BatchInferenceResult();
if (e instanceof BaseException) {
BaseException baseException = (BaseException) e;
batchInferenceResult.setRetcode(baseException.getRetcode());
batchInferenceResult.setRetmsg(e.getMessage());
} else {
batchInferenceResult.setRetcode(StatusCode.SYSTEM_ERROR);
}
postProcess(context, batchInferenceResult);
context.setReturnCode(batchInferenceResult.getRetcode());
outboundPackage.setData(batchInferenceResult);
return outboundPackage;
}
private FederatedRpcInvoker.RpcDataWraper buildRpcDataWraper(Model model, Model remoteModel, Object batchHostFederatedParams) {
FederatedRpcInvoker.RpcDataWraper rpcDataWraper = new FederatedRpcInvoker.RpcDataWraper();
rpcDataWraper.setGuestModel(model);
rpcDataWraper.setHostModel(remoteModel);
rpcDataWraper.setData(batchHostFederatedParams);
rpcDataWraper.setRemoteMethodName(Dict.REMOTE_METHOD_BATCH);
return rpcDataWraper;
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/guest/provider/AbstractServingServiceProvider.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/guest/provider/AbstractServingServiceProvider.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.guest.provider;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.rpc.core.AbstractServiceAdaptor;
import com.webank.ai.fate.serving.common.rpc.core.FederatedRpcInvoker;
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.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.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.List;
import java.util.Map;
public abstract class AbstractServingServiceProvider<req, resp> extends AbstractServiceAdaptor<req, resp> {
final String baseLogString = "{}|{}|{}|{}|{}|{}|{}|{}";
@Override
protected resp transformExceptionInfo(Context context, ExceptionInfo exceptionInfo) {
return null;
}
@Override
protected resp doService(Context context, InboundPackage<req> data, OutboundPackage<resp> outboundPackage) {
Map<String, Method> methodMap = this.getMethodMap();
String actionType = context.getActionType();
resp result = null;
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) {
BaseException baseException = (BaseException) e.getCause();
throw baseException;
} else if (e instanceof InvocationTargetException) {
InvocationTargetException ex = (InvocationTargetException) e;
throw new SysException(ex.getTargetException().getMessage());
} else {
throw new SysException(e.getMessage());
}
}
return result;
}
@Override
protected void printFlowLog(Context context) {
flowLogger.info(baseLogString,
context.getCaseId(), 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 List<FederatedRpcInvoker.RpcDataWraper> buildRpcDataWraper(Context context, String methodName, Object data) {
List<FederatedRpcInvoker.RpcDataWraper> result = Lists.newArrayList();
Model model = ((ServingServerContext) context).getModel();
Map<String, Model> hostModelMap = model.getFederationModelMap();
hostModelMap.forEach((partId, hostModel) -> {
FederatedRpcInvoker.RpcDataWraper rpcDataWraper = new FederatedRpcInvoker.RpcDataWraper();
rpcDataWraper.setGuestModel(model);
rpcDataWraper.setHostModel(hostModel);
rpcDataWraper.setRemoteMethodName(methodName);
rpcDataWraper.setData(data);
result.add(rpcDataWraper);
});
return result;
}
protected void postProcess(Context context, ReturnResult returnResult) {
Model model = ((ServingServerContext) context).getModel();
context.setReturnCode(returnResult.getRetcode());
if (model != null) {
Map<String, Object> data = returnResult.getData();
if (data == null) {
data = Maps.newHashMap();
}
data.put(Dict.MODEL_ID, model.getNamespace());
data.put(Dict.MODEL_VERSION, model.getTableName());
data.put(Dict.TIMESTAMP, model.getTimestamp());
returnResult.setData(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-server/src/main/java/com/webank/ai/fate/serving/guest/interceptors/GuestSingleParamInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/guest/interceptors/GuestSingleParamInterceptor.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.guest.interceptors;
import com.google.common.base.Preconditions;
import com.webank.ai.fate.api.serving.InferenceServiceProto;
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.InferenceRequest;
import com.webank.ai.fate.serving.core.exceptions.GuestInvalidParamException;
import com.webank.ai.fate.serving.core.utils.InferenceUtils;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
@Service
public class GuestSingleParamInterceptor implements Interceptor {
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
try {
InferenceServiceProto.InferenceMessage message = (InferenceServiceProto.InferenceMessage) inboundPackage.getBody();
InferenceRequest inferenceRequest = null;
inferenceRequest = JsonUtil.json2Object(message.getBody().toByteArray(), InferenceRequest.class);
inboundPackage.setBody(inferenceRequest);
Preconditions.checkArgument(inferenceRequest != null, "request message parse error");
Preconditions.checkArgument(inferenceRequest.getFeatureData() != null, "no feature data");
Preconditions.checkArgument(inferenceRequest.getSendToRemoteFeatureData() != null, "no send to remote feature data");
Preconditions.checkArgument(StringUtils.isNotBlank(inferenceRequest.getServiceId()), "no service id");
if (inferenceRequest.getCaseId() == null || inferenceRequest.getCaseId().length() == 0) {
inferenceRequest.setCaseId(InferenceUtils.generateCaseid());
}
context.setCaseId(inferenceRequest.getCaseId());
context.setServiceId(inferenceRequest.getServiceId());
if (inferenceRequest.getApplyId() != null) {
context.setApplyId(inferenceRequest.getApplyId());
}
} catch (Exception e) {
throw new GuestInvalidParamException(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-server/src/main/java/com/webank/ai/fate/serving/guest/interceptors/GuestBatchParamInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/guest/interceptors/GuestBatchParamInterceptor.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.guest.interceptors;
import com.google.common.base.Preconditions;
import com.webank.ai.fate.api.serving.InferenceServiceProto;
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.BatchInferenceRequest;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.exceptions.GuestInvalidParamException;
import com.webank.ai.fate.serving.core.utils.InferenceUtils;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class GuestBatchParamInterceptor implements Interceptor {
Logger logger = LoggerFactory.getLogger(GuestBatchParamInterceptor.class);
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
InferenceServiceProto.InferenceMessage message = (InferenceServiceProto.InferenceMessage) inboundPackage.getBody();
BatchInferenceRequest batchInferenceRequest = null;
try {
batchInferenceRequest = JsonUtil.json2Object(message.getBody().toByteArray(), BatchInferenceRequest.class);
inboundPackage.setBody(batchInferenceRequest);
Preconditions.checkArgument(batchInferenceRequest != null, "request message parse error");
Preconditions.checkArgument(StringUtils.isNotBlank(batchInferenceRequest.getServiceId()), "no service id");
if (batchInferenceRequest.getCaseId() == null || batchInferenceRequest.getCaseId().length() == 0) {
batchInferenceRequest.setCaseId(InferenceUtils.generateCaseid());
}
context.setCaseId(batchInferenceRequest.getCaseId());
context.setServiceId(batchInferenceRequest.getServiceId());
if (batchInferenceRequest.getApplyId() != null) {
context.setApplyId(batchInferenceRequest.getApplyId());
}
} catch (Exception e) {
throw new GuestInvalidParamException(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-server/src/main/java/com/webank/ai/fate/serving/guest/interceptors/GuestModelInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/guest/interceptors/GuestModelInterceptor.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.guest.interceptors;
import com.google.common.base.Preconditions;
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.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.BatchInferenceRequest;
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.exceptions.ModelNullException;
import com.webank.ai.fate.serving.core.exceptions.OverLoadException;
import com.webank.ai.fate.serving.model.ModelManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class GuestModelInterceptor implements Interceptor {
Logger logger = LoggerFactory.getLogger(GuestModelInterceptor.class);
@Autowired
ModelManager modelManager;
@Autowired
FlowCounterManager flowCounterManager;
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
String serviceId = context.getServiceId();
Model model = modelManager.getModelByServiceId(serviceId);
Preconditions.checkArgument(model != null, "model is null");
if (model == null) {
throw new ModelNullException("can not find model by service id " + serviceId);
}
((ServingServerContext) context).setModel(model);
int times = 1;
if (context.getServiceName().equalsIgnoreCase(Dict.SERVICENAME_BATCH_INFERENCE)) {
BatchInferenceRequest batchInferenceRequest = (BatchInferenceRequest) inboundPackage.getBody();
times = batchInferenceRequest.getBatchDataList().size();
}
context.putData(Dict.PASS_QPS, times);
boolean pass = flowCounterManager.pass(model.getResourceName(), times);
if (!pass) {
flowCounterManager.block(model.getResourceName(), times);
throw new OverLoadException("request was block by over load, model resource: " + model.getResourceName());
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-server/src/main/java/com/webank/ai/fate/serving/controller/ServerModelController.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/controller/ServerModelController.java | package com.webank.ai.fate.serving.controller;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ListenableFuture;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceGrpc;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceProto;
import com.webank.ai.fate.serving.core.bean.GrpcConnectionPool;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.bean.RequestParamWrapper;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import com.webank.ai.fate.serving.core.utils.NetUtils;
import io.grpc.ManagedChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
* @author hcy
*/
@RestController
public class ServerModelController {
Logger logger = LoggerFactory.getLogger(ServerModelController.class);
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
@RequestMapping(value = "/server/model/unbind", method = RequestMethod.POST)
@ResponseBody
public Callable<ReturnResult> unbind(@RequestBody RequestParamWrapper requestParams) throws Exception {
return () -> {
String host = requestParams.getHost();
Integer port = requestParams.getPort();
String tableName = requestParams.getTableName();
String namespace = requestParams.getNamespace();
List<String> serviceIds = requestParams.getServiceIds();
Preconditions.checkArgument(StringUtils.isNotBlank(tableName), "parameter tableName is blank");
Preconditions.checkArgument(StringUtils.isNotBlank(namespace), "parameter namespace is blank");
Preconditions.checkArgument(serviceIds != null && serviceIds.size() != 0, "parameter serviceId is blank");
ReturnResult result = new ReturnResult();
logger.debug("unbind model by tableName and namespace, host: {}, port: {}, tableName: {}, namespace: {}", host, port, tableName, namespace);
ModelServiceGrpc.ModelServiceFutureStub futureStub = getModelServiceFutureStub(host, port);
ModelServiceProto.UnbindRequest unbindRequest = ModelServiceProto.UnbindRequest.newBuilder()
.setTableName(tableName)
.setNamespace(namespace)
.addAllServiceIds(serviceIds)
.build();
ListenableFuture<ModelServiceProto.UnbindResponse> future = futureStub.unbind(unbindRequest);
ModelServiceProto.UnbindResponse response = future.get(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
logger.debug("response: {}", response);
result.setRetcode(response.getStatusCode());
result.setRetmsg(response.getMessage());
return result;
};
}
@RequestMapping(value = "/server/model/transfer", method = RequestMethod.POST)
@ResponseBody
public Callable<ReturnResult> transfer(@RequestBody RequestParamWrapper requestParams) {
return () -> {
String host = requestParams.getHost();
Integer port = requestParams.getPort();
String tableName = requestParams.getTableName();
String namespace = requestParams.getNamespace();
String targetHost = requestParams.getTargetHost();
Integer targetPort = requestParams.getTargetPort();
Preconditions.checkArgument(StringUtils.isNotBlank(tableName), "parameter tableName is blank");
Preconditions.checkArgument(StringUtils.isNotBlank(namespace), "parameter namespace is blank");
ReturnResult result = new ReturnResult();
logger.debug("transfer model by tableName and namespace, host: {}, port: {}, tableName: {}, namespace: {}, targetHost: {}, targetPort: {}"
, host, port, tableName, namespace, targetHost, targetPort);
ModelServiceGrpc.ModelServiceFutureStub futureStub = getModelServiceFutureStub(targetHost, targetPort);
ModelServiceProto.FetchModelRequest fetchModelRequest = ModelServiceProto.FetchModelRequest.newBuilder()
.setNamespace(namespace).setTableName(tableName).setSourceIp(host).setSourcePort(port).build();
ListenableFuture<ModelServiceProto.FetchModelResponse> future = futureStub.fetchModel(fetchModelRequest);
ModelServiceProto.FetchModelResponse response = future.get(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
logger.debug("response: {}", response);
result.setRetcode(response.getStatusCode());
result.setRetmsg(response.getMessage());
return result;
};
}
private ModelServiceGrpc.ModelServiceFutureStub getModelServiceFutureStub(String host, Integer port) {
Preconditions.checkArgument(StringUtils.isNotBlank(host), "parameter host is blank");
Preconditions.checkArgument(port != null && port != 0, "parameter port was wrong");
if (!NetUtils.isValidAddress(host + ":" + port)) {
throw new SysException("invalid address");
}
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
return ModelServiceGrpc.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-server/src/main/java/com/webank/ai/fate/serving/controller/DynamicLogController.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/controller/DynamicLogController.java | package com.webank.ai.fate.serving.controller;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
/**
* @author hcy
*/
@RequestMapping("/server")
@RestController
public class DynamicLogController {
private static final Logger logger = LoggerFactory.getLogger(DynamicLogController.class);
@GetMapping("/alterSysLogLevel/{level}")
public String alterSysLogLevel(@PathVariable String level){
try {
LoggerContext context = (LoggerContext) LogManager.getContext(false);
context.getLogger("ROOT").setLevel(Level.valueOf(level));
return "ok";
} catch (Exception ex) {
logger.error("server alterSysLogLevel failed : " + ex);
return "failed";
}
}
@GetMapping("/alterPkgLogLevel")
public String alterPkgLogLevel(@RequestParam String level, @RequestParam String pkgName){
try {
LoggerContext context = (LoggerContext) LogManager.getContext(false);
context.getLogger(pkgName).setLevel(Level.valueOf(level));
return "ok";
} catch (Exception ex) {
logger.error("server alterPkgLogLevel failed : " + ex);
return "failed";
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-server/src/main/java/com/webank/ai/fate/serving/controller/ServerServiceController.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/controller/ServerServiceController.java | package com.webank.ai.fate.serving.controller;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ListenableFuture;
import com.webank.ai.fate.api.networking.common.CommonServiceGrpc;
import com.webank.ai.fate.api.networking.common.CommonServiceProto;
import com.webank.ai.fate.serving.core.bean.GrpcConnectionPool;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.bean.RequestParamWrapper;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import com.webank.ai.fate.serving.core.utils.NetUtils;
import io.grpc.ManagedChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;
/**
* @author hcy
*/
@RestController
public class ServerServiceController {
Logger logger = LoggerFactory.getLogger(ServerServiceController.class);
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
@RequestMapping(value = "/server/service/weight/update", method = RequestMethod.POST)
@ResponseBody
public ReturnResult updateService(@RequestBody RequestParamWrapper requestParams) throws Exception {
String host = requestParams.getHost();
int port = requestParams.getPort();
String url = requestParams.getUrl();
String routerMode = requestParams.getRouterMode();
Integer weight = requestParams.getWeight();
Long version = requestParams.getVersion();
if (logger.isDebugEnabled()) {
logger.debug("try to update service");
}
Preconditions.checkArgument(StringUtils.isNotBlank(url), "parameter url is blank");
logger.info("update url: {}, routerMode: {}, weight: {}, version: {}", url, routerMode, weight, version);
CommonServiceGrpc.CommonServiceFutureStub commonServiceFutureStub = getCommonServiceFutureStub(host, port);
CommonServiceProto.UpdateServiceRequest.Builder builder = CommonServiceProto.UpdateServiceRequest.newBuilder();
builder.setUrl(url);
if (StringUtils.isNotBlank(routerMode)) {
builder.setRouterMode(routerMode);
}
if (weight != null) {
builder.setWeight(weight);
} else {
builder.setWeight(-1);
}
if (version != null) {
builder.setVersion(version);
} else {
builder.setVersion(-1);
}
ListenableFuture<CommonServiceProto.CommonResponse> future = commonServiceFutureStub.updateService(builder.build());
CommonServiceProto.CommonResponse response = future.get(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
ReturnResult result = new ReturnResult();
result.setRetcode(response.getStatusCode());
result.setRetmsg(response.getMessage());
return result;
}
private CommonServiceGrpc.CommonServiceFutureStub getCommonServiceFutureStub(String host, Integer port) {
Preconditions.checkArgument(StringUtils.isNotBlank(host), "parameter host is blank");
Preconditions.checkArgument(port != null && port != 0, "parameter port was wrong");
if (!NetUtils.isValidAddress(host + ":" + port)) {
throw new SysException("invalid address");
}
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
return CommonServiceGrpc.newFutureStub(managedChannel);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/LocalCacheModelLoader.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/LocalCacheModelLoader.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.model;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.common.model.ModelProcessor;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.exceptions.ModelLoadException;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.federatedml.PipelineModelProcessor;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Map;
@Service
public class LocalCacheModelLoader extends AbstractModelLoader<Map<String, byte[]>> {
@Override
protected byte[] serialize(Context context, Map<String, byte[]> data) {
Map<String, String> result = Maps.newHashMap();
if (data != null) {
data.forEach((k, v) -> {
String base64String = new String(Base64.getEncoder().encode(v));
result.put(k, base64String);
});
return JsonUtil.object2Json(result).getBytes();
}
return null;
}
@Override
protected Map<String, byte[]> unserialize(Context context, byte[] data) {
Map<String, byte[]> result = Maps.newHashMap();
if (data != null) {
String dataString = null;
try {
dataString = new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.getMessage();
}
Map originData = JsonUtil.json2Object(dataString, Map.class);
if (originData != null) {
originData.forEach((k, v) -> {
result.put(k.toString(), Base64.getDecoder().decode(v.toString()));
});
return result;
}
}
return null;
}
@Override
protected ModelProcessor initPipeLine(Context context, Map<String, byte[]> stringMap) {
if (stringMap != null) {
PipelineModelProcessor modelProcessor = new PipelineModelProcessor();
modelProcessor.initModel(context, stringMap);
return modelProcessor;
} else {
return null;
}
}
@Override
protected Map<String, byte[]> doLoadModel(Context context, ModelLoaderParam modelLoaderParam) {
String filePath = modelLoaderParam.getFilePath();
File file = new File(filePath);
if (!file.exists()) {
throw new ModelLoadException("model cache file " + file.getAbsolutePath() + " is not exist");
}
byte[] content = readFile(file);
Map<String, byte[]> data = unserialize(context, content);
return data;
}
protected byte[] readFile(File file) {
if (file != null && file.exists()) {
try (InputStream in = new FileInputStream(file)) {
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
int readCount = in.read(filecontent);
if (readCount > 0) {
return filecontent;
} else {
return null;
}
} catch (Throwable e) {
logger.error("failed to doRestore file ", e);
}
}
return null;
}
@Override
public String getResource(Context context, ModelLoaderParam modelLoaderParam) {
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-server/src/main/java/com/webank/ai/fate/serving/model/ModelUtil.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/ModelUtil.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.model;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceProto;
import com.webank.ai.fate.serving.core.bean.FederatedRoles;
import com.webank.ai.fate.serving.core.bean.ModelInfo;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class ModelUtil {
private static final String MODEL_KEY_SEPARATOR = "&";
public static String genModelKey(String tableName, String namespace) {
return StringUtils.join(Arrays.asList(tableName, namespace), MODEL_KEY_SEPARATOR);
}
public static String[] splitModelKey(String key) {
return StringUtils.split(key, MODEL_KEY_SEPARATOR);
}
public static FederatedRoles getFederatedRoles(Map<String, ModelServiceProto.Party> federatedRolesProto) {
FederatedRoles federatedRoles = new FederatedRoles();
federatedRolesProto.forEach((roleName, party) -> {
federatedRoles.setRole(roleName, party.getPartyIdList());
});
return federatedRoles;
}
public static Map<String, Map<String, ModelInfo>> getFederatedRolesModel(Map<String, ModelServiceProto.RoleModelInfo> federatedRolesModelProto) {
Map<String, Map<String, ModelInfo>> federatedRolesModel = new HashMap<>(8);
federatedRolesModelProto.forEach((roleName, roleModelInfo) -> {
federatedRolesModel.put(roleName, new HashMap<>(8));
roleModelInfo.getRoleModelInfoMap().forEach((partyId, modelInfo) -> {
federatedRolesModel.get(roleName).put(partyId, new ModelInfo(modelInfo.getTableName(), modelInfo.getNamespace()));
});
});
return federatedRolesModel;
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/model/AbstractModelLoader.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/AbstractModelLoader.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.model;
import com.webank.ai.fate.serving.common.model.ModelProcessor;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.exceptions.ModelSerializeException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public abstract class AbstractModelLoader<MODELDATA> implements ModelLoader {
Logger logger = LoggerFactory.getLogger(AbstractModelLoader.class);
@Override
public ModelProcessor loadModel(Context context, ModelLoaderParam modelLoaderParam) {
MODELDATA modelData = doLoadModel(context, modelLoaderParam);
if (modelData == null) {
logger.info("load model error, name {} namespace {} ,try to restore from local cache", modelLoaderParam.tableName, modelLoaderParam.nameSpace);
modelData = restore(context, modelLoaderParam.tableName, modelLoaderParam.nameSpace);
if (modelData == null) {
logger.info("load model from local cache error, name {} namespace {}", modelLoaderParam.tableName, modelLoaderParam.nameSpace);
return null;
}
} else {
this.store(context, modelLoaderParam.tableName, modelLoaderParam.nameSpace, modelData);
}
return this.initPipeLine(context, modelData);
}
@Override
public ModelProcessor restoreModel(Context context, ModelLoaderParam modelLoaderParam) {
logger.info("load model error, name {} namespace {} ,try to restore from local cache", modelLoaderParam.tableName, modelLoaderParam.nameSpace);
MODELDATA modelData = restore(context, modelLoaderParam.tableName, modelLoaderParam.nameSpace);
if (modelData == null) {
logger.info("load model from local cache error, name {} namespace {}", modelLoaderParam.tableName, modelLoaderParam.nameSpace);
return null;
}
return this.initPipeLine(context, modelData);
}
protected void store(Context context, String name, String namespace, MODELDATA data) {
try {
String cachePath = getCachePath(context, name, namespace);
if (cachePath != null) {
byte[] bytes = this.serialize(context, data);
if (bytes == null) {
throw new ModelSerializeException();
}
File file = new File(cachePath);
this.doStore(context, bytes, file);
}
} catch (ModelSerializeException e) {
logger.error("serialize mode data error", e);
} catch (Exception e) {
logger.error("store mode data error", e);
}
}
protected abstract byte[] serialize(Context context, MODELDATA data);
protected abstract MODELDATA unserialize(Context context, byte[] data);
protected MODELDATA restore(Context context, String name, String namespace) {
try {
String cachePath = getCachePath(context, name, namespace);
if (cachePath != null) {
byte[] bytes = doRestore(new File(cachePath));
MODELDATA modelData = this.unserialize(context, bytes);
return modelData;
}
} catch (Throwable e) {
logger.error("restore model data error", e);
}
return null;
}
protected abstract ModelProcessor initPipeLine(Context context, MODELDATA modeldata);
@Override
public String getCachePath(Context context, String name, String namespace) {
StringBuilder sb = new StringBuilder();
String locationPre = MetaInfo.PROPERTY_MODEL_CACHE_PATH;
if (StringUtils.isNotEmpty(locationPre) && StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(namespace)) {
String cacheFilePath = sb.append(locationPre).append("/.fate/model_").append(name).append("_").append(namespace).append("_").append("cache").toString();
return cacheFilePath;
}
return null;
}
protected void doStore(Context context, byte[] data, File file) {
if (file == null) {
return;
}
// Save
try {
File lockfile = new File(file.getAbsolutePath() + ".lock");
if (!lockfile.exists()) {
lockfile.createNewFile();
}
try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
FileChannel channel = raf.getChannel()) {
FileLock lock = channel.tryLock();
if (lock == null) {
throw new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file");
}
try {
if (!file.exists()) {
file.createNewFile();
}
try (FileOutputStream outputFile = new FileOutputStream(file)) {
outputFile.write(data);
}
} finally {
lock.release();
}
}
} catch (Throwable e) {
logger.error("Failed to save model cache file, will retry, cause: " + e.getMessage(), e);
}
}
protected byte[] doRestore(File file) {
if (file != null && file.exists()) {
try (InputStream in = new FileInputStream(file)) {
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
int readCount = in.read(filecontent);
if (readCount > 0) {
return filecontent;
} else {
return null;
}
} catch (Throwable e) {
logger.error("failed to doRestore file ", e);
}
}
return null;
}
protected abstract MODELDATA doLoadModel(Context context, ModelLoaderParam modelLoaderParam);
public void saveCacheData(Context context, String cachePath, byte[] bytes) {
this.doStore(context, bytes, new File(cachePath));
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/model/FateFlowModelLoader.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/FateFlowModelLoader.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.model;
import com.google.common.collect.Maps;
import com.webank.ai.fate.register.router.RouterService;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.common.model.ModelProcessor;
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.MetaInfo;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.federatedml.PipelineModelProcessor;
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.Component;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
@Component
public class FateFlowModelLoader extends AbstractModelLoader<Map<String, byte[]>> {
private static final Logger logger = LoggerFactory.getLogger(FateFlowModelLoader.class);
private static final String TRANSFER_URI = "flow/online/transfer";
@Autowired(required = false)
private RouterService routerService;
@Autowired(required = false)
private ZookeeperRegistry zookeeperRegistry;
@Override
protected byte[] serialize(Context context, Map<String, byte[]> data) {
Map<String, String> result = Maps.newHashMap();
if (data != null) {
data.forEach((k, v) -> {
String base64String = new String(Base64.getEncoder().encode(v));
result.put(k, base64String);
});
return JsonUtil.object2Json(result).getBytes();
}
return null;
}
@Override
protected Map<String, byte[]> unserialize(Context context, byte[] data) {
Map<String, byte[]> result = Maps.newHashMap();
if (data != null) {
String dataString = new String(data);
Map originData = JsonUtil.json2Object(dataString, Map.class);
if (originData != null) {
originData.forEach((k, v) -> {
result.put(k.toString(), Base64.getDecoder().decode(v.toString()));
});
return result;
}
}
return null;
}
@Override
protected ModelProcessor initPipeLine(Context context, Map<String, byte[]> stringMap) {
if (stringMap != null) {
PipelineModelProcessor modelProcessor = new PipelineModelProcessor();
modelProcessor.initModel(context,stringMap);
return modelProcessor;
} else {
return null;
}
}
@Override
protected Map<String, byte[]> doLoadModel(Context context, ModelLoaderParam modelLoaderParam) {
logger.info("read model, name: {} namespace: {}", modelLoaderParam.tableName, modelLoaderParam.nameSpace);
try {
String requestUrl =getResource(context,modelLoaderParam);
Map<String, Object> requestData = new HashMap<>(8);
requestData.put("name", modelLoaderParam.tableName);
requestData.put("namespace", modelLoaderParam.nameSpace);
long start = System.currentTimeMillis();
String responseBody = HttpClientPool.transferPost(requestUrl, requestData);
long end = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("{}|{}|{}|{}", requestUrl, start, end, (end - start) + " ms");
}
if (StringUtils.isEmpty(responseBody)) {
logger.info("read model fail, {}, {}", modelLoaderParam.tableName, modelLoaderParam.nameSpace);
return null;
}
Map responseData = JsonUtil.json2Object(responseBody, Map.class);
if (responseData.get(Dict.RET_CODE) != null && (int) responseData.get(Dict.RET_CODE) != StatusCode.SUCCESS) {
logger.info("read model fail, {}, {}, {}", modelLoaderParam.tableName, modelLoaderParam.nameSpace, responseData.get(Dict.RET_MSG));
return null;
}
Map<String, byte[]> resultMap = new HashMap<>(8);
Map<String, Object> dataMap = responseData.get(Dict.DATA) != null ? (Map<String, Object>) responseData.get(Dict.DATA) : null;
if (dataMap == null || dataMap.isEmpty()) {
logger.info("read model fail, {}, {}, {}", modelLoaderParam.tableName, modelLoaderParam.nameSpace, dataMap);
return null;
}
for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
resultMap.put(entry.getKey(), Base64.getDecoder().decode(String.valueOf(entry.getValue())));
}
return resultMap;
} catch (Exception e) {
logger.error("get model info from fateflow error", e);
}
return null;
}
@Override
public String getResource(Context context,ModelLoaderParam modelLoaderParam) {
String requestUrl = "";
try {
String filePath = modelLoaderParam.getFilePath();
if (StringUtils.isNotBlank(filePath)) {
requestUrl = URLDecoder.decode(filePath,"UTF-8");
} else if (routerService != null && zookeeperRegistry != null) {
//serving 2.1.0兼容
String modelParentPathx = "/" + Dict.DEFAULT_FATE_ROOT + "/" + TRANSFER_URI + "/providers";
List<String> children = zookeeperRegistry.getZkClient().getChildren(modelParentPathx);
URL url = null;
List<URL> urls = new ArrayList<>();
if (children != null && children.size() > 0) {
String modelVersion = modelLoaderParam.tableName;
String modelId = modelLoaderParam.nameSpace.replace("#", "~");
String uri = "/" + modelId + "/" + modelVersion;
String encodeUri = URLEncoder.encode(uri,"UTF-8");
for (String child : children) {
if(child.endsWith(encodeUri)){
urls.add(URL.valueOf(URLDecoder.decode(child,"UTF-8")));
break;
}
}
}
if (urls == null || urls.isEmpty()) {
url = URL.valueOf(TRANSFER_URI);
urls = routerService.router(url);
}
if (urls == null || urls.isEmpty()) {
logger.info("register url not found, {}", url);
} else {
url = urls.get(0);
requestUrl = url.toFullString();
}
}
if (StringUtils.isBlank(requestUrl)) {
requestUrl = MetaInfo.PROPERTY_MODEL_TRANSFER_URL;
}
if (StringUtils.isBlank(requestUrl)) {
logger.info("fateflow address not found");
return null;
}
logger.info("use request url: {}", requestUrl);
}catch (Exception e){
logger.error("get flow address error = {}",e);
}
return requestUrl;
}
} | 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-server/src/main/java/com/webank/ai/fate/serving/model/LocalFileModelLoader.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/LocalFileModelLoader.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.model;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.common.model.ModelProcessor;
import com.webank.ai.fate.serving.common.utils.TransferUtils;
import com.webank.ai.fate.serving.common.utils.ZipUtil;
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.exceptions.ModelLoadException;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.federatedml.PipelineModelProcessor;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.Base64;
import java.util.List;
import java.util.Map;
@Service
public class LocalFileModelLoader extends AbstractModelLoader<Map<String, byte[]>> {
@Override
protected byte[] serialize(Context context, Map<String, byte[]> data) {
Map<String, String> result = Maps.newHashMap();
if (data != null) {
data.forEach((k, v) -> {
String base64String = new String(Base64.getEncoder().encode(v));
result.put(k, base64String);
});
return JsonUtil.object2Json(result).getBytes();
}
return null;
}
@Override
protected Map<String, byte[]> unserialize(Context context, byte[] data) {
Map<String, byte[]> result = Maps.newHashMap();
try {
if (data != null) {
Map originData = JsonUtil.json2Object(data, Map.class);
if (originData != null) {
originData.forEach((k, v) -> {
result.put(k.toString(), Base64.getDecoder().decode(v.toString()));
});
return result;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected ModelProcessor initPipeLine(Context context, Map<String, byte[]> stringMap) {
if (stringMap != null) {
PipelineModelProcessor modelProcessor = new PipelineModelProcessor();
modelProcessor.initModel(context, stringMap);
return modelProcessor;
} else {
return null;
}
}
@Override
protected Map<String, byte[]> doLoadModel(Context context, ModelLoaderParam modelLoaderParam) {
String filePath = modelLoaderParam.getFilePath();
File file = new File(filePath);
if (!file.exists()) {
throw new ModelLoadException("model file" + file.getAbsolutePath() + " is not exist");
}
byte[] content = readFile(file);
Map<String, byte[]> data = unserialize(context, content);
return data;
}
protected byte[] readFile(File file) {
String outputPath = "";
try {
String tempDir = System.getProperty(Dict.PROPERTY_USER_HOME) + "/.fate/temp/";
outputPath = ZipUtil.unzip(file, tempDir);
File outputDir = new File(outputPath);
if (!outputDir.exists()) {
throw new FileNotFoundException();
}
Map<String, Object> resultMap = Maps.newHashMap();
String root = outputDir.getAbsolutePath();
List<String> properties = TransferUtils.yml2Properties(root + File.separator + "define" + File.separator + "define_meta.yaml");
if (properties != null) {
InputStream in = null;
try {
for (String property : properties) {
if (property.startsWith("describe.model_proto")) {
String[] split = property.split("=");
String key = split[0];
String value = split[1];
String[] keySplit = key.split("\\.");
File dataFile = new File(root + File.separator + "variables" + File.separator + "data" + File.separator + keySplit[2] + File.separator + keySplit[3] + File.separator + keySplit[4]);
if (dataFile.exists()) {
in = new FileInputStream(dataFile);
try{
Long length = dataFile.length();
byte[] content = new byte[length.intValue()];
int readCount = in.read(content);
if (readCount > 0) {
String resultKey = keySplit[2] + "." + keySplit[3] + ":" + keySplit[4];
resultMap.put(resultKey, content);
}}finally {
in.close();
}
} else {
logger.warn("model proto file not found {}", dataFile.getPath());
}
}
}
} catch (Exception e) {
logger.error("read model file error, {}", e.getMessage());
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return JsonUtil.object2Json(resultMap).getBytes();
} catch (Exception e) {
logger.error("read file {} error, cause by {}", file.getAbsolutePath(), e.getMessage());
e.printStackTrace();
} finally {
ZipUtil.clear(outputPath);
}
return null;
}
@Override
public String getResource(Context context, ModelLoaderParam modelLoaderParam){
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-server/src/main/java/com/webank/ai/fate/serving/model/SimpleModelLoaderFactory.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/SimpleModelLoaderFactory.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.model;
import com.webank.ai.fate.serving.core.bean.Context;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Service
public class SimpleModelLoaderFactory implements ModelLoaderFactory, ApplicationContextAware {
ApplicationContext applicationContext;
@Override
public ModelLoader getModelLoader(Context context, ModelLoader.LoadModelType loadModelType) {
switch (loadModelType.toString()) {
case "FATEFLOW":
return (ModelLoader) applicationContext.getBean("fateFlowModelLoader");
case "CACHE":
return (ModelLoader) applicationContext.getBean("localCacheModelLoader");
case "FILE":
return (ModelLoader) applicationContext.getBean("localFileModelLoader");
default:
return null;
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/model/ModelLoaderFactory.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/ModelLoaderFactory.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.model;
import com.webank.ai.fate.serving.core.bean.Context;
public interface ModelLoaderFactory {
ModelLoader getModelLoader(Context context, ModelLoader.LoadModelType loadModelType);
}
| 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-server/src/main/java/com/webank/ai/fate/serving/model/ModelLoader.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/ModelLoader.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.model;
import com.webank.ai.fate.serving.common.model.ModelProcessor;
import com.webank.ai.fate.serving.core.bean.Context;
public interface ModelLoader {
ModelProcessor loadModel(Context context, ModelLoaderParam modelLoaderParam);
ModelProcessor restoreModel(Context context, ModelLoaderParam modelLoaderParam);
String getCachePath(Context context, String tableName, String namespace);
String getResource(Context context,ModelLoaderParam modelLoaderParam);
public enum LoadModelType {
FATEFLOW,
FILE,
CACHE
}
public class ModelLoaderParam {
String tableName;
String nameSpace;
LoadModelType loadModelType;
String filePath;
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getNameSpace() {
return nameSpace;
}
public void setNameSpace(String nameSpace) {
this.nameSpace = nameSpace;
}
public LoadModelType getLoadModelType() {
return loadModelType;
}
public void setLoadModelType(LoadModelType loadModelType) {
this.loadModelType = loadModelType;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/ModelManager.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/model/ModelManager.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.model;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceProto;
import com.webank.ai.fate.register.common.NamedThreadFactory;
import com.webank.ai.fate.register.provider.FateServer;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.common.bean.BaseContext;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.model.ModelProcessor;
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.ModelNullException;
import com.webank.ai.fate.serving.core.exceptions.ModelProcessorInitException;
import com.webank.ai.fate.serving.core.utils.EncryptUtils;
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.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.SerializationUtils;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@Service
public class ModelManager implements InitializingBean {
@Autowired(required = false)
ZookeeperRegistry zookeeperRegistry;
@Autowired
ModelLoaderFactory modelLoaderFactory;
File serviceIdFile;
File namespaceFile;
// old version cache file
File publishLoadStoreFile;
File publishOnlineStoreFile;
Logger logger = LoggerFactory.getLogger(this.getClass());
ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(), new NamedThreadFactory("ModelService", true));
private ConcurrentMap<String, String> serviceIdNamespaceMap = new ConcurrentHashMap<>();
private ConcurrentMap<String, Model> namespaceMap = new ConcurrentHashMap<String, Model>();
// (guest) name + namespace -> (host) model
private ConcurrentMap<String, Model> partnerModelMap = new ConcurrentHashMap<String, Model>();
private static String[] URL_FILTER_CHARACTER = {"?", ":", "/", "&"};
public synchronized ModelServiceProto.UnbindResponse unbind(Context context, ModelServiceProto.UnbindRequest req) {
ModelServiceProto.UnbindResponse.Builder resultBuilder = ModelServiceProto.UnbindResponse.newBuilder();
List<String> serviceIds = req.getServiceIdsList();
Preconditions.checkArgument(serviceIds != null && serviceIds.size() != 0, "param service id is blank");
logger.info("try to unbind model, service id : {}", serviceIds);
String modelKey = this.getNameSpaceKey(req.getTableName(), req.getNamespace());
if (!this.namespaceMap.containsKey(modelKey)) {
logger.error("not found model info table name {} namespace {}, please check if the model is already loaded.", req.getTableName(), req.getNamespace());
throw new ModelNullException("not found model info, please check if the model is already loaded.");
}
Model model = this.namespaceMap.get(modelKey);
String tableNamekey = this.getNameSpaceKey(model.getTableName(), model.getNamespace());
serviceIds.forEach(serviceId -> {
if (!tableNamekey.equals(this.serviceIdNamespaceMap.get(serviceId))) {
logger.info("unbind request info is error {}", req);
throw new ModelNullException("unbind request info is error");
}
});
if (zookeeperRegistry != null) {
Set<URL> registered = zookeeperRegistry.getRegistered();
List<URL> unRegisterUrls = Lists.newArrayList();
for (URL url : registered) {
if (model.getPartId().equalsIgnoreCase(url.getEnvironment()) || serviceIds.contains(url.getEnvironment())) {
unRegisterUrls.add(url);
}
}
for (URL url : unRegisterUrls) {
zookeeperRegistry.unregister(url);
}
logger.info("Unregister urls: {}", unRegisterUrls);
}
serviceIds.forEach(serviceId -> {
this.serviceIdNamespaceMap.remove(serviceId);
});
this.store(serviceIdNamespaceMap, serviceIdFile);
logger.info("unbind model success");
resultBuilder.setStatusCode(StatusCode.SUCCESS);
return resultBuilder.build();
}
public synchronized void store(Map data, File file) {
executorService.submit(() -> {
doSaveCache(data, file, 0);
});
logger.info("Store model cache success, file path: {}", serviceIdFile.getAbsolutePath());
}
public synchronized void store() {
executorService.submit(() -> {
doSaveCache(namespaceMap, namespaceFile, 0);
doSaveCache(serviceIdNamespaceMap, serviceIdFile, 0);
});
logger.info("Store model cache success");
}
private List<RequestWapper> doLoadOldVersionCache(File file) {
Map<String, RequestWapper> properties = new HashMap<>(8);
if (file != null && file.exists()) {
try (InputStream in = new FileInputStream(file)) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in))) {
final AtomicInteger count = new AtomicInteger(0);
bufferedReader.lines().forEach(temp -> {
count.addAndGet(1);
int index = temp.indexOf("=");
if (index > 0) {
String key = temp.substring(0, index);
String value = temp.substring(index + 1);
String[] args = value.split(":");
String content = args[0];
long timestamp = count.longValue();
;
if (args.length >= 2) {
timestamp = new Long(args[1]);
}
properties.put(key, new RequestWapper(content, timestamp, key));
}
});
}
if (logger.isInfoEnabled()) {
logger.info("load model cache file " + file + ", data: " + properties);
}
List<RequestWapper> list = Lists.newArrayList();
properties.forEach((k, v) -> {
list.add(v);
});
Collections.sort(list, (o1, o2) -> o1.timestamp - o2.timestamp > 0 ? 1 : -1);
return list;
} catch (Throwable e) {
logger.error("failed to load cache file {} ", file);
}
}
return null;
}
private void restoreOldVersionCache() {
// restore 1.2.x model cache
if (!namespaceFile.exists() && publishLoadStoreFile.exists()) {
List<RequestWapper> requestWappers = doLoadOldVersionCache(publishLoadStoreFile);
if (requestWappers != null && !requestWappers.isEmpty()) {
requestWappers.forEach((v) -> {
try {
byte[] data = Base64.getDecoder().decode(v.content.getBytes());
ModelServiceProto.PublishRequest req = ModelServiceProto.PublishRequest.parseFrom(data);
if (logger.isDebugEnabled()) {
logger.debug("restore publishLoadModel req {}", req);
}
this.load(new BaseContext(), req);
} catch (Exception e) {
logger.error("restore publishLoadModel error", e);
e.printStackTrace();
}
});
}
try {
// Create new cache file after restore
generateParent(namespaceFile);
namespaceFile.createNewFile();
} catch (IOException e) {
throw new IllegalArgumentException("Invalid model cache file " + namespaceFile + ", cause: Failed to create file " + namespaceFile.getAbsolutePath() + "!");
}
}
if (!serviceIdFile.exists() && publishOnlineStoreFile.exists()) {
List<RequestWapper> requestWappers = doLoadOldVersionCache(publishOnlineStoreFile);
if (requestWappers != null && !requestWappers.isEmpty()) {
requestWappers.forEach((v) -> {
try {
byte[] data = Base64.getDecoder().decode(v.content.getBytes());
ModelServiceProto.PublishRequest req = ModelServiceProto.PublishRequest.parseFrom(data);
if (logger.isDebugEnabled()) {
logger.debug("restore publishOnlineModel req {} base64 {}", req, v);
}
this.bind(new BaseContext(), req);
} catch (Exception e) {
logger.error("restore publishOnlineModel error", e);
e.printStackTrace();
}
});
}
try {
// Create new cache file after restore
generateParent(serviceIdFile);
serviceIdFile.createNewFile();
} catch (IOException e) {
throw new IllegalArgumentException("Invalid model cache file " + serviceIdFile + ", cause: Failed to create file " + serviceIdFile.getAbsolutePath() + "!");
}
}
}
public synchronized void restore(Context context) {
// compatible 1.2.x
restoreOldVersionCache();
ConcurrentMap<String, String> tempServiceIdNamespaceMap = new ConcurrentHashMap<>(8);
ConcurrentMap<String, Model> tempNamespaceMap = new ConcurrentHashMap<>(8);
doLoadCache(tempNamespaceMap, namespaceFile);
doLoadCache(tempServiceIdNamespaceMap, serviceIdFile);
ModelLoader.ModelLoaderParam modelLoaderParam = new ModelLoader.ModelLoaderParam();
ModelLoader modelLoader = this.modelLoaderFactory.getModelLoader(context, ModelLoader.LoadModelType.FATEFLOW);
tempNamespaceMap.forEach((k, model) -> {
try {
modelLoaderParam.setLoadModelType(ModelLoader.LoadModelType.FATEFLOW);
modelLoaderParam.setTableName(model.getTableName());
modelLoaderParam.setNameSpace(model.getNamespace());
ModelProcessor modelProcessor = modelLoader.restoreModel(context, modelLoaderParam);
modelProcessor.setModel(model);
if (modelProcessor != null) {
model.setModelProcessor(modelProcessor);
if (model.getRole().equals(Dict.GUEST)) {
for (Model value : model.getFederationModelMap().values()) {
value.setRole(Dict.HOST);
}
}
namespaceMap.put(k, model);
if (Dict.HOST.equals(model.getRole())) {
model.getFederationModelMap().values().forEach(remoteModel -> {
String remoteNamespaceKey = this.getNameSpaceKey(remoteModel.getTableName(), remoteModel.getNamespace());
this.partnerModelMap.put(remoteNamespaceKey, model);
});
}
logger.info("restore model {} success ", k);
}
} catch (Exception e) {
logger.info("restore model {} error {} ", k, e.getMessage());
}
});
tempServiceIdNamespaceMap.forEach((k, v) -> {
if (namespaceMap.get(v) != null) {
serviceIdNamespaceMap.put(k, v);
}
});
// register service after restore
if (namespaceMap != null && namespaceMap.size() > 0) {
List<String> hostEnvironments = Lists.newArrayList();
for (Model model : namespaceMap.values()) {
if (Dict.HOST.equals(model.getRole())) {
String modelKey = ModelUtil.genModelKey(model.getTableName(), model.getNamespace());
hostEnvironments.add(EncryptUtils.encrypt(modelKey, EncryptMethod.MD5));
}
}
this.registerHostService(hostEnvironments);
}
if (serviceIdNamespaceMap != null && serviceIdNamespaceMap.size() > 0) {
List<String> environments = Lists.newArrayList();
for (Map.Entry<String, String> modelEntry : serviceIdNamespaceMap.entrySet()) {
if(namespaceMap!=null) {
Model model = namespaceMap.get(modelEntry.getValue());
if (model != null) {
environments.add(modelEntry.getKey());
//environments.add(model.getPartId());
}
}
}
this.registerGuestService(environments);
}
logger.info("restore model success ");
}
private void registerService(Collection environments) {
if (zookeeperRegistry != null) {
zookeeperRegistry.addDynamicEnvironment(environments);
zookeeperRegistry.register(FateServer.serviceSets);
}
}
private void registerGuestService(Collection environments) {
if (zookeeperRegistry != null) {
zookeeperRegistry.addDynamicEnvironment(environments);
zookeeperRegistry.register(FateServer.guestServiceSets, environments);
}
}
private void registerHostService(Collection<String> environments) {
if (zookeeperRegistry != null) {
zookeeperRegistry.register(FateServer.hostServiceSets, environments);
}
}
public synchronized ReturnResult bind(Context context, ModelServiceProto.PublishRequest req) {
if (logger.isDebugEnabled()) {
logger.debug("try to bind model, receive request : {}", req);
}
ReturnResult returnResult = new ReturnResult();
String serviceId = req.getServiceId();
Preconditions.checkArgument(StringUtils.isNotBlank(serviceId), "param service id is blank");
Preconditions.checkArgument(!StringUtils.containsAny(serviceId, URL_FILTER_CHARACTER), "Service id contains special characters, " + JsonUtil.object2Json(URL_FILTER_CHARACTER));
returnResult.setRetcode(StatusCode.SUCCESS);
Model model = this.buildModelForBind(context, req);
String modelKey = this.getNameSpaceKey(model.getTableName(), model.getNamespace());
Model loadedModel = this.namespaceMap.get(modelKey);
if (loadedModel == null) {
throw new ModelNullException("model " + modelKey + " is not exist ");
}
this.serviceIdNamespaceMap.put(serviceId, modelKey);
if (zookeeperRegistry != null) {
if (StringUtils.isNotEmpty(serviceId)) {
zookeeperRegistry.addDynamicEnvironment(serviceId);
}
zookeeperRegistry.register(FateServer.guestServiceSets, Lists.newArrayList(serviceId));
}
//update cache
this.store(serviceIdNamespaceMap, serviceIdFile);
return returnResult;
}
private Model buildModelForBind(Context context, ModelServiceProto.PublishRequest req) {
Model model = new Model();
String role = req.getLocal().getRole();
model.setPartId(req.getLocal().getPartyId());
model.setRole(Dict.GUEST.equals(role) ? Dict.GUEST : Dict.HOST);
String serviceId = req.getServiceId();
model.getServiceIds().add(serviceId);
Map<String, ModelServiceProto.RoleModelInfo> modelMap = req.getModelMap();
ModelServiceProto.RoleModelInfo roleModelInfo = modelMap.get(model.getRole());
Map<String, ModelServiceProto.ModelInfo> modelInfoMap = roleModelInfo.getRoleModelInfoMap();
Map<String, ModelServiceProto.Party> roleMap = req.getRoleMap();
ModelServiceProto.Party selfParty = roleMap.get(model.getRole());
String selfPartyId = selfParty.getPartyIdList().get(0);
ModelServiceProto.ModelInfo selfModelInfo = modelInfoMap.get(selfPartyId);
String selfNamespace = selfModelInfo.getNamespace();
String selfTableName = selfModelInfo.getTableName();
model.setNamespace(selfNamespace);
model.setTableName(selfTableName);
return model;
}
private Model buildModelForLoad(Context context, ModelServiceProto.PublishRequest req) {
Model model = new Model();
String role = req.getLocal().getRole();
model.setPartId(req.getLocal().getPartyId());
model.setRole(Dict.GUEST.equals(role) ? Dict.GUEST : Dict.HOST);
Map<String, ModelServiceProto.RoleModelInfo> modelMap = req.getModelMap();
ModelServiceProto.RoleModelInfo roleModelInfo = modelMap.get(model.getRole());
Map<String, ModelServiceProto.ModelInfo> modelInfoMap = roleModelInfo.getRoleModelInfoMap();
Map<String, ModelServiceProto.Party> roleMap = req.getRoleMap();
String remotePartyRole = model.getRole().equals(Dict.GUEST) ? Dict.HOST : Dict.GUEST;
ModelServiceProto.Party remoteParty = roleMap.get(remotePartyRole);
List<String> remotePartyIdList = remoteParty.getPartyIdList();
for (String remotePartyId : remotePartyIdList) {
ModelServiceProto.RoleModelInfo remoteRoleModelInfo = modelMap.get(remotePartyRole);
ModelServiceProto.ModelInfo remoteModelInfo = remoteRoleModelInfo.getRoleModelInfoMap().get(remotePartyId);
Model remoteModel = new Model();
remoteModel.setPartId(remotePartyId);
remoteModel.setNamespace(remoteModelInfo.getNamespace());
remoteModel.setTableName(remoteModelInfo.getTableName());
remoteModel.setRole(remotePartyRole);
model.getFederationModelMap().put(remotePartyId, remoteModel);
}
ModelServiceProto.Party selfParty = roleMap.get(model.getRole());
String selfPartyId = selfParty.getPartyIdList().get(0);
ModelServiceProto.ModelInfo selfModelInfo = modelInfoMap.get(model.getPartId());
Preconditions.checkArgument(selfModelInfo != null, "model info is invalid");
String selfNamespace = selfModelInfo.getNamespace();
String selfTableName = selfModelInfo.getTableName();
model.setNamespace(selfNamespace);
model.setTableName(selfTableName);
if (ModelLoader.LoadModelType.FATEFLOW.name().equals(req.getLoadType())) {
try {
ModelLoader.ModelLoaderParam modelLoaderParam = new ModelLoader.ModelLoaderParam();
modelLoaderParam.setLoadModelType(ModelLoader.LoadModelType.FATEFLOW);
modelLoaderParam.setTableName(model.getTableName());
modelLoaderParam.setNameSpace(model.getNamespace());
modelLoaderParam.setFilePath(req.getFilePath());
ModelLoader modelLoader = this.modelLoaderFactory.getModelLoader(context, ModelLoader.LoadModelType.FATEFLOW);
model.setResourceAdress(getAdressForUrl(modelLoader.getResource(context, modelLoaderParam)));
} catch (Exception e) {
logger.error("getloadModelUrl error = {}", e);
}
}
return model;
}
public String getAdressForUrl(String url) {
String address = "";
if (StringUtils.isBlank(url)) {
return address;
}
if (url.contains("//")) {
String tempUrl = url.substring(url.indexOf("//") + 2);
if (tempUrl.contains("/")) {
address = tempUrl.substring(0, tempUrl.indexOf("/"));
}
}
return address;
}
public synchronized ReturnResult load(Context context, ModelServiceProto.PublishRequest req) {
if (logger.isDebugEnabled()) {
logger.debug("try to load model, receive request : {}", req);
}
ReturnResult returnResult = new ReturnResult();
returnResult.setRetcode(StatusCode.SUCCESS);
Model model = this.buildModelForLoad(context, req);
String namespaceKey = this.getNameSpaceKey(model.getTableName(), model.getNamespace());
ModelLoader.ModelLoaderParam modelLoaderParam = new ModelLoader.ModelLoaderParam();
String loadType = req.getLoadType();
if (StringUtils.isNotEmpty(loadType)) {
modelLoaderParam.setLoadModelType(ModelLoader.LoadModelType.valueOf(loadType));
} else {
modelLoaderParam.setLoadModelType(ModelLoader.LoadModelType.FATEFLOW);
}
modelLoaderParam.setTableName(model.getTableName());
modelLoaderParam.setNameSpace(model.getNamespace());
modelLoaderParam.setFilePath(req.getFilePath());
ModelLoader modelLoader = this.modelLoaderFactory.getModelLoader(context, modelLoaderParam.getLoadModelType());
Preconditions.checkArgument(modelLoader != null, "model loader not found");
ModelProcessor modelProcessor = modelLoader.loadModel(context, modelLoaderParam);
if (modelProcessor == null) {
throw new ModelProcessorInitException("model initialization error, please check if the model exists and the configuration of the FATEFLOW load model process is correct.");
}
model.setModelProcessor(modelProcessor);
modelProcessor.setModel(model);
this.namespaceMap.put(namespaceKey, model);
if (Dict.HOST.equals(model.getRole())) {
model.getFederationModelMap().values().forEach(remoteModel -> {
String remoteNamespaceKey = this.getNameSpaceKey(remoteModel.getTableName(), remoteModel.getNamespace());
this.partnerModelMap.put(remoteNamespaceKey, model);
});
}
/**
* host model
*/
if (Dict.HOST.equals(model.getRole()) && zookeeperRegistry != null) {
String modelKey = ModelUtil.genModelKey(model.getTableName(), model.getNamespace());
zookeeperRegistry.addDynamicEnvironment(EncryptUtils.encrypt(modelKey, EncryptMethod.MD5));
zookeeperRegistry.register(FateServer.hostServiceSets);
}
// update cache
this.store(namespaceMap, namespaceFile);
return returnResult;
}
/**
* query model by service id
*
* @param serviceId
* @return
*/
public Model queryModel(String serviceId) {
String namespaceKey = this.serviceIdNamespaceMap.get(serviceId);
if (namespaceKey != null && this.namespaceMap.get(namespaceKey) != null) {
Model model = (Model) this.namespaceMap.get(namespaceKey).clone();
if (model.getServiceIds() == null) {
model.setServiceIds(Lists.newArrayList());
}
model.getServiceIds().add(serviceId);
return model;
}
return null;
}
/**
* query model by tablename and namespace
*
* @param tableName
* @param namespace
* @return
*/
public Model queryModel(String tableName, String namespace) {
String namespaceKey = this.getNameSpaceKey(tableName, namespace);
Model model = this.namespaceMap.get(namespaceKey);
if (model == null) {
return null;
}
Model clone = (Model) model.clone();
this.serviceIdNamespaceMap.forEach((k, v) -> {
if (clone.getServiceIds() == null) {
clone.setServiceIds(Lists.newArrayList());
}
if (namespaceKey.equals(v)) {
clone.getServiceIds().add(k);
}
});
return clone;
}
public void restoreByLocalCache(Context context, Model model, byte[] cacheData) {
// use local cache model loader
LocalCacheModelLoader modelLoader = (LocalCacheModelLoader) this.modelLoaderFactory.getModelLoader(context, ModelLoader.LoadModelType.CACHE);
// save to local cache
String cachePath = modelLoader.getCachePath(context, model.getTableName(), model.getNamespace());
modelLoader.saveCacheData(context, cachePath, cacheData);
// restore
ModelLoader.ModelLoaderParam param = new ModelLoader.ModelLoaderParam();
param.setTableName(model.getTableName());
param.setNameSpace(model.getNamespace());
// first lookup form fateflow
param.setLoadModelType(ModelLoader.LoadModelType.FATEFLOW);
// param.setFilePath(cachePath);
List<String> serviceIds= model.getServiceIds();
//remove serviceId in the fetched model
model.setServiceIds(null);
//save fetched model
this.doLoad(context, model, param);
//bind the relation <serviceId,model>
if (serviceIds != null) {
for (String serviceId : serviceIds) {
this.doBind(context, model, serviceId);
}
}
}
public byte[] getModelCacheData(Context context, String tableName, String namespace) {
ModelLoader modelLoader = this.modelLoaderFactory.getModelLoader(context, ModelLoader.LoadModelType.CACHE);
String cachePath = modelLoader.getCachePath(context, tableName, namespace);
if (cachePath == null) {
return null;
}
File file = new File(cachePath);
if (file != null && file.exists()) {
try (InputStream in = new FileInputStream(file)) {
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
int readCount = in.read(filecontent);
if (readCount > 0) {
return filecontent;
}
} catch (Throwable e) {
logger.error("load model cache fail ", e);
}
}
return null;
}
public List<Model> queryModel(Context context, ModelServiceProto.QueryModelRequest queryModelRequest) {
int queryType = queryModelRequest.getQueryType();
switch (queryType) {
case 0:
List<Model> allModels = listAllModel();
return allModels.stream().map(e -> {
Model clone = (Model) e.clone();
clone.setModelProcessor(e.getModelProcessor());
this.serviceIdNamespaceMap.forEach((k, v) -> {
if (clone.getServiceIds() == null) {
clone.setServiceIds(Lists.newArrayList());
}
String nameSpaceKey = this.getNameSpaceKey(clone.getTableName(), clone.getNamespace());
if (nameSpaceKey.equals(v)) {
clone.getServiceIds().add(k);
}
});
return clone;
}).collect(Collectors.toList());
case 1:
// Fuzzy query
String serviceId = queryModelRequest.getServiceId();
return this.namespaceMap.values().stream()
.filter(e -> {
String nameSpaceKey = this.getNameSpaceKey(e.getTableName(), e.getNamespace());
boolean isMatch = false;
for (Map.Entry<String, String> entry : this.serviceIdNamespaceMap.entrySet()) {
if (entry.getKey().toLowerCase().indexOf(serviceId.toLowerCase()) > -1 && nameSpaceKey.equals(entry.getValue())) {
isMatch = true;
break;
}
}
return isMatch;
})
.map(e -> {
Model clone = (Model) e.clone();
if (clone.getServiceIds() == null) {
clone.setServiceIds(Lists.newArrayList());
}
String nameSpaceKey = this.getNameSpaceKey(clone.getTableName(), clone.getNamespace());
this.serviceIdNamespaceMap.forEach((k, v) -> {
if (v.equals(nameSpaceKey)) {
clone.getServiceIds().add(k);
}
});
return clone;
})
.collect(Collectors.toList());
case 2:
// query model by tableName and namespace
List<Model> modelList = new ArrayList<>();
Model model = queryModel(queryModelRequest.getTableName(), queryModelRequest.getNamespace());
if (model != null)
modelList.add(model);
return modelList;
default:
return null;
}
}
public Model getModelByServiceId(String serviceId) {
String namespaceKey = serviceIdNamespaceMap.get(serviceId);
if (namespaceKey == null) {
throw new ModelNullException("serviceId is not bind model");
}
return this.namespaceMap.get(namespaceKey);
}
/**
* 获取所有模型信息
*
* @return
*/
public List<Model> listAllModel() {
return new ArrayList(this.namespaceMap.values());
}
public Model getModelByTableNameAndNamespace(String tableName, String namespace) {
String key = getNameSpaceKey(tableName, namespace);
return namespaceMap.get(key);
}
private String getNameSpaceKey(String tableName, String namespace) {
return new StringBuilder().append(tableName).append("_").append(namespace).toString();
}
private void clearCache(String name, String namespace) {
StringBuilder sb = new StringBuilder();
String locationPre = MetaInfo.PROPERTY_MODEL_CACHE_PATH;
if (StringUtils.isNotEmpty(locationPre) && StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(namespace)) {
String cacheFilePath = sb.append(locationPre).append("/.fate/model_").append(name).append("_").append(namespace).append("_").append("cache").toString();
File cacheFile = new File(cacheFilePath);
if (cacheFile.exists()) {
cacheFile.delete();
}
File lockFile = new File(cacheFilePath + ".lock");
if (lockFile.exists()) {
lockFile.delete();
}
}
}
public synchronized ModelServiceProto.UnloadResponse unload(Context context, ModelServiceProto.UnloadRequest request) {
ModelServiceProto.UnloadResponse.Builder resultBuilder = ModelServiceProto.UnloadResponse.newBuilder();
if (logger.isDebugEnabled()) {
logger.debug("try to unload model, name: {}, namespace: {}", request.getTableName(), request.getNamespace());
}
resultBuilder.setStatusCode(StatusCode.SUCCESS);
Model model = this.getModelByTableNameAndNamespace(request.getTableName(), request.getNamespace());
if (model == null) {
logger.error("not found model info table name {} namespace {}, please check if the model is already loaded.", request.getTableName(), request.getNamespace());
throw new ModelNullException(" found model info, please check if the model is already loaded.");
}
List<String> serviceIds = Lists.newArrayList();
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | true |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-server/src/main/java/com/webank/ai/fate/serving/rpc/BatchInferenceFuture.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/rpc/BatchInferenceFuture.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.rpc;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.ListenableFuture;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.serving.common.async.AsyncMessageEvent;
import com.webank.ai.fate.serving.common.cache.Cache;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.rpc.core.FederatedRpcInvoker;
import com.webank.ai.fate.serving.common.utils.DisruptorUtil;
import com.webank.ai.fate.serving.core.bean.BatchInferenceRequest;
import com.webank.ai.fate.serving.core.bean.BatchInferenceResult;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.EncryptMethod;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.utils.EncryptUtils;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class BatchInferenceFuture extends AbstractFuture {
Logger logger = LoggerFactory.getLogger(BatchInferenceFuture.class);
ListenableFuture<Proxy.Packet> future;
FederatedRpcInvoker.RpcDataWraper rpcDataWraper;
BatchInferenceRequest batchInferenceRequest;
boolean useCache;
Map<Integer, BatchInferenceResult.SingleInferenceResult> cacheData;
public BatchInferenceFuture(ListenableFuture<Proxy.Packet> future,
FederatedRpcInvoker.RpcDataWraper rpcDataWraper,
BatchInferenceRequest batchInferenceRequest,
boolean useCache,
Map<Integer, BatchInferenceResult.SingleInferenceResult> cacheData) {
this.future = future;
this.rpcDataWraper = rpcDataWraper;
this.batchInferenceRequest = batchInferenceRequest;
this.useCache = useCache;
this.cacheData = cacheData;
}
@Override
public BatchInferenceResult get() throws InterruptedException, ExecutionException {
if (future != null) {
BatchInferenceResult remoteBatchInferenceResult = parse(future.get());
return mergeCache(remoteBatchInferenceResult);
} else {
return mergeCache(null);
}
}
public BatchInferenceResult mergeCache(BatchInferenceResult remoteBatchInferenceResult) {
if (cacheData != null && cacheData.size() > 0) {
if (remoteBatchInferenceResult != null) {
cacheData.forEach((k, v) -> {
remoteBatchInferenceResult.getBatchDataList().add(v);
});
remoteBatchInferenceResult.rebuild();
return remoteBatchInferenceResult;
} else {
BatchInferenceResult newBatchInferenceResult = new BatchInferenceResult();
newBatchInferenceResult.setRetcode(StatusCode.SUCCESS);
cacheData.forEach((k, v) -> {
newBatchInferenceResult.getBatchDataList().add(v);
});
newBatchInferenceResult.rebuild();
return newBatchInferenceResult;
}
} else {
return remoteBatchInferenceResult;
}
}
@Override
public BatchInferenceResult get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
if (future != null) {
BatchInferenceResult remoteBatchInferenceResult = parse(future.get(timeout, unit));
return mergeCache(remoteBatchInferenceResult);
} else {
return mergeCache(null);
}
}
private BatchInferenceResult parse(Proxy.Packet remote) {
if (remote != null) {
String remoteContent = remote.getBody().getValue().toStringUtf8();
BatchInferenceResult remoteInferenceResult = JsonUtil.json2Object(remoteContent, BatchInferenceResult.class);
if (useCache && StatusCode.SUCCESS == remoteInferenceResult.getRetcode()) {
try {
AsyncMessageEvent asyncMessageEvent = new AsyncMessageEvent();
List<Cache.DataWrapper> cacheEventDataList = Lists.newArrayList();
for (BatchInferenceRequest.SingleInferenceData singleInferenceData : batchInferenceRequest.getBatchDataList()) {
BatchInferenceResult.SingleInferenceResult singleInferenceResult = remoteInferenceResult.getSingleInferenceResultMap().get(singleInferenceData.getIndex());
if (singleInferenceResult != null && StatusCode.SUCCESS == singleInferenceResult.getRetcode()) {
Cache.DataWrapper dataWrapper = new Cache.DataWrapper(buildCacheKey(rpcDataWraper.getGuestModel(), rpcDataWraper.getHostModel(),
singleInferenceData.getSendToRemoteFeatureData()), JsonUtil.object2Json(singleInferenceResult.getData()));
cacheEventDataList.add(dataWrapper);
}
}
asyncMessageEvent.setName(Dict.EVENT_SET_BATCH_INFERENCE_CACHE);
asyncMessageEvent.setData(cacheEventDataList);
DisruptorUtil.producer(asyncMessageEvent);
} catch (Exception e) {
logger.error("send cache event error", e);
}
}
return remoteInferenceResult;
} else {
return null;
}
}
private String buildCacheKey(Model guestModel, Model hostModel, Map sendToRemote) {
String tableName = guestModel.getTableName();
String namespace = guestModel.getNamespace();
String partId = hostModel.getPartId();
StringBuilder sb = new StringBuilder();
sb.append(partId).append(tableName).append(namespace).append(JsonUtil.object2Json(sendToRemote));
String key = EncryptUtils.encrypt(sb.toString(), EncryptMethod.MD5);
return key;
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/rpc/DefaultFederatedRpcInvoker.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/rpc/DefaultFederatedRpcInvoker.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.rpc;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.networking.proxy.DataTransferServiceGrpc;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.register.router.RouterService;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.url.URL;
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.cache.Cache;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.rpc.core.FederatedRpcInvoker;
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.utils.EncryptUtils;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.event.CacheEventData;
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 java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Service
public class DefaultFederatedRpcInvoker implements FederatedRpcInvoker<Proxy.Packet> {
private static final Logger logger = LoggerFactory.getLogger(FederatedRpcInvoker.class);
@Autowired(required = false)
public RouterService routerService;
@Autowired
private Cache cache;
private Proxy.Packet build(Context context, RpcDataWraper rpcDataWraper) {
Model model = ((ServingServerContext) context).getModel();
Preconditions.checkArgument(model != null);
Proxy.Packet.Builder packetBuilder = Proxy.Packet.newBuilder();
packetBuilder.setBody(Proxy.Data.newBuilder().setValue(ByteString.copyFrom(JsonUtil.object2Json(rpcDataWraper.getData()).getBytes())).build());
Proxy.Metadata.Builder metaDataBuilder = Proxy.Metadata.newBuilder();
Proxy.Topic.Builder topicBuilder = Proxy.Topic.newBuilder();
metaDataBuilder.setSrc(topicBuilder.setPartyId(String.valueOf(model.getPartId())).setRole(MetaInfo.PROPERTY_SERVICE_ROLE_NAME).setName(Dict.PARTNER_PARTY_NAME).build());
metaDataBuilder.setDst(topicBuilder.setPartyId(String.valueOf(rpcDataWraper.getHostModel().getPartId())).setRole(MetaInfo.PROPERTY_SERVICE_ROLE_NAME).setName(Dict.PARTY_NAME).build());
metaDataBuilder.setCommand(Proxy.Command.newBuilder().setName(rpcDataWraper.getRemoteMethodName()).build());
String version = Long.toString(MetaInfo.CURRENT_VERSION);
metaDataBuilder.setOperator(version);
Proxy.Task.Builder taskBuilder = com.webank.ai.fate.api.networking.proxy.Proxy.Task.newBuilder();
Proxy.Model.Builder modelBuilder = Proxy.Model.newBuilder();
modelBuilder.setNamespace(rpcDataWraper.getHostModel().getNamespace());
modelBuilder.setTableName(rpcDataWraper.getHostModel().getTableName());
taskBuilder.setModel(modelBuilder.build());
metaDataBuilder.setTask(taskBuilder.build());
packetBuilder.setHeader(metaDataBuilder.build());
Proxy.AuthInfo.Builder authBuilder = Proxy.AuthInfo.newBuilder();
if (context.getCaseId() != null) {
authBuilder.setNonce(context.getCaseId());
}
if (version != null) {
authBuilder.setVersion(version);
}
if (context.getServiceId() != null) {
authBuilder.setServiceId(context.getServiceId());
}
if (context.getApplyId() != null) {
authBuilder.setApplyId(context.getApplyId());
}
packetBuilder.setAuth(authBuilder.build());
return packetBuilder.build();
}
private String route() {
boolean routerByzk = MetaInfo.PROPERTY_USE_ZK_ROUTER;
String address = null;
if (!routerByzk) {
address = MetaInfo.PROPERTY_PROXY_ADDRESS;
} else {
List<URL> urls = routerService.router(Dict.PROPERTY_PROXY_ADDRESS, Dict.ONLINE_ENVIRONMENT, Dict.UNARYCALL);
if (urls != null && urls.size() > 0) {
URL url = urls.get(0);
String ip = url.getHost();
int port = url.getPort();
address = ip + ":" + port;
}
}
return address;
}
@Override
public Proxy.Packet sync(Context context, RpcDataWraper rpcDataWraper, long timeout) {
Proxy.Packet resultPacket = null;
try {
ListenableFuture<Proxy.Packet> future = this.async(context, rpcDataWraper);
if (future != null) {
resultPacket = future.get(timeout, TimeUnit.MILLISECONDS);
}
return resultPacket;
} catch (Exception e) {
logger.error("getFederatedPredictFromRemote error", e.getMessage());
throw new RuntimeException(e);
} finally {
context.setDownstreamCost(System.currentTimeMillis() - context.getDownstreamBegin());
}
}
private String buildCacheKey(Model guestModel, Model hostModel, Map sendToRemote) {
String tableName = guestModel.getTableName();
String namespace = guestModel.getNamespace();
String partId = hostModel.getPartId();
StringBuilder sb = new StringBuilder();
sb.append(partId).append(tableName).append(namespace).append(JsonUtil.object2Json(sendToRemote));
String key = EncryptUtils.encrypt(sb.toString(), EncryptMethod.MD5);
return key;
}
@Override
public ListenableFuture<ReturnResult> singleInferenceRpcWithCache(Context context, RpcDataWraper rpcDataWraper, boolean useCache) {
InferenceRequest inferenceRequest = (InferenceRequest) rpcDataWraper.getData();
if (useCache) {
Object result = cache.get(buildCacheKey(rpcDataWraper.getGuestModel(), rpcDataWraper.getHostModel(), inferenceRequest.getSendToRemoteFeatureData()));
if (result != null) {
Map data = JsonUtil.json2Object(result.toString(), Map.class);
ReturnResult returnResult = new ReturnResult();
returnResult.setRetcode(StatusCode.SUCCESS);
returnResult.setRetmsg("hit host cache");
return new AbstractFuture<ReturnResult>() {
@Override
public ReturnResult get() throws InterruptedException, ExecutionException {
returnResult.setData(data);
return returnResult;
}
@Override
public ReturnResult get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
returnResult.setData(data);
return returnResult;
}
};
}
}
ListenableFuture<Proxy.Packet> future = this.async(context, rpcDataWraper);
return new AbstractFuture<ReturnResult>() {
@Override
public ReturnResult get() throws InterruptedException, ExecutionException {
return parse(future.get());
}
@Override
public ReturnResult get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return parse(future.get(timeout, unit));
}
private ReturnResult parse(Proxy.Packet remote) {
if (remote != null) {
String remoteContent = remote.getBody().getValue().toStringUtf8();
ReturnResult remoteInferenceResult = JsonUtil.json2Object(remoteContent, ReturnResult.class);
if (useCache && StatusCode.SUCCESS == remoteInferenceResult.getRetcode()) {
try {
AsyncMessageEvent asyncMessageEvent = new AsyncMessageEvent();
CacheEventData cacheEventData = new CacheEventData(buildCacheKey(rpcDataWraper.getGuestModel(), rpcDataWraper.getHostModel(), inferenceRequest.getSendToRemoteFeatureData()), remoteInferenceResult.getData());
asyncMessageEvent.setName(Dict.EVENT_SET_INFERENCE_CACHE);
asyncMessageEvent.setData(cacheEventData);
DisruptorUtil.producer(asyncMessageEvent);
} catch (Exception e) {
logger.error("send cache event error", e);
}
}
return remoteInferenceResult;
} else {
return null;
}
}
};
}
@Override
public ListenableFuture<BatchInferenceResult> batchInferenceRpcWithCache(Context context, RpcDataWraper rpcDataWraper, boolean useCache) {
BatchInferenceRequest inferenceRequest = (BatchInferenceRequest) rpcDataWraper.getData();
Map<Integer, BatchInferenceResult.SingleInferenceResult> cacheData = Maps.newHashMap();
if (useCache) {
List<BatchInferenceRequest.SingleInferenceData> listData = inferenceRequest.getBatchDataList();
List<String> cacheKeys = Lists.newArrayList();
Map<String, List<Integer>> keyIndexMap = Maps.newHashMap();
for (int i = 0; i < listData.size(); i++) {
BatchInferenceRequest.SingleInferenceData singleInferenceData = listData.get(i);
String key = buildCacheKey(rpcDataWraper.getGuestModel(), rpcDataWraper.getHostModel(), singleInferenceData.getSendToRemoteFeatureData());
cacheKeys.add(key);
if (keyIndexMap.get(key) == null) {
keyIndexMap.put(key, Lists.newArrayList(i));
} else {
keyIndexMap.get(key).add(i);
}
}
if (CollectionUtils.isNotEmpty(cacheKeys)) {
List<Cache.DataWrapper<String, String>> dataWrapperList = this.cache.get(cacheKeys.toArray());
if (dataWrapperList != null) {
Set<Integer> prepareToRemove = Sets.newHashSet();
for (Cache.DataWrapper<String, String> cacheDataWrapper : dataWrapperList) {
String key = cacheDataWrapper.getKey();
List<Integer> indexs = keyIndexMap.get(key);
if (indexs != null) {
prepareToRemove.addAll(indexs);
for (Integer index : indexs) {
String value = cacheDataWrapper.getValue();
Map data = JsonUtil.json2Object(value, Map.class);
BatchInferenceResult.SingleInferenceResult finalSingleResult = new BatchInferenceResult.SingleInferenceResult();
finalSingleResult.setRetcode(StatusCode.SUCCESS);
finalSingleResult.setData(data);
finalSingleResult.setRetmsg("hit host cache");
finalSingleResult.setIndex(listData.get(index).getIndex());
cacheData.put(listData.get(index).getIndex(), finalSingleResult);
}
}
}
List<BatchInferenceRequest.SingleInferenceData> newRequestList = Lists.newArrayList();
for (int index = 0; index < listData.size(); index++) {
if (!prepareToRemove.contains(index)) {
newRequestList.add(listData.get(index));
}
}
inferenceRequest.getBatchDataList().clear();
inferenceRequest.getBatchDataList().addAll(newRequestList);
}
}
}
ListenableFuture<Proxy.Packet> future = null;
if (inferenceRequest.getBatchDataList().size() > 0) {
future = this.async(context, rpcDataWraper);
}
return new BatchInferenceFuture(future, rpcDataWraper, inferenceRequest, useCache, cacheData);
}
@Override
public ListenableFuture<Proxy.Packet> async(Context context, RpcDataWraper rpcDataWraper) {
Proxy.Packet packet = this.build(context, rpcDataWraper);
String address = this.route();
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
Preconditions.checkArgument(StringUtils.isNotEmpty(address));
ManagedChannel channel1 = grpcConnectionPool.getManagedChannel(address);
DataTransferServiceGrpc.DataTransferServiceFutureStub stub1 = DataTransferServiceGrpc.newFutureStub(channel1);
context.setDownstreamBegin(System.currentTimeMillis());
ListenableFuture<Proxy.Packet> future = stub1.unaryCall(packet);
return future;
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/host/provider/HostSingleInferenceProvider.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/host/provider/HostSingleInferenceProvider.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.host.provider;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.model.ModelProcessor;
import com.webank.ai.fate.serving.common.rpc.core.*;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.InferenceRequest;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.guest.provider.AbstractServingServiceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@FateService(name = "hostInferenceProvider", preChain = {
"requestOverloadBreaker",
"hostParamInterceptor",
"hostModelInterceptor",
"hostSingleFeatureAdaptorInterceptor"
}, postChain = {
})
@Service
public class HostSingleInferenceProvider extends AbstractServingServiceProvider<InferenceRequest, ReturnResult> {
private static final Logger logger = LoggerFactory.getLogger(HostSingleInferenceProvider.class);
@Override
protected OutboundPackage<ReturnResult> serviceFailInner(Context context, InboundPackage<InferenceRequest> data, Throwable e) {
Map result = new HashMap(8);
OutboundPackage<ReturnResult> outboundPackage = new OutboundPackage<ReturnResult>();
ReturnResult returnResult = ErrorMessageUtil.handleExceptionToReturnResult(e);
outboundPackage.setData(returnResult);
context.setReturnCode(returnResult.getRetcode());
return outboundPackage;
}
@FateServiceMethod(name = "federatedInference")
public ReturnResult federatedInference(Context context, InboundPackage<InferenceRequest> data) {
InferenceRequest params = data.getBody();
Model model = ((ServingServerContext) context).getModel();
ModelProcessor modelProcessor = model.getModelProcessor();
ReturnResult result = modelProcessor.hostInference(context, params);
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-server/src/main/java/com/webank/ai/fate/serving/host/provider/HostBatchInferenceProvider.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/host/provider/HostBatchInferenceProvider.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.host.provider;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.rpc.core.FateService;
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.BatchHostFederatedParams;
import com.webank.ai.fate.serving.core.bean.BatchInferenceRequest;
import com.webank.ai.fate.serving.core.bean.BatchInferenceResult;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.BaseException;
import com.webank.ai.fate.serving.guest.provider.AbstractServingServiceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@FateService(name = "batchInference", preChain = {
"requestOverloadBreaker",
"hostBatchParamInterceptor",
"hostModelInterceptor",
"hostBatchFeatureAdaptorInterceptor"
}, postChain = {
})
@Service
public class HostBatchInferenceProvider extends AbstractServingServiceProvider<BatchInferenceRequest, BatchInferenceResult> {
private static final Logger logger = LoggerFactory.getLogger(HostBatchInferenceProvider.class);
@Override
public BatchInferenceResult doService(Context context, InboundPackage data, OutboundPackage outboundPackage) {
BatchHostFederatedParams batchHostFederatedParams = (BatchHostFederatedParams) data.getBody();
Model model = ((ServingServerContext) context).getModel();
BatchInferenceResult batchInferenceResult = model.getModelProcessor().hostBatchInference(context, batchHostFederatedParams);
return batchInferenceResult;
}
@Override
protected OutboundPackage<BatchInferenceResult> serviceFailInner(Context context, InboundPackage<BatchInferenceRequest> data, Throwable e) {
OutboundPackage<BatchInferenceResult> outboundPackage = new OutboundPackage<BatchInferenceResult>();
BatchInferenceResult batchInferenceResult = new BatchInferenceResult();
if (e instanceof BaseException) {
BaseException baseException = (BaseException) e;
batchInferenceResult.setRetcode(baseException.getRetcode());
batchInferenceResult.setRetmsg(e.getMessage());
} else {
batchInferenceResult.setRetcode(StatusCode.SYSTEM_ERROR);
batchInferenceResult.setRetmsg(e.getMessage());
}
context.setReturnCode(batchInferenceResult.getRetcode());
outboundPackage.setData(batchInferenceResult);
return outboundPackage;
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/host/interceptors/HostBatchParamInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/host/interceptors/HostBatchParamInterceptor.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.host.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.BatchHostFederatedParams;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.exceptions.HostInvalidParamException;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class HostBatchParamInterceptor implements Interceptor {
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
try {
byte[] reqBody = (byte[]) inboundPackage.getBody();
BatchHostFederatedParams batchHostFederatedParams = null;
batchHostFederatedParams = JsonUtil.json2Object(reqBody, BatchHostFederatedParams.class);
inboundPackage.setBody(batchHostFederatedParams);
Preconditions.checkArgument(batchHostFederatedParams != null, "");
Preconditions.checkArgument(batchHostFederatedParams.getBatchDataList() != null && batchHostFederatedParams.getBatchDataList().size() > 0);
List<BatchHostFederatedParams.SingleInferenceData> datalist = batchHostFederatedParams.getBatchDataList();
int batchSizeLimit = MetaInfo.PROPERTY_BATCH_INFERENCE_MAX;
Preconditions.checkArgument(datalist.size() <= batchSizeLimit, "batch size is big than " + batchSizeLimit);
} catch (Exception e) {
throw new HostInvalidParamException(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-server/src/main/java/com/webank/ai/fate/serving/host/interceptors/HostSingleFeatureAdaptorInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/host/interceptors/HostSingleFeatureAdaptorInterceptor.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.host.interceptors;
import com.webank.ai.fate.register.utils.StringUtils;
import com.webank.ai.fate.serving.adaptor.dataaccess.AbstractSingleFeatureDataAdaptor;
import com.webank.ai.fate.serving.common.interceptors.AbstractInterceptor;
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.adaptor.SingleFeatureDataAdaptor;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.InferenceRequest;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.FeatureDataAdaptorException;
import com.webank.ai.fate.serving.core.exceptions.HostGetFeatureErrorException;
import com.webank.ai.fate.serving.core.utils.InferenceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
@Service
public class HostSingleFeatureAdaptorInterceptor extends AbstractInterceptor<InferenceRequest, ReturnResult> implements InitializingBean {
Logger logger = LoggerFactory.getLogger(HostSingleFeatureAdaptorInterceptor.class);
SingleFeatureDataAdaptor singleFeatureDataAdaptor = null;
@Override
public void doPreProcess(Context context, InboundPackage<InferenceRequest> inboundPackage, OutboundPackage<ReturnResult> outboundPackage) throws Exception {
if (singleFeatureDataAdaptor == null) {
throw new FeatureDataAdaptorException("adaptor not found");
}
InferenceRequest inferenceRequest = inboundPackage.getBody();
ReturnResult singleFeatureDataAdaptorData = singleFeatureDataAdaptor.getData(context, inboundPackage.getBody().getSendToRemoteFeatureData());
if (singleFeatureDataAdaptorData == null) {
throw new HostGetFeatureErrorException("adaptor return null");
}
if (StatusCode.SUCCESS != singleFeatureDataAdaptorData.getRetcode()) {
throw new HostGetFeatureErrorException(singleFeatureDataAdaptorData.getRetcode(), "adaptor return error");
}
inferenceRequest.getFeatureData().clear();
inferenceRequest.getFeatureData().putAll(singleFeatureDataAdaptorData.getData());
}
@Override
public void afterPropertiesSet() throws Exception {
String adaptorClass = MetaInfo.PROPERTY_FEATURE_SINGLE_ADAPTOR;
if (StringUtils.isNotEmpty(adaptorClass)) {
logger.info("try to load adaptor {}", adaptorClass);
singleFeatureDataAdaptor = (SingleFeatureDataAdaptor) InferenceUtils.getClassByName(adaptorClass);
try {
((AbstractSingleFeatureDataAdaptor) singleFeatureDataAdaptor).setEnvironment(environment);
singleFeatureDataAdaptor.init();
} catch (Exception e) {
logger.error("single adaptor init error");
}
logger.info("single adaptor class is {}", adaptorClass);
}
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/host/interceptors/HostParamInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/host/interceptors/HostParamInterceptor.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.host.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.bean.InferenceRequest;
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.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class HostParamInterceptor implements Interceptor {
Logger logger = LoggerFactory.getLogger(HostParamInterceptor.class);
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
byte[] reqBody = (byte[]) inboundPackage.getBody();
if (context.getActionType().equalsIgnoreCase(Dict.FEDERATED_INFERENCE_FOR_TREE)) {
Map params = JsonUtil.json2Object(reqBody, HashMap.class);
Preconditions.checkArgument(params != null, "parse inference params error");
inboundPackage.setBody(params);
} else {
InferenceRequest inferenceRequest = JsonUtil.json2Object(reqBody, InferenceRequest.class);
if (StringUtils.isBlank(context.getVersion()) || Double.parseDouble(context.getVersion()) < 200) {
Map hostParams = JsonUtil.json2Object(reqBody, Map.class);
Preconditions.checkArgument(hostParams != null, "parse inference params error");
Preconditions.checkArgument(hostParams.get("featureIdMap") != null, "parse inference params featureIdMap error");
inferenceRequest.getSendToRemoteFeatureData().putAll((Map) hostParams.get("featureIdMap"));
}
Preconditions.checkArgument(inferenceRequest != null, "parse inference params error");
inboundPackage.setBody(inferenceRequest);
}
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/host/interceptors/HostModelInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/host/interceptors/HostModelInterceptor.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.host.interceptors;
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.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.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.exceptions.HostModelNullException;
import com.webank.ai.fate.serving.core.exceptions.OverLoadException;
import com.webank.ai.fate.serving.model.ModelManager;
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;
@Service
public class HostModelInterceptor implements Interceptor {
Logger logger = LoggerFactory.getLogger(HostModelInterceptor.class);
@Autowired
ModelManager modelManager;
@Autowired
FlowCounterManager flowCounterManager;
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
ServingServerContext servingServerContext = ((ServingServerContext) context);
String tableName = servingServerContext.getModelTableName();
String nameSpace = servingServerContext.getModelNamesapce();
Model model;
if (StringUtils.isBlank(context.getVersion()) || Double.parseDouble(context.getVersion()) < 200) {
model = modelManager.getPartnerModel(tableName, nameSpace);
} else {
model = modelManager.getModelByTableNameAndNamespace(tableName, nameSpace);
}
if (model == null) {
logger.error("table name {} namepsace {} is not exist", tableName, nameSpace);
throw new HostModelNullException("mode is null");
}
servingServerContext.setModel(model);
int times = 1;
if (context.getServiceName().equalsIgnoreCase(Dict.SERVICENAME_BATCH_INFERENCE)) {
BatchHostFederatedParams batchHostFederatedParams = (BatchHostFederatedParams) inboundPackage.getBody();
times = batchHostFederatedParams.getBatchDataList().size();
}
context.putData(Dict.PASS_QPS, times);
boolean pass = flowCounterManager.pass(model.getResourceName(), times);
if (!pass) {
flowCounterManager.block(model.getResourceName(), times);
throw new OverLoadException("request was block by over load, model resource: " + model.getResourceName());
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-server/src/main/java/com/webank/ai/fate/serving/host/interceptors/HostBatchFeatureAdaptorInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/host/interceptors/HostBatchFeatureAdaptorInterceptor.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.host.interceptors;
import com.webank.ai.fate.register.utils.StringUtils;
import com.webank.ai.fate.serving.adaptor.dataaccess.AbstractBatchFeatureDataAdaptor;
import com.webank.ai.fate.serving.common.interceptors.AbstractInterceptor;
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.adaptor.BatchFeatureDataAdaptor;
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.FeatureDataAdaptorException;
import com.webank.ai.fate.serving.core.exceptions.HostGetFeatureErrorException;
import com.webank.ai.fate.serving.core.utils.InferenceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class HostBatchFeatureAdaptorInterceptor extends AbstractInterceptor<BatchInferenceRequest, BatchInferenceResult> implements InitializingBean {
Logger logger = LoggerFactory.getLogger(HostBatchFeatureAdaptorInterceptor.class);
BatchFeatureDataAdaptor batchFeatureDataAdaptor = null;
@Override
public void doPreProcess(Context context, InboundPackage<BatchInferenceRequest> inboundPackage, OutboundPackage<BatchInferenceResult> outboundPackage) throws Exception {
long begin = System.currentTimeMillis();
if (batchFeatureDataAdaptor == null) {
throw new FeatureDataAdaptorException("adaptor not found");
}
BatchInferenceRequest batchInferenceRequest = inboundPackage.getBody();
BatchHostFeatureAdaptorResult batchHostFeatureAdaptorResult = batchFeatureDataAdaptor.getFeatures(context, inboundPackage.getBody().getBatchDataList());
if (batchHostFeatureAdaptorResult == null) {
throw new HostGetFeatureErrorException("adaptor return null");
}
if (StatusCode.SUCCESS != batchHostFeatureAdaptorResult.getRetcode()) {
throw new HostGetFeatureErrorException(batchHostFeatureAdaptorResult.getRetcode(), "adaptor return error");
}
Map<Integer, BatchHostFeatureAdaptorResult.SingleBatchHostFeatureAdaptorResult> featureResultMap = batchHostFeatureAdaptorResult.getIndexResultMap();
batchInferenceRequest.getBatchDataList().forEach(request -> {
request.setNeedCheckFeature(true);
BatchHostFeatureAdaptorResult.SingleBatchHostFeatureAdaptorResult featureAdaptorResult = featureResultMap.get(request.getIndex());
if (featureAdaptorResult != null && StatusCode.SUCCESS == featureAdaptorResult.getRetcode() && featureAdaptorResult.getFeatures() != null) {
request.setFeatureData(featureAdaptorResult.getFeatures());
}
});
long end = System.currentTimeMillis();
logger.info("batch adaptor cost {} ", end - begin);
}
@Override
public void afterPropertiesSet() throws Exception {
String adaptorClass = MetaInfo.PROPERTY_FEATURE_BATCH_ADAPTOR;
if (StringUtils.isNotEmpty(adaptorClass)) {
logger.info("try to load adaptor {}", adaptorClass);
batchFeatureDataAdaptor = (BatchFeatureDataAdaptor) InferenceUtils.getClassByName(adaptorClass);
try {
((AbstractBatchFeatureDataAdaptor) batchFeatureDataAdaptor).setEnvironment(environment);
batchFeatureDataAdaptor.init();
} catch (Exception e) {
logger.error("batch adaptor init error");
}
}
logger.info("batch adaptor class is {}", adaptorClass);
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/common/provider/ModelServiceProvider.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/common/provider/ModelServiceProvider.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.provider;
import com.google.gson.Gson;
import com.google.protobuf.ByteString;
import com.google.protobuf.Message;
import com.google.protobuf.ProtocolStringList;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceGrpc;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceProto;
import com.webank.ai.fate.register.url.CollectionUtils;
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.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.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.federatedml.PipelineModelProcessor;
import com.webank.ai.fate.serving.guest.provider.AbstractServingServiceProvider;
import com.webank.ai.fate.serving.model.ModelManager;
import io.grpc.ManagedChannel;
import org.apache.commons.compress.utils.Lists;
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 java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@FateService(name = "modelService", preChain = {
"requestOverloadBreaker"
}, postChain = {
})
@Service
public class ModelServiceProvider extends AbstractServingServiceProvider {
@Autowired
ModelManager modelManager;
@Autowired
FlowCounterManager flowCounterManager;
Logger logger = LoggerFactory.getLogger(ModelServiceProvider.class);
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
@FateServiceMethod(name = "MODEL_LOAD")
public Object load(Context context, InboundPackage data) {
ModelServiceProto.PublishRequest publishRequest = (ModelServiceProto.PublishRequest) data.getBody();
ReturnResult returnResult = modelManager.load(context, publishRequest);
return returnResult;
}
@FateServiceMethod(name = "MODEL_PUBLISH_ONLINE")
public Object bind(Context context, InboundPackage data) {
ModelServiceProto.PublishRequest req = (ModelServiceProto.PublishRequest) data.getBody();
ReturnResult returnResult = modelManager.bind(context, req);
return returnResult;
}
@FateServiceMethod(name = "QUERY_MODEL")
public ModelServiceProto.QueryModelResponse queryModel(Context context, InboundPackage data) {
ModelServiceProto.QueryModelRequest req = (ModelServiceProto.QueryModelRequest) data.getBody();
List<Model> models = modelManager.queryModel(context, req);
ModelServiceProto.QueryModelResponse.Builder builder = ModelServiceProto.QueryModelResponse.newBuilder();
if (CollectionUtils.isNotEmpty(models)) {
for (int i = 0; i < models.size(); i++) {
Model model = models.get(i);
if (model == null) {
continue;
}
List<Map> rolePartyMapList = model.getRolePartyMapList();
if (rolePartyMapList == null) {
rolePartyMapList = new ArrayList<>();
}
Map rolePartyMap = new HashMap();
rolePartyMap.put(Dict.ROLE, model.getRole());
rolePartyMap.put(Dict.PART_ID, model.getPartId());
rolePartyMapList.add(rolePartyMap);
if (model.getFederationModelMap() != null) {
for (Model value : model.getFederationModelMap().values()) {
rolePartyMap = new HashMap();
rolePartyMap.put(Dict.ROLE, value.getRole());
rolePartyMap.put(Dict.PART_ID, value.getPartId());
rolePartyMapList.add(rolePartyMap);
}
}
model.setRolePartyMapList(rolePartyMapList);
model.setAllowQps(flowCounterManager.getAllowedQps(model.getResourceName()));
ModelServiceProto.ModelInfoEx.Builder modelExBuilder = ModelServiceProto.ModelInfoEx.newBuilder();
modelExBuilder.setIndex(i);
modelExBuilder.setTableName(model.getTableName());
modelExBuilder.setNamespace(model.getNamespace());
modelExBuilder.setResourceAdress(model.getResourceAdress() == null ? "" : model.getResourceAdress());
if (model.getServiceIds() != null) {
modelExBuilder.addAllServiceIds(model.getServiceIds());
}
//JsonUtil.object2Json(model)
Gson gson = new Gson();
modelExBuilder.setContent(gson.toJson(model));
if (model.getModelProcessor() instanceof PipelineModelProcessor) {
ModelServiceProto.ModelProcessorExt.Builder modelProcessorExtBuilder = ModelServiceProto.ModelProcessorExt.newBuilder();
PipelineModelProcessor pipelineModelProcessor = (PipelineModelProcessor) model.getModelProcessor();
// System.out.println(JsonUtil.object2Json(pipelineModelProcessor.getParmasMap()));
//pipelineModelProcessor.getPipeLineNode()
// modelProcessorExtBuilder.setDslParser(JsonUtil.object2Json(pipelineModelProcessor .getDslParser()));
// modelProcessorExtBuilder.setParamsMap(JsonUtil.object2Json(pipelineModelProcessor.getParmasMap()));
// modelProcessorExtBuilder.setPipelineNodes()
if (pipelineModelProcessor != null) {
pipelineModelProcessor.getPipeLineNode().forEach(node -> {
try{
if (node != null) {
ModelServiceProto.PipelineNode.Builder pipelineNodeBuilder = ModelServiceProto.PipelineNode.newBuilder();
if (node.getComponentName() != null) {
pipelineNodeBuilder.setName(node.getComponentName());
} else {
pipelineNodeBuilder.setName("unknow");
}
if (node.getParam() != null) {
pipelineNodeBuilder.setParams(node.getParam() instanceof Message ? JsonUtil.pbToJson((Message) node.getParam()) : JsonUtil.object2Json(node.getParam()));
}
modelProcessorExtBuilder.addNodes(pipelineNodeBuilder.build());
}
}catch(Exception e){
logger.error("query model info error",e);
}
});
}
modelExBuilder.setModelProcessorExt(modelProcessorExtBuilder.build());
}
builder.addModelInfos(modelExBuilder.build());
}
}
builder.setRetcode(StatusCode.SUCCESS);
return builder.build();
}
@FateServiceMethod(name = "UNLOAD")
public ModelServiceProto.UnloadResponse unload(Context context, InboundPackage data) {
ModelServiceProto.UnloadRequest req = (ModelServiceProto.UnloadRequest) data.getBody();
ModelServiceProto.UnloadResponse res = modelManager.unload(context, req);
return res;
}
@FateServiceMethod(name = "UNBIND")
public ModelServiceProto.UnbindResponse unbind(Context context, InboundPackage data) {
ModelServiceProto.UnbindRequest req = (ModelServiceProto.UnbindRequest) data.getBody();
ModelServiceProto.UnbindResponse res = modelManager.unbind(context, req);
return res;
}
@FateServiceMethod(name = "FETCH_MODEL")
public ModelServiceProto.FetchModelResponse fetchModel(Context context, InboundPackage data) {
ModelServiceProto.FetchModelRequest req = (ModelServiceProto.FetchModelRequest) data.getBody();
ModelServiceProto.FetchModelResponse.Builder responseBuilder = ModelServiceProto.FetchModelResponse.newBuilder();
if (!MetaInfo.PROPERTY_MODEL_SYNC) {
return responseBuilder.setStatusCode(StatusCode.MODEL_SYNC_ERROR)
.setMessage("no synchronization allowed, to use this function, please configure model.synchronize=true").build();
}
String tableName = req.getTableName();
String namespace = req.getNamespace();
List<String> serviceIds = Lists.newArrayList();
ProtocolStringList serviceIdsList = req.getServiceIdsList();
ModelServiceProto.ModelTransferRequest.Builder modelTransferRequestBuilder = ModelServiceProto.ModelTransferRequest.newBuilder();
// if(serviceIdsList!=null){
// serviceIdsList.asByteStringList().forEach(serviceIdByte ->{
// serviceIds.add(serviceIdByte.toString());
// });
// }
String sourceIp = req.getSourceIp();
int sourcePort = req.getSourcePort();
if (!NetUtils.isValidAddress(sourceIp + ":" + sourcePort)) {
throw new SysException("invalid address");
}
// check model exist
Model model;
// if (StringUtils.isNotBlank(serviceId)) {
// model = modelManager.queryModel(serviceId);
// } else {
// model = modelManager.queryModel(tableName, namespace);
// }
// if (model != null) {
// return responseBuilder.setStatusCode(StatusCode.MODEL_SYNC_ERROR)
// .setMessage("model already exists").build();
// }
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(sourceIp, sourcePort);
ModelServiceGrpc.ModelServiceBlockingStub blockingStub = ModelServiceGrpc.newBlockingStub(managedChannel)
.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
ModelServiceProto.ModelTransferRequest modelTransferRequest = modelTransferRequestBuilder
.setTableName(tableName).setNamespace(namespace).build();
ModelServiceProto.ModelTransferResponse modelTransferResponse = blockingStub.modelTransfer(modelTransferRequest);
if (modelTransferResponse.getStatusCode() != StatusCode.SUCCESS) {
return responseBuilder.setStatusCode(modelTransferResponse.getStatusCode()).setMessage(modelTransferResponse.getMessage()).build();
}
byte[] modelData = modelTransferResponse.getModelData().toByteArray();
byte[] cacheData = modelTransferResponse.getCacheData().toByteArray();
Model fetchModel = JsonUtil.json2Object(modelData, Model.class);
modelManager.restoreByLocalCache(context, fetchModel, cacheData);
return responseBuilder.setStatusCode(StatusCode.SUCCESS).setMessage(Dict.SUCCESS).build();
}
@FateServiceMethod(name = "MODEL_TRANSFER")
public synchronized ModelServiceProto.ModelTransferResponse modelTransfer(Context context, InboundPackage data) {
ModelServiceProto.ModelTransferRequest req = (ModelServiceProto.ModelTransferRequest) data.getBody();
ModelServiceProto.ModelTransferResponse.Builder responseBuilder = ModelServiceProto.ModelTransferResponse.newBuilder();
if (!MetaInfo.PROPERTY_MODEL_SYNC) {
return responseBuilder.setStatusCode(StatusCode.MODEL_SYNC_ERROR)
.setMessage("no synchronization allowed, to use this function, please configure model.synchronize=true")
.build();
}
//String serviceId = req.getServiceId();
String tableName = req.getTableName();
String namespace = req.getNamespace();
logger.info("model transfer by tableName:{}, namespace:{}", tableName, namespace);
Model model;
// if (StringUtils.isNotBlank(serviceId)) {
// model = modelManager.queryModel(serviceId);
// } else {
model = modelManager.queryModel(tableName, namespace);
//}
if (model == null) {
logger.error("model {}_{} is not exist", tableName, namespace);
// throw new ModelNullException("model is not exist ");
return responseBuilder.setStatusCode(StatusCode.MODEL_NULL)
.setMessage("model is not exist")
.build();
}
byte[] cacheData = modelManager.getModelCacheData(context, model.getTableName(), model.getNamespace());
if (cacheData == null) {
logger.error("model {}_{} cache data is null", model.getTableName(), model.getNamespace());
// throw new ModelNullException("model cache data is null");
return responseBuilder.setStatusCode(StatusCode.MODEL_NULL)
.setMessage("model cache data is null")
.build();
}
responseBuilder.setStatusCode(StatusCode.SUCCESS).setMessage(Dict.SUCCESS)
.setModelData(ByteString.copyFrom(JsonUtil.object2Json(model).getBytes()))
.setCacheData(ByteString.copyFrom(cacheData));
return responseBuilder.build();
}
@Override
protected Object transformExceptionInfo(Context context, ExceptionInfo data) {
String actionType = context.getActionType();
if (data != null) {
int code = data.getCode();
String msg = data.getMessage() != null ? data.getMessage().toString() : "";
if (StringUtils.isNotEmpty(actionType)) {
switch (actionType) {
case "MODEL_LOAD":
;
case "MODEL_PUBLISH_ONLINE":
ReturnResult returnResult = new ReturnResult();
returnResult.setRetcode(code);
returnResult.setRetmsg(msg);
return returnResult;
case "QUERY_MODEL":
ModelServiceProto.QueryModelResponse queryModelResponse = ModelServiceProto.QueryModelResponse.newBuilder().setRetcode(code).setMessage(msg).build();
return queryModelResponse;
case "UNLOAD":
ModelServiceProto.UnloadResponse unloadResponse = ModelServiceProto.UnloadResponse.newBuilder().setStatusCode(code).setMessage(msg).build();
return unloadResponse;
case "UNBIND":
ModelServiceProto.UnbindResponse unbindResponse = ModelServiceProto.UnbindResponse.newBuilder().setStatusCode(code).setMessage(msg).build();
return unbindResponse;
}
}
}
return null;
}
@Override
protected void printFlowLog(Context context) {
Method method = (Method) this.getMethodMap().get(context.getActionType());
flowLogger.info("{}|{}|{}|{}|{}|{}|{}|{}",
context.getCaseId(), context.getReturnCode(), context.getCostTime(),
context.getDownstreamCost(), serviceName + "." + method.getName(), 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) : ""
);
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/common/provider/CommonServiceProvider.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/common/provider/CommonServiceProvider.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.provider;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.networking.common.CommonServiceProto;
import com.webank.ai.fate.register.common.Constants;
import com.webank.ai.fate.register.common.RouterMode;
import com.webank.ai.fate.register.common.ServiceWrapper;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.common.health.HealthCheckResult;
import com.webank.ai.fate.serving.common.flow.FlowCounterManager;
import com.webank.ai.fate.serving.common.flow.JvmInfo;
import com.webank.ai.fate.serving.common.flow.JvmInfoCounter;
import com.webank.ai.fate.serving.common.flow.MetricNode;
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.Context;
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.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.grpc.service.HealthCheckEndPointService;
import com.webank.ai.fate.serving.guest.provider.AbstractServingServiceProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
@FateService(name = "commonService", preChain = {
"requestOverloadBreaker",
}, postChain = {
})
@Service
public class CommonServiceProvider extends AbstractServingServiceProvider {
@Autowired
HealthCheckEndPointService healthCheckEndPointService;
@Autowired
FlowCounterManager flowCounterManager;
@Autowired(required = false)
ZookeeperRegistry zookeeperRegistry;
@Override
protected Object transformExceptionInfo(Context context, ExceptionInfo data) {
CommonServiceProto.CommonResponse.Builder builder = CommonServiceProto.CommonResponse.newBuilder();
builder.setStatusCode(data.getCode());
builder.setMessage(data.getMessage());
return builder.build();
}
@FateServiceMethod(name = "QUERY_METRICS")
public CommonServiceProto.CommonResponse queryMetrics(Context context, InboundPackage inboundPackage) {
CommonServiceProto.QueryMetricRequest queryMetricRequest = (CommonServiceProto.QueryMetricRequest) inboundPackage.getBody();
long beginMs = queryMetricRequest.getBeginMs();
long endMs = queryMetricRequest.getEndMs();
String sourceName = queryMetricRequest.getSource();
CommonServiceProto.MetricType type = queryMetricRequest.getType();
List<MetricNode> metricNodes = null;
if (type.equals(CommonServiceProto.MetricType.INTERFACE)) {
if (StringUtils.isBlank(sourceName)) {
metricNodes = flowCounterManager.queryAllMetrics(beginMs, 300);
} else {
metricNodes = flowCounterManager.queryMetrics(beginMs, endMs, sourceName);
}
} else {
metricNodes = flowCounterManager.queryModelMetrics(beginMs, endMs, sourceName);
}
CommonServiceProto.CommonResponse.Builder builder = CommonServiceProto.CommonResponse.newBuilder();
String response = metricNodes != null ? JsonUtil.object2Json(metricNodes) : "";
builder.setStatusCode(StatusCode.SUCCESS);
builder.setData(ByteString.copyFrom(response.getBytes()));
return builder.build();
}
@FateServiceMethod(name = "UPDATE_FLOW_RULE")
public CommonServiceProto.CommonResponse updateFlowRule(Context context, InboundPackage inboundPackage) {
CommonServiceProto.UpdateFlowRuleRequest updateFlowRuleRequest = (CommonServiceProto.UpdateFlowRuleRequest) inboundPackage.getBody();
flowCounterManager.setAllowQps(updateFlowRuleRequest.getSource(), updateFlowRuleRequest.getAllowQps());
CommonServiceProto.CommonResponse.Builder builder = CommonServiceProto.CommonResponse.newBuilder();
builder.setStatusCode(StatusCode.SUCCESS);
builder.setMessage(Dict.SUCCESS);
return builder.build();
}
@FateServiceMethod(name = "LIST_PROPS")
public CommonServiceProto.CommonResponse listProps(Context context, InboundPackage inboundPackage) {
CommonServiceProto.QueryPropsRequest queryPropsRequest = (CommonServiceProto.QueryPropsRequest) inboundPackage.getBody();
String keyword = queryPropsRequest.getKeyword();
CommonServiceProto.CommonResponse.Builder builder = CommonServiceProto.CommonResponse.newBuilder();
builder.setStatusCode(StatusCode.SUCCESS);
Map metaInfoMap = MetaInfo.toMap();
Map map;
if (StringUtils.isNotBlank(keyword)) {
Map resultMap = Maps.newHashMap();
metaInfoMap.forEach((k, v) -> {
if (String.valueOf(k).toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
resultMap.put(k, v);
}
});
map = resultMap;
} else {
map = metaInfoMap;
}
builder.setData(ByteString.copyFrom(JsonUtil.object2Json(map).getBytes()));
return builder.build();
}
@FateServiceMethod(name = "QUERY_JVM")
public CommonServiceProto.CommonResponse listJvmMem(Context context, InboundPackage inboundPackage) {
try {
CommonServiceProto.CommonResponse.Builder builder = CommonServiceProto.CommonResponse.newBuilder();
builder.setStatusCode(StatusCode.SUCCESS);
List<JvmInfo> jvmInfos = JvmInfoCounter.getMemInfos();
builder.setData(ByteString.copyFrom(JsonUtil.object2Json(jvmInfos).getBytes()));
return builder.build();
} catch (Exception e) {
throw new SysException(e.getMessage());
}
}
@FateServiceMethod(name = "UPDATE_SERVICE")
public CommonServiceProto.CommonResponse updateService(Context context, InboundPackage inboundPackage) {
try {
Preconditions.checkArgument(zookeeperRegistry != null);
CommonServiceProto.UpdateServiceRequest request = (CommonServiceProto.UpdateServiceRequest) inboundPackage.getBody();
String url = request.getUrl();
String routerMode = request.getRouterMode();
int weight = request.getWeight();
//long version = request.getVersion();
URL originUrl = URL.valueOf(url);
boolean hasChange = false;
ServiceWrapper serviceWrapper = new ServiceWrapper();
HashMap<String, String> parameters = Maps.newHashMap(originUrl.getParameters());
if (RouterMode.contains(routerMode) && !routerMode.equalsIgnoreCase(originUrl.getParameter(Constants.ROUTER_MODE))) {
parameters.put(Constants.ROUTER_MODE, routerMode);
serviceWrapper.setRouterMode(routerMode);
hasChange = true;
}
String originWeight = originUrl.getParameter(Constants.WEIGHT_KEY);
if (weight != -1 && (originWeight == null || weight != Integer.parseInt(originWeight))) {
parameters.put(Constants.WEIGHT_KEY, String.valueOf(weight));
serviceWrapper.setWeight(weight);
hasChange = true;
}
String originVersion = originUrl.getParameter(Constants.VERSION_KEY);
// if (version != -1 && (originVersion == null || version != Long.parseLong(originVersion))) {
// parameters.put(Constants.VERSION_KEY, String.valueOf(version));
// serviceWrapper.setVersion(version);
// hasChange = true;
// }
CommonServiceProto.CommonResponse.Builder builder = CommonServiceProto.CommonResponse.newBuilder();
builder.setStatusCode(StatusCode.SUCCESS);
if (hasChange) {
// update service cache map
ConcurrentMap<String, ServiceWrapper> serviceCacheMap = zookeeperRegistry.getServiceCacheMap();
ServiceWrapper cacheServiceWrapper = serviceCacheMap.get(originUrl.getEnvironment() + "/" + originUrl.getPath());
if (cacheServiceWrapper == null) {
cacheServiceWrapper = new ServiceWrapper();
}
cacheServiceWrapper.update(serviceWrapper);
serviceCacheMap.put(originUrl.getEnvironment() + "/" + originUrl.getPath(), cacheServiceWrapper);
boolean success = zookeeperRegistry.tryUnregister(originUrl);
if (success) {
URL newUrl = new URL(originUrl.getProtocol(), originUrl.getProject(), originUrl.getEnvironment(),
originUrl.getHost(), originUrl.getPort(), originUrl.getPath(), parameters);
zookeeperRegistry.register(newUrl);
builder.setMessage(Dict.SUCCESS);
} else {
builder.setStatusCode(StatusCode.UNREGISTER_ERROR);
builder.setMessage("no node");
}
} else {
builder.setMessage("no change");
}
return builder.build();
} catch (Exception e) {
throw new SysException(e.getMessage());
}
}
@FateServiceMethod(name = "CHECK_HEALTH")
public CommonServiceProto.CommonResponse checkHealthService(Context context, InboundPackage inboundPackage) {
CommonServiceProto.CommonResponse.Builder builder = CommonServiceProto.CommonResponse.newBuilder();
HealthCheckResult healthCheckResult = healthCheckEndPointService.check(context);
// Map<String,Object> resultMap = new HashMap<>();
// List<Object> machineInfoList = new ArrayList<>();
// List<String> warnList = Lists.newArrayList();
// List<String> errorList = Lists.newArrayList();
// 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)));
// machineInfoList.add(CPUInfo);
//
// 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));
// machineInfoList.add(memoryInfo);
// } catch (Exception e) {
// // e.printStackTrace();
// }
// resultMap.put("MachineInfo",machineInfoList);
//
// resultMap.put(Dict.ERROR_LIST,errorList);
// resultMap.put(Dict.WARN_LIST,warnList);
// //check whether fate flow is connected
// String fullUrl = MetaInfo.PROPERTY_MODEL_TRANSFER_URL;
// if(StringUtils.isNotBlank(fullUrl)) {
// String host = fullUrl.substring(fullUrl.indexOf('/') + 2, fullUrl.lastIndexOf(':'));
// int port = Integer.parseInt(fullUrl.substring(fullUrl.lastIndexOf(':') + 1,
// fullUrl.indexOf('/', fullUrl.lastIndexOf(':'))));
// TelnetClient telnetClient = new TelnetClient("vt200");
// telnetClient.setDefaultTimeout(5000);
// boolean isConnected = false;
// try {
// telnetClient.connect(host, port);
// isConnected = true;
// telnetClient.disconnect();
// } catch (Exception e) {
// // e.printStackTrace();
// }
// if(!isConnected){
// String result1 = String.format("default fateflow config %s can not connected", fullUrl);
// warnList.add(result1);
// }
//
// resultMap.put("FateFlow Status", isConnected);
// }
//
//// host = MetaInfo.PROPERTY_REDIS_IP;
//// port = MetaInfo.PROPERTY_REDIS_PORT;
//// isConnected = false;
//// if(MetaInfo.PROPERTY_CACHE_TYPE.equals(Dict.CACHE_TYPE_REDIS)) {
//// try {
//// telnetClient.connect(host, port);
//// isConnected = true;
//// telnetClient.disconnect();
//// } catch (Exception e) {
//// e.printStackTrace();
//// }
//// resultMap.put("Redis Status", isConnected);
//// }
builder.setStatusCode(StatusCode.SUCCESS);
builder.setData(ByteString.copyFrom(JsonUtil.object2Json(healthCheckResult).getBytes()));
return builder.build();
}
@Override
protected void printFlowLog(Context context) {
Method method = (Method) this.getMethodMap().get(context.getActionType());
flowLogger.info("{}|{}|{}|{}|{}|{}|{}|{}",
context.getCaseId(), context.getReturnCode(), context.getCostTime(),
context.getDownstreamCost(), serviceName + "." + method.getName(), 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) : ""
);
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/common/interceptors/DefaultPostProcess.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/common/interceptors/DefaultPostProcess.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.interceptors;
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 org.springframework.stereotype.Component;
@Component
public class DefaultPostProcess extends AbstractInterceptor {
@Override
public void doPostProcess(Context context, InboundPackage inboundPackage, OutboundPackage 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-server/src/main/java/com/webank/ai/fate/serving/common/interceptors/RequestOverloadBreaker.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/common/interceptors/RequestOverloadBreaker.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.interceptors;
import com.webank.ai.fate.serving.common.flow.FlowCounterManager;
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.exceptions.OverLoadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Description TODO
* @Author
**/
@Service
public class RequestOverloadBreaker implements Interceptor {
Logger logger = LoggerFactory.getLogger(RequestOverloadBreaker.class);
@Autowired
FlowCounterManager flowCounterManager;
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
String resource = context.getResourceName();
boolean pass = flowCounterManager.pass(resource, 1);
if (!pass) {
flowCounterManager.block(context.getServiceName(), 1);
logger.warn("request was block by over load, service name: {}", context.getServiceName());
throw new OverLoadException("request was block by over load, service name: " + context.getServiceName());
}
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/common/interceptors/AbstractInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/common/interceptors/AbstractInterceptor.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.interceptors;
import com.webank.ai.fate.serving.common.rpc.core.Interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
public class AbstractInterceptor<req, resp> implements Interceptor<req, resp>, EnvironmentAware {
protected Environment environment;
Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
protected boolean checkAddress(String address) {
return address.indexOf(":") > 0;
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/common/interceptors/FederationRouterInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/common/interceptors/FederationRouterInterceptor.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.interceptors;
import com.webank.ai.fate.register.router.RouterService;
import com.webank.ai.fate.register.url.URL;
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.bean.Dict;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.NoRouterInfoException;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FederationRouterInterceptor extends AbstractInterceptor {
@Autowired(required = false)
RouterService routerService;
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
RouterInfo routerInfo = new RouterInfo();
String address = null;
if (routerService == null) {
address = MetaInfo.PROPERTY_PROXY_ADDRESS;
if (!checkAddress(address)) {
throw new NoRouterInfoException(StatusCode.GUEST_ROUTER_ERROR, "address is error in config file");
}
String[] args = address.split(":");
routerInfo.setHost(args[0]);
routerInfo.setPort(new Integer(args[1]));
} else {
List<URL> urls = routerService.router(Dict.SERVICE_PROXY, Dict.ONLINE_ENVIRONMENT, Dict.UNARYCALL);
if (urls != null && urls.size() > 0) {
URL url = urls.get(0);
String ip = url.getHost();
int port = url.getPort();
routerInfo.setHost(ip);
routerInfo.setPort(port);
} else {
throw new NoRouterInfoException(StatusCode.GUEST_ROUTER_ERROR, "serving-proxy address is not found in zk");
}
}
context.setRouterInfo(routerInfo);
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/common/interceptors/MonitorInterceptor.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/common/interceptors/MonitorInterceptor.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.interceptors;
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 org.springframework.stereotype.Service;
@Service
public class MonitorInterceptor extends AbstractInterceptor {
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
context.preProcess();
}
@Override
public void doPostProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
context.postProcess(inboundPackage.getBody(), outboundPackage.getData());
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/event/CacheEventData.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/event/CacheEventData.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.event;
public class CacheEventData {
String key;
Object data;
public CacheEventData(String key, Object data) {
this.key = key;
this.data = data;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-server/src/main/java/com/webank/ai/fate/serving/event/ErrorEventHandler.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/event/ErrorEventHandler.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.event;
import com.webank.ai.fate.register.utils.StringUtils;
import com.webank.ai.fate.serving.common.async.AbstractAsyncMessageProcessor;
import com.webank.ai.fate.serving.common.async.AsyncMessageEvent;
import com.webank.ai.fate.serving.common.async.Subscribe;
import com.webank.ai.fate.serving.common.flow.FlowCounterManager;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ErrorEventHandler extends AbstractAsyncMessageProcessor implements InitializingBean {
@Autowired
FlowCounterManager flowCounterManager;
@Subscribe(value = Dict.EVENT_ERROR)
public void handleMetricsEvent(AsyncMessageEvent event) {
Context context = event.getContext();
String serviceName = context.getServiceName();
String actionType = context.getActionType();
String resource = StringUtils.isNotEmpty(actionType) ? actionType : serviceName;
// flowCounterManager.exception(resource);
// if (context instanceof ServingServerContext) {
// ServingServerContext servingServerContext = (ServingServerContext) context;
// Model model = servingServerContext.getModel();
// if (model != null) {
// flowCounterManager.exception(model.getResourceName());
// }
// }
}
@Override
public void afterPropertiesSet() throws Exception {
// String clazz = environment.getProperty(ALTER_CLASS, "com.webank.ai.fate.serving.core.upload.MockAlertInfoUploader");
// alertInfoUploader = (AlertInfoUploader) InferenceUtils.getClassByName(clazz);
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/event/SingleCacheEventHandler.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/event/SingleCacheEventHandler.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.event;
import com.webank.ai.fate.serving.common.async.AbstractAsyncMessageProcessor;
import com.webank.ai.fate.serving.common.async.AsyncMessageEvent;
import com.webank.ai.fate.serving.common.async.Subscribe;
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.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class SingleCacheEventHandler extends AbstractAsyncMessageProcessor {
Logger logger = LoggerFactory.getLogger(SingleCacheEventHandler.class);
@Autowired
Cache cache;
@Subscribe(value = Dict.EVENT_SET_INFERENCE_CACHE)
public void handleMetricsEvent(AsyncMessageEvent event) {
CacheEventData cacheEventData = (CacheEventData) event.getData();
Map map = (Map) cacheEventData.getData();
cache.put(cacheEventData.getKey(), JsonUtil.object2Json(map));
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/event/BatchCacheEventHandler.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/event/BatchCacheEventHandler.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.event;
import com.webank.ai.fate.serving.common.async.AbstractAsyncMessageProcessor;
import com.webank.ai.fate.serving.common.async.AsyncMessageEvent;
import com.webank.ai.fate.serving.common.async.Subscribe;
import com.webank.ai.fate.serving.common.cache.Cache;
import com.webank.ai.fate.serving.core.bean.Dict;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BatchCacheEventHandler extends AbstractAsyncMessageProcessor {
Logger logger = LoggerFactory.getLogger(BatchCacheEventHandler.class);
@Autowired
Cache cache;
@Subscribe(value = Dict.EVENT_SET_BATCH_INFERENCE_CACHE)
public void handleMetricsEvent(AsyncMessageEvent event) {
List<Cache.DataWrapper> lists = (List<Cache.DataWrapper>) event.getData();
if (lists != null) {
cache.put(lists);
}
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/grpc/service/HostInferenceService.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/grpc/service/HostInferenceService.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.grpc.service;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.networking.proxy.DataTransferServiceGrpc;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.api.networking.proxy.Proxy.Packet;
import com.webank.ai.fate.register.annotions.RegisterService;
import com.webank.ai.fate.register.common.Role;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
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.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.JsonUtil;
import com.webank.ai.fate.serving.core.utils.ThreadPoolUtil;
import com.webank.ai.fate.serving.host.provider.HostBatchInferenceProvider;
import com.webank.ai.fate.serving.host.provider.HostSingleInferenceProvider;
import io.grpc.stub.StreamObserver;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
@Service
public class HostInferenceService extends DataTransferServiceGrpc.DataTransferServiceImplBase {
private static ThreadPoolExecutor executor = ThreadPoolUtil.newThreadPoolExecutor();
@Autowired
HostBatchInferenceProvider hostBatchInferenceProvider;
@Autowired
HostSingleInferenceProvider hostSingleInferenceProvider;
@Override
@RegisterService(serviceName = Dict.UNARYCALL, useDynamicEnvironment = true, role = Role.HOST)
public void unaryCall(Proxy.Packet req, StreamObserver<Proxy.Packet> responseObserver) {
executor.submit(() -> {
String actionType = req.getHeader().getCommand().getName();
ServingServerContext context = (ServingServerContext) prepareContext();
String namespace = req.getHeader().getTask().getModel().getNamespace();
String tableName = req.getHeader().getTask().getModel().getTableName();
context.setActionType(actionType);
context.setVersion(req.getHeader().getOperator());
if (StringUtils.isBlank(context.getVersion()) || Double.parseDouble(context.getVersion()) < 200) {
// 1.x
Map hostFederatedParams = JsonUtil.json2Object(req.getBody().getValue().toStringUtf8(), Map.class);
Map partnerModelInfo = (Map) hostFederatedParams.get("partnerModelInfo");
namespace = partnerModelInfo.get("namespace").toString();
tableName = partnerModelInfo.get("name").toString();
}
context.setModelNamesapce(namespace);
context.setModelTableName(tableName);
context.setCaseId(req.getAuth().getNonce());
Object result = null;
byte[] data = req.getBody().getValue().toByteArray();
InboundPackage inboundPackage = new InboundPackage();
switch (actionType) {
case Dict.FEDERATED_INFERENCE:
context.setActionType(Dict.FEDERATED_INFERENCE);
inboundPackage.setBody(data);
OutboundPackage singleInferenceOutbound = hostSingleInferenceProvider.service(context, inboundPackage);
result = singleInferenceOutbound.getData();
break;
case Dict.FEDERATED_INFERENCE_FOR_TREE:
context.setActionType(Dict.FEDERATED_INFERENCE_FOR_TREE);
inboundPackage.setBody(data);
OutboundPackage secureBoostTreeOutboundPackage = hostSingleInferenceProvider.service(context, inboundPackage);
result = secureBoostTreeOutboundPackage.getData();
break;
case Dict.REMOTE_METHOD_BATCH:
inboundPackage.setBody(data);
OutboundPackage outboundPackage = this.hostBatchInferenceProvider.service(context, inboundPackage);
ReturnResult responseResult = null;
result = (ReturnResult) outboundPackage.getData();
break;
default:
responseResult = new ReturnResult();
responseResult.setRetcode(StatusCode.HOST_UNSUPPORTED_COMMAND_ERROR);
break;
}
Packet.Builder packetBuilder = Packet.newBuilder();
packetBuilder.setBody(Proxy.Data.newBuilder()
.setValue(ByteString.copyFrom(JsonUtil.object2Json(result).getBytes()))
.build());
responseObserver.onNext(packetBuilder.build());
responseObserver.onCompleted();
});
}
private Context prepareContext() {
ServingServerContext context = new ServingServerContext();
return 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-server/src/main/java/com/webank/ai/fate/serving/grpc/service/GuestInferenceService.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/grpc/service/GuestInferenceService.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.grpc.service;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.serving.InferenceServiceGrpc;
import com.webank.ai.fate.api.serving.InferenceServiceProto;
import com.webank.ai.fate.api.serving.InferenceServiceProto.InferenceMessage;
import com.webank.ai.fate.register.annotions.RegisterService;
import com.webank.ai.fate.register.common.Role;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
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.BatchInferenceResult;
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.utils.ObjectTransform;
import com.webank.ai.fate.serving.core.utils.ThreadPoolUtil;
import com.webank.ai.fate.serving.guest.provider.GuestBatchInferenceProvider;
import com.webank.ai.fate.serving.guest.provider.GuestSingleInferenceProvider;
import io.grpc.stub.StreamObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.ThreadPoolExecutor;
@Service
public class GuestInferenceService extends InferenceServiceGrpc.InferenceServiceImplBase {
static final String BATCH_INFERENCE = "batchInference";
static final String INFERENCE = "inference";
private static ThreadPoolExecutor executor = ThreadPoolUtil.newThreadPoolExecutor();
@Autowired
GuestBatchInferenceProvider guestBatchInferenceProvider;
@Autowired
GuestSingleInferenceProvider guestSingleInferenceProvider;
@Override
@RegisterService(useDynamicEnvironment = true, serviceName = INFERENCE,role = Role.GUEST)
public void inference(InferenceMessage req, StreamObserver<InferenceMessage> responseObserver) {
executor.submit(() -> {
InferenceMessage.Builder response = InferenceMessage.newBuilder();
Context context = prepareContext();
InboundPackage inboundPackage = new InboundPackage();
inboundPackage.setBody(req);
OutboundPackage outboundPackage = this.guestSingleInferenceProvider.service(context, inboundPackage);
ReturnResult returnResult = (ReturnResult) outboundPackage.getData();
response.setBody(ByteString.copyFrom(ObjectTransform.bean2Json(returnResult).getBytes()));
responseObserver.onNext(response.build());
responseObserver.onCompleted();
});
}
@Override
@RegisterService(useDynamicEnvironment = true, serviceName = BATCH_INFERENCE,role = Role.GUEST)
public void batchInference(InferenceServiceProto.InferenceMessage req, StreamObserver<InferenceServiceProto.InferenceMessage> responseObserver) {
executor.submit(() -> {
InferenceMessage.Builder response = InferenceMessage.newBuilder();
Context context = prepareContext();
InboundPackage inboundPackage = new InboundPackage();
inboundPackage.setBody(req);
OutboundPackage outboundPackage = this.guestBatchInferenceProvider.service(context, inboundPackage);
BatchInferenceResult returnResult = (BatchInferenceResult) outboundPackage.getData();
response.setBody(ByteString.copyFrom(ObjectTransform.bean2Json(returnResult).getBytes()));
responseObserver.onNext(response.build());
responseObserver.onCompleted();
});
}
private Context prepareContext() {
ServingServerContext context = new ServingServerContext();
return 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-server/src/main/java/com/webank/ai/fate/serving/grpc/service/ServiceOverloadProtectionHandle.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/grpc/service/ServiceOverloadProtectionHandle.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.grpc.service;
import io.grpc.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServiceOverloadProtectionHandle implements ServerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ServiceOverloadProtectionHandle.class);
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata, ServerCallHandler<ReqT, RespT> serverCallHandler) {
String fullMethodName = serverCall.getMethodDescriptor().getFullMethodName();
String serviceName = fullMethodName.split("/")[1];
if (StringUtils.isBlank(serviceName)) {
serverCall.close(Status.DATA_LOSS, metadata);
}
ServerCall.Listener<ReqT> delegate = serverCallHandler.startCall(serverCall, metadata);
return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(delegate) {
@Override
public void onHalfClose() {
try {
super.onHalfClose();
} catch (Exception e) {
logger.error("ServiceException:", e);
serverCall.close(Status.CANCELLED.withCause(e).withDescription(e.getMessage()), metadata);
}
}
@Override
public void onCancel() {
super.onCancel();
}
@Override
public void onComplete() {
super.onComplete();
}
};
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/grpc/service/HealthCheckEndPointService.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/grpc/service/HealthCheckEndPointService.java | package com.webank.ai.fate.serving.grpc.service;
import com.webank.ai.fate.register.router.RouterService;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.common.health.*;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.utils.TelnetUtil;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.model.ModelManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
public class HealthCheckEndPointService implements HealthCheckAware{
@Autowired(required = false)
private RouterService routerService;
@Autowired
private ModelManager modelManager;
private void checkFateFlow(HealthCheckResult healthCheckResult){
if (routerService != null) {
String transferUri = "flow/online/transfer";
URL url = URL.valueOf(transferUri);
List urls = routerService.router(url);
if(urls== null||urls.size()==0){
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_FATEFLOW_IN_ZK.getItemName(), "fateflow is not found in zookeeper ",HealthCheckStatus.warn));
}else{
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_FATEFLOW_IN_ZK.getItemName(), "fateflow is found in zookeeper",HealthCheckStatus.ok));
}
}
}
private void checkModel(HealthCheckResult healthCheckResult){
List<Model> models = modelManager.listAllModel();
if(models==null||models.size()>0){
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_MODEL_LOADED.getItemName(),"model is loaded",HealthCheckStatus.ok));
}
else{
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_MODEL_LOADED.getItemName(),"model is not loaded",HealthCheckStatus.warn));
}
}
private void checkDefaultFateflow(HealthCheckResult healthCheckResult){
String fullUrl = MetaInfo.PROPERTY_MODEL_TRANSFER_URL;
if(StringUtils.isNotBlank(fullUrl)) {
String host = fullUrl.substring(fullUrl.indexOf('/') + 2, fullUrl.lastIndexOf(':'));
int port = Integer.parseInt(fullUrl.substring(fullUrl.lastIndexOf(':') + 1,
fullUrl.indexOf('/', fullUrl.lastIndexOf(':'))));
boolean isConnected = TelnetUtil.tryTelnet(host, port);
if (!isConnected) {
String result1 = String.format(" %s can not connected", fullUrl);
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_DEFAULT_FATEFLOW.getItemName(),result1,HealthCheckStatus.warn));
}else{
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_DEFAULT_FATEFLOW.getItemName(),"default fateflow url is ok",HealthCheckStatus.ok));
}
}
}
@Autowired(required = false)
ZookeeperRegistry zookeeperRegistry;
private void checkZkConfig(HealthCheckResult healthCheckResult){
if(zookeeperRegistry==null){
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_ZOOKEEPER_CONFIG.getItemName(),"zookeeper is not used or config is invalid",HealthCheckStatus.warn));
}else{
boolean isConnected = zookeeperRegistry.getZkClient().isConnected();
if(isConnected){
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_ZOOKEEPER_CONFIG.getItemName(),"zookeeper can not touched",HealthCheckStatus.error));
}
}
}
private void metircCheck(HealthCheckResult healthCheckResult){
}
@Override
public HealthCheckResult check(Context context) {
if(MetaInfo.PROPERTY_ALLOW_HEALTH_CHECK) {
HealthCheckItemEnum[] items = HealthCheckItemEnum.values();
HealthCheckResult healthCheckResult = new HealthCheckResult();
Arrays.stream(items).filter((item) -> {
HealthCheckComponent healthCheckComponent = item.getComponent();
return healthCheckComponent == HealthCheckComponent.ALL || healthCheckComponent == HealthCheckComponent.SERVINGSERVER;
}).forEach((item) -> {
switch (item) {
case CHECK_MEMORY_USAGE:
HealthCheckUtil.memoryCheck(healthCheckResult);
break;
case CHECK_MODEL_LOADED:
checkModel(healthCheckResult);
break;
case CHECK_FATEFLOW_IN_ZK:
checkFateFlow(healthCheckResult);
break;
case CHECK_DEFAULT_FATEFLOW:
checkDefaultFateflow(healthCheckResult);
break;
}
}
);
return healthCheckResult;
}else{
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-server/src/main/java/com/webank/ai/fate/serving/grpc/service/ServiceExceptionHandler.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/grpc/service/ServiceExceptionHandler.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.grpc.service;
import io.grpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServiceExceptionHandler implements ServerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ServiceExceptionHandler.class);
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
Metadata requestHeaders, ServerCallHandler<ReqT, RespT> next) {
ServerCall.Listener<ReqT> delegate = next.startCall(call, requestHeaders);
return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(delegate) {
@Override
public void onHalfClose() {
try {
super.onHalfClose();
} catch (Exception e) {
logger.error("ServiceException:", e);
call.close(Status.INTERNAL
.withCause(e)
.withDescription(e.getMessage()), new Metadata());
}
}
};
}
}
| 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-server/src/main/java/com/webank/ai/fate/serving/grpc/service/ModelService.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/grpc/service/ModelService.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.grpc.service;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceGrpc;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceProto;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceProto.PublishRequest;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceProto.PublishResponse;
import com.webank.ai.fate.register.annotions.RegisterService;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
import com.webank.ai.fate.serving.common.provider.ModelServiceProvider;
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.bean.ModelActionType;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
@Service
public class ModelService extends ModelServiceGrpc.ModelServiceImplBase {
@Autowired
ModelServiceProvider modelServiceProvider;
Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
@RegisterService(serviceName = "publishLoad")
public synchronized void publishLoad(PublishRequest req, StreamObserver<PublishResponse> responseObserver) {
Context context = prepareContext(ModelActionType.MODEL_LOAD.name());
InboundPackage<PublishRequest> inboundPackage = new InboundPackage();
inboundPackage.setBody(req);
OutboundPackage outboundPackage = modelServiceProvider.service(context, inboundPackage);
ReturnResult returnResult = (ReturnResult) outboundPackage.getData();
logger.info("PublishRequest = {}",req);
PublishResponse.Builder builder = PublishResponse.newBuilder();
builder.setStatusCode(Integer.valueOf(returnResult.getRetcode()));
builder.setMessage(returnResult.getRetmsg() != null ? returnResult.getRetmsg() : "");
builder.setData(ByteString.copyFrom(JsonUtil.object2Json(returnResult.getData()).getBytes()));
responseObserver.onNext(builder.build());
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = "publishOnline")
public synchronized void publishOnline(PublishRequest req, StreamObserver<PublishResponse> responseObserver) {
Context context = prepareContext(ModelActionType.MODEL_PUBLISH_ONLINE.name());
InboundPackage<ModelServiceProto.PublishRequest> inboundPackage = new InboundPackage();
inboundPackage.setBody(req);
OutboundPackage outboundPackage = modelServiceProvider.service(context, inboundPackage);
ReturnResult returnResult = (ReturnResult) outboundPackage.getData();
PublishResponse.Builder builder = PublishResponse.newBuilder();
builder.setStatusCode(Integer.valueOf(returnResult.getRetcode()));
builder.setMessage(returnResult.getRetmsg() != null ? returnResult.getRetmsg() : "");
builder.setData(ByteString.copyFrom(JsonUtil.object2Json(returnResult.getData()).getBytes()));
responseObserver.onNext(builder.build());
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = "publishBind")
public synchronized void publishBind(PublishRequest req, StreamObserver<PublishResponse> responseObserver) {
Context context = prepareContext(ModelActionType.MODEL_PUBLISH_ONLINE.name());
InboundPackage<ModelServiceProto.PublishRequest> inboundPackage = new InboundPackage();
inboundPackage.setBody(req);
OutboundPackage outboundPackage = modelServiceProvider.service(context, inboundPackage);
ReturnResult returnResult = (ReturnResult) outboundPackage.getData();
PublishResponse.Builder builder = PublishResponse.newBuilder();
builder.setStatusCode(Integer.valueOf(returnResult.getRetcode()));
builder.setMessage(returnResult.getRetmsg() != null ? returnResult.getRetmsg() : "");
builder.setData(ByteString.copyFrom(JsonUtil.object2Json(returnResult.getData()).getBytes()));
responseObserver.onNext(builder.build());
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = "unload")
public synchronized void unload(ModelServiceProto.UnloadRequest request, StreamObserver<ModelServiceProto.UnloadResponse> responseObserver) {
Context context = prepareContext(ModelActionType.UNLOAD.name());
InboundPackage<ModelServiceProto.UnloadRequest> inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = modelServiceProvider.service(context, inboundPackage);
ModelServiceProto.UnloadResponse unloadResponse = (ModelServiceProto.UnloadResponse) outboundPackage.getData();
responseObserver.onNext(unloadResponse);
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = "unbind")
public synchronized void unbind(ModelServiceProto.UnbindRequest request, StreamObserver<ModelServiceProto.UnbindResponse> responseObserver) {
Context context = prepareContext(ModelActionType.UNBIND.name());
InboundPackage<ModelServiceProto.UnbindRequest> inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = modelServiceProvider.service(context, inboundPackage);
ModelServiceProto.UnbindResponse unbindResponse = (ModelServiceProto.UnbindResponse) outboundPackage.getData();
responseObserver.onNext(unbindResponse);
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = "fetchModel")
public void fetchModel(ModelServiceProto.FetchModelRequest request, StreamObserver<ModelServiceProto.FetchModelResponse> responseObserver) {
Context context = prepareContext(ModelActionType.FETCH_MODEL.name());
InboundPackage<ModelServiceProto.FetchModelRequest> inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = modelServiceProvider.service(context, inboundPackage);
ModelServiceProto.FetchModelResponse fetchModelResponse = (ModelServiceProto.FetchModelResponse) outboundPackage.getData();
responseObserver.onNext(fetchModelResponse);
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = "modelTransfer")
public void modelTransfer(ModelServiceProto.ModelTransferRequest request, StreamObserver<ModelServiceProto.ModelTransferResponse> responseObserver) {
Context context = prepareContext(ModelActionType.MODEL_TRANSFER.name());
InboundPackage<ModelServiceProto.ModelTransferRequest> inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = modelServiceProvider.service(context, inboundPackage);
ModelServiceProto.ModelTransferResponse modelTransferResponse = (ModelServiceProto.ModelTransferResponse) outboundPackage.getData();
responseObserver.onNext(modelTransferResponse);
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = "queryModel")
public void queryModel(ModelServiceProto.QueryModelRequest request, StreamObserver<ModelServiceProto.QueryModelResponse> responseObserver) {
Context context = prepareContext(ModelActionType.QUERY_MODEL.name());
InboundPackage<ModelServiceProto.QueryModelRequest> inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = modelServiceProvider.service(context, inboundPackage);
ModelServiceProto.QueryModelResponse queryModelResponse = (ModelServiceProto.QueryModelResponse) outboundPackage.getData();
responseObserver.onNext(queryModelResponse);
responseObserver.onCompleted();
}
private Context prepareContext(String actionType) {
ServingServerContext context = new ServingServerContext();
context.setActionType(actionType);
context.setCaseId(UUID.randomUUID().toString().replaceAll("-", ""));
return 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-server/src/main/java/com/webank/ai/fate/serving/grpc/service/CommonService.java | fate-serving-server/src/main/java/com/webank/ai/fate/serving/grpc/service/CommonService.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.grpc.service;
import com.webank.ai.fate.api.networking.common.CommonServiceGrpc;
import com.webank.ai.fate.api.networking.common.CommonServiceProto;
import com.webank.ai.fate.register.annotions.RegisterService;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
import com.webank.ai.fate.serving.common.provider.CommonServiceProvider;
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.CommonActionType;
import com.webank.ai.fate.serving.core.bean.Context;
import io.grpc.stub.StreamObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
@Service
public class CommonService extends CommonServiceGrpc.CommonServiceImplBase {
private static final String QUERY_METRICS = "queryMetrics";
private static final String UPDATE_FLOW_RULE = "updateFlowRule";
private static final String LIST_PROPS = "listProps";
private static final String QUERY_JVM = "queryJvm";
private static final String UPDATE_SERVICE = "updateService";
private static final String CHECK_HEALTH = "checkHealth";
@Autowired
CommonServiceProvider commonServiceProvider;
@Override
@RegisterService(serviceName = QUERY_METRICS)
public void queryMetrics(CommonServiceProto.QueryMetricRequest request, StreamObserver<CommonServiceProto.CommonResponse> responseObserver) {
Context context = prepareContext(CommonActionType.QUERY_METRICS.name());
InboundPackage inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = commonServiceProvider.service(context, inboundPackage);
CommonServiceProto.CommonResponse response = (CommonServiceProto.CommonResponse) outboundPackage.getData();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = UPDATE_FLOW_RULE)
public void updateFlowRule(CommonServiceProto.UpdateFlowRuleRequest request, StreamObserver<CommonServiceProto.CommonResponse> responseObserver) {
Context context = prepareContext(CommonActionType.UPDATE_FLOW_RULE.name());
InboundPackage inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = commonServiceProvider.service(context, inboundPackage);
CommonServiceProto.CommonResponse response = (CommonServiceProto.CommonResponse) outboundPackage.getData();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = LIST_PROPS)
public void listProps(CommonServiceProto.QueryPropsRequest request, StreamObserver<CommonServiceProto.CommonResponse> responseObserver) {
Context context = prepareContext(CommonActionType.LIST_PROPS.name());
InboundPackage inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = commonServiceProvider.service(context, inboundPackage);
CommonServiceProto.CommonResponse response = (CommonServiceProto.CommonResponse) outboundPackage.getData();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = QUERY_JVM)
public void queryJvmInfo(CommonServiceProto.QueryJvmInfoRequest request, StreamObserver<CommonServiceProto.CommonResponse> responseObserver) {
Context context = prepareContext(CommonActionType.QUERY_JVM.name());
InboundPackage inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = commonServiceProvider.service(context, inboundPackage);
CommonServiceProto.CommonResponse response = (CommonServiceProto.CommonResponse) outboundPackage.getData();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
@Override
@RegisterService(serviceName = UPDATE_SERVICE)
public void updateService(CommonServiceProto.UpdateServiceRequest request, StreamObserver<CommonServiceProto.CommonResponse> responseObserver) {
Context context = prepareContext(CommonActionType.UPDATE_SERVICE.name());
InboundPackage inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = commonServiceProvider.service(context, inboundPackage);
CommonServiceProto.CommonResponse response = (CommonServiceProto.CommonResponse) outboundPackage.getData();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
private Context prepareContext(String actionType) {
ServingServerContext context = new ServingServerContext();
context.setActionType(actionType);
context.setCaseId(UUID.randomUUID().toString().replaceAll("-", ""));
return context;
}
@Override
@RegisterService(serviceName = CHECK_HEALTH)
public void checkHealthService(CommonServiceProto.HealthCheckRequest request, StreamObserver<CommonServiceProto.CommonResponse> responseObserver) {
Context context = prepareContext(CommonActionType.CHECK_HEALTH.name());
InboundPackage inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = commonServiceProvider.service(context, inboundPackage);
CommonServiceProto.CommonResponse response = (CommonServiceProto.CommonResponse) outboundPackage.getData();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/DSLParser.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/DSLParser.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.federatedml;
import com.webank.ai.fate.serving.core.bean.Dict;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class DSLParser {
private static final Logger logger = LoggerFactory.getLogger(DSLParser.class);
private HashMap<String, String> componentModuleMap = new HashMap<String, String>();
private HashMap<String, Integer> componentIds = new HashMap<String, Integer>();
private HashMap<String, List<String>> downStream = new HashMap<String, List<String>>();
private HashMap<Integer, HashSet<Integer>> upInputs = new HashMap<Integer, HashSet<Integer>>();
private ArrayList<String> topoRankComponent = new ArrayList<String>();
private String modelPackage = "com.webank.ai.fate.serving.federatedml.model";
public int parseDagFromDSL(String jsonStr) {
logger.info("start parse dag from dsl");
try {
JSONObject dsl = new JSONObject(jsonStr);
JSONObject components = dsl.getJSONObject(Dict.DSL_COMPONENTS);
logger.info("start topo sort");
topoSort(components, this.topoRankComponent);
logger.info("components size is {}", this.topoRankComponent.size());
for (int i = 0; i < this.topoRankComponent.size(); ++i) {
this.componentIds.put(this.topoRankComponent.get(i), i);
}
for (int i = 0; i < topoRankComponent.size(); ++i) {
String componentName = topoRankComponent.get(i);
logger.info("component is {}", componentName);
JSONObject component = components.getJSONObject(componentName);
String[] codePath = ((String) component.get(Dict.DSL_CODE_PATH)).split("/", -1);
logger.info("code path splits is {}", codePath);
String module = codePath[codePath.length - 1];
logger.info("module is {}", module);
componentModuleMap.put(componentName, module);
JSONObject upData = null;
if (component.has(Dict.DSL_INPUT) && component.getJSONObject(Dict.DSL_INPUT).has(Dict.DSL_DATA)) {
upData = component.getJSONObject(Dict.DSL_INPUT).getJSONObject(Dict.DSL_DATA);
}
if (upData != null) {
int componentId = this.componentIds.get(componentName);
Iterator<String> dataKeyIterator = upData.keys();
while (dataKeyIterator.hasNext()) {
String dataKey = dataKeyIterator.next();
JSONArray data = upData.getJSONArray(dataKey);
for (int j = 0; j < data.length(); j++) {
String upComponent = data.getString(j).split("\\.", -1)[0];
if (!upInputs.containsKey(componentId)) {
upInputs.put(componentId, new HashSet<Integer>());
}
if (upComponent.equals(Dict.DSL_ARGS)) {
upInputs.get(componentId).add(-1);
} else {
upInputs.get(componentId).add(this.componentIds.get(upComponent));
}
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
logger.info("DSLParser init catch error:{}", ex);
}
logger.info("Finish init DSLParser");
return 0;
}
public void topoSort(JSONObject components, ArrayList<String> topoRankComponent) {
Stack<Integer> stk = new Stack();
HashMap<String, Integer> componentIndexMapping = new HashMap<String, Integer>(8);
ArrayList<String> componentList = new ArrayList<String>();
int index = 0;
Iterator<String> componentNames = components.keys();
while (componentNames.hasNext()) {
String componentName = componentNames.next();
componentIndexMapping.put(componentName, index);
++index;
componentList.add(componentName);
}
int[] inDegree = new int[index];
HashMap<Integer, ArrayList<Integer>> edges = new HashMap<Integer, ArrayList<Integer>>(8);
for (int i = 0; i < componentList.size(); ++i) {
String componentName = componentList.get(i);
JSONObject component = components.getJSONObject(componentName);
JSONObject upData = null;
if (component.has(Dict.DSL_INPUT) && component.getJSONObject(Dict.DSL_INPUT).has(Dict.DSL_DATA)) {
upData = component.getJSONObject(Dict.DSL_INPUT).getJSONObject(Dict.DSL_DATA);
}
Integer componentId = componentIndexMapping.get(componentName);
if (upData != null) {
Iterator<String> dataKeyIterator = upData.keys();
while (dataKeyIterator.hasNext()) {
String dataKey = dataKeyIterator.next();
JSONArray data = upData.getJSONArray(dataKey);
for (int j = 0; j < data.length(); j++) {
String upComponent = data.getString(j).split("\\.", -1)[0];
int upComponentId = -1;
if (!"args".equals(upComponent)) {
upComponentId = componentIndexMapping.get(upComponent);
}
if (upComponentId != -1) {
if (!edges.containsKey(upComponentId)) {
edges.put(upComponentId, new ArrayList<Integer>());
}
inDegree[componentId]++;
edges.get(upComponentId).add(componentId);
}
}
}
}
}
logger.info("end of construct edges");
for (int i = 0; i < index; i++) {
if (inDegree[i] == 0) {
stk.push(i);
}
}
while (!stk.empty()) {
Integer vertex = stk.pop();
topoRankComponent.add(componentList.get(vertex));
ArrayList<Integer> adjV = edges.get(vertex);
if (adjV == null) {
continue;
}
for (int i = 0; i < adjV.size(); ++i) {
Integer downV = adjV.get(i);
--inDegree[downV];
if (inDegree[downV] == 0) {
stk.push(downV);
}
}
}
logger.info("end of topo");
}
public HashMap<String, String> getComponentModuleMap() {
return this.componentModuleMap;
}
public ArrayList<String> getAllComponent() {
return this.topoRankComponent;
}
public HashSet<Integer> getUpInputComponents(int idx) {
if (this.upInputs.containsKey(idx)) {
return this.upInputs.get(idx);
} else {
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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/PipelineModelProcessor.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/PipelineModelProcessor.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.federatedml;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.core.mlmodel.buffer.PipelineProto;
import com.webank.ai.fate.serving.common.model.MergeInferenceAware;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.model.ModelProcessor;
import com.webank.ai.fate.serving.common.rpc.core.ErrorMessageUtil;
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.*;
import com.webank.ai.fate.serving.core.utils.EncryptUtils;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.federatedml.model.BaseComponent;
import com.webank.ai.fate.serving.federatedml.model.Returnable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.*;
import static com.webank.ai.fate.serving.common.rpc.core.ErrorMessageUtil.buildRemoteRpcErrorMsg;
import static com.webank.ai.fate.serving.common.rpc.core.ErrorMessageUtil.transformRemoteErrorCode;
import static com.webank.ai.fate.serving.core.bean.Dict.PIPLELINE_IN_MODEL;
public class PipelineModelProcessor implements ModelProcessor {
private static final Logger logger = LoggerFactory.getLogger(PipelineModelProcessor.class);
private static String flower = "pipeline.pipeline:Pipeline";
private static ForkJoinPool forkJoinPool = new ForkJoinPool();
private List<BaseComponent> pipeLineNode = new ArrayList<>();
private Map<String, BaseComponent> componentMap = new HashMap<String, BaseComponent>();
private Map<String, Map<String, Object>> componentParmasMap = new HashMap<String, Map<String, Object>>();
private DSLParser dslParser = new DSLParser();
private String modelPackage = "com.webank.ai.fate.serving.federatedml.model";
private int splitSize = MetaInfo.PROPERTY_BATCH_SPLIT_SIZE;
private Model model;
public List<BaseComponent> getPipeLineNode() {
return pipeLineNode;
}
public Map<String, BaseComponent> getComponentMap() {
return componentMap;
}
public DSLParser getDslParser() {
return dslParser;
}
public String getModelPackage() {
return modelPackage;
}
public int getSplitSize() {
return splitSize;
}
@Override
public BatchInferenceResult guestBatchInference(Context context, BatchInferenceRequest batchInferenceRequest, Map<String, Future> remoteFutureMap, long timeout) {
BatchInferenceResult batchFederatedResult = new BatchInferenceResult();
Map<Integer, Map<String, Object>> localResult = batchLocalInference(context, batchInferenceRequest);
Map<String, BatchInferenceResult> remoteResultMap = Maps.newHashMap();
remoteFutureMap.forEach((partyId, future) -> {
Proxy.Packet packet = null;
try {
BatchInferenceResult remoteInferenceResult = (BatchInferenceResult) future.get(timeout, TimeUnit.MILLISECONDS);
if (StatusCode.SUCCESS != remoteInferenceResult.getRetcode()) {
throw new RemoteRpcException(transformRemoteErrorCode(remoteInferenceResult.getRetcode()), buildRemoteRpcErrorMsg(remoteInferenceResult.getRetcode(), remoteInferenceResult.getRetmsg()));
}
remoteResultMap.put(partyId, remoteInferenceResult);
} catch (RemoteRpcException e) {
throw e;
} catch (Exception e) {
throw new RemoteRpcException("party id " + partyId + " remote error");
} finally {
context.setDownstreamCost(System.currentTimeMillis() - context.getDownstreamBegin());
}
});
batchFederatedResult = batchMergeHostResult(context, localResult, remoteResultMap);
return batchFederatedResult;
}
/**
* host 端只需要本地预测即可
*
* @param context
* @param batchHostFederatedParams
* @return
*/
@Override
public BatchInferenceResult hostBatchInference(Context context, BatchHostFederatedParams batchHostFederatedParams) {
Map<Integer, Map<String, Object>> localResult = batchLocalInference(context, batchHostFederatedParams);
BatchInferenceResult batchFederatedResult = new BatchInferenceResult();
localResult.forEach((index, data) -> {
BatchInferenceResult.SingleInferenceResult singleInferenceResult = new BatchInferenceResult.SingleInferenceResult();
if (data != null) {
int retcode = data.get(Dict.RET_CODE) != null ? (int) data.get(Dict.RET_CODE) : StatusCode.SYSTEM_ERROR;
data.remove(Dict.RET_CODE);
singleInferenceResult.setData(data);
singleInferenceResult.setIndex(index);
singleInferenceResult.setRetcode(retcode);
}
batchFederatedResult.getBatchDataList().add(singleInferenceResult);
});
batchFederatedResult.setRetcode(StatusCode.SUCCESS);
return batchFederatedResult;
}
@Override
public ReturnResult guestInference(Context context, InferenceRequest inferenceRequest, Map<String, Future> futureMap, long timeout) {
Map<String, Object> localResult = singleLocalPredict(context, inferenceRequest.getFeatureData());
ReturnResult remoteResult = new ReturnResult();
Map<String, Object> remoteResultMap = Maps.newHashMap();
futureMap.forEach((partId, future) -> {
try {
ReturnResult remoteReturnResult = (ReturnResult) future.get(timeout, TimeUnit.MILLISECONDS);
if (remoteReturnResult != null) {
HashMap<String, Object> remoteData = Maps.newHashMap(remoteReturnResult.getData());
remoteData.put(Dict.RET_CODE, remoteReturnResult.getRetcode());
remoteData.put(Dict.MESSAGE, remoteReturnResult.getRetmsg());
remoteData.put(Dict.DATA, remoteReturnResult.getData());
remoteResultMap.put(partId, remoteData);
}
} catch (Exception e) {
logger.error("host " + partId + " remote error : " + e.getMessage());
throw new RemoteRpcException("host " + partId + " remote error : " + e.getMessage());
} finally {
context.setDownstreamCost(System.currentTimeMillis() - context.getDownstreamBegin());
}
});
Map<String, Object> tempResult = singleMerge(context, localResult, remoteResultMap);
int retcode = (int) tempResult.get(Dict.RET_CODE);
String message = tempResult.get(Dict.MESSAGE) == null ? "" : tempResult.get(Dict.MESSAGE).toString();
tempResult.remove(Dict.RET_CODE);
tempResult.remove(Dict.MESSAGE);
remoteResult.setData(tempResult);
remoteResult.setRetcode(retcode);
remoteResult.setRetmsg(message);
return remoteResult;
}
@Override
public ReturnResult hostInference(Context context, InferenceRequest InferenceRequest) {
Map<String, Object> featureData = InferenceRequest.getFeatureData();
Map<String, Object> returnData = this.singleLocalPredict(context, featureData);
ReturnResult returnResult = new ReturnResult();
returnResult.setRetcode(StatusCode.SUCCESS);
returnResult.setData(returnData);
return returnResult;
}
@Override
public Object getComponent(String name) {
return this.componentMap.get(name);
}
@Override
public void setModel(Model model) {
this.model = model;
this.getPipeLineNode().forEach(baseComponent -> {
if(baseComponent!=null) {
baseComponent.setModel(model);
baseComponent.setSite(model.getPartId());
}
});
}
// @Override
// public ModelProcessor initComponentParmasMap() {
//// componentMap.forEach((cptName,instance)->{
//// componentParmasMap.put(cptName,instance.getParam());
//// });
// return this;
// }
public int initModel(Context context, Map<String, byte[]> modelProtoMap) {
if (modelProtoMap != null) {
logger.info("start init pipeline,model components {}", modelProtoMap.keySet());
try {
Map<String, byte[]> newModelProtoMap = changeModelProto(modelProtoMap);
logger.info("after parse pipeline {}", newModelProtoMap.keySet());
Preconditions.checkArgument(newModelProtoMap.get(PIPLELINE_IN_MODEL) != null);
PipelineProto.Pipeline pipeLineProto = PipelineProto.Pipeline.parseFrom(newModelProtoMap.get(PIPLELINE_IN_MODEL));
String dsl = pipeLineProto.getInferenceDsl().toStringUtf8();
dslParser.parseDagFromDSL(dsl);
ArrayList<String> components = dslParser.getAllComponent();
HashMap<String, String> componentModuleMap = dslParser.getComponentModuleMap();
for (int i = 0; i < components.size(); ++i) {
String componentName = components.get(i);
String className = componentModuleMap.get(componentName);
logger.info("try to get class:{}", className);
try {
Class modelClass = Class.forName(this.modelPackage + "." + className);
BaseComponent mlNode = (BaseComponent) modelClass.getConstructor().newInstance();
mlNode.setComponentName(componentName);
byte[] protoMeta = newModelProtoMap.get(componentName + ".Meta");
byte[] protoParam = newModelProtoMap.get(componentName + ".Param");
int returnCode = mlNode.initModel(protoMeta, protoParam);
if (returnCode == Integer.valueOf(StatusCode.SUCCESS)) {
componentMap.put(componentName, mlNode);
pipeLineNode.add(mlNode);
logger.info(" add class {} to pipeline task list", className);
} else {
throw new RuntimeException("init model error");
}
} catch (Exception ex) {
pipeLineNode.add(null);
logger.warn("Can not instance {} class", className);
}
}
} catch (Exception ex) {
logger.info("initModel error:{}", ex);
throw new RuntimeException("initModel error");
}
logger.info("Finish init Pipeline");
return Integer.valueOf(StatusCode.SUCCESS);
} else {
logger.error("model content is null ");
throw new RuntimeException("model content is null");
}
}
public Map<Integer, Map<String, Object>> batchLocalInference(Context context,
BatchInferenceRequest batchFederatedParams) {
long begin = System.currentTimeMillis();
List<BatchInferenceRequest.SingleInferenceData> inputList = batchFederatedParams.getBatchDataList();
Map<String, Map<String, Object>> tempCache = Maps.newConcurrentMap();
ForkJoinTask<Map<Integer, Map<String, Object>>> future = forkJoinPool.submit(new LocalInferenceTask(context, inputList, tempCache));
Map<Integer, Map<String, Object>> result = null;
try {
result = future.get();
} catch (Exception e) {
throw new SysException("get local inference result error");
}
long end = System.currentTimeMillis();
logger.info("batchLocalInference cost {}", end - begin);
return result;
}
private BatchInferenceResult batchMergeHostResult(Context context, Map<Integer, Map<String, Object>> localResult, Map<String, BatchInferenceResult> remoteResult) {
long begin = System.currentTimeMillis();
try {
Preconditions.checkArgument(localResult != null);
Preconditions.checkArgument(remoteResult != null);
BatchInferenceResult batchFederatedResult = new BatchInferenceResult();
batchFederatedResult.setRetcode(StatusCode.SUCCESS);
List<Integer> keys = Lists.newArrayList(localResult.keySet().iterator());
ForkJoinTask<List<BatchInferenceResult.SingleInferenceResult>> forkJoinTask = forkJoinPool.submit(new MergeTask(context, localResult, remoteResult, keys));
List<BatchInferenceResult.SingleInferenceResult> resultList = forkJoinTask.get();
batchFederatedResult.setBatchDataList(resultList);
return batchFederatedResult;
} catch (Exception e) {
throw new GuestMergeException(e.getMessage());
}
}
private boolean checkResult(Map<String, Object> result) {
if (result == null) {
return false;
}
if (result.get(Dict.RET_CODE) == null) {
return false;
}
int retCode = (int) result.get(Dict.RET_CODE);
if (StatusCode.SUCCESS != retCode) {
return false;
}
return true;
}
public Map<String, Object> singleMerge(Context context, Map<String, Object> localData, Map<String, Object> remoteData) {
if (localData == null || localData.size() == 0) {
throw new BaseException(StatusCode.GUEST_MERGE_ERROR, "local inference result is null");
}
if (remoteData == null || remoteData.size() == 0) {
throw new BaseException(StatusCode.GUEST_MERGE_ERROR, "remote inference result is null");
}
List<Map<String, Object>> outputData = Lists.newArrayList();
List<Map<String, Object>> tempList = Lists.newArrayList();
Map<String, Object> result = Maps.newHashMap();
result.put(Dict.RET_CODE, StatusCode.SUCCESS);
int pipelineSize = this.pipeLineNode.size();
for (int i = 0; i < pipelineSize; i++) {
BaseComponent component = this.pipeLineNode.get(i);
List<Map<String, Object>> inputs = new ArrayList<>();
HashSet<Integer> upInputComponents = this.dslParser.getUpInputComponents(i);
if (upInputComponents != null) {
Iterator<Integer> iters = upInputComponents.iterator();
while (iters.hasNext()) {
Integer upInput = iters.next();
if (upInput == -1) {
inputs.add(localData);
} else {
inputs.add(outputData.get(upInput));
}
}
} else {
inputs.add(localData);
}
if (component != null) {
Map<String, Object> mergeResult = null;
if (component instanceof MergeInferenceAware) {
String componentResultKey = component.getComponentName();
mergeResult = ((MergeInferenceAware) component).mergeRemoteInference(context, inputs, remoteData);
outputData.add(mergeResult);
tempList.add(mergeResult);
} else {
outputData.add(inputs.get(0));
}
if (component instanceof Returnable && mergeResult != null) {
tempList.add(mergeResult);
}
} else {
outputData.add(inputs.get(0));
}
}
if (tempList.size() > 0) {
result.putAll(tempList.get(tempList.size() - 1));
}
return result;
}
public Map<String, Object> singleLocalPredict(Context context, Map<String, Object> inputData) {
List<Map<String, Object>> outputData = Lists.newArrayList();
List<Map<String, Object>> tempList = Lists.newArrayList();
Map<String, Object> result = Maps.newHashMap();
result.put(Dict.RET_CODE, StatusCode.SUCCESS);
context.putData(Dict.ORIGINAL_PREDICT_DATA, inputData);
int pipelineSize = this.pipeLineNode.size();
for (int i = 0; i < pipelineSize; i++) {
BaseComponent component = this.pipeLineNode.get(i);
if (logger.isDebugEnabled()) {
if (component != null) {
logger.debug("component class is {}", component.getClass().getName());
} else {
logger.debug("component class is {}", component);
}
}
List<Map<String, Object>> inputs = new ArrayList<>();
HashSet<Integer> upInputComponents = this.dslParser.getUpInputComponents(i);
if (upInputComponents != null) {
Iterator<Integer> iters = upInputComponents.iterator();
while (iters.hasNext()) {
Integer upInput = iters.next();
if (upInput == -1) {
inputs.add(inputData);
} else {
inputs.add(outputData.get(upInput));
}
}
} else {
inputs.add(inputData);
}
if (component != null) {
Map<String, Object> componentResult = component.localInference(context, inputs);
outputData.add(componentResult);
tempList.add(componentResult);
if (component instanceof Returnable) {
result.put(component.getComponentName(), componentResult);
if (logger.isDebugEnabled()) {
logger.debug("component {} is Returnable return data {}", component, result);
}
if (StringUtils.isBlank(context.getVersion()) || Double.parseDouble(context.getVersion()) < 200) {
result.putAll(componentResult);
}
}
} else {
outputData.add(inputs.get(0));
}
}
return result;
}
private HashMap<String, byte[]> changeModelProto(Map<String, byte[]> modelProtoMap) {
HashMap<String, byte[]> newModelProtoMap = new HashMap<String, byte[]>(8);
for (Map.Entry<String, byte[]> entry : modelProtoMap.entrySet()) {
String key = entry.getKey();
if (!flower.equals(key)) {
String[] componentNameSegments = key.split("\\.", -1);
if (componentNameSegments.length != 2) {
newModelProtoMap.put(entry.getKey(), entry.getValue());
continue;
}
if (componentNameSegments[1].endsWith("Meta")) {
newModelProtoMap.put(componentNameSegments[0] + ".Meta", entry.getValue());
} else if (componentNameSegments[1].endsWith("Param")) {
newModelProtoMap.put(componentNameSegments[0] + ".Param", entry.getValue());
}
} else {
newModelProtoMap.put(entry.getKey(), entry.getValue());
}
}
return newModelProtoMap;
}
// public Map<String,Object> getParmasMap(){
// Map<String,Object> parmas = Maps.newHashMap();
// componentMap.forEach((k,v)->{parmas.put(k,v.getParams());});
// return parmas;
// }
class LocalInferenceTask extends RecursiveTask<Map<Integer, Map<String, Object>>> {
Context context;
Map<String, Map<String, Object>> tempCache;
List<BatchInferenceRequest.SingleInferenceData> inputList;
LocalInferenceTask(Context context, List<BatchInferenceRequest.SingleInferenceData> inputList, Map<String, Map<String, Object>> tempCache) {
this.context = context;
this.inputList = inputList;
this.tempCache = tempCache;
}
@Override
protected Map<Integer, Map<String, Object>> compute() {
Map<Integer, Map<String, Object>> result = new HashMap<>();
if (inputList.size() <= splitSize) {
for (int i = 0; i < inputList.size(); i++) {
BatchInferenceRequest.SingleInferenceData input = inputList.get(i);
try {
String key = EncryptUtils.encrypt(JsonUtil.object2Json(input.getFeatureData()), EncryptMethod.MD5);
Map<String, Object> singleResult = tempCache.get(key);
if (singleResult == null) {
singleResult = singleLocalPredict(context, input.getFeatureData());
if (singleResult != null && singleResult.size() != 0) {
tempCache.putIfAbsent(key, singleResult);
}
} else {
singleResult = Maps.newHashMap(tempCache.get(key));
}
result.put(input.getIndex(), singleResult);
if (input.isNeedCheckFeature()) {
if (input.getFeatureData() == null || input.getFeatureData().size() == 0) {
throw new HostGetFeatureErrorException("no feature");
}
}
} catch (Throwable e) {
logger.error(" compute error = {}", e);
if (result.get(input.getIndex()) == null) {
result.put(input.getIndex(), ErrorMessageUtil.handleExceptionToMap(e));
} else {
result.get(input.getIndex()).putAll(ErrorMessageUtil.handleExceptionToMap(e));
}
}
}
return result;
} else {
List<List<BatchInferenceRequest.SingleInferenceData>> splits = new ArrayList<List<BatchInferenceRequest.SingleInferenceData>>();
int size = inputList.size();
int count = (size + splitSize - 1) / splitSize;
List<LocalInferenceTask> subJobs = Lists.newArrayList();
for (int i = 0; i < count; i++) {
List<BatchInferenceRequest.SingleInferenceData> subList = inputList.subList(i * splitSize, ((i + 1) * splitSize > size ? size : splitSize * (i + 1)));
LocalInferenceTask subLocalInferenceTask = new LocalInferenceTask(context, subList, tempCache);
subLocalInferenceTask.fork();
subJobs.add(subLocalInferenceTask);
}
subJobs.forEach(localInferenceTask -> {
Map<Integer, Map<String, Object>> splitResult = localInferenceTask.join();
if (splitResult != null) {
result.putAll(splitResult);
}
});
return result;
}
}
}
class MergeTask extends RecursiveTask<List<BatchInferenceResult.SingleInferenceResult>> {
Map<Integer, Map<String, Object>> localResult;
Map<String, BatchInferenceResult> remoteResult;
List<Integer> keys;
Context context;
MergeTask(Context context, Map<Integer, Map<String, Object>> localResult,
Map<String, BatchInferenceResult> remoteResult, List<Integer> keys) {
this.context = context;
this.localResult = localResult;
this.remoteResult = remoteResult;
this.keys = keys;
}
@Override
protected List<BatchInferenceResult.SingleInferenceResult> compute() {
List<BatchInferenceResult.SingleInferenceResult> singleResultLists = Lists.newArrayList();
if (keys.size() <= splitSize) {
keys.forEach((index) -> {
Map<String, Object> remoteSingleMap = Maps.newHashMap();
remoteResult.forEach((partyId, batchResult) -> {
if (batchResult.getSingleInferenceResultMap() != null) {
if (batchResult.getSingleInferenceResultMap().get(index) != null) {
BatchInferenceResult.SingleInferenceResult singleInferenceResult = batchResult.getSingleInferenceResultMap().get(index);
Map<String, Object> realRemoteData = singleInferenceResult.getData();
realRemoteData.put(Dict.RET_CODE, singleInferenceResult.getRetcode());
remoteSingleMap.put(partyId, realRemoteData);
}
}
});
try {
Map<String, Object> localData = localResult.get(index);
Map<String, Object> mergeResult = singleMerge(context, localData, remoteSingleMap);
int retcode = (int) mergeResult.get(Dict.RET_CODE);
String msg = mergeResult.get(Dict.MESSAGE) != null ? mergeResult.get(Dict.MESSAGE).toString() : "";
mergeResult.remove(Dict.RET_CODE);
mergeResult.remove(Dict.MESSAGE);
singleResultLists.add(new BatchInferenceResult.SingleInferenceResult(index, retcode, msg, mergeResult));
} catch (Exception e) {
logger.error("merge remote error", e);
int retcode = ErrorMessageUtil.getLocalExceptionCode(e);
singleResultLists.add(new BatchInferenceResult.SingleInferenceResult(index, retcode, e.getMessage(), null));
}
});
} else {
List<List<Integer>> splits = new ArrayList<List<Integer>>();
int size = keys.size();
int count = (size + splitSize - 1) / splitSize;
List<MergeTask> subJobs = Lists.newArrayList();
for (int i = 0; i < count; i++) {
List<Integer> subList = keys.subList(i * splitSize, ((i + 1) * splitSize > size ? size : splitSize * (i + 1)));
MergeTask subMergeTask = new MergeTask(context, localResult, remoteResult, subList);
subMergeTask.fork();
subJobs.add(subMergeTask);
}
for (MergeTask mergeTask : subJobs) {
List<BatchInferenceResult.SingleInferenceResult> subResultList = mergeTask.join();
singleResultLists.addAll(subResultList);
}
}
return singleResultLists;
}
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/OneHotEncoder.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/OneHotEncoder.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.federatedml.model;
import com.fasterxml.jackson.core.type.TypeReference;
import com.webank.ai.fate.core.mlmodel.buffer.OneHotMetaProto.OneHotMeta;
import com.webank.ai.fate.core.mlmodel.buffer.OneHotParamProto.ColsMap;
import com.webank.ai.fate.core.mlmodel.buffer.OneHotParamProto.OneHotParam;
import com.webank.ai.fate.serving.common.model.LocalInferenceAware;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public class OneHotEncoder extends BaseComponent implements LocalInferenceAware {
private static final Logger logger = LoggerFactory.getLogger(OneHotEncoder.class);
Pattern doublePattern = Pattern.compile("^-?([1-9]\\\\d*\\\\.\\\\d*|0\\\\.\\\\d*[1-9]\\\\d*|0?\\\\.0+|0)$");
private List<String> cols;
private Map<String, ColsMap> colsMapMap;
private boolean needRun;
private OneHotParam oneHotParam;
@Override
public int initModel(byte[] protoMeta, byte[] protoParam) {
logger.info("start init OneHot Encoder class");
try {
OneHotMeta oneHotMeta = this.parseModel(OneHotMeta.parser(), protoMeta);
oneHotParam = this.parseModel(OneHotParam.parser(), protoParam);
this.needRun = oneHotMeta.getNeedRun();
this.cols = oneHotMeta.getTransformColNamesList();
this.colsMapMap = oneHotParam.getColMapMap();
} catch (Exception ex) {
logger.error("OneHotEncoder initModel error", ex);
return ILLEGALDATA;
}
logger.info("Finish init OneHot Encoder class");
return OK;
}
private boolean isDouble(String str) {
if (null == str || "".equals(str)) {
return false;
}
return this.doublePattern.matcher(str).matches();
}
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> inputData) {
HashMap<String, Object> outputData = new HashMap<>();
Map<String, Object> firstData = inputData.get(0);
if (!this.needRun) {
return firstData;
}
for (String colName : firstData.keySet()) {
try {
if (!this.cols.contains(colName)) {
outputData.put(colName, firstData.get(colName));
continue;
}
ColsMap colsMap = this.colsMapMap.get(colName);
List<String> values = colsMap.getValuesList();
List<String> encodedVariables = colsMap.getTransformedHeadersList();
Integer inputValue = 0;
try {
String thisInputValue = firstData.get(colName).toString();
if (this.isDouble(thisInputValue)) {
double d = Double.valueOf(thisInputValue);
inputValue = (int) Math.ceil(d);
} else {
inputValue = Integer.valueOf(thisInputValue);
}
} catch (Throwable e) {
logger.error("Onehot component accept number input value only");
}
for (int i = 0; i < values.size(); i++) {
Integer possibleValue = Integer.parseInt(values.get(i));
String newColName = encodedVariables.get(i);
if (inputValue.equals(possibleValue)) {
outputData.put(newColName, 1.0);
} else {
outputData.put(newColName, 0.0);
}
}
} catch (Throwable e) {
logger.error("HeteroFeatureBinning error", e);
}
}
return outputData;
}
@Override
public Object getParam() {
return oneHotParam;
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroSecureBoostingTreeGuest.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroSecureBoostingTreeGuest.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.federatedml.model;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.common.model.LocalInferenceAware;
import com.webank.ai.fate.serving.common.model.MergeInferenceAware;
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.GuestMergeException;
import com.webank.ai.fate.serving.core.exceptions.ModelLoadException;
import com.webank.ai.fate.serving.core.exceptions.SbtDataException;
import org.apache.commons.collections4.map.HashedMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HeteroSecureBoostingTreeGuest extends HeteroSecureBoost implements MergeInferenceAware, LocalInferenceAware, Returnable {
private final String role = "guest";
private boolean fastMode = true;
private double sigmoid(double x) {
return 1. / (1. + Math.exp(-x));
}
private Map<String, Object> softmax(double weights[]) {
int n = weights.length;
double max = weights[0];
int maxIndex = 0;
double denominator = 0.0;
for (int i = 1; i < n; ++i) {
if (weights[i] > weights[maxIndex]) {
maxIndex = i;
max = weights[i];
}
}
for (int i = 0; i < n; i++) {
weights[i] = Math.exp(weights[i] - max);
denominator += weights[i];
}
ArrayList<Double> scores = new ArrayList<Double>();
for (int i = 0; i < n; ++i) {
scores.add(weights[i] / denominator);
}
Map<String, Object> ret = Maps.newHashMap();
ret.put("label", this.classes.get(maxIndex));
ret.put("score", scores);
return ret;
}
private boolean isLocateInLeaf(int treeId, int treeNodeId) {
return this.trees.get(treeId).getTree(treeNodeId).getIsLeaf();
}
private boolean checkLeafAll(int[] treeNodeIds) {
for (int i = 0; i < this.treeNum; ++i) {
if (!isLocateInLeaf(i, treeNodeIds[i])) {
return false;
}
}
return true;
}
private double getTreeLeafWeight(int treeId, int treeNodeId) {
return this.trees.get(treeId).getTree(treeNodeId).getWeight();
}
private int traverseTree(int treeId, int treeNodeId, Map<String, Object> input) {
while (!this.isLocateInLeaf(treeId, treeNodeId) && this.getSite(treeId, treeNodeId).equals(this.site)) {
treeNodeId = this.gotoNextLevel(treeId, treeNodeId, input);
}
return treeNodeId;
}
private int fastTraverseTree(int treeId, int treeNodeId, Map<String, Object> input, Map<String, Object> lookUpTable) {
while (!this.isLocateInLeaf(treeId, treeNodeId)) {
if (this.getSite(treeId, treeNodeId).equals(this.site)) {
treeNodeId = this.gotoNextLevel(treeId, treeNodeId, input);
} else {
Map<String, Boolean> lookUp = (Map<String, Boolean>) lookUpTable.get(String.valueOf(treeId));
if(lookUp==null){
logger.error("treeId {} is not exist in {}",treeId,lookUpTable.keySet());
throw new SbtDataException();
}
if(lookUp.get(String.valueOf(treeNodeId))!=null) {
if (lookUp.get(String.valueOf(treeNodeId))) {
treeNodeId = this.trees.get(treeId).getTree(treeNodeId).getLeftNodeid();
} else {
treeNodeId = this.trees.get(treeId).getTree(treeNodeId).getRightNodeid();
}
}else{
logger.error("tree node id {} not exist in {} ,lookup table {}",treeNodeId,lookUp,lookUpTable);
throw new SbtDataException();
}
}
if (logger.isDebugEnabled()) {
logger.info("tree id is {}, tree node is {}", treeId, treeNodeId);
}
}
return treeNodeId;
}
private Map<String, Object> getFinalPredict(double[] weights) {
Map<String, Object> ret = new HashMap<String, Object>(8);
if (this.numClasses == 2) {
double sum = 0;
for (int i = 0; i < this.treeNum; ++i) {
sum += weights[i] * this.learningRate;
}
ret.put(Dict.SCORE, this.sigmoid(sum));
} else if (this.numClasses > 2) {
double[] sumWeights = new double[this.treeDim];
for (int i = 0; i < this.treeNum; ++i) {
sumWeights[i % this.treeDim] += weights[i] * this.learningRate;
}
for (int i = 0; i < this.treeDim; i++) {
sumWeights[i] += this.initScore.get(i);
}
ret = softmax(sumWeights);
} else {
double sum = this.initScore.get(0);
for (int i = 0; i < this.treeNum; ++i) {
sum += weights[i] * this.learningRate;
}
ret.put(Dict.SCORE, sum);
}
return ret;
}
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> inputData) {
Map<String, Object> result = Maps.newHashMap();
int[] treeNodeIds = new int[this.treeNum];
HashMap<String, Object> fidValueMapping = new HashMap<String, Object>(8);
HashMap<String, Object> treeLocation = new HashMap<String, Object>(8);
Map<String, Object> input = inputData.get(0);
int featureHit = 0;
for (String key : input.keySet()) {
if (this.featureNameFidMapping.containsKey(key)) {
fidValueMapping.put(this.featureNameFidMapping.get(key).toString(), input.get(key));
++featureHit;
}
}
logger.info("feature hit rate : {}", 1.0 * featureHit / this.featureNameFidMapping.size());
double[] weights = new double[this.treeNum];
int communicationRound = 0;
for (int i = 0; i < this.treeNum; ++i) {
if (this.isLocateInLeaf(i, treeNodeIds[i])) {
continue;
}
treeNodeIds[i] = this.traverseTree(i, treeNodeIds[i], fidValueMapping);
if (!this.isLocateInLeaf(i, treeNodeIds[i])) {
treeLocation.put(String.valueOf(i), treeNodeIds[i]);
}
}
result.put(Dict.SBT_TREE_NODE_ID_ARRAY, treeNodeIds);
result.put("fidValueMapping", fidValueMapping);
return result;
}
private Map<String, Boolean> mergeTwoLookUpTable(Map<String, Boolean> lookUp1, Map<String, Boolean> lookUp2){
Map<String, Boolean> merged = new HashMap<>();
merged.putAll(lookUp1);
merged.putAll(lookUp2);
return merged;
}
private Map<String, Object> extractMultiPartiesData(Map<String, Object> remoteData, int tree_num){
// merge multi host lookup table (if there are multiple hosts)
Map<String, Object> extract_result = new HashedMap<String, Object>();
Map<String, Object> mergedLookUpTable = new HashMap<>();
// extract component data
remoteData.forEach((k, v) -> {
Map<String, Object> onePartyData = (Map<String, Object>) v;
Map<String, Object> remoteComopnentData = (Map<String, Object>) onePartyData.get(this.getComponentName());
if (remoteComopnentData == null) {
remoteComopnentData = onePartyData;
}
extract_result.put(k, remoteComopnentData);
});
// merge host look up tables
extract_result.forEach((k, v) -> {
Map<String, Map<String, Boolean>> lookUp = (Map<String, Map<String, Boolean>>) v;
for(int treeId=0; treeId<tree_num; treeId++){
String str_key = String.valueOf(treeId);
Map<String, Boolean> treeLookUp = lookUp.get(str_key);
if(!mergedLookUpTable.containsKey(str_key)){
mergedLookUpTable.put(str_key,treeLookUp);
}
else{
Map<String, Boolean> savedLookUp = (Map<String, Boolean>)mergedLookUpTable.get(str_key);
Map<String, Boolean> mergedResult = this.mergeTwoLookUpTable(savedLookUp, treeLookUp);
mergedLookUpTable.put(str_key, mergedResult);
}
}
});
return mergedLookUpTable;
}
@Override
public Map<String, Object> mergeRemoteInference(Context context, List<Map<String, Object>> localDataList, Map<String, Object> remoteData) {
Map<String, Object> result = this.handleRemoteReturnData(remoteData);
if ((int) result.get(Dict.RET_CODE) != StatusCode.SUCCESS) {
return result;
}
Map<String, Object> localData = (Map<String, Object>) localDataList.get(0).get(this.getComponentName());
int[] treeNodeIds = (int[]) localData.get(Dict.SBT_TREE_NODE_ID_ARRAY);
double[] weights = new double[this.treeNum];
if (treeNodeIds == null) {
throw new GuestMergeException("tree node id array is not return from first loop");
}
HashMap<String, Object> fidValueMapping = (HashMap<String, Object>) localData.get("fidValueMapping");
Map<String, Object> lookUpTable = this.extractMultiPartiesData(remoteData, this.treeNum);
HashMap<String, Object> treeLocation = new HashMap<String, Object>(8);
for (int i = 0; i < this.treeNum; ++i) {
if (this.isLocateInLeaf(i, treeNodeIds[i])) {
continue;
}
treeNodeIds[i] = this.traverseTree(i, treeNodeIds[i], fidValueMapping);
if (!this.isLocateInLeaf(i, treeNodeIds[i])) {
treeLocation.put(String.valueOf(i), treeNodeIds[i]);
}
}
for (String treeIdx : treeLocation.keySet()) {
int idx = Integer.valueOf(treeIdx);
int curNodeId = (Integer) treeLocation.get(treeIdx);
int final_node_id = this.fastTraverseTree(idx, curNodeId, fidValueMapping, lookUpTable);
treeNodeIds[idx] = final_node_id;
}
for (int i = 0; i < this.treeNum; ++i) {
weights[i] = getTreeLeafWeight(i, treeNodeIds[i]);
}
if (logger.isDebugEnabled()) {
logger.info("tree leaf ids is {}", treeNodeIds);
logger.info("weights is {}", weights);
}
return getFinalPredict(weights);
}
} | 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFeatureSelectionHost.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFeatureSelectionHost.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.federatedml.model;
public class HeteroFeatureSelectionHost extends FeatureSelection {
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/PrepareRemoteable.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/PrepareRemoteable.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.federatedml.model;
import com.webank.ai.fate.serving.core.bean.Context;
import java.util.Map;
public interface PrepareRemoteable {
public Map<String, Object> prepareRemoteData(Context context, 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroLRGuest.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroLRGuest.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.federatedml.model;
import com.webank.ai.fate.serving.common.model.MergeInferenceAware;
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.GuestMergeException;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static java.lang.Math.exp;
public class HeteroLRGuest extends HeteroLR implements MergeInferenceAware, Returnable {
private static final Logger logger = LoggerFactory.getLogger(HeteroLRGuest.class);
private double sigmod(double x) {
return 1. / (1. + exp(-x));
}
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> input
) {
Map<String, Object> result = new HashMap<>(8);
Map<String, Double> forwardRet = forward(input);
double score = forwardRet.get(Dict.SCORE);
result.put(Dict.SCORE, score);
return result;
}
@Override
public Map<String, Object> mergeRemoteInference(Context context, List<Map<String, Object>> guestData,
Map<String, Object> hostData) {
Map<String, Object> result = this.handleRemoteReturnData(hostData);
if ((int) result.get(Dict.RET_CODE) == StatusCode.SUCCESS) {
if (CollectionUtils.isNotEmpty(guestData)) {
AtomicReference<Double> score = new AtomicReference<>((double) 0);
Map<String, Object> tempMap = guestData.get(0);
Map<String, Object> componentData = (Map<String, Object>) tempMap.get(this.getComponentName());
double localScore = 0;
if (componentData != null && componentData.get(Dict.SCORE) != null) {
localScore = ((Number) componentData.get(Dict.SCORE)).doubleValue();
} else {
throw new GuestMergeException("local result is invalid ");
}
score.set(localScore);
hostData.forEach((k, v) -> {
Map<String, Object> onePartyData = (Map<String, Object>) v;
Map<String, Object> remoteComopnentData = (Map<String, Object>) onePartyData.get(this.getComponentName());
double remoteScore;
if (remoteComopnentData != null) {
remoteScore = ((Number) remoteComopnentData.get(Dict.SCORE)).doubleValue();
} else {
if (onePartyData.get(Dict.PROB) != null) {
remoteScore = ((Number) onePartyData.get(Dict.PROB)).doubleValue();
} else {
throw new GuestMergeException("host data score is null");
}
}
score.updateAndGet(v1 -> new Double((double) (v1 + remoteScore)));
});
double prob = sigmod(score.get());
result.put(Dict.SCORE, prob);
}
}
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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/Outlier.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/Outlier.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.federatedml.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class Outlier {
private static final Logger logger = LoggerFactory.getLogger(Outlier.class);
public HashSet<String> outlierValueSet;
public Map<String, String> outlierReplaceValues;
public Outlier(List<String> outlierValues, Map<String, String> outlierReplaceValue) {
this.outlierValueSet = new HashSet<String>(outlierValues);
this.outlierReplaceValues = outlierReplaceValue;
}
public Map<String, Object> transform(Map<String, Object> inputData) {
if (inputData != null) {
for (String key : inputData.keySet()) {
if (inputData.get(key) != null) {
String value = inputData.get(key).toString();
if (this.outlierValueSet.contains(value.toLowerCase())) {
try {
inputData.put(key, outlierReplaceValues.get(key));
} catch (Exception ex) {
ex.printStackTrace();
inputData.put(key, 0.);
}
}
}
}
}
return inputData;
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/DataTransform.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/DataTransform.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.federatedml.model;
import com.webank.ai.fate.core.mlmodel.buffer.DataTransformMetaProto.DataTransformMeta;
import com.webank.ai.fate.core.mlmodel.buffer.DataTransformParamProto.DataTransformParam;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DataTransform extends BaseComponent {
private static final Logger logger = LoggerFactory.getLogger(DataTransform.class);
private DataTransformMeta dataTransformMeta;
private DataTransformParam dataTransformParam;
private List<String> header;
private String inputformat;
private Imputer imputer;
private Outlier outlier;
private boolean isImputer;
private boolean isOutlier;
@Override
public int initModel(byte[] protoMeta, byte[] protoParam) {
logger.info("start init DataTransform class");
try {
this.dataTransformMeta = this.parseModel(DataTransformMeta.parser(), protoMeta);
this.dataTransformParam = this.parseModel(DataTransformParam.parser(), protoParam);
this.isImputer = this.dataTransformMeta.getImputerMeta().getIsImputer();
logger.info("data transform isImputer {}", this.isImputer);
if (this.isImputer) {
this.imputer = new Imputer(this.dataTransformMeta.getImputerMeta().getMissingValueList(),
this.dataTransformParam.getImputerParam().getMissingReplaceValue());
}
this.isOutlier = this.dataTransformMeta.getOutlierMeta().getIsOutlier();
logger.info("data io isOutlier {}", this.isOutlier);
if (this.isOutlier) {
this.outlier = new Outlier(this.dataTransformMeta.getOutlierMeta().getOutlierValueList(),
this.dataTransformParam.getOutlierParam().getOutlierReplaceValue());
}
this.header = this.dataTransformParam.getHeaderList();
this.inputformat = this.dataTransformMeta.getInputFormat();
} catch (Exception ex) {
//ex.printStackTrace();
logger.error("init DataTransform error", ex);
return ILLEGALDATA;
}
logger.info("Finish init DataTransform class");
return OK;
}
@Override
public Object getParam() {
return dataTransformParam;
}
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> inputData) {
Map<String, Object> data = inputData.get(0);
Map<String, Object> outputData = new HashMap<>();
if (this.inputformat.equals(Dict.TAG_INPUT_FORMAT) || this.inputformat.equals(Dict.SPARSE_INPUT_FORMAT
)) {
if (logger.isDebugEnabled()) {
logger.debug("Sparse Data Filling");
}
for (String col : this.header) {
if (this.isImputer) {
outputData.put(col, data.getOrDefault(col, ""));
} else {
outputData.put(col, data.getOrDefault(col, 0));
}
}
if(logger.isDebugEnabled()) {
logger.debug("sparse input-format, data {}", outputData);
}
} else {
outputData = data;
if (logger.isDebugEnabled()) {
logger.debug("Dense input-format, not filling, {}", outputData);
}
}
if (this.isImputer) {
outputData = this.imputer.transform(outputData);
}
if (this.isOutlier) {
outputData = this.outlier.transform(outputData);
}
return outputData;
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/DataIO.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/DataIO.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.federatedml.model;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.webank.ai.fate.core.mlmodel.buffer.DataIOMetaProto.DataIOMeta;
import com.webank.ai.fate.core.mlmodel.buffer.DataIOParamProto.DataIOParam;
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.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DataIO extends BaseComponent {
private static final Logger logger = LoggerFactory.getLogger(DataIO.class);
private DataIOMeta dataIOMeta;
private DataIOParam dataIOParam;
private List<String> header;
private String inputformat;
private Imputer imputer;
private Outlier outlier;
private boolean isImputer;
private boolean isOutlier;
@Override
public int initModel(byte[] protoMeta, byte[] protoParam) {
logger.info("start init DataIO class");
try {
this.dataIOMeta = this.parseModel(DataIOMeta.parser(), protoMeta);
this.dataIOParam = this.parseModel(DataIOParam.parser(), protoParam);
this.isImputer = this.dataIOMeta.getImputerMeta().getIsImputer();
logger.info("data io isImputer {}", this.isImputer);
if (this.isImputer) {
this.imputer = new Imputer(this.dataIOMeta.getImputerMeta().getMissingValueList(),
this.dataIOParam.getImputerParam().getMissingReplaceValue());
}
this.isOutlier = this.dataIOMeta.getOutlierMeta().getIsOutlier();
logger.info("data io isOutlier {}", this.isOutlier);
if (this.isOutlier) {
this.outlier = new Outlier(this.dataIOMeta.getOutlierMeta().getOutlierValueList(),
this.dataIOParam.getOutlierParam().getOutlierReplaceValue());
}
this.header = this.dataIOParam.getHeaderList();
this.inputformat = this.dataIOMeta.getInputFormat();
} catch (Exception ex) {
//ex.printStackTrace();
logger.error("init DataIo error", ex);
return ILLEGALDATA;
}
logger.info("Finish init DataIO class");
return OK;
}
@Override
public Object getParam() {
// for (Field declaredField : dataIOParam.getClass().getDeclaredFields()) {
// logger.info(declaredField.getName());
// }
//// Gson gson = new Gson();
// Map result = Maps.newHashMap();
// result.put("dataIOParam",dataIOParam );
return dataIOParam;
//
// dataIOParam.
// gson.toJson()
// return JsonUtil.object2Objcet(dataIOParam, new TypeReference<Map<String, Object>>() {});
}
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> inputData) {
Map<String, Object> data = inputData.get(0);
Map<String, Object> outputData = new HashMap<>();
if (this.inputformat.equals(Dict.TAG_INPUT_FORMAT) || this.inputformat.equals(Dict.SPARSE_INPUT_FORMAT
)) {
if (logger.isDebugEnabled()) {
logger.debug("Sparse Data Filling");
}
for (String col : this.header) {
if (this.isImputer) {
outputData.put(col, data.getOrDefault(col, ""));
} else {
outputData.put(col, data.getOrDefault(col, 0));
}
}
if(logger.isDebugEnabled()) {
logger.debug("sparse input-format, data {}", outputData);
}
} else {
outputData = data;
if (logger.isDebugEnabled()) {
logger.debug("Dense input-format, not filling, {}", outputData);
}
}
if (this.isImputer) {
outputData = this.imputer.transform(outputData);
}
if (this.isOutlier) {
outputData = this.outlier.transform(outputData);
}
return outputData;
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/BaseComponent.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/BaseComponent.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.federatedml.model;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.serving.common.cache.Cache;
import com.webank.ai.fate.serving.common.model.LocalInferenceAware;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.rpc.core.ErrorMessageUtil;
import com.webank.ai.fate.serving.common.rpc.core.FederatedRpcInvoker;
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.utils.ProtobufUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ForkJoinPool;
public abstract class BaseComponent implements LocalInferenceAware {
protected static final int OK = 0;
protected static final int UNKNOWNERROR = 1;
protected static final int PARAMERROR = 2;
protected static final int ILLEGALDATA = 3;
protected static final int NOMODEL = 4;
protected static final int NOTME = 5;
protected static final int FEDERATEDERROR = 6;
protected static final int TIMEOUT = -1;
protected static final int NOFILE = -2;
protected static final int NETWORKERROR = -3;
protected static final int IOERROR = -4;
protected static final int RUNTIMEERROR = -5;
private static final Logger logger = LoggerFactory.getLogger(BaseComponent.class);
static ForkJoinPool forkJoinPool = new ForkJoinPool();
protected String componentName;
protected String shortName;
protected int index;
protected FederatedRpcInvoker<Proxy.Packet> federatedRpcInvoker;
protected Cache cache;
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = site;
}
protected String site;
protected Model model;
public abstract int initModel(byte[] protoMeta, byte[] protoParam);
protected <T> T parseModel(com.google.protobuf.Parser<T> protoParser, byte[] protoString) throws com.google.protobuf.InvalidProtocolBufferException {
return ProtobufUtils.parseProtoObject(protoParser, protoString);
}
public Map<String, Double> featureHitRateStatistics(Context context, Set<String> features) {
Map<String, Object> data = (Map)context.getData(Dict.ORIGINAL_PREDICT_DATA);
if(logger.isDebugEnabled()) {
logger.debug("original input data is {}, modeling features is {}", data, features);
}
int inputDataShape = data.size();
int featureShape = features.size();
int featureHit = 0;
Map<String, Double> ret = new HashMap<>();
for (String name : features) {
if (data.containsKey(name)) {
featureHit++;
}
}
double featureHitRate = -1.0;
double inputDataHitRate = -1.0;
try {
featureHitRate = 1.0 * featureHit / featureShape;
inputDataHitRate = 1.0 * featureHit / inputDataShape;
} catch (Exception ex) {
ex.printStackTrace();
}
if(logger.isDebugEnabled()) {
logger.debug("input feature data's shape is {}, header shape is {}, input feature hit rate is {}, modeling feature hit rate is {}", inputDataShape, featureShape, inputDataHitRate, featureHitRate);
}
ret.put(Dict.MODELING_FEATURE_HIT_RATE, featureHitRate);
ret.put(Dict.INPUT_DATA_HIT_RATE, inputDataHitRate);
return ret;
}
protected Map<String, Object> handleRemoteReturnData(Map<String, Object> hostData) {
Map<String, Object> result = new HashMap<>(8);
result.put(Dict.RET_CODE, StatusCode.SUCCESS);
hostData.forEach((partId, partyDataObject) -> {
Map partyData = (Map) partyDataObject;
result.put(Dict.MESSAGE, partyData.get(Dict.MESSAGE));
if (partyData.get(Dict.RET_CODE) != null && StatusCode.SUCCESS != (int) partyData.get(Dict.RET_CODE)) {
int remoteCode = (int) partyData.get(Dict.RET_CODE);
String remoteMsg = partyData.get(Dict.MESSAGE) != null ? partyData.get(Dict.MESSAGE).toString() : "";
String errorMsg = ErrorMessageUtil.buildRemoteRpcErrorMsg(remoteCode, remoteMsg);
int retcode = ErrorMessageUtil.transformRemoteErrorCode(remoteCode);
result.put(Dict.RET_CODE, retcode);
result.put(Dict.MESSAGE, errorMsg);
}
});
return result;
}
public String getComponentName() {
return componentName;
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public FederatedRpcInvoker getFederatedRpcInvoker() {
return federatedRpcInvoker;
}
public void setFederatedRpcInvoker(FederatedRpcInvoker federatedRpcInvoker) {
this.federatedRpcInvoker = federatedRpcInvoker;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public Cache getCache() {
return cache;
}
public void setCache(Cache cache) {
this.cache = cache;
}
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
public abstract Object getParam();
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFeatureBinningGuest.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFeatureBinningGuest.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.federatedml.model;
public class HeteroFeatureBinningGuest extends HeteroFeatureBinning {
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFeatureBinning.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFeatureBinning.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.federatedml.model;
import com.fasterxml.jackson.core.type.TypeReference;
import com.webank.ai.fate.core.mlmodel.buffer.FeatureBinningMetaProto.FeatureBinningMeta;
import com.webank.ai.fate.core.mlmodel.buffer.FeatureBinningMetaProto.TransformMeta;
import com.webank.ai.fate.core.mlmodel.buffer.FeatureBinningParamProto.FeatureBinningParam;
import com.webank.ai.fate.core.mlmodel.buffer.FeatureBinningParamProto.FeatureBinningResult;
import com.webank.ai.fate.core.mlmodel.buffer.FeatureBinningParamProto.IVParam;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HeteroFeatureBinning extends BaseComponent {
private static final Logger logger = LoggerFactory.getLogger(HeteroFeatureBinning.class);
private Map<String, List<Double>> splitPoints;
private List<Long> transformCols;
private List<String> header;
private boolean needRun;
private FeatureBinningParam featureBinningParam;
@Override
public int initModel(byte[] protoMeta, byte[] protoParam) {
logger.info("start init Feature Binning class");
this.needRun = false;
this.splitPoints = new HashMap<>(8);
try {
FeatureBinningMeta featureBinningMeta = this.parseModel(FeatureBinningMeta.parser(), protoMeta);
this.needRun = featureBinningMeta.getNeedRun();
TransformMeta transformMeta = featureBinningMeta.getTransformParam();
this.transformCols = transformMeta.getTransformColsList();
featureBinningParam = this.parseModel(FeatureBinningParam.parser(), protoParam);
this.header = featureBinningParam.getHeaderList();
FeatureBinningResult featureBinningResult = featureBinningParam.getBinningResult();
Map<String, IVParam> binningResult = featureBinningResult.getBinningResultMap();
for (String key : binningResult.keySet()) {
IVParam oneColResult = binningResult.get(key);
List<Double> splitPoints = oneColResult.getSplitPointsList();
this.splitPoints.put(key, splitPoints);
}
} catch (Exception ex) {
logger.error("init model error:", ex);
return ILLEGALDATA;
}
logger.info("Finish init Feature Binning class");
return OK;
}
@Override
public Object getParam() {
return featureBinningParam;
//return JsonUtil.object2Objcet(featureBinningParam, new TypeReference<Map<String, Object>>() {});
}
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> inputData) {
HashMap<String, Object> outputData = new HashMap<>(8);
HashMap<String, Long> headerMap = new HashMap<>(8);
Map<String, Object> firstData = inputData.get(0);
if (!this.needRun) {
return firstData;
}
for (int i = 0; i < this.header.size(); i++) {
headerMap.put(this.header.get(i), (long) i);
}
for (String colName : firstData.keySet()) {
try {
if (!this.splitPoints.containsKey(colName)) {
outputData.put(colName, firstData.get(colName));
continue;
}
Long thisColIndex = headerMap.get(colName);
if (!this.transformCols.contains(thisColIndex)) {
outputData.put(colName, firstData.get(colName));
continue;
}
List<Double> splitPoint = this.splitPoints.get(colName);
Double colValue = Double.valueOf(firstData.get(colName).toString());
int colIndex = Collections.binarySearch(splitPoint, colValue);
if (colIndex < 0) {
colIndex = Math.min((- colIndex - 1), splitPoint.size() - 1);
}
outputData.put(colName, colIndex);
} catch (Throwable e) {
logger.error("HeteroFeatureBinning error", e);
}
}
if (logger.isDebugEnabled()) {
logger.debug("DEBUG: HeteroFeatureBinning output {}", outputData);
}
return outputData;
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroSecureBoost.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroSecureBoost.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.federatedml.model;
import com.google.common.collect.Maps;
import com.webank.ai.fate.core.mlmodel.buffer.BoostTreeModelMetaProto.BoostingTreeModelMeta;
import com.webank.ai.fate.core.mlmodel.buffer.BoostTreeModelParamProto.BoostingTreeModelParam;
import com.webank.ai.fate.core.mlmodel.buffer.BoostTreeModelParamProto.DecisionTreeModelParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
public abstract class HeteroSecureBoost extends BaseComponent {
public static final Logger logger = LoggerFactory.getLogger(HeteroSecureBoost.class);
protected List<Map<Integer, Double>> splitMaskdict;
protected Map<String, Integer> featureNameFidMapping = Maps.newHashMap();
protected int treeNum;
protected List<Double> initScore;
protected List<DecisionTreeModelParam> trees;
protected int numClasses;
protected List<String> classes;
protected int treeDim;
protected double learningRate;
BoostingTreeModelParam param;
public Object getParam(){
return param;
}
@Override
public int initModel(byte[] protoMeta, byte[] protoParam) {
logger.info("start init HeteroSecureBoost class");
try {
param= this.parseModel(BoostingTreeModelParam.parser(), protoParam);
BoostingTreeModelMeta meta = this.parseModel(BoostingTreeModelMeta.parser(), protoMeta);
Map<Integer, String> featureNameMapping = param.getFeatureNameFidMapping();
featureNameMapping.forEach((k, v) -> {
featureNameFidMapping.put(v, k);
});
this.treeNum = param.getTreeNum();
this.initScore = param.getInitScoreList();
this.trees = param.getTreesList();
this.numClasses = param.getNumClasses();
this.classes = param.getClassesList();
this.treeDim = param.getTreeDim();
this.learningRate = meta.getLearningRate();
} catch (Exception ex) {
ex.printStackTrace();
return ILLEGALDATA;
}
logger.info("Finish init HeteroSecureBoost class");
return OK;
}
protected String getSite(int treeId, int treeNodeId) {
String siteName = this.trees.get(treeId).getTree(treeNodeId).getSitename();
if(siteName != null && siteName.contains(":")){
return siteName.split(":")[1];
}else{
return siteName;
}
}
protected String generateTag(String caseId, String modelId, int communicationRound) {
return caseId + "_" + modelId + "_" + String.valueOf(communicationRound);
}
protected String[] parseTag(String tag) {
return tag.split("_");
}
protected int gotoNextLevel(int treeId, int treeNodeId, Map<String, Object> input) {
int nextTreeNodeId;
int fid = this.trees.get(treeId).getTree(treeNodeId).getFid();
double splitValue = this.trees.get(treeId).getSplitMaskdict().get(treeNodeId);
String fidStr = String.valueOf(fid);
if (input.containsKey(fidStr)) {
if (logger.isDebugEnabled()) {
logger.info("treeId {}, treeNodeId {}, splitValue {}, fid {}", treeId, treeNodeId, splitValue,Double.parseDouble(input.get(fidStr).toString()) );
}
if (Double.parseDouble(input.get(fidStr).toString()) <= splitValue + 1e-8) {
nextTreeNodeId = this.trees.get(treeId).getTree(treeNodeId).getLeftNodeid();
} else {
nextTreeNodeId = this.trees.get(treeId).getTree(treeNodeId).getRightNodeid();
}
} else {
if (this.trees.get(treeId).getMissingDirMaskdict().containsKey(treeNodeId)) {
int missingDir = this.trees.get(treeId).getMissingDirMaskdict().get(treeNodeId);
if (missingDir == 1) {
nextTreeNodeId = this.trees.get(treeId).getTree(treeNodeId).getRightNodeid();
} else {
nextTreeNodeId = this.trees.get(treeId).getTree(treeNodeId).getLeftNodeid();
}
} else {
nextTreeNodeId = this.trees.get(treeId).getTree(treeNodeId).getRightNodeid();
}
}
return nextTreeNodeId;
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/Scale.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/Scale.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.federatedml.model;
import com.fasterxml.jackson.core.type.TypeReference;
import com.webank.ai.fate.core.mlmodel.buffer.ScaleMetaProto.ScaleMeta;
import com.webank.ai.fate.core.mlmodel.buffer.ScaleParamProto.ScaleParam;
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.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
public class Scale extends BaseComponent {
private static final Logger logger = LoggerFactory.getLogger(Scale.class);
private ScaleMeta scaleMeta;
private ScaleParam scaleParam;
private boolean needRun;
@Override
public int initModel(byte[] protoMeta, byte[] protoParam) {
logger.info("start init Scale class");
try {
this.scaleMeta = this.parseModel(ScaleMeta.parser(), protoMeta);
this.scaleParam = this.parseModel(ScaleParam.parser(), protoParam);
this.needRun = this.scaleMeta.getNeedRun();
} catch (Exception ex) {
logger.error("Scale initModel error", ex);
return ILLEGALDATA;
}
logger.info("Finish init Scale class");
return OK;
}
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> inputDatas) {
Map<String, Object> outputData = inputDatas.get(0);
if (this.needRun) {
String scaleMethod = this.scaleMeta.getMethod();
if (scaleMethod.toLowerCase().equals(Dict.MIN_MAX_SCALE)) {
MinMaxScale minMaxScale = new MinMaxScale();
outputData = minMaxScale.transform(inputDatas.get(0), this.scaleParam.getColScaleParamMap());
} else if (scaleMethod.toLowerCase().equals(Dict.STANDARD_SCALE)) {
StandardScale standardScale = new StandardScale();
outputData = standardScale.transform(inputDatas.get(0), this.scaleParam.getColScaleParamMap());
}
}
return outputData;
}
@Override
public Object getParam() {
return scaleParam;
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFeatureSelectionGuest.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFeatureSelectionGuest.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.federatedml.model;
public class HeteroFeatureSelectionGuest extends FeatureSelection {
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroLRHost.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroLRHost.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.federatedml.model;
import com.google.common.collect.Maps;
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.MetaInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HeteroLRHost extends HeteroLR implements Returnable {
private static final Logger logger = LoggerFactory.getLogger(HeteroLRHost.class);
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> inputData) {
HashMap<String, Object> result = new HashMap<>(8);
Map<String, Double> ret = Maps.newHashMap();
if(MetaInfo.PROPERTY_LR_USE_PARALLEL){
ret = forwardParallel(inputData);
}
else{
ret = forward(inputData);
}
result.put(Dict.SCORE, ret.get(Dict.SCORE));
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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFeatureBinningHost.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFeatureBinningHost.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.federatedml.model;
public class HeteroFeatureBinningHost extends HeteroFeatureBinning {
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFMHost.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFMHost.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.federatedml.model;
import com.webank.ai.fate.serving.common.model.LocalInferenceAware;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HeteroFMHost extends HeteroFM implements LocalInferenceAware, Returnable {
private static final Logger logger = LoggerFactory.getLogger(HeteroFMHost.class);
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> inputData) {
HashMap<String, Object> result = new HashMap<>();
Map<String, Object> ret = forward(inputData);
result.put(Dict.SCORE, ret.get(Dict.SCORE));
result.put(Dict.FM_CROSS, ret.get(Dict.FM_CROSS));
if (logger.isDebugEnabled()) {
logger.debug("hetero fm host predict ends, result is {}", result);
}
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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/Imputer.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/Imputer.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.federatedml.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class Imputer {
private static final Logger logger = LoggerFactory.getLogger(Imputer.class);
public HashSet<String> missingValueSet;
public Map<String, String> missingReplaceValues;
public Imputer(List<String> missingValues, Map<String, String> missingReplaceValue) {
this.missingValueSet = new HashSet<String>(missingValues);
this.missingReplaceValues = missingReplaceValue;
}
public Map<String, Object> transform(Map<String, Object> inputData) {
Map<String, Object> output = new HashMap<>();
for (String col : this.missingReplaceValues.keySet()) {
if (inputData.containsKey(col)) {
String value = inputData.get(col).toString();
if (this.missingValueSet.contains(value.toLowerCase())) {
output.put(col, this.missingReplaceValues.get(col));
} else {
output.put(col, inputData.get(col));
}
} else {
output.put(col, this.missingReplaceValues.get(col));
}
}
return output;
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFM.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFM.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.federatedml.model;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import com.webank.ai.fate.core.mlmodel.buffer.fm.FMModelParamProto.Embedding;
import com.webank.ai.fate.core.mlmodel.buffer.fm.FMModelParamProto.FMModelParam;
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 java.util.HashMap;
import java.util.List;
import java.util.Map;
public abstract class HeteroFM extends BaseComponent {
private static final Logger logger = LoggerFactory.getLogger(HeteroFM.class);
private Map<String, Double> weight;
private Double intercept;
private Map<String, Embedding> embedding;
private int embedSize;
@Override
public int initModel(byte[] protoMeta, byte[] protoParam) {
logger.info("start init HeteroFM class");
try {
FMModelParam fmModelParam = this.parseModel(FMModelParam.parser(), protoParam);
this.weight = fmModelParam.getWeightMap();
this.intercept = fmModelParam.getIntercept();
this.embedding = fmModelParam.getEmbeddingMap();
this.embedSize = fmModelParam.getEmbedSize();
} catch (Exception ex) {
ex.printStackTrace();
return ILLEGALDATA;
}
logger.info("Finish init HeteroFM class, model weight is {}, model embedding is {}", this.weight, this.embedding);
return OK;
}
Map<String, Object> forward(List<Map<String, Object>> inputDatas) {
Map<String, Object> inputData = inputDatas.get(0);
int modelWeightHitCount = 0;
int inputDataHitCount = 0;
int weightNum = this.weight.size();
int inputFeaturesNum = inputData.size();
if (logger.isDebugEnabled()) {
logger.debug("model weight number:{}", weightNum);
logger.debug("input data features number:{}", inputFeaturesNum);
}
double score = 0;
for (String key : inputData.keySet()) {
if (this.weight.containsKey(key)) {
Double x = new Double(inputData.get(key).toString());
Double w = new Double(this.weight.get(key).toString());
score += w * x;
modelWeightHitCount += 1;
inputDataHitCount += 1;
if (logger.isDebugEnabled()) {
logger.debug("key {} weight is {}, value is {}", key, this.weight.get(key), inputData.get(key));
}
}
}
double[] multiplies = new double[this.embedSize];
double[] squares = new double[this.embedSize];
for (String key : this.embedding.keySet()) {
if (inputData.containsKey(key)) {
Double x = new Double(inputData.get(key).toString());
List<Double> wList = this.embedding.get(key).getWeightList();
for (int i = 0; i < this.embedSize; i++) {
multiplies[i] = multiplies[i] + wList.get(i) * x;
squares[i] = squares[i] + Math.pow(wList.get(i) * x, 2);
}
}
}
double cross = 0.0;
for (int i = 0; i < this.embedSize; i++) {
cross += (Math.pow(multiplies[i], 2) - squares[i]);
}
score += cross * 0.5;
score += this.intercept;
double modelWeightHitRate = -1.0;
double inputDataHitRate = -1.0;
try {
modelWeightHitRate = (double) modelWeightHitCount / weightNum;
inputDataHitRate = (double) inputDataHitCount / inputFeaturesNum;
} catch (Exception ex) {
ex.printStackTrace();
}
if (logger.isDebugEnabled()) {
logger.debug("model weight hit rate:{}", modelWeightHitRate);
logger.debug("input data features hit rate:{}", inputDataHitRate);
}
Map<String, Object> ret = new HashMap<>();
ret.put(Dict.SCORE, score);
ret.put(Dict.MODEL_WRIGHT_HIT_RATE, modelWeightHitRate);
ret.put(Dict.INPUT_DATA_HIT_RATE, inputDataHitRate);
ret.put(Dict.FM_CROSS, multiplies);
return ret;
}
@Override
public Object getParam() {
Map<String,Object> paramsMap = Maps.newHashMap();
paramsMap.putAll(weight);
return paramsMap;
}
}
| 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-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/Returnable.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/Returnable.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.federatedml.model;
/**
* 实现该接口的组件,可以提供返回值
*/
public interface Returnable {
}
| 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.