repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroLR.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroLR.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.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.webank.ai.fate.core.mlmodel.buffer.LRModelParamProto.LRModelParam;
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.*;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
public abstract class HeteroLR extends BaseComponent {
private static final Logger logger = LoggerFactory.getLogger(HeteroLR.class);
private Map<String, Double> weight;
private Double intercept;
LRModelParam lrModelParam;
@Override
public int initModel(byte[] protoMeta, byte[] protoParam) {
logger.info("start init HeteroLR class");
try {
lrModelParam = this.parseModel(LRModelParam.parser(), protoParam);
this.weight = lrModelParam.getWeightMap();
this.intercept = lrModelParam.getIntercept();
} catch (Exception ex) {
ex.printStackTrace();
return ILLEGALDATA;
}
logger.info("Finish init HeteroLR class, model weight is {}", this.weight);
return OK;
}
Map<String, Double> 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));
}
}
}
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, Double> ret = new HashMap<>(8);
ret.put(Dict.SCORE, score);
ret.put(Dict.MODEL_WRIGHT_HIT_RATE, modelWeightHitRate);
ret.put(Dict.INPUT_DATA_HIT_RATE, inputDataHitRate);
return ret;
}
Map<String, Double> forwardParallel(List<Map<String, Object>> inputDatas) {
Map<String, Object> inputData = inputDatas.get(0);
Map<String, Double> ret = new HashMap<>(8);
double modelWeightHitRate = -1.0;
double inputDataHitRate = -1.0;
Set<String> inputKeys = inputData.keySet();
Set<String> weightKeys = weight.keySet();
Set<String> joinKeys = Sets.newHashSet();
joinKeys.addAll(inputKeys);
joinKeys.retainAll(weightKeys);
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;
ForkJoinTask<LRTaskResult> result = forkJoinPool.submit(new LRTask(weight, inputData, Lists.newArrayList(joinKeys)));
if (result != null) {
try {
LRTaskResult lrTaskResult = result.get();
score = lrTaskResult.score;
modelWeightHitCount = lrTaskResult.modelWeightHitCount;
inputDataHitCount = lrTaskResult.inputDataHitCount;
score += this.intercept;
ret.put(Dict.SCORE, score);
modelWeightHitRate = (double) modelWeightHitCount / weightNum;
inputDataHitRate = (double) inputDataHitCount / inputFeaturesNum;
ret.put(Dict.MODEL_WRIGHT_HIT_RATE, modelWeightHitRate);
ret.put(Dict.INPUT_DATA_HIT_RATE, inputDataHitRate);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return ret;
}
public class LRTask extends RecursiveTask<LRTaskResult> {
double modelWeightHitRate = -1.0;
double inputDataHitRate = -1.0;
int splitSize = MetaInfo.PROPERTY_LR_SPLIT_SIZE;
List<String> keys;
Map<String, Object> inputData;
Map<String, Double> weight;
public LRTask(Map<String, Double> weight, Map<String, Object> inputData, List<String> keys) {
this.keys = keys;
this.inputData = inputData;
this.weight = weight;
}
@Override
protected LRTaskResult compute() {
double score = 0;
int modelWeightHitCount = 0;
int inputDataHitCount = 0;
if (keys.size() <= splitSize) {
for (String key : keys) {
inputData.get(key);
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));
}
}
}
} else {
List<List<Integer>> splits = new ArrayList<List<Integer>>();
int size = keys.size();
int count = (size + splitSize - 1) / splitSize;
List<LRTask> subJobs = Lists.newArrayList();
for (int i = 0; i < count; i++) {
List<String> subList = keys.subList(i * splitSize, ((i + 1) * splitSize > size ? size : splitSize * (i + 1)));
// logger.info("new subLRTask {}",i);
LRTask subLRTask = new LRTask(weight, inputData, subList);
subLRTask.fork();
subJobs.add(subLRTask);
}
for (LRTask lrTask : subJobs) {
LRTaskResult subResult = lrTask.join();
if (subResult != null) {
score = score + subResult.score;
modelWeightHitCount = modelWeightHitCount + subResult.modelWeightHitCount;
inputDataHitCount = inputDataHitCount + subResult.inputDataHitCount;
}
}
}
LRTaskResult lrTaskResult = new LRTaskResult(score, modelWeightHitCount, inputDataHitCount);
return lrTaskResult;
}
}
public class LRTaskResult {
double score = 0;
int modelWeightHitCount = 0;
int inputDataHitCount = 0;
public LRTaskResult(double score, int modelWeightHitCount, int inputDataHitCount) {
this.score = score;
this.modelWeightHitCount = modelWeightHitCount;
this.inputDataHitCount = inputDataHitCount;
}
}
@Override
public Object getParam() {
// Map<String,Object> paramsMap = Maps.newHashMap();
// paramsMap.putAll(weight);
// return paramsMap;
return lrModelParam;
}
public static void main(String[] args) {
Set set1 = new HashSet();
set1.add("1");
set1.add("2");
set1.add("3");
Set set2 = new HashSet();
set2.add("2");
set2.add("3");
Set set3 = new HashSet();
set3.addAll(set1);
set3.retainAll(set2);
System.err.println(set3);
}
}
| java | 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/MinMaxScale.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/MinMaxScale.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.ScaleParamProto.ColumnScaleParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class MinMaxScale {
private static final Logger logger = LoggerFactory.getLogger(MinMaxScale.class);
public Map<String, Object> transform(Map<String, Object> inputData, Map<String, ColumnScaleParam> scales) {
if (logger.isDebugEnabled()) {
logger.info("Start MinMaxScale transform");
}
for (String key : inputData.keySet()) {
try {
if (scales.containsKey(key)) {
ColumnScaleParam scale = scales.get(key);
double value = Double.parseDouble(inputData.get(key).toString());
if (value > scale.getColumnUpper()) {
value = 1;
} else if (value < scale.getColumnLower()) {
value = 0;
} else {
double range = scale.getColumnUpper() - scale.getColumnLower();
if (range < 0) {
if (logger.isDebugEnabled()) {
logger.warn("min_max_scale range may be error, it should be larger than 0, but is {}, set value to 0 ", range);
}
value = 0;
} else {
if (Math.abs(range - 0) < 1e-6) {
range = 1;
}
value = (value - scale.getColumnLower()) / range;
}
}
inputData.put(key, value);
} else {
if (logger.isDebugEnabled()) {
logger.warn("feature {} is not in scale, maybe missing or do not need to be scaled", key);
}
}
} catch (Exception ex) {
//ex.printStackTrace();
logger.error("MinMaxScale transform error", ex);
}
}
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/HeteroSecureBoostingTreeHost.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroSecureBoostingTreeHost.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.BoostTreeModelParamProto.DecisionTreeModelParam;
import com.webank.ai.fate.core.mlmodel.buffer.BoostTreeModelParamProto.NodeParam;
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 java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HeteroSecureBoostingTreeHost extends HeteroSecureBoost implements LocalInferenceAware, Returnable {
private final String role = "host";
private final String modelId = "HeteroSecureBoostingTreeHost"; // need to change
private boolean fastMode = true;
private int traverseTree(int treeId, int treeNodeId, Map<String, Object> input) {
while (getSite(treeId, treeNodeId).equals(this.site)) {
treeNodeId = this.gotoNextLevel(treeId, treeNodeId, input);
}
return treeNodeId;
}
public Map<String, Object> extractHostNodeRoute(Map<String, Object> input) {
Map<String, Object> result = new HashMap<String, Object>(8);
for (int i = 0; i < this.treeNum; i++) {
DecisionTreeModelParam treeParam = this.trees.get(i);
List<NodeParam> nodes = treeParam.getTreeList();
Map<String, Boolean> treeRoute = new HashMap<String, Boolean>(8);
for (int j = 0; j < nodes.size(); j++) {
NodeParam node = nodes.get(j);
if (!this.getSite(i, j).trim().equals(this.site.trim())) {
if (logger.isDebugEnabled()) {
logger.info("{} not equals {}",this.getSite(i, j),this.site);
}
continue;
}
int fid = this.trees.get(i).getTree(j).getFid();
double splitValue = this.trees.get(i).getSplitMaskdict().get(j);
boolean direction = false; // false go right, true go left
if (logger.isDebugEnabled()) {
logger.info("i is {}, j is {}", i, j);
logger.info("best fid is {}", fid);
logger.info("best split val is {}", splitValue);
}
if (input.containsKey(Integer.toString(fid))) {
Object featVal = input.get(Integer.toString(fid));
direction = Double.parseDouble(featVal.toString()) <= splitValue + 1e-8;
} else {
if (this.trees.get(i).getMissingDirMaskdict().containsKey(j)) {
int missingDir = this.trees.get(i).getMissingDirMaskdict().get(j);
direction = (missingDir != 1);
}
}
treeRoute.put(Integer.toString(j), direction);
}
result.put(Integer.toString(i), treeRoute);
}
if (logger.isDebugEnabled()) {
logger.info("show return route:{}", result);
}
return result;
}
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> request) {
String tag = context.getCaseId() + "." + this.componentName + "." + Dict.INPUT_DATA;
Map<String, Object> input = request.get(0);
Map<String, Object> ret = new HashMap<String, Object>(8);
HashMap<String, Object> fidValueMapping = new HashMap<String, Object>(8);
int featureHit = 0;
for (String key : input.keySet()) {
if (this.featureNameFidMapping.containsKey(key)) {
fidValueMapping.put(this.featureNameFidMapping.get(key).toString(), input.get(key));
++featureHit;
}
}
ret = this.extractHostNodeRoute(fidValueMapping);
return ret;
}
} | java | 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/StandardScale.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/StandardScale.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.ScaleParamProto.ColumnScaleParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class StandardScale {
private static final Logger logger = LoggerFactory.getLogger(StandardScale.class);
public Map<String, Object> transform(Map<String, Object> inputData, Map<String, ColumnScaleParam> standardScalesMap) {
for (String key : inputData.keySet()) {
try {
if (standardScalesMap.containsKey(key)) {
ColumnScaleParam standardScale = standardScalesMap.get(key);
double value = Double.parseDouble(inputData.get(key).toString());
double upper = standardScale.getColumnUpper();
double lower = standardScale.getColumnLower();
if (value > upper) {
value = upper;
} else if (value < lower) {
value = lower;
}
double std = standardScale.getStd();
if (std == 0) {
std = 1;
}
value = (value - standardScale.getMean()) / std;
inputData.put(key, value);
} else {
if (logger.isDebugEnabled()) {
logger.debug("feature {} is not in scale, maybe missing or do not need to be scaled");
}
}
} catch (Exception ex) {
logger.error("StandardScale transform error", ex);
}
}
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/FeatureSelection.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/FeatureSelection.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.FeatureSelectionMetaProto.FeatureSelectionMeta;
import com.webank.ai.fate.core.mlmodel.buffer.FeatureSelectionParamProto.FeatureSelectionParam;
import com.webank.ai.fate.core.mlmodel.buffer.FeatureSelectionParamProto.LeftCols;
import com.webank.ai.fate.serving.common.flow.MetricNode;
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;
public class FeatureSelection extends BaseComponent {
private static final Logger logger = LoggerFactory.getLogger(FeatureSelection.class);
private FeatureSelectionParam featureSelectionParam;
private FeatureSelectionMeta featureSelectionMeta;
private LeftCols finalLeftCols;
private boolean needRun;
@Override
public int initModel(byte[] protoMeta, byte[] protoParam) {
logger.info("start init Feature Selection class");
this.needRun = false;
try {
this.featureSelectionMeta = this.parseModel(FeatureSelectionMeta.parser(), protoMeta);
this.needRun = this.featureSelectionMeta.getNeedRun();
this.featureSelectionParam = this.parseModel(FeatureSelectionParam.parser(), protoParam);
this.finalLeftCols = featureSelectionParam.getFinalLeftCols();
} catch (Exception ex) {
ex.printStackTrace();
return ILLEGALDATA;
}
logger.info("Finish init Feature Selection class");
return OK;
}
@Override
public Object getParam() {
// return JsonUtil.object2Objcet(featureSelectionParam, new TypeReference<Map<String, Object>>() {});
return featureSelectionParam;
}
@Override
public Map<String, Object> localInference(Context context, List<Map<String, Object>> inputData) {
HashMap<String, Object> outputData = new HashMap<>(8);
Map<String, Object> firstData = inputData.get(0);
if (!this.needRun) {
return firstData;
}
for (String key : firstData.keySet()) {
if (this.finalLeftCols.getLeftCols().containsKey(key)) {
Boolean isLeft = this.finalLeftCols.getLeftCols().get(key);
if (isLeft) {
outputData.put(key, firstData.get(key));
}
}
}
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/HeteroFMGuest.java | fate-serving-federatedml/src/main/java/com/webank/ai/fate/serving/federatedml/model/HeteroFMGuest.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.base.Preconditions;
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.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.lang.Math.exp;
public class HeteroFMGuest extends HeteroFM implements MergeInferenceAware, Returnable {
private static final Logger logger = LoggerFactory.getLogger(HeteroFMGuest.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> forwardRet = forward(input);
return forwardRet;
}
@Override
public Map<String, Object> mergeRemoteInference(Context context, List<Map<String, Object>> localDataList, Map<String, Object> hostData) {
Map<String, Object> result = this.handleRemoteReturnData(hostData);
if ((int) result.get(Dict.RET_CODE) == StatusCode.SUCCESS) {
Map<String, Object> localData = (Map<String, Object>) localDataList.get(0).get(this.getComponentName());
Preconditions.checkArgument(localData != null);
Preconditions.checkArgument(hostData != null);
Preconditions.checkArgument(localData.get(Dict.SCORE) != null);
Preconditions.checkArgument(localData.get(Dict.FM_CROSS) != null);
Set<String> set = hostData.keySet();
String partyId = (String) set.toArray()[0];
Map<String, Object> remoteData = (Map<String, Object>) hostData.get(partyId);
Preconditions.checkArgument(remoteData.get(Dict.RET_CODE) != null);
Map<String, Object> dataMap = (Map<String, Object>) remoteData.get(this.getComponentName());
double localScore = ((Number) localData.get(Dict.SCORE)).doubleValue();
logger.info("local score: {}", localScore);
double[] guestCrosses = (double[]) localData.get(Dict.FM_CROSS);
localData.get(Dict.FM_CROSS);
double score = localScore;
double hostScore = ((Number) dataMap.get(Dict.SCORE)).doubleValue();
logger.info("host score: {}", hostScore);
Preconditions.checkArgument(dataMap.get(Dict.FM_CROSS) != null);
List<Double> hostCrosses = JsonUtil.json2List(dataMap.get(Dict.FM_CROSS).toString(), new TypeReference<List<Double>>() {
});
Preconditions.checkArgument(hostCrosses.size() == guestCrosses.length, "");
score += hostScore;
for (int i = 0; i < guestCrosses.length; i++) {
score += hostCrosses.get(i) * guestCrosses[i];
}
double prob = sigmod(score);
result.put(Dict.SCORE, prob);
result.put(Dict.GUEST_MODEL_WEIGHT_HIT_RATE, localData.get(Dict.MODEL_WRIGHT_HIT_RATE));
result.put(Dict.GUEST_INPUT_DATA_HIT_RATE, localData.get(Dict.INPUT_DATA_HIT_RATE));
}
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-proxy/src/test/java/com/webank/ai/fate/serving/proxy/test/CommonServiceTest.java | fate-serving-proxy/src/test/java/com/webank/ai/fate/serving/proxy/test/CommonServiceTest.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.proxy.test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Preconditions;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceProto;
import com.webank.ai.fate.api.networking.common.CommonServiceProto;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.serving.common.bean.BaseContext;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
import com.webank.ai.fate.serving.common.flow.MetricNode;
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.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.utils.JsonUtil;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.runners.MethodSorters;
import java.util.List;
@RunWith(JUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CommonServiceTest {
static {
HttpClientPool.initPool();
}
@BeforeClass
public static void init() {
}
private Proxy.Packet buildPacket(Context context, FederatedRpcInvoker.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();
}
@Test
public void test_http_unary() {
String url = "http://localhost:8059/uncary";
Model guestModel = new Model();
Model hostModel = new Model();
guestModel.setPartId("9999");
hostModel.setPartId("10000");
hostModel.setNamespace("testNamespace");
hostModel.setTableName("testTablename");
MetaInfo.PROPERTY_SERVICE_ROLE_NAME="serving";
ServingServerContext context = new ServingServerContext();
context.setModel(guestModel);
FederatedRpcInvoker.RpcDataWraper rpcDataWraper = new FederatedRpcInvoker.RpcDataWraper();
rpcDataWraper.setRemoteMethodName("uncaryCall");
rpcDataWraper.setData("my name is test");
rpcDataWraper.setHostModel(hostModel);
Proxy.Packet packet =buildPacket(context,rpcDataWraper);
try {
String content= JsonFormat.printer().print(packet);
System.err.println("================"+content);
String result = HttpClientPool.sendPost(url,content,null);
System.err.println("==============result:"+result);
Proxy.Packet.Builder resultBuilder = Proxy.Packet.newBuilder();
JsonFormat.parser().merge(result,resultBuilder);
Proxy.Packet resultPacket = resultBuilder.build();
System.err.println(resultPacket.getBody().getValue().toStringUtf8());
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/controller/ProxyController.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/controller/ProxyController.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.proxy.controller;
import com.google.common.collect.Maps;
import com.google.protobuf.ByteString;
import com.google.protobuf.util.JsonFormat;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.serving.common.bean.BaseContext;
import com.webank.ai.fate.serving.common.rpc.core.InboundPackage;
import com.webank.ai.fate.serving.common.rpc.core.OutboundPackage;
import com.webank.ai.fate.serving.common.rpc.core.ServiceAdaptor;
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.rpc.grpc.GrpcType;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.core.utils.ProtobufUtils;
import com.webank.ai.fate.serving.proxy.rpc.core.ProxyServiceRegister;
import com.webank.ai.fate.serving.proxy.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
/**
* @Description TODO
* @Author
**/
@Controller
public class ProxyController {
Logger logger = LoggerFactory.getLogger(ProxyController.class);
@Autowired
ProxyServiceRegister proxyServiceRegister;
@RequestMapping(value = "/unary", method = {RequestMethod.POST, RequestMethod.GET})
@ResponseBody
public Callable<String> uncaryCall(
@RequestBody String data,
HttpServletRequest httpServletRequest,
@RequestHeader HttpHeaders headers
) throws Exception {
return new Callable<String>() {
@Override
public String call() throws Exception {
final ServiceAdaptor serviceAdaptor = proxyServiceRegister.getServiceAdaptor("unaryCall");
Proxy.Packet.Builder packetBuilder = Proxy.Packet.newBuilder();
try {
JsonFormat.parser().merge(data, packetBuilder);
}catch(Exception e){
logger.error("invalid http param {}",data);
return JsonFormat.printer().print(returnInvalidParam());
}
packetBuilder.build();
Context context = new BaseContext();
context.setCallName("unaryCall");
context.setGrpcType(GrpcType.INTER_GRPC);
InboundPackage<Proxy.Packet> inboundPackage = buildInboundPackage(context, packetBuilder.build());
OutboundPackage<Proxy.Packet> result = serviceAdaptor.service(context, inboundPackage);
return JsonFormat.printer().print(result.getData());
}
};
}
@RequestMapping(value = "/federation/{version}/{callName}", method = {RequestMethod.POST, RequestMethod.GET})
@ResponseBody
public Callable<String> federation(@PathVariable String version,
@PathVariable String callName,
@RequestBody String data,
HttpServletRequest httpServletRequest,
@RequestHeader HttpHeaders headers
) throws Exception {
return new Callable<String>() {
@Override
public String call() throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("receive : {} headers {}", data, headers.toSingleValueMap());
}
String caseId = headers.getFirst("caseId");
final ServiceAdaptor serviceAdaptor = proxyServiceRegister.getServiceAdaptor(callName);
Context context = new BaseContext();
context.setCallName(callName);
context.setVersion(version);
context.setCaseId(caseId);
if (null == context.getCaseId() || context.getCaseId().isEmpty()) {
context.setCaseId(UUID.randomUUID().toString().replaceAll("-", ""));
}
InboundPackage<Map> inboundPackage = buildInboundPackageFederation(context, data, httpServletRequest);
OutboundPackage<Map> result = serviceAdaptor.service(context, inboundPackage);
if (result != null && result.getData() != null) {
result.getData().remove("log");
result.getData().remove("warn");
result.getData().remove("caseid");
return JsonUtil.object2Json(result.getData());
}
return "";
}
};
}
private InboundPackage<Map> buildInboundPackageFederation(Context context, String data,
HttpServletRequest httpServletRequest) {
String sourceIp = WebUtil.getIpAddr(httpServletRequest);
context.setSourceIp(sourceIp);
context.setGuestAppId(String.valueOf(MetaInfo.PROPERTY_COORDINATOR));
Map jsonObject = JsonUtil.json2Object(data, Map.class);
Map head = (Map) jsonObject.getOrDefault(Dict.HEAD, new HashMap<>());
Map body = (Map) jsonObject.getOrDefault(Dict.BODY, new HashMap<>());
context.setHostAppid((String) head.getOrDefault(Dict.APP_ID, ""));
InboundPackage<Map> inboundPackage = new InboundPackage<Map>();
inboundPackage.setBody(body);
inboundPackage.setHead(head);
return inboundPackage;
}
private InboundPackage<Proxy.Packet> buildInboundPackage(Context context, Proxy.Packet req) {
context.setCaseId(Long.toString(System.currentTimeMillis()));
if (StringUtils.isNotBlank(req.getHeader().getOperator())) {
context.setVersion(req.getHeader().getOperator());
}
context.setGuestAppId(req.getHeader().getSrc().getPartyId());
context.setHostAppid(req.getHeader().getDst().getPartyId());
InboundPackage<Proxy.Packet> inboundPackage = new InboundPackage<Proxy.Packet>();
inboundPackage.setBody(req);
return inboundPackage;
}
private Proxy.Packet returnInvalidParam(){
Proxy.Packet.Builder builder = Proxy.Packet.newBuilder();
Proxy.Data.Builder dataBuilder = Proxy.Data.newBuilder();
Map fateMap = Maps.newHashMap();
fateMap.put(Dict.RET_CODE, StatusCode.PROXY_PARAM_ERROR);
fateMap.put(Dict.RET_MSG, "invalid http param");
builder.setBody(dataBuilder.setValue(ByteString.copyFromUtf8(JsonUtil.object2Json(fateMap))));
return builder.build();
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/controller/DynamicLogController.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/controller/DynamicLogController.java | package com.webank.ai.fate.serving.proxy.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("/proxy")
@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("proxy 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("proxy 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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/exceptions/GlobalExceptionHandler.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/exceptions/GlobalExceptionHandler.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.proxy.exceptions;
import com.webank.ai.fate.serving.common.rpc.core.ErrorMessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {
Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Throwable.class)
@ResponseBody
public Map defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
Map resultMap = ErrorMessageUtil.handleException(new HashMap(), e);
return resultMap;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/bootstrap/Bootstrap.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/bootstrap/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.proxy.bootstrap;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
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
@ComponentScan(basePackages = {"com.webank.ai.fate.serving.proxy.*"})
@PropertySource("classpath:application.properties")
@EnableScheduling
public class Bootstrap {
private static ApplicationContext applicationContext;
private static Logger logger = LoggerFactory.getLogger(Bootstrap.class);
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) {
System.err.println("server start error, " + ex.getMessage());
ex.printStackTrace();
System.exit(1);
}
}
public static void parseConfig() {
ClassPathResource classPathResource = new ClassPathResource("application.properties");
try {
File file = classPathResource.getFile();
Properties environment = new Properties();
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
environment.load(inputStream);
} catch (FileNotFoundException e) {
logger.error("profile application.properties not found");
} catch (IOException e) {
logger.error("parse config error, {}", e.getMessage());
}
MetaInfo.PROPERTY_COORDINATOR = Integer.valueOf(environment.getProperty(Dict.PROPERTY_COORDINATOR, "9999"));
MetaInfo.PROPERTY_SERVER_PORT = Integer.valueOf(environment.getProperty(Dict.PROPERTY_SERVER_PORT, "8059"));
MetaInfo.PROPERTY_INFERENCE_SERVICE_NAME = environment.getProperty(Dict.PROPERTY_INFERENCE_SERVICE_NAME, "serving");
MetaInfo.PROPERTY_ROUTE_TYPE = environment.getProperty(Dict.PROPERTY_ROUTE_TYPE, "random");
MetaInfo.PROPERTY_ROUTE_TABLE = environment.getProperty(Dict.PROPERTY_ROUTE_TABLE);
MetaInfo.PROPERTY_AUTH_FILE = environment.getProperty(Dict.PROPERTY_AUTH_FILE);
MetaInfo.PROPERTY_AUTH_OPEN = Boolean.valueOf(environment.getProperty(Dict.PROPERTY_AUTH_OPEN, "false"));
MetaInfo.PROPERTY_ZK_URL = environment.getProperty(Dict.PROPERTY_ZK_URL);
MetaInfo.PROPERTY_USE_ZK_ROUTER = Boolean.valueOf(environment.getProperty(Dict.PROPERTY_USE_ZK_ROUTER, "true"));
MetaInfo.PROPERTY_PROXY_GRPC_INTRA_PORT = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_GRPC_INTRA_PORT, "8879"));
MetaInfo.PROPERTY_PROXY_GRPC_INTER_PORT = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_GRPC_INTER_PORT, "8869"));
MetaInfo.PROPERTY_PROXY_GRPC_INFERENCE_TIMEOUT = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_GRPC_INFERENCE_TIMEOUT, "3000"));
MetaInfo.PROPERTY_PROXY_GRPC_INFERENCE_ASYNC_TIMEOUT = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_GRPC_INFERENCE_ASYNC_TIMEOUT, "1000"));
MetaInfo.PROPERTY_PROXY_GRPC_UNARYCALL_TIMEOUT = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_GRPC_UNARYCALL_TIMEOUT, "3000"));
MetaInfo.PROPERTY_PROXY_GRPC_THREADPOOL_CORESIZE = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_GRPC_THREADPOOL_CORESIZE, "50"));
MetaInfo.PROPERTY_PROXY_GRPC_THREADPOOL_MAXSIZE = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_GRPC_THREADPOOL_MAXSIZE, "100"));
MetaInfo.PROPERTY_PROXY_GRPC_THREADPOOL_QUEUESIZE = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_GRPC_THREADPOOL_QUEUESIZE, "10"));
MetaInfo.PROPERTY_PROXY_ASYNC_TIMEOUT = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_ASYNC_TIMEOUT, "5000"));
MetaInfo.PROPERTY_PROXY_ASYNC_CORESIZE = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_ASYNC_CORESIZE, "10"));
MetaInfo.PROPERTY_PROXY_ASYNC_MAXSIZE = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_ASYNC_MAXSIZE, "100"));
MetaInfo.PROPERTY_PROXY_GRPC_BATCH_INFERENCE_TIMEOUT = Integer.valueOf(environment.getProperty(Dict.PROPERTY_PROXY_GRPC_BATCH_INFERENCE_TIMEOUT, "10000"));
MetaInfo.PROPERTY_ACL_ENABLE = Boolean.valueOf(environment.getProperty(Dict.PROPERTY_ACL_ENABLE, "false"));
MetaInfo.PROPERTY_ACL_USERNAME = environment.getProperty(Dict.PROPERTY_ACL_USERNAME);
MetaInfo.PROPERTY_ACL_PASSWORD = environment.getProperty(Dict.PROPERTY_ACL_PASSWORD);
MetaInfo.PROPERTY_PRINT_INPUT_DATA = environment.getProperty(Dict.PROPERTY_PRINT_INPUT_DATA) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_PRINT_INPUT_DATA)) : false;
MetaInfo.PROPERTY_PRINT_OUTPUT_DATA = environment.getProperty(Dict.PROPERTY_PRINT_OUTPUT_DATA) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_PRINT_OUTPUT_DATA)) : false;
// TLS
MetaInfo.PROPERTY_PROXY_GRPC_INTER_NEGOTIATIONTYPE = environment.getProperty(Dict.PROPERTY_PROXY_GRPC_INTER_NEGOTIATIONTYPE, "PLAINTEXT");
MetaInfo.PROPERTY_PROXY_GRPC_INTER_CA_FILE = environment.getProperty(Dict.PROPERTY_PROXY_GRPC_INTER_CA_FILE);
MetaInfo.PROPERTY_PROXY_GRPC_INTER_CLIENT_CERTCHAIN_FILE = environment.getProperty(Dict.PROPERTY_PROXY_GRPC_INTER_CLIENT_CERTCHAIN_FILE);
MetaInfo.PROPERTY_PROXY_GRPC_INTER_CLIENT_PRIVATEKEY_FILE = environment.getProperty(Dict.PROPERTY_PROXY_GRPC_INTER_CLIENT_PRIVATEKEY_FILE);
MetaInfo.PROPERTY_PROXY_GRPC_INTER_SERVER_CERTCHAIN_FILE = environment.getProperty(Dict.PROPERTY_PROXY_GRPC_INTER_SERVER_CERTCHAIN_FILE);
MetaInfo.PROPERTY_PROXY_GRPC_INTER_SERVER_PRIVATEKEY_FILE = environment.getProperty(Dict.PROPERTY_PROXY_GRPC_INTER_SERVER_PRIVATEKEY_FILE);
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) {
applicationContext = SpringApplication.run(Bootstrap.class, args);
JvmInfoCounter.start();
HttpClientPool.initPool();
}
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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/services/UnaryCallService.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/services/UnaryCallService.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.proxy.rpc.services;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.webank.ai.fate.api.networking.proxy.DataTransferServiceGrpc;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.serving.common.rpc.core.AbstractServiceAdaptor;
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.common.utils.HttpClientPool;
import com.webank.ai.fate.serving.core.bean.*;
import com.webank.ai.fate.serving.core.exceptions.*;
import com.webank.ai.fate.serving.core.rpc.router.Protocol;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.proxy.security.AuthUtils;
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.Map;
import java.util.concurrent.TimeUnit;
@Service
@FateService(name = "unaryCall", preChain = {
"requestOverloadBreaker",
"federationParamValidator",
"defaultAuthentication",
"defaultServingRouter"})
public class UnaryCallService extends AbstractServiceAdaptor<Proxy.Packet, Proxy.Packet> {
Logger logger = LoggerFactory.getLogger(UnaryCallService.class);
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
@Autowired
AuthUtils authUtils;
private int timeout = MetaInfo.PROPERTY_PROXY_GRPC_UNARYCALL_TIMEOUT;
@Override
public Proxy.Packet doService(Context context, InboundPackage<Proxy.Packet> data, OutboundPackage<Proxy.Packet> outboundPackage) {
Proxy.Packet sourcePackage = data.getBody();
RouterInfo routerInfo = data.getRouterInfo();
try {
sourcePackage = authUtils.addAuthInfo(sourcePackage);
} catch (Exception e) {
logger.error("add auth info error", e);
throw new ProxyAuthException("add auth info error");
}
if(routerInfo.getProtocol()==null||routerInfo.getProtocol().equals(Protocol.GRPC)){
return grpcTransfer(context,sourcePackage,routerInfo);
}else if(routerInfo.getProtocol().equals(Protocol.HTTP)){
return httpTransfer(context,sourcePackage,routerInfo);
}else{
throw new RemoteRpcException("");
}
}
private Proxy.Packet grpcTransfer(Context context,Proxy.Packet sourcePackage,RouterInfo routerInfo){
try {
NettyServerInfo nettyServerInfo;
if (routerInfo.isUseSSL()) {
nettyServerInfo = new NettyServerInfo(routerInfo.getNegotiationType(), routerInfo.getCertChainFile(),
routerInfo.getPrivateKeyFile(), routerInfo.getCaFile());
} else {
nettyServerInfo = new NettyServerInfo();
}
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(routerInfo.getHost(), routerInfo.getPort(), nettyServerInfo);
DataTransferServiceGrpc.DataTransferServiceFutureStub stub1 = DataTransferServiceGrpc.newFutureStub(managedChannel);
stub1.withDeadlineAfter(timeout, TimeUnit.MILLISECONDS);
context.setDownstreamBegin(System.currentTimeMillis());
ListenableFuture<Proxy.Packet> future = stub1.unaryCall(sourcePackage);
Proxy.Packet packet = future.get(timeout, TimeUnit.MILLISECONDS);
return packet;
} catch (Exception e) {
logger.error("unaryCall error", e);
throw new RemoteRpcException("grpc unaryCall error " + routerInfo.toString());
} finally {
long end = System.currentTimeMillis();
context.setDownstreamCost(end - context.getDownstreamBegin());
}
}
private Proxy.Packet httpTransfer(Context context,Proxy.Packet sourcePackage,RouterInfo routerInfo) throws BaseException{
try {
String url = routerInfo.getUrl();
String content = null;
content = JsonFormat.printer().print(sourcePackage);
String resultJson = HttpClientPool.sendPost(url, content, null);
logger.info("result json {}", resultJson);
Proxy.Packet.Builder resultBuilder = Proxy.Packet.newBuilder();
try {
JsonFormat.parser().merge(resultJson, resultBuilder);
}catch(Exception e){
logger.error("receive invalid http response {}",resultJson);
throw new InvalidResponseException("receive invalid http response");
}
return resultBuilder.build();
}catch(Exception e){
if(e instanceof BaseException){
throw (BaseException) e;
}else{
throw new SysException(e.getMessage());
}
}
}
@Override
protected Proxy.Packet transformExceptionInfo(Context context, ExceptionInfo exceptionInfo) {
Proxy.Packet.Builder builder = Proxy.Packet.newBuilder();
Proxy.Data.Builder dataBuilder = Proxy.Data.newBuilder();
Map fateMap = Maps.newHashMap();
fateMap.put(Dict.RET_CODE, exceptionInfo.getCode()+500);
fateMap.put(Dict.RET_MSG, exceptionInfo.getMessage());
builder.setBody(dataBuilder.setValue(ByteString.copyFromUtf8(JsonUtil.object2Json(fateMap))));
return builder.build();
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/services/InferenceService.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/services/InferenceService.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.proxy.rpc.services;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.serving.InferenceServiceGrpc;
import com.webank.ai.fate.api.serving.InferenceServiceProto;
import com.webank.ai.fate.serving.common.rpc.core.AbstractServiceAdaptor;
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.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.GrpcConnectionPool;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.exceptions.RemoteRpcException;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import io.grpc.ManagedChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
@FateService(name = Dict.SERVICENAME_INFERENCE, preChain = {
"requestOverloadBreaker",
"inferenceParamValidator",
"defaultServingRouter"})
public class InferenceService extends AbstractServiceAdaptor<Map, Map> {
Logger logger = LoggerFactory.getLogger(InferenceService.class);
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
private int timeout = MetaInfo.PROPERTY_PROXY_GRPC_INFERENCE_TIMEOUT;
public InferenceService() {
}
@Override
public Map doService(Context context, InboundPackage<Map> data, OutboundPackage<Map> outboundPackage) {
Map resultMap = Maps.newHashMap();
RouterInfo routerInfo = data.getRouterInfo();
ManagedChannel managedChannel = null;
String resultString = null;
ListenableFuture<InferenceServiceProto.InferenceMessage> resultFuture;
try {
managedChannel = this.grpcConnectionPool.getManagedChannel(routerInfo.getHost(), routerInfo.getPort());
} catch (Exception e) {
logger.error("get grpc channel error", e);
throw new RemoteRpcException("remote rpc exception");
}
Map reqBodyMap = data.getBody();
Map reqHeadMap = data.getHead();
Map inferenceReqMap = Maps.newHashMap();
inferenceReqMap.put(Dict.CASE_ID, context.getCaseId());
inferenceReqMap.putAll(reqHeadMap);
inferenceReqMap.putAll(reqBodyMap);
InferenceServiceProto.InferenceMessage.Builder reqBuilder = InferenceServiceProto.InferenceMessage.newBuilder();
reqBuilder.setBody(ByteString.copyFrom(JsonUtil.object2Json(inferenceReqMap).getBytes()));
InferenceServiceGrpc.InferenceServiceFutureStub futureStub = InferenceServiceGrpc.newFutureStub(managedChannel);
resultFuture = futureStub.inference(reqBuilder.build());
try {
InferenceServiceProto.InferenceMessage result = resultFuture.get(timeout, TimeUnit.MILLISECONDS);
resultString = new String(result.getBody().toByteArray());
} catch (Exception e) {
logger.error("remote {} get grpc result error", routerInfo);
throw new RemoteRpcException("remote rpc exception");
}
if (StringUtils.isNotEmpty(resultString)) {
resultMap = JsonUtil.json2Object(resultString, Map.class);
}
return resultMap;
}
@Override
protected Map transformExceptionInfo(Context context, ExceptionInfo exceptionInfo) {
Map map = Maps.newHashMap();
map.put(Dict.RET_CODE, exceptionInfo.getCode());
map.put(Dict.RET_MSG, exceptionInfo.getMessage());
return 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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/services/HealthCheckEndPointService.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/services/HealthCheckEndPointService.java | package com.webank.ai.fate.serving.proxy.rpc.services;
import com.google.common.collect.Maps;
import com.webank.ai.fate.api.core.BasicMeta;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.register.utils.StringUtils;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.common.health.*;
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.core.rpc.router.RouterInfo;
import com.webank.ai.fate.serving.proxy.rpc.router.ConfigFileBasedServingRouter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
public class HealthCheckEndPointService implements HealthCheckAware {
@Autowired
ConfigFileBasedServingRouter configFileBasedServingRouter;
@Autowired(required = false)
ZookeeperRegistry zookeeperRegistry;
Logger logger = LoggerFactory.getLogger(HealthCheckEndPointService.class);
private void checkSshCertConfig(HealthCheckResult healthCheckResult){
Map<Proxy.Topic, List<RouterInfo>> routerInfoMap = configFileBasedServingRouter.getAllRouterInfoMap();
if(routerInfoMap!=null&&routerInfoMap.size()>0){
routerInfoMap.forEach((k,v)-> {
if(v!=null){
v.forEach(routerInfo -> {
if (routerInfo.isUseSSL()) {
String caFilePath = routerInfo.getCaFile();
if (StringUtils.isNotEmpty(caFilePath)) {
File caFile = new File(caFilePath);
if (caFile.exists()) {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_ROUTER_NET.getItemName(), "check cert file :" + caFilePath + " is found", HealthCheckStatus.ok));
} else {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_ROUTER_NET.getItemName(), "check cert file :" + caFilePath + " is not found", HealthCheckStatus.error));
}
} else {
// healthCheckResult.ge();
}
String certChainFilePath = routerInfo.getCertChainFile();
if (StringUtils.isNotEmpty(certChainFilePath)) {
File certChainFile = new File(certChainFilePath);
if (certChainFile.exists()) {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_CERT_FILE.getItemName(), "check cert file :" + certChainFilePath + " is found", HealthCheckStatus.ok));
} else {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_CERT_FILE.getItemName(), "check cert file :" + certChainFilePath + " is not found", HealthCheckStatus.ok));
}
}
String privateKeyFilePath = routerInfo.getPrivateKeyFile();
if (StringUtils.isNotEmpty(privateKeyFilePath)) {
File privateKeyFile = new File(privateKeyFilePath);
if (privateKeyFile.exists()) {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_CERT_FILE.getItemName(), "check cert file :" + privateKeyFilePath + " is found", HealthCheckStatus.ok));
// healthCheckResult.getOkList().add("check cert file :" + privateKeyFilePath + " is found");
} else {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_CERT_FILE.getItemName(), "check cert file :" + privateKeyFilePath + " is found", HealthCheckStatus.ok));
// healthCheckResult.getErrorList().add("check cert file :" + privateKeyFilePath + " is not found");
}
}
}
});
}
});
}
}
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));
}
}
// if(!MetaInfo.PROPERTY_USE_ZK_ROUTER.booleanValue()){
// healthCheckResult.getWarnList().add(MetaInfo.PROPERTY_USE_ZK_ROUTER+":"+MetaInfo.PROPERTY_USE_ZK_ROUTER+"="+MetaInfo.PROPERTY_USE_ZK_ROUTER);
// }else{
// if(StringUtils.isNotEmpty(MetaInfo.PROPERTY_ZK_URL)){
// healthCheckResult.getOkList().add("check zk config "+": ok ");
// }else {
// healthCheckResult.getErrorList().add("check zk config "+": no config ");
// }
// }
}
private void checkRouterInfo(HealthCheckResult healthCheckResult){
// if(!MetaInfo.PROPERTY_USE_REGISTER.booleanValue()){
// healthCheckResult.getWarnList().add(MetaInfo.PROPERTY_USE_REGISTER+":"+MetaInfo.PROPERTY_USE_REGISTER+"="+MetaInfo.PROPERTY_USE_REGISTER);
// }else{
// if(StringUtils.isNotEmpty(MetaInfo.PROPERTY_ZK_URL)){
// healthCheckResult.getOkList().add(MetaInfo.PROPERTY_ZK_URL+":"+MetaInfo.PROPERTY_ZK_URL);
// }else {
// healthCheckResult.getErrorList().add(MetaInfo.PROPERTY_ZK_URL+":"+MetaInfo.PROPERTY_ZK_URL);
// }
// }
HealthCheckRecord routerConfigCheck = new HealthCheckRecord();
if(configFileBasedServingRouter.getRouteTable()==null||configFileBasedServingRouter.getRouteTable().size()==0){
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_ROUTER_FILE.getItemName(),"check router file : no router info found",HealthCheckStatus.error));
// healthCheckResult.getErrorList().add("check route_table.json "+": no router info found");
}else{
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_ROUTER_FILE.getItemName(),"check router file : router info is found",HealthCheckStatus.ok));
// healthCheckResult.getOkList().add("check route_table.json "+": route_table.json is found");
}
routerInfoCheck(healthCheckResult);
}
private void routerInfoCheck(HealthCheckResult healthCheckResult){
Map<String, Map<String, List<BasicMeta.Endpoint>>> routerInfoMap = configFileBasedServingRouter.getRouteTable();
if(routerInfoMap!=null&&routerInfoMap.size()>0){
routerInfoMap.values().forEach(value->{
value.forEach((k,v)->{
if(v!=null){
v.forEach(endpoint -> {
try {
boolean connectAble;
if(StringUtils.isNotEmpty(endpoint.getUrl())){
Map<String,String> resultMap = getIpPortFromUrl(endpoint.getUrl());
connectAble = TelnetUtil.tryTelnet(resultMap.get("IP"), Integer.valueOf(resultMap.get("PORT")));
if (!connectAble) {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_ROUTER_NET.getItemName(), resultMap.get("IP") + " " + Integer.valueOf(resultMap.get("PORT")) + ": can not be telneted",HealthCheckStatus.warn));
//("check router " + routerInfo.getHost() + " " + routerInfo.getPort() + ": can not be telneted");
} else {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_ROUTER_NET.getItemName(), resultMap.get("IP") + " " + Integer.valueOf(resultMap.get("PORT")) + ": telneted",HealthCheckStatus.ok
));
}
}else{
connectAble = TelnetUtil.tryTelnet(endpoint.getIp(), endpoint.getPort());
if (!connectAble) {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_ROUTER_NET.getItemName(), endpoint.getIp() + " " + endpoint.getPort() + ": can not be telneted",HealthCheckStatus.warn));
//("check router " + routerInfo.getHost() + " " + routerInfo.getPort() + ": can not be telneted");
} else {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_ROUTER_NET.getItemName(), endpoint.getIp() + " " + endpoint.getPort() + ": telneted",HealthCheckStatus.ok
));
}
}
}catch (Exception e){
e.printStackTrace();
}
});
}
});
});
}
}
private static Map<String,String> getIpPortFromUrl(String url){
Map<String,String> resutlMap = Maps.newHashMap();
if(url.startsWith("http://localhost")){
url = url.replace("http://localhost","http://127.0.0.1");
}
if(url.startsWith("https://localhost")){
url = url.replace("https://localhost","https://127.0.0.1");
}
String host = "";
Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+(:\\d{0,5})?");
Matcher matcher = p.matcher(url);
if(matcher.find()){
host = matcher.group();
}
if(host.contains(":") == false){
resutlMap.put("IP",host);
resutlMap.put("PORT","80");
return resutlMap;
}
String[] ipPortArr = host.split(":");
resutlMap.put("IP",ipPortArr[0]);
resutlMap.put("PORT",ipPortArr[1]);
return resutlMap;
}
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.SERVINGPROXY;
}).forEach((item) -> {
switch (item) {
// CHECK_ROUTER_FILE("check route_table.json exist",HealthCheckComponent.SERVINGPROXY),
// CHECK_ZOOKEEPER_CONFIG("check zk config",HealthCheckComponent.ALL),
// CHECK_ROUTER_NET("check router",HealthCheckComponent.SERVINGPROXY),
// CHECK_MEMORY_USAGE("check memory usage",HealthCheckComponent.ALL),
// CHECK_CERT_FILE("check cert file",HealthCheckComponent.SERVINGPROXY);
case CHECK_MEMORY_USAGE:
HealthCheckUtil.memoryCheck(healthCheckResult);
break;
case CHECK_CERT_FILE:
this.checkSshCertConfig(healthCheckResult);break;
case CHECK_ZOOKEEPER_CONFIG:
break;
case CHECK_ROUTER_FILE:
this.checkRouterInfo(healthCheckResult);
break;
// case HealthCheckItemEnum.CHECK_CERT_FILE: 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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/services/NotFoundService.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/services/NotFoundService.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.proxy.rpc.services;
import com.webank.ai.fate.serving.common.rpc.core.AbstractServiceAdaptor;
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.Context;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
@FateService(name = "NotFound")
public class NotFoundService extends AbstractServiceAdaptor<String, Map> {
@Override
public Map doService(Context context, InboundPackage<String> data, OutboundPackage<Map> outboundPackage) {
ReturnResult returnResult = ReturnResult.build(StatusCode.SERVICE_NOT_FOUND, "SERVICE_NOT_FOUND");
return JsonUtil.json2Object(returnResult.toString(), Map.class);
}
@Override
public OutboundPackage<Map> serviceFail(Context context, InboundPackage<String> data, List<Throwable> e) {
return null;
}
@Override
protected Map transformExceptionInfo(Context context, ExceptionInfo exceptionInfo) {
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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/services/BatchInferenceService.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/services/BatchInferenceService.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.proxy.rpc.services;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.serving.InferenceServiceGrpc;
import com.webank.ai.fate.api.serving.InferenceServiceProto;
import com.webank.ai.fate.serving.common.rpc.core.AbstractServiceAdaptor;
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.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.GrpcConnectionPool;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.exceptions.RemoteRpcException;
import com.webank.ai.fate.serving.core.exceptions.UnSupportMethodException;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import io.grpc.ManagedChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
@FateService(name = Dict.SERVICENAME_BATCH_INFERENCE, preChain = {
"requestOverloadBreaker",
"inferenceParamValidator",
"defaultServingRouter"})
public class BatchInferenceService extends AbstractServiceAdaptor<Map, Map> {
Logger logger = LoggerFactory.getLogger(BatchInferenceService.class);
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
private int timeout = MetaInfo.PROPERTY_PROXY_GRPC_BATCH_INFERENCE_TIMEOUT;
public BatchInferenceService() {
}
@Override
public Map doService(Context context, InboundPackage<Map> data, OutboundPackage<Map> outboundPackage) {
Map resultMap = Maps.newHashMap();
RouterInfo routerInfo = data.getRouterInfo();
ManagedChannel managedChannel = null;
String resultString = null;
String callName = context.getCallName();
ListenableFuture<InferenceServiceProto.InferenceMessage> resultFuture;
try {
if (logger.isDebugEnabled()) {
logger.debug("try to get grpc connection");
}
managedChannel = this.grpcConnectionPool.getManagedChannel(routerInfo.getHost(), routerInfo.getPort());
} catch (Exception e) {
logger.error("get grpc channel error", e);
throw new RemoteRpcException("remote rpc exception");
}
Map reqBodyMap = data.getBody();
Map reqHeadMap = data.getHead();
Map inferenceReqMap = Maps.newHashMap();
inferenceReqMap.put(Dict.CASE_ID, context.getCaseId());
inferenceReqMap.putAll(reqHeadMap);
inferenceReqMap.putAll(reqBodyMap);
if (logger.isDebugEnabled()) {
logger.debug("batch inference req : {}", JsonUtil.object2Json(inferenceReqMap));
}
InferenceServiceProto.InferenceMessage.Builder reqBuilder = InferenceServiceProto.InferenceMessage.newBuilder();
reqBuilder.setBody(ByteString.copyFrom(JsonUtil.object2Json(inferenceReqMap).getBytes()));
InferenceServiceGrpc.InferenceServiceFutureStub futureStub = InferenceServiceGrpc.newFutureStub(managedChannel);
if (callName.equals(Dict.SERVICENAME_BATCH_INFERENCE)) {
resultFuture = futureStub.batchInference(reqBuilder.build());
} else {
logger.error("unknown callName {}.", callName);
throw new UnSupportMethodException();
}
try {
logger.info("routerinfo {}", routerInfo);
InferenceServiceProto.InferenceMessage result = resultFuture.get(timeout, TimeUnit.MILLISECONDS);
if (logger.isDebugEnabled()) {
logger.debug("send {} result {}", routerInfo, inferenceReqMap, result);
}
resultString = new String(result.getBody().toByteArray());
} catch (Exception e) {
logger.error("get grpc result error", e);
throw new RemoteRpcException("remote rpc exception");
}
if (StringUtils.isNotEmpty(resultString)) {
resultMap = JsonUtil.json2Object(resultString, Map.class);
}
return resultMap;
}
@Override
protected Map transformExceptionInfo(Context context, ExceptionInfo exceptionInfo) {
Map map = Maps.newHashMap();
map.put(Dict.RET_CODE, exceptionInfo.getCode());
map.put(Dict.RET_MSG, exceptionInfo.getMessage());
return 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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/provider/AbstractProxyServiceProvider.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/provider/AbstractProxyServiceProvider.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.proxy.rpc.provider;
import com.webank.ai.fate.serving.common.rpc.core.AbstractServiceAdaptor;
import com.webank.ai.fate.serving.common.rpc.core.InboundPackage;
import com.webank.ai.fate.serving.common.rpc.core.OutboundPackage;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.exceptions.BaseException;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import com.webank.ai.fate.serving.core.exceptions.UnSupportMethodException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
public abstract class AbstractProxyServiceProvider<req, resp> extends AbstractServiceAdaptor<req, resp> {
Logger logger = LoggerFactory.getLogger(AbstractProxyServiceProvider.class);
@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) {
logger.error("xxxxxxx",e);
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("{}|{}|" +
"{}|{}|{}|{}|" +
"{}|{}",
context.getCaseId(), context.getReturnCode(), context.getCostTime(),
context.getDownstreamCost(), serviceName, context.getRouterInfo() != null ? context.getRouterInfo() : "");
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/provider/CommonServiceProvider.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/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.proxy.rpc.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.proxy.bean.RouteTableWrapper;
import com.webank.ai.fate.serving.proxy.rpc.router.ConfigFileBasedServingRouter;
import com.webank.ai.fate.serving.proxy.rpc.services.HealthCheckEndPointService;
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.io.File;
import java.io.FileOutputStream;
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 AbstractProxyServiceProvider {
private static final Logger logger = LoggerFactory.getLogger(CommonServiceProvider.class);
private String userDir = System.getProperty(Dict.PROPERTY_USER_DIR);
private final String fileSeparator = System.getProperty(Dict.PROPERTY_FILE_SEPARATOR);
private final String DEFAULT_ROUTER_FILE = "conf" + System.getProperty(Dict.PROPERTY_FILE_SEPARATOR) + "route_table.json";
@Autowired
FlowCounterManager flowCounterManager;
@Autowired
HealthCheckEndPointService healthCheckEndPointService;
@Autowired
ConfigFileBasedServingRouter configFileBasedServingRouter;
@Autowired(required = false)
ZookeeperRegistry zookeeperRegistry;
@Override
protected Object transformExceptionInfo(Context context, ExceptionInfo exceptionInfo) {
CommonServiceProto.CommonResponse.Builder builder = CommonServiceProto.CommonResponse.newBuilder();
builder.setStatusCode(exceptionInfo.getCode());
builder.setMessage(exceptionInfo.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();
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())).setStatusCode(StatusCode.SUCCESS).setMessage(Dict.SUCCESS);
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) {
// register
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 = "UPDATE_CONFIG")
public CommonServiceProto.CommonResponse updateConfig(Context context, InboundPackage inboundPackage) {
try {
CommonServiceProto.UpdateConfigRequest request = (CommonServiceProto.UpdateConfigRequest) inboundPackage.getBody();
CommonServiceProto.CommonResponse.Builder builder = CommonServiceProto.CommonResponse.newBuilder();
Preconditions.checkArgument(StringUtils.isNotBlank(request.getFilePath()), "file path is blank");
Preconditions.checkArgument(StringUtils.isNotBlank(request.getData()), "data is blank");
// serving-proxy can only modify the route table
try {
// valid json
RouteTableWrapper wrapper = new RouteTableWrapper();
wrapper.parse(request.getData());
} catch (Exception e) {
logger.error("invalid json format, parse json error");
throw new SysException("invalid json format, parse json error");
}
String filePath = request.getFilePath();
// file exist check
File file = new File(filePath);
if (!file.exists()) {
logger.info("file {} not exist, create new file.", filePath);
file.createNewFile();
}
try (FileOutputStream outputFile = new FileOutputStream(file)) {
outputFile.write(request.getDataBytes().toByteArray());
builder.setStatusCode(StatusCode.SUCCESS).setMessage(Dict.SUCCESS);
}
return builder.build();
} catch (Exception e) {
throw new SysException(e.getMessage());
}
}
@FateServiceMethod(name = "CHECK_HEALTH")
public CommonServiceProto.CommonResponse checkHealthService(Context context, InboundPackage inboundPackage) {
HealthCheckResult healthCheckResult = healthCheckEndPointService.check(context);
CommonServiceProto.CommonResponse.Builder builder = CommonServiceProto.CommonResponse.newBuilder();
builder.setStatusCode(StatusCode.SUCCESS);
builder.setData(ByteString.copyFrom(JsonUtil.object2Json(healthCheckResult).getBytes()));
return builder.build();
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/provider/RouterTableServiceProvider.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/provider/RouterTableServiceProvider.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.proxy.rpc.provider;
import com.google.gson.JsonObject;
import com.google.protobuf.ByteString;
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.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.RouterInfoOperateException;
import com.webank.ai.fate.serving.proxy.common.RouterTableUtils;
import com.webank.ai.fate.serving.proxy.rpc.grpc.RouterTableServiceProto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@FateService(name = "routerTableService", preChain = {
"requestOverloadBreaker"
}, postChain = {
})
@Service
public class RouterTableServiceProvider extends AbstractProxyServiceProvider {
private static final Logger logger = LoggerFactory.getLogger(RouterTableServiceProvider.class);
@FateServiceMethod(name = "QUERY_ROUTER")
public RouterTableServiceProto.RouterOperatetResponse queryRouterTableService(Context context, InboundPackage inboundPackage) {
RouterTableServiceProto.RouterOperatetResponse.Builder builder = RouterTableServiceProto.RouterOperatetResponse.newBuilder();
JsonObject routTableJson = RouterTableUtils.loadRoutTable();
if (routTableJson == null) {
builder.setStatusCode(StatusCode.PROXY_LOAD_ROUTER_TABLE_ERROR);
builder.setMessage("proxy load router table error");
return builder.build();
}
// List<RouterTableResponseRecord> routerTableInfoList = RouterTableUtils.parseJson2RouterInfoList(routTableJson.getAsJsonObject("route_table"));
builder.setStatusCode(StatusCode.SUCCESS);
builder.setMessage(Dict.SUCCESS);
ByteString bytes = ByteString.copyFrom(routTableJson.toString().getBytes());
builder.setData(bytes);
return builder.build();
}
// @FateServiceMethod(name = "ADD_ROUTER")
// public RouterTableServiceProto.RouterOperatetResponse addRouterTableService(Context context, InboundPackage inboundPackage) {
// RouterTableServiceProto.RouterOperatetResponse.Builder builder = RouterTableServiceProto.RouterOperatetResponse.newBuilder();
// RouterTableServiceProto.RouterOperatetRequest request = (RouterTableServiceProto.RouterOperatetRequest) inboundPackage.getBody();
// try {
// RouterTableUtils.addRouter(request.getRouterTableInfoList());
// builder.setStatusCode(StatusCode.SUCCESS);
// builder.setMessage(Dict.SUCCESS);
// } catch (RouterInfoOperateException e) {
// builder.setStatusCode(StatusCode.PROXY_UPDATE_ROUTER_TABLE_ERROR);
// builder.setMessage(e.getMessage());
// }
// return builder.build();
// }
// @FateServiceMethod(name = "UPDATE_ROUTER")
// public RouterTableServiceProto.RouterOperatetResponse updateRouterTableService(Context context, InboundPackage inboundPackage) {
// RouterTableServiceProto.RouterOperatetResponse.Builder builder = RouterTableServiceProto.RouterOperatetResponse.newBuilder();
// RouterTableServiceProto.RouterOperatetRequest request = (RouterTableServiceProto.RouterOperatetRequest) inboundPackage.getBody();
// try {
// RouterTableUtils.updateRouter(request.getRouterTableInfoList());
// builder.setStatusCode(StatusCode.SUCCESS);
// builder.setMessage(Dict.SUCCESS);
// } catch (RouterInfoOperateException e) {
// builder.setStatusCode(StatusCode.PROXY_UPDATE_ROUTER_TABLE_ERROR);
// builder.setMessage(e.getMessage());
// }
// return builder.build();
// }
//
// @FateServiceMethod(name = "DELETE_ROUTER")
// public RouterTableServiceProto.RouterOperatetResponse deleteRouterTableService(Context context, InboundPackage inboundPackage) {
// RouterTableServiceProto.RouterOperatetResponse.Builder builder = RouterTableServiceProto.RouterOperatetResponse.newBuilder();
// RouterTableServiceProto.RouterOperatetRequest request = (RouterTableServiceProto.RouterOperatetRequest) inboundPackage.getBody();
// try {
// RouterTableUtils.deleteRouter(request.getRouterTableInfoList());
// builder.setStatusCode(StatusCode.SUCCESS);
// builder.setMessage(Dict.SUCCESS);
// } catch (RouterInfoOperateException e) {
// builder.setStatusCode(StatusCode.PROXY_UPDATE_ROUTER_TABLE_ERROR);
// builder.setMessage(e.getMessage());
// }
// return builder.build();
// }
@FateServiceMethod(name = "SAVE_ROUTER")
public RouterTableServiceProto.RouterOperatetResponse saveRouterTableService(Context context, InboundPackage inboundPackage) {
RouterTableServiceProto.RouterOperatetResponse.Builder builder = RouterTableServiceProto.RouterOperatetResponse.newBuilder();
RouterTableServiceProto.RouterOperatetRequest request = (RouterTableServiceProto.RouterOperatetRequest) inboundPackage.getBody();
try {
RouterTableUtils.saveRouter(request.getRouterInfo());
builder.setStatusCode(StatusCode.SUCCESS);
builder.setMessage(Dict.SUCCESS);
} catch (RouterInfoOperateException e) {
builder.setStatusCode(StatusCode.PROXY_UPDATE_ROUTER_TABLE_ERROR);
builder.setMessage(e.getMessage());
}
return builder.build();
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/InterRequestHandler.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/InterRequestHandler.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.proxy.rpc.grpc;
import com.webank.ai.fate.api.networking.proxy.Proxy;
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.rpc.grpc.GrpcType;
import com.webank.ai.fate.serving.proxy.rpc.core.ProxyServiceRegister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class InterRequestHandler extends ProxyRequestHandler {
private static final Logger logger = LoggerFactory.getLogger(InterRequestHandler.class);
@Autowired
ProxyServiceRegister proxyServiceRegister;
@Override
public ProxyServiceRegister getProxyServiceRegister() {
return proxyServiceRegister;
}
@Override
public void setExtraInfo(Context context, InboundPackage<Proxy.Packet> inboundPackage, Proxy.Packet req) {
context.setGrpcType(GrpcType.INTER_GRPC);
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/RouterTableService.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/RouterTableService.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.proxy.rpc.grpc;
import com.webank.ai.fate.register.annotions.RegisterService;
import com.webank.ai.fate.serving.common.bean.BaseContext;
import com.webank.ai.fate.serving.common.rpc.core.InboundPackage;
import com.webank.ai.fate.serving.common.rpc.core.OutboundPackage;
import com.webank.ai.fate.serving.core.bean.CommonActionType;
import com.webank.ai.fate.serving.proxy.rpc.provider.RouterTableServiceProvider;
import io.grpc.stub.StreamObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
@Service
public class RouterTableService extends RouterTableServiceGrpc.RouterTableServiceImplBase {
@Autowired
RouterTableServiceProvider RouterTableServiceProvider;
@Override
@RegisterService(serviceName = "queryRouter")
public synchronized void queryRouter(RouterTableServiceProto.RouterOperatetRequest request, StreamObserver<RouterTableServiceProto.RouterOperatetResponse> responseObserver) {
service(request, responseObserver, CommonActionType.QUERY_ROUTER.name());
}
@Override
@RegisterService(serviceName = "addRouter")
public void addRouter(RouterTableServiceProto.RouterOperatetRequest request, StreamObserver<RouterTableServiceProto.RouterOperatetResponse> responseObserver) {
service(request, responseObserver, CommonActionType.ADD_ROUTER.name());
}
@Override
@RegisterService(serviceName = "updateRouter")
public void updateRouter(RouterTableServiceProto.RouterOperatetRequest request, StreamObserver<RouterTableServiceProto.RouterOperatetResponse> responseObserver) {
service(request, responseObserver, CommonActionType.UPDATE_ROUTER.name());
}
@Override
@RegisterService(serviceName = "deleteRouter")
public void deleteRouter(RouterTableServiceProto.RouterOperatetRequest request, StreamObserver<RouterTableServiceProto.RouterOperatetResponse> responseObserver) {
service(request, responseObserver, CommonActionType.DELETE_ROUTER.name());
}
@Override
@RegisterService(serviceName = "saveRouter")
public void saveRouter(RouterTableServiceProto.RouterOperatetRequest request, StreamObserver<RouterTableServiceProto.RouterOperatetResponse> responseObserver) {
service(request, responseObserver, CommonActionType.SAVE_ROUTER.name());
}
private void service(RouterTableServiceProto.RouterOperatetRequest request, StreamObserver<RouterTableServiceProto.RouterOperatetResponse> responseObserver, String actionType) {
BaseContext context = new BaseContext();
context.setActionType(actionType);
context.setCaseId(UUID.randomUUID().toString().replaceAll("-", ""));
InboundPackage inboundPackage = new InboundPackage();
inboundPackage.setBody(request);
OutboundPackage outboundPackage = RouterTableServiceProvider.service(context, inboundPackage);
RouterTableServiceProto.RouterOperatetResponse response = (RouterTableServiceProto.RouterOperatetResponse) 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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/ProxyRequestHandler.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/ProxyRequestHandler.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.proxy.rpc.grpc;
import com.webank.ai.fate.api.networking.proxy.DataTransferServiceGrpc;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.register.annotions.RegisterService;
import com.webank.ai.fate.serving.common.bean.BaseContext;
import com.webank.ai.fate.serving.common.rpc.core.InboundPackage;
import com.webank.ai.fate.serving.common.rpc.core.OutboundPackage;
import com.webank.ai.fate.serving.common.rpc.core.ServiceAdaptor;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.proxy.rpc.core.ProxyServiceRegister;
import io.grpc.stub.StreamObserver;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class ProxyRequestHandler extends DataTransferServiceGrpc.DataTransferServiceImplBase {
private static final Logger logger = LoggerFactory.getLogger(ProxyRequestHandler.class);
public abstract ProxyServiceRegister getProxyServiceRegister();
public abstract void setExtraInfo(Context context, InboundPackage<Proxy.Packet> inboundPackage, Proxy.Packet req);
@RegisterService(serviceName = "unaryCall")
@Override
public void unaryCall(Proxy.Packet req, StreamObserver<Proxy.Packet> responseObserver) {
if (logger.isDebugEnabled()) {
logger.debug("unaryCall req {}", req);
}
ServiceAdaptor unaryCallService = getProxyServiceRegister().getServiceAdaptor("unaryCall");
Context context = new BaseContext();
InboundPackage<Proxy.Packet> inboundPackage = buildInboundPackage(context, req);
setExtraInfo(context, inboundPackage, req);
OutboundPackage<Proxy.Packet> outboundPackage = null;
outboundPackage = unaryCallService.service(context, inboundPackage);
Proxy.Packet result = (Proxy.Packet) outboundPackage.getData();
responseObserver.onNext(result);
responseObserver.onCompleted();
}
public InboundPackage<Proxy.Packet> buildInboundPackage(Context context, Proxy.Packet req) {
context.setCaseId(Long.toString(System.currentTimeMillis()));
if (StringUtils.isNotBlank(req.getHeader().getOperator())) {
context.setVersion(req.getHeader().getOperator());
}
context.setGuestAppId(req.getHeader().getSrc().getPartyId());
context.setHostAppid(req.getHeader().getDst().getPartyId());
InboundPackage<Proxy.Packet> inboundPackage = new InboundPackage<Proxy.Packet>();
inboundPackage.setBody(req);
return inboundPackage;
}
@RegisterService(serviceName = "federation/v1/inference",protocol = Dict.HTTP)
public void inference() {
//The method implementation is not here ,just register zk
}
@RegisterService(serviceName = "federation/v1/batchInference",protocol = Dict.HTTP)
public void batchInference() {
//The method implementation is not here ,just register zk
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/IntraRequestHandler.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/IntraRequestHandler.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.proxy.rpc.grpc;
import com.webank.ai.fate.api.networking.proxy.Proxy;
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.rpc.grpc.GrpcType;
import com.webank.ai.fate.serving.proxy.rpc.core.ProxyServiceRegister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class IntraRequestHandler extends ProxyRequestHandler {
private static final Logger logger = LoggerFactory.getLogger(IntraRequestHandler.class);
@Autowired
ProxyServiceRegister proxyServiceRegister;
@Override
public ProxyServiceRegister getProxyServiceRegister() {
return proxyServiceRegister;
}
@Override
public void setExtraInfo(Context context, InboundPackage<Proxy.Packet> inboundPackage, Proxy.Packet req) {
context.setGrpcType(GrpcType.INTRA_GRPC);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/ServiceExceptionHandler.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/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.proxy.rpc.grpc;
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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/IntraGrpcServer.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/IntraGrpcServer.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.proxy.rpc.grpc;
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.core.bean.MetaInfo;
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 javax.annotation.Resource;
import java.util.concurrent.Executor;
@Service
public class IntraGrpcServer implements InitializingBean {
Logger logger = LoggerFactory.getLogger(InterGrpcServer.class);
@Autowired
IntraRequestHandler intraRequestHandler;
@Autowired
CommonRequestHandler commonRequestHandler;
@Autowired
RouterTableService routerTableService;
@Autowired(required = false)
ZookeeperRegistry zookeeperRegistry;
@Resource(name = "grpcExecutorPool")
Executor executor;
Server server;
@Override
public void afterPropertiesSet() throws Exception {
FateServerBuilder serverBuilder = (FateServerBuilder) ServerBuilder.forPort(MetaInfo.PROPERTY_PROXY_GRPC_INTRA_PORT);
serverBuilder.executor(executor);
serverBuilder.addService(ServerInterceptors.intercept(intraRequestHandler, new ServiceExceptionHandler()), IntraRequestHandler.class);
serverBuilder.addService(ServerInterceptors.intercept(commonRequestHandler, new ServiceExceptionHandler()), CommonRequestHandler.class);
serverBuilder.addService(ServerInterceptors.intercept(routerTableService, new ServiceExceptionHandler()), RouterTableService.class);
server = serverBuilder.build();
server.start();
if (zookeeperRegistry != null) {
logger.info("register zk , {}", FateServer.serviceSets);
zookeeperRegistry.register(FateServer.serviceSets);
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/InterGrpcServer.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/InterGrpcServer.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.proxy.rpc.grpc;
import com.webank.ai.fate.register.provider.FateServerBuilder;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerInterceptors;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NegotiationType;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth;
import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.SslProvider;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.net.ssl.SSLException;
import java.io.File;
import java.util.concurrent.Executor;
/**
* @Description TODO
* @Author
**/
@Service
public class InterGrpcServer implements InitializingBean {
Logger logger = LoggerFactory.getLogger(InterGrpcServer.class);
Server server;
@Autowired
InterRequestHandler interRequestHandler;
@Resource(name = "grpcExecutorPool")
Executor executor;
@Override
public void afterPropertiesSet() throws Exception {
int port = MetaInfo.PROPERTY_PROXY_GRPC_INTER_PORT;
String negotiationType = MetaInfo.PROPERTY_PROXY_GRPC_INTER_NEGOTIATIONTYPE;
String certChainFilePath = MetaInfo.PROPERTY_PROXY_GRPC_INTER_SERVER_CERTCHAIN_FILE;
String privateKeyFilePath = MetaInfo.PROPERTY_PROXY_GRPC_INTER_SERVER_PRIVATEKEY_FILE;
String trustCertCollectionFilePath = MetaInfo.PROPERTY_PROXY_GRPC_INTER_CA_FILE;
FateServerBuilder serverBuilder;
if(NegotiationType.TLS == NegotiationType.valueOf(negotiationType) && StringUtils.isNotBlank(certChainFilePath)
&& StringUtils.isNotBlank(privateKeyFilePath) && StringUtils.isNotBlank(trustCertCollectionFilePath)) {
try {
SslContextBuilder sslContextBuilder = GrpcSslContexts.forServer(new File(certChainFilePath), new File(privateKeyFilePath))
.trustManager(new File(trustCertCollectionFilePath))
.clientAuth(ClientAuth.REQUIRE)
.sessionTimeout(3600 << 4)
.sessionCacheSize(65536);
GrpcSslContexts.configure(sslContextBuilder, SslProvider.OPENSSL);
serverBuilder = new FateServerBuilder(NettyServerBuilder.forPort(port));
serverBuilder.sslContext(sslContextBuilder.build());
logger.info("running in secure mode. server crt path: {}, server key path: {}, ca crt path: {}.",
certChainFilePath, privateKeyFilePath, trustCertCollectionFilePath);
} catch (SSLException e) {
throw new SecurityException(e);
}
} else {
serverBuilder = (FateServerBuilder) ServerBuilder.forPort(port);
logger.info("running in insecure mode.");
}
serverBuilder.executor(executor);
serverBuilder.addService(ServerInterceptors.intercept(interRequestHandler, new ServiceExceptionHandler()), InterRequestHandler.class);
server = serverBuilder.build();
server.start();
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/CommonRequestHandler.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/grpc/CommonRequestHandler.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.proxy.rpc.grpc;
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.BaseContext;
import com.webank.ai.fate.serving.common.rpc.core.InboundPackage;
import com.webank.ai.fate.serving.common.rpc.core.OutboundPackage;
import com.webank.ai.fate.serving.core.bean.CommonActionType;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.proxy.rpc.provider.CommonServiceProvider;
import com.webank.ai.fate.serving.proxy.rpc.provider.RouterTableServiceProvider;
import io.grpc.stub.StreamObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
import java.util.stream.Stream;
@Service
public class CommonRequestHandler 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";
private static final String UPDATE_ROUTE_TABLE = "updateRouteTable";
@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();
}
@Override
public void updateConfig(CommonServiceProto.UpdateConfigRequest request, StreamObserver<CommonServiceProto.CommonResponse> responseObserver) {
Context context = prepareContext(CommonActionType.UPDATE_CONFIG.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) {
BaseContext context = new BaseContext();
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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/core/ProxyServiceRegister.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/core/ProxyServiceRegister.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.proxy.rpc.core;
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.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @Description TODO
* @Author
**/
@Component
public class ProxyServiceRegister implements ServiceRegister, ApplicationContextAware, ApplicationListener<ApplicationEvent> {
Logger logger = LoggerFactory.getLogger(ProxyServiceRegister.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(ApplicationEvent applicationEvent) {
if (applicationEvent instanceof ContextRefreshedEvent) {
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);
if (proxyService != null) {
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);
}
}
}
serviceAdaptor.setServiceName(proxyService.name());
// TODO utu: may load from cfg file is a better choice?
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);
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/router/ConfigFileBasedServingRouter.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/router/ConfigFileBasedServingRouter.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.proxy.rpc.router;
import com.google.common.base.Preconditions;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import com.webank.ai.fate.api.core.BasicMeta;
import com.webank.ai.fate.api.networking.proxy.Proxy;
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.rpc.router.Protocol;
import com.webank.ai.fate.serving.core.rpc.router.RouteType;
import com.webank.ai.fate.serving.core.rpc.router.RouteTypeConvertor;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
import com.webank.ai.fate.serving.proxy.utils.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class ConfigFileBasedServingRouter extends BaseServingRouter implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(ConfigFileBasedServingRouter.class);
private static final String IP = "ip";
private static final String PORT = "port";
private static final String URL = "url";
private static final String USE_SSL = "useSSL";
private static final String HOSTNAME = "hostname";
private static final String negotiationType = "negotiationType";
private static final String certChainFile = "certChainFile";
private static final String privateKeyFile = "privateKeyFile";
private static final String caFile = "caFile";
private static final String DEFAULT = "default";
private final String DEFAULT_ROUTER_FILE = "conf" + System.getProperty(Dict.PROPERTY_FILE_SEPARATOR) + "route_table.json";
private final String fileSeparator = System.getProperty(Dict.PROPERTY_FILE_SEPARATOR);
private RouteType routeType;
private String userDir = System.getProperty(Dict.PROPERTY_USER_DIR);
private String lastFileMd5;
private Map<Proxy.Topic, Set<Proxy.Topic>> allow;
private Map<Proxy.Topic, Set<Proxy.Topic>> deny;
private boolean defaultAllow;
public Map<String, Map<String, List<BasicMeta.Endpoint>>> getRouteTable() {
return routeTable;
}
public void setRouteTable(Map<String, Map<String, List<BasicMeta.Endpoint>>> routeTable) {
this.routeTable = routeTable;
}
private Map<String, Map<String, List<BasicMeta.Endpoint>>> routeTable;
private Map<Proxy.Topic, List<RouterInfo>> topicEndpointMapping;
private BasicMeta.Endpoint.Builder endpointBuilder;
@Override
public RouteType getRouteType() {
return routeType;
}
public Map<Proxy.Topic, List<RouterInfo>> getAllRouterInfoMap(){
return topicEndpointMapping;
}
@Override
public List<RouterInfo> getRouterInfoList(Context context, InboundPackage inboundPackage) {
Proxy.Topic dstTopic;
Proxy.Topic srcTopic;
if (Dict.SERVICENAME_INFERENCE.equals(context.getServiceName()) || Dict.SERVICENAME_BATCH_INFERENCE.equals(context.getServiceName())) {
Proxy.Topic.Builder topicBuilder = Proxy.Topic.newBuilder();
dstTopic = topicBuilder.setPartyId(String.valueOf(MetaInfo.PROPERTY_COORDINATOR)).
setRole(MetaInfo.PROPERTY_INFERENCE_SERVICE_NAME)
.setName(Dict.PARTNER_PARTY_NAME)
.build();
srcTopic = topicBuilder.setPartyId(String.valueOf(MetaInfo.PROPERTY_COORDINATOR)).
setRole(Dict.SELF_PROJECT_NAME)
.setName(Dict.PARTNER_PARTY_NAME)
.build();
} else { // default unaryCall
Proxy.Packet sourcePacket = (Proxy.Packet) inboundPackage.getBody();
dstTopic = sourcePacket.getHeader().getDst();
srcTopic = sourcePacket.getHeader().getSrc();
}
Preconditions.checkNotNull(dstTopic, "dstTopic cannot be null");
if (!isAllowed(srcTopic, dstTopic)) {
logger.warn("from {} to {} is not allowed!", srcTopic, dstTopic);
return null;
}
List<RouterInfo> routeList = topicEndpointMapping.getOrDefault(dstTopic, null);
if (routeList != null) {
return routeList;
}
// to get route list from routeTable
String topicName = dstTopic.getName();
String coordinator = dstTopic.getPartyId();
String serviceName = dstTopic.getRole();
if (StringUtils.isAnyBlank(topicName, coordinator, serviceName)) {
throw new IllegalArgumentException("one of dstTopic name, coordinator, role is null. dstTopic: " + dstTopic);
}
Map<String, List<BasicMeta.Endpoint>> serviceTable =
routeTable.getOrDefault(coordinator, routeTable.getOrDefault(DEFAULT, null));
if (serviceTable == null) {
throw new IllegalStateException("No available endpoint for the coordinator: " + coordinator +
". Considering adding a default endpoint?");
}
List<BasicMeta.Endpoint> endpoints =
serviceTable.getOrDefault(serviceName, serviceTable.getOrDefault(DEFAULT, null));
if (endpoints == null || endpoints.isEmpty()) {
throw new IllegalStateException("No available endpoint for this service: " + serviceName +
". Considering adding a default endpoint, or check if the list is empty?");
}
routeList = new ArrayList<>();
for (BasicMeta.Endpoint epoint : endpoints) {
RouterInfo router = new RouterInfo();
// ip is first priority
if (!epoint.getIp().isEmpty()) {
router.setHost(epoint.getIp());
} else {
router.setHost(epoint.getHostname());
}
if(epoint.getUrl()!=null&&StringUtils.isNotBlank(epoint.getUrl())){
router.setProtocol(Protocol.HTTP);
}
router.setUrl(epoint.getUrl());
router.setUseSSL(epoint.getUseSSL());
router.setPort(epoint.getPort());
router.setNegotiationType(epoint.getNegotiationType());
router.setCertChainFile(epoint.getCertChainFile());
router.setPrivateKeyFile(epoint.getPrivateKeyFile());
router.setCaFile(epoint.getCaFile());
routeList.add(router);
}
topicEndpointMapping.put(dstTopic, routeList);
return routeList;
}
private boolean isAllowed(Proxy.Topic from, Proxy.Topic to) {
if (hasRule(deny, from, to)) {
return false;
} else if (hasRule(allow, from, to)) {
return true;
} else {
return defaultAllow;
}
}
// TODO utu: sucks here, need to be optimized on efficiency
private boolean hasRule(Map<Proxy.Topic, Set<Proxy.Topic>> target, Proxy.Topic from, Proxy.Topic to) {
boolean result = false;
if (target == null || target.isEmpty()) {
return result;
}
Proxy.Topic.Builder fromBuilder = Proxy.Topic.newBuilder();
Proxy.Topic.Builder toBuilder = Proxy.Topic.newBuilder();
Proxy.Topic fromValidator = fromBuilder.setPartyId(from.getPartyId()).setRole(from.getRole()).build();
Proxy.Topic toValidator = toBuilder.setPartyId(to.getPartyId()).setRole(to.getRole()).build();
Set<Proxy.Topic> rules = null;
if (target.containsKey(fromValidator)) {
rules = target.get(fromValidator);
}
int stage = 0;
while (stage < 3 && rules == null) {
switch (stage) {
case 0:
break;
case 1:
fromValidator = fromBuilder.setRole("*").build();
break;
case 2:
fromValidator = fromBuilder.setPartyId("*").build();
break;
default:
throw new IllegalStateException("Illegal state when checking from rule");
}
if (target.containsKey(fromValidator)) {
rules = target.get(fromValidator);
}
++stage;
}
if (rules == null) {
return result;
}
stage = 0;
while (stage < 3 && !result) {
switch (stage) {
case 0:
break;
case 1:
toValidator = toBuilder.setRole("*").build();
break;
case 2:
toValidator = toBuilder.setPartyId("*").build();
break;
default:
throw new IllegalStateException("Illegal state when checking to rule");
}
if (rules.contains(toValidator)) {
result = true;
}
++stage;
}
return result;
}
@Scheduled(fixedRate = 10000)
public void loadRouteTable() {
//logger.info("load route table");
String filePath = "";
if (StringUtils.isNotEmpty(MetaInfo.PROPERTY_ROUTE_TABLE)) {
filePath = MetaInfo.PROPERTY_ROUTE_TABLE;
} else {
filePath = userDir + this.fileSeparator + DEFAULT_ROUTER_FILE;
}
if (logger.isDebugEnabled()) {
logger.debug("start refreshed route table...,try to load {}", filePath);
}
File file = new File(filePath);
if (!file.exists()) {
logger.error("router table {} is not exist", filePath);
return;
}
String fileMd5 = FileUtils.fileMd5(filePath);
if (StringUtils.isNotBlank(lastFileMd5)&&null != fileMd5 && fileMd5.equals(lastFileMd5)) {
return;
}
JsonReader jsonReader = null;
JsonObject confJson = null;
try {
jsonReader = new JsonReader(new FileReader(filePath));
confJson = JsonParser.parseReader(jsonReader).getAsJsonObject();
MetaInfo.PROXY_ROUTER_TABLE = confJson.toString();
logger.info("load router table {}", confJson);
} catch (Exception e) {
logger.error("parse router table error: {}", filePath);
throw new RuntimeException(e);
} finally {
if (jsonReader != null) {
try {
jsonReader.close();
} catch (IOException ignore) {
}
}
}
initRouteTable(confJson.getAsJsonObject("route_table"));
initPermission(confJson.getAsJsonObject("permission"));
logger.info("refreshed route table at: {}", filePath);
lastFileMd5 = fileMd5;
}
@Override
public void afterPropertiesSet() throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("in ConfigFileBasedServingRouter:afterPropertiesSet");
}
routeType = RouteTypeConvertor.string2RouteType(MetaInfo.PROPERTY_ROUTE_TYPE);
routeTable = new ConcurrentHashMap<>();
topicEndpointMapping = new WeakHashMap<>();
endpointBuilder = BasicMeta.Endpoint.newBuilder();
allow = new ConcurrentHashMap<>();
deny = new ConcurrentHashMap<>();
defaultAllow = false;
lastFileMd5 = "";
try {
loadRouteTable();
} catch (Throwable e) {
logger.error("load route table fail. ", e);
}
}
private void initRouteTable(JsonObject confJson) {
Map<String, Map<String, List<BasicMeta.Endpoint>>> newRouteTable = new ConcurrentHashMap<>();
// loop through coordinator
for (Map.Entry<String, JsonElement> coordinatorEntry : confJson.entrySet()) {
String coordinatorKey = coordinatorEntry.getKey();
JsonObject coordinatorValue = coordinatorEntry.getValue().getAsJsonObject();
Map<String, List<BasicMeta.Endpoint>> serviceTable = newRouteTable.get(coordinatorKey);
if (serviceTable == null) {
serviceTable = new ConcurrentHashMap<>(4);
newRouteTable.put(coordinatorKey, serviceTable);
}
// loop through role in coordinator
for (Map.Entry<String, JsonElement> roleEntry : coordinatorValue.entrySet()) {
String roleKey = roleEntry.getKey();
if(roleKey.equals("createTime")||roleKey.equals("updateTime")){
continue;
}
JsonArray roleValue = roleEntry.getValue().getAsJsonArray();
List<BasicMeta.Endpoint> endpoints = serviceTable.get(roleKey);
if (endpoints == null) {
endpoints = new ArrayList<>();
serviceTable.put(roleKey, endpoints);
}
// loop through endpoints
for (JsonElement endpointElement : roleValue) {
endpointBuilder.clear();
JsonObject endpointJson = endpointElement.getAsJsonObject();
if (endpointJson.has(IP)) {
String targetIp = endpointJson.get(IP).getAsString();
endpointBuilder.setIp(targetIp);
}
if (endpointJson.has(PORT)) {
int targetPort = endpointJson.get(PORT).getAsInt();
endpointBuilder.setPort(targetPort);
}
if(endpointJson.has(URL)){
String url = endpointJson.get(URL).getAsString();
endpointBuilder.setUrl(url);
}
if (endpointJson.has(USE_SSL)) {
boolean targetUseSSL = endpointJson.get(USE_SSL).getAsBoolean();
endpointBuilder.setUseSSL(targetUseSSL);
}
if (endpointJson.has(HOSTNAME)) {
String targetHostname = endpointJson.get(HOSTNAME).getAsString();
endpointBuilder.setHostname(targetHostname);
}
if (endpointJson.has(negotiationType)) {
String targetNegotiationType = endpointJson.get(negotiationType).getAsString();
endpointBuilder.setNegotiationType(targetNegotiationType);
}
if (endpointJson.has(certChainFile)) {
String targetCertChainFile = endpointJson.get(certChainFile).getAsString();
endpointBuilder.setCertChainFile(targetCertChainFile);
}
if (endpointJson.has(privateKeyFile)) {
String targetPrivateKeyFile = endpointJson.get(privateKeyFile).getAsString();
endpointBuilder.setPrivateKeyFile(targetPrivateKeyFile);
}
if (endpointJson.has(caFile)) {
String targetCaFile = endpointJson.get(caFile).getAsString();
endpointBuilder.setCaFile(targetCaFile);
}
BasicMeta.Endpoint endpoint = endpointBuilder.build();
endpoints.add(endpoint);
}
}
}
routeTable = newRouteTable;
topicEndpointMapping.clear();
}
private void initPermission(JsonObject confJson) {
boolean newDefaultAllow = false;
Map<Proxy.Topic, Set<Proxy.Topic>> newAllow = new ConcurrentHashMap<>();
Map<Proxy.Topic, Set<Proxy.Topic>> newDeny = new ConcurrentHashMap<>();
if (confJson.has("default_allow")) {
newDefaultAllow = confJson.getAsJsonPrimitive("default_allow").getAsBoolean();
}
if (confJson.has("allow")) {
initPermissionType(newAllow, confJson.getAsJsonArray("allow"));
}
if (confJson.has("deny")) {
initPermissionType(newDeny, confJson.getAsJsonArray("deny"));
}
defaultAllow = newDefaultAllow;
allow = newAllow;
deny = newDeny;
}
private void initPermissionType(Map<Proxy.Topic, Set<Proxy.Topic>> target, JsonArray conf) {
for (JsonElement pairElement : conf) {
JsonObject pair = pairElement.getAsJsonObject();
JsonObject from = pair.getAsJsonObject("from");
Proxy.Topic fromTopic = createTopicFromJson(from);
JsonObject to = pair.getAsJsonObject("to");
Proxy.Topic toTopic = createTopicFromJson(to);
if (!target.containsKey(fromTopic)) {
target.put(fromTopic, new HashSet<>());
}
Set<Proxy.Topic> toTopics = target.get(fromTopic);
toTopics.add(toTopic);
}
}
private Proxy.Topic createTopicFromJson(JsonObject json) {
Proxy.Topic.Builder topicBuilder = Proxy.Topic.newBuilder();
if (json.has("coordinator")) {
topicBuilder.setPartyId(json.get("coordinator").getAsString());
}
if (json.has("role")) {
topicBuilder.setRole(json.get("role").getAsString());
}
return topicBuilder.build();
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/router/ZkServingRouter.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/router/ZkServingRouter.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.proxy.rpc.router;
import com.webank.ai.fate.api.networking.proxy.Proxy;
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.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.rpc.grpc.GrpcType;
import com.webank.ai.fate.serving.core.rpc.router.RouteType;
import com.webank.ai.fate.serving.core.rpc.router.RouteTypeConvertor;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
import com.webank.ai.fate.serving.proxy.utils.FederatedModelUtils;
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.ArrayList;
import java.util.List;
@Service
public class ZkServingRouter extends BaseServingRouter implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(ZkServingRouter.class);
private RouteType routeType;
@Autowired(required = false)
private RouterService zkRouterService;
@Override
public RouteType getRouteType() {
return routeType;
}
@Override
public List<RouterInfo> getRouterInfoList(Context context, InboundPackage inboundPackage) {
if (!MetaInfo.PROPERTY_USE_ZK_ROUTER) {
return null;
}
String environment = getEnvironment(context, inboundPackage);
if (environment == null) {
return null;
}
List<URL> list = zkRouterService.router(Dict.SERVICE_SERVING, environment, context.getServiceName());
logger.info("try to find zk ,{}:{}:{}, result {}", "serving", environment, context.getServiceName(), list);
if (null == list || list.isEmpty()) {
return null;
}
List<RouterInfo> routeList = new ArrayList<>();
for (URL url : list) {
String urlip = url.getHost();
int port = url.getPort();
RouterInfo router = new RouterInfo();
router.setHost(urlip);
router.setPort(port);
routeList.add(router);
}
return routeList;
}
// TODO utu: sucks! have to reconstruct the entire protocol of online serving
private String getEnvironment(Context context, InboundPackage inboundPackage) {
if (Dict.SERVICENAME_INFERENCE.equals(context.getServiceName()) || Dict.SERVICENAME_BATCH_INFERENCE.equals(context.getServiceName())) {
// guest, proxy -> serving
return (String) inboundPackage.getHead().get(Dict.SERVICE_ID);
}
if (Dict.UNARYCALL.equals(context.getServiceName()) && context.getGrpcType() == GrpcType.INTER_GRPC) {
// host, proxy -> serving
Proxy.Packet sourcePacket = (Proxy.Packet) inboundPackage.getBody();
return FederatedModelUtils.getModelRouteKey(context, sourcePacket);
}
// default unaryCall proxy -> proxy
return null;
}
@Override
public void afterPropertiesSet() throws Exception {
routeType = RouteTypeConvertor.string2RouteType(MetaInfo.PROPERTY_ROUTE_TYPE);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/router/BaseServingRouter.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/router/BaseServingRouter.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.proxy.rpc.router;
import com.google.common.hash.Hashing;
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.common.rpc.core.RouterInterface;
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.NoRouterInfoException;
import com.webank.ai.fate.serving.core.rpc.router.RouteType;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public abstract class BaseServingRouter implements RouterInterface {
private static final Logger logger = LoggerFactory.getLogger(BaseServingRouter.class);
public abstract List<RouterInfo> getRouterInfoList(Context context, InboundPackage inboundPackage);
public abstract RouteType getRouteType();
@Override
public RouterInfo route(Context context, InboundPackage inboundPackage) {
List<RouterInfo> routeList = getRouterInfoList(context, inboundPackage);
if (routeList == null
|| 0 == routeList.size()) {
return null;
}
int idx = 0;
RouteType routeType = getRouteType();
switch (routeType) {
case RANDOM_ROUTE: {
idx = ThreadLocalRandom.current().nextInt(routeList.size());
break;
}
case CONSISTENT_HASH_ROUTE: {
idx = Hashing.consistentHash(context.getRouteBasis(), routeList.size());
break;
}
default: {
// to use the first one.
break;
}
}
RouterInfo routerInfo = routeList.get(idx);
context.setRouterInfo(routerInfo);
logger.info("caseid {} get route info {}:{}", context.getCaseId(), routerInfo.getHost(), routerInfo.getPort());
return routerInfo;
}
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
RouterInfo routerInfo = this.route(context, inboundPackage);
if (routerInfo == null) {
throw new NoRouterInfoException(StatusCode.PROXY_ROUTER_ERROR,"PROXY_ROUTER_ERROR");
}
inboundPackage.setRouterInfo(routerInfo);
}
@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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/router/DefaultServingRouter.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/rpc/router/DefaultServingRouter.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.proxy.rpc.router;
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.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.NoRouterInfoException;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
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 DefaultServingRouter implements Interceptor {
Logger logger = LoggerFactory.getLogger(DefaultServingRouter.class);
@Autowired(required = false)
private ZkServingRouter zkServingRouter;
@Autowired
private ConfigFileBasedServingRouter configFileBasedServingRouter;
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
RouterInfo routerInfo = null;
if (zkServingRouter != null) {
routerInfo = zkServingRouter.route(context, inboundPackage);
}
if (null == routerInfo) {
routerInfo = configFileBasedServingRouter.route(context, inboundPackage);
}
if (null == routerInfo) {
throw new NoRouterInfoException(StatusCode.PROXY_ROUTER_ERROR,"serving-proxy can not find router info ");
}
inboundPackage.setRouterInfo(routerInfo);
}
@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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/utils/FederatedModelUtils.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/utils/FederatedModelUtils.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.proxy.utils;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.EncryptMethod;
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 java.util.Arrays;
import java.util.Map;
public class FederatedModelUtils {
private static final Logger logger = LoggerFactory.getLogger(FederatedModelUtils.class);
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 getModelRouteKey(Context context, Proxy.Packet packet) {
String namespace;
String tableName;
if (StringUtils.isBlank(context.getVersion()) || Double.parseDouble(context.getVersion()) < 200) {
// version 1.x
String data = packet.getBody().getValue().toStringUtf8();
Map hostFederatedParams = JsonUtil.json2Object(data, Map.class);
Map partnerModelInfo = (Map) hostFederatedParams.get("partnerModelInfo");
namespace = partnerModelInfo.get("namespace").toString();
tableName = partnerModelInfo.get("name").toString();
} else {
// version 2.0.0+
Proxy.Model model = packet.getHeader().getTask().getModel();
namespace = model.getNamespace();
tableName = model.getTableName();
}
String key = genModelKey(tableName, namespace);
logger.info("get model route key by version: {} namespace: {} tablename: {}, key: {}", context.getVersion(), namespace, tableName, key);
return EncryptUtils.encrypt(key, EncryptMethod.MD5);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/utils/FileUtils.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/utils/FileUtils.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.proxy.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileUtils {
private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
public static String fileMd5(String filePath) {
InputStream in = null;
try {
in = new FileInputStream(filePath);
return DigestUtils.md5DigestAsHex(in);
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
return null;
}
public static boolean writeFile(String context, File target) {
BufferedWriter out = null;
try {
if (!target.exists()) {
target.createNewFile();
}
out = new BufferedWriter(new FileWriter(target));
out.write(context);
} catch (IOException e) {
logger.error(e.getMessage());
return false;
} finally {
try {
if(out!=null) {
out.flush();
out.close();
}
} catch (IOException ex) {
logger.error("write file error",ex);
}
}
return true;
}
/**
* Write string to file,
* synchronize operation, exclusive lock
*/
public static boolean writeStr2ReplaceFileSync(String str, String pathFile) throws Exception {
File file = new File(pathFile);
try {
if (!file.exists()) {
file.createNewFile();
}
} catch (IOException e) {
logger.error("Failed to create the file. Check whether the path is valid and the read/write permission is correct");
throw new IOException("Failed to create the file. Check whether the path is valid and the read/write permission is correct");
}
FileOutputStream fileOutputStream = null;
FileChannel fileChannel = null;
FileLock fileLock;
try {
/**
* write file
*/
fileOutputStream = new FileOutputStream(file);
fileChannel = fileOutputStream.getChannel();
try {
fileLock = fileChannel.tryLock();// exclusive lock
} catch (Exception e) {
throw new IOException("another thread is writing ,refresh and try again");
}
if (fileLock != null) {
fileChannel.write(ByteBuffer.wrap(str.getBytes()));
if (fileLock.isValid()) {
fileLock.release(); // release-write-lock
}
if (file.length() != str.getBytes().length) {
throw new IOException("write successfully but the content was lost, reedit and try again");
}
}
} catch (IOException e) {
logger.error(e.getMessage());
throw new IOException(e.getMessage());
} finally {
close(fileChannel);
close(fileOutputStream);
}
return true;
}
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/utils/WebUtil.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/utils/WebUtil.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.proxy.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @Description TODO
* @Author
**/
public class WebUtil {
static Logger logger = LoggerFactory.getLogger(WebUtil.class);
/**
* 获取来源ip
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = "";
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
String localIp = "127.0.0.1";
String localIpv6 = "0:0:0:0:0:0:0:1";
if (ipAddress.equals(localIp) || ipAddress.equals(localIpv6)) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
ipAddress = inet.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
String ipSeparate = ",";
int ipLength = 15;
if (ipAddress != null && ipAddress.length() > ipLength) {
if (ipAddress.indexOf(ipSeparate) > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(ipSeparate));
}
}
} catch (Exception e) {
logger.error("get remote ip error", e);
}
return ipAddress;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/utils/ToStringUtils.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/utils/ToStringUtils.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.proxy.utils;
import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class ToStringUtils {
private static final String NULL_STRING = "[null]";
private static final String LEFT_BRACKET = "[";
private static final String RIGHT_BRACKET = "]";
private static final String LEFT_BRACE = "{";
private static final String RIGHT_BRACE = "}";
private static final String LEFT_PARENTHESIS = "(";
private static final String RIGHT_PARENTHESIS = ")";
private static final String COLON = ":";
private static final String SEMICOLON = ";";
private static final String COMMA = ",";
private static final Logger logger = LoggerFactory.getLogger(ToStringUtils.class);
private JsonFormat.Printer protoPrinter = JsonFormat.printer()
.preservingProtoFieldNames()
.omittingInsignificantWhitespace();
public String toOneLineString(Message target) {
String result = "[null]";
if (target == null) {
logger.info("target is null");
return result;
}
try {
result = protoPrinter.print(target);
} catch (Exception e) {
logger.info(ExceptionUtils.getStackTrace(e));
}
return result;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/common/RouterTableUtils.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/common/RouterTableUtils.java | package com.webank.ai.fate.serving.proxy.common;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
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.RouterTableResponseRecord;
import com.webank.ai.fate.serving.core.exceptions.RouterInfoOperateException;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.proxy.utils.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @auther Xiongli
* @date 2021/6/23
* @remark
*/
public class RouterTableUtils {
private static final Logger logger = LoggerFactory.getLogger(RouterTableUtils.class);
private static final String USER_DIR = System.getProperty(Dict.PROPERTY_USER_DIR);
private static final String FILE_SEPARATOR = System.getProperty(Dict.PROPERTY_FILE_SEPARATOR);
private static final String DEFAULT_ROUTER_FILE = "conf" + System.getProperty(Dict.PROPERTY_FILE_SEPARATOR) + "route_table.json";
private final static String DEFAULT_ROUTER_TABLE = "{\"route_table\":{\"default\":{\"default\":[{\"ip\":\"127.0.0.1\",\"port\":9999,\"useSSL\":false}]}},\"permission\":{\"default_allow\":true}}";
private final static String BASE_ROUTER_TABLE = "{\"route_table\":{},\"permission\":{\"default_allow\":true}}";
static String router_table;
public static String getRouterFile(){
String filePath;
if (StringUtils.isNotEmpty(MetaInfo.PROPERTY_ROUTE_TABLE)) {
filePath = MetaInfo.PROPERTY_ROUTE_TABLE;
} else {
filePath = USER_DIR + FILE_SEPARATOR + DEFAULT_ROUTER_FILE;
}
return filePath;
}
public static JsonObject loadRoutTable() {
String filePath = getRouterFile();
if (logger.isDebugEnabled()) {
logger.debug("start load route table...,try to load {}", filePath);
}
File file = new File(filePath);
if (!file.exists()) {
logger.error("router table {} is not exist", filePath);
return null;
}
JsonReader routerReader = null;
JsonObject confJson;
try {
routerReader = new JsonReader(new FileReader(filePath));
confJson = JsonParser.parseReader(routerReader).getAsJsonObject();
if (confJson == null || confJson.size() == 0) {
confJson = initRouter();
} else {
router_table = confJson.toString();
}
logger.info("load router table {} {}", filePath,confJson);
} catch (Exception e) {
logger.error("parse router table error: {}", filePath);
throw new RuntimeException(e);
} finally {
if (routerReader != null) {
try {
routerReader.close();
} catch (IOException ignore) {
}
}
}
return confJson;
}
public static JsonObject initRouter() {
router_table = DEFAULT_ROUTER_TABLE;
return JsonParser.parseString(DEFAULT_ROUTER_TABLE).getAsJsonObject();
}
// public static void addRouter(List<RouterTableServiceProto.RouterTableInfo> routerInfoList) {
// try {
// long now = new Date().getTime();
// JsonObject routerJson = loadRoutTable();
// if (routerJson == null) {
// throw new RouterInfoOperateException("route_table.json not exists");
// }
// JsonObject route_table = routerJson.getAsJsonObject("route_table");
// if (route_table == null) {
// throw new RouterInfoOperateException("missing routing configuration");
// }
// for (RouterTableServiceProto.RouterTableInfo routerInfo : routerInfoList) {
// JsonObject partyIdRouter = route_table.getAsJsonObject(routerInfo.getPartyId());
// if (partyIdRouter == null) {
// partyIdRouter = new JsonObject();
// partyIdRouter.addProperty("createTime", now);
// partyIdRouter.addProperty("updateTime", now);
// route_table.add(routerInfo.getPartyId(), partyIdRouter);
// }
// JsonArray serverTypeArray = partyIdRouter.getAsJsonArray(routerInfo.getServerType());
// if (serverTypeArray == null) {
// serverTypeArray = new JsonArray();
// partyIdRouter.add(routerInfo.getServerType(), serverTypeArray);
// }
// if (getIndex(serverTypeArray, routerInfo.getHost(), routerInfo.getPort()) != -1) {
// throw new RouterInfoOperateException("partyId : " + routerInfo.getPartyId() + ", serverType : " + routerInfo.getServerType()
// + ", Network Access : " + routerInfo.getHost() + ":" + routerInfo.getPort() + " is already exists");
// }
// serverTypeArray.add(parseRouterInfo(routerInfo));
// partyIdRouter.add(routerInfo.getServerType(), serverTypeArray);
// }
// routerJson.add("route_table", route_table);
// if (writeRouterFile(JsonUtil.formatJson(routerJson.toString()))) {
// logger.error("write route_table.json error");
// throw new RouterInfoOperateException("write route_table.json error");
// }
// } catch (RouterInfoOperateException routerEx) {
// throw new RouterInfoOperateException(routerEx.getMessage());
// } catch (Exception e) {
// logger.error("parse router table error", e);
// throw new RouterInfoOperateException("parse router table error");
// }
// }
// public static void updateRouter(List<RouterTableServiceProto.RouterTableInfo> routerInfoList) {
// try {
// JsonObject routerJson = loadRoutTable();
// if (routerJson == null) {
// throw new RouterInfoOperateException("route_table.json not exists");
// }
// JsonObject route_table = routerJson.getAsJsonObject("route_table");
// if (route_table == null) {
// throw new RouterInfoOperateException("missing routing configuration");
// }
// for (RouterTableServiceProto.RouterTableInfo routerInfo : routerInfoList) {
// JsonObject partyIdRouter = route_table.getAsJsonObject(routerInfo.getPartyId());
// if (partyIdRouter == null) {
// throw new RouterInfoOperateException("there is no configuration with partyId = " + routerInfo.getPartyId());
// }
// partyIdRouter.addProperty("updateTime", new Date().getTime());
// JsonArray serverTypeArray = partyIdRouter.getAsJsonArray(routerInfo.getServerType());
// if (serverTypeArray == null)
// throw new RouterInfoOperateException("there is no configuration with partyId = " + routerInfo.getPartyId() + " and serverType = " + routerInfo.getServerType());
// int index = getIndex(serverTypeArray, routerInfo.getHost(), routerInfo.getPort());
// if (index == -1) {
// throw new RouterInfoOperateException("partyId : " + routerInfo.getPartyId() + ", serverType : " + routerInfo.getServerType()
// + ", Network Access : " + routerInfo.getHost() + ":" + routerInfo.getPort() + " is not exists");
// }
// JsonObject singleRoute;
// singleRoute = parseRouterInfo(routerInfo);
// serverTypeArray.set(index, singleRoute);
// partyIdRouter.add(routerInfo.getServerType(), serverTypeArray);
// }
// if (writeRouterFile(JsonUtil.formatJson(routerJson.toString()))) {
// logger.error("write route_table.json error");
// throw new RouterInfoOperateException("write route_table.json error");
// }
// } catch (RouterInfoOperateException routerEx) {
// throw new RouterInfoOperateException(routerEx.getMessage());
// } catch (Exception e) {
// logger.error("parse router table error");
// throw new RouterInfoOperateException("parse router table error");
// }
// }
// public static void deleteRouter(List<RouterTableServiceProto.RouterTableInfo> routerInfoList) {
// try {
// JsonObject routerJson = loadRoutTable();
// if (routerJson == null) {
// throw new RouterInfoOperateException("route_table.json not exists");
// }
// JsonObject route_table = routerJson.getAsJsonObject("route_table");
// if (route_table == null) {
// throw new RouterInfoOperateException("missing routing configuration");
// }
// for (RouterTableServiceProto.RouterTableInfo routerInfo : routerInfoList) {
// JsonObject partyIdRouter = route_table.getAsJsonObject(routerInfo.getPartyId());
// if (StringUtils.isBlank(routerInfo.getServerType())) {
// route_table.remove(routerInfo.getPartyId());
// if (writeRouterFile(JsonUtil.formatJson(routerJson.toString()))) {
// logger.error("write route_table.json error");
// throw new RouterInfoOperateException("write route_table.json error");
// }
// return;
// }
// if (partyIdRouter == null) {
// throw new RouterInfoOperateException("there is no configuration with partyId = " + routerInfo.getPartyId());
// }
// partyIdRouter.addProperty("updateTime", new Date().getTime());
// JsonArray serverTypeArray = partyIdRouter.getAsJsonArray(routerInfo.getServerType());
// if (serverTypeArray == null) {
// throw new RouterInfoOperateException("there is no configuration with partyId = " + routerInfo.getPartyId() + " and serverType = " + routerInfo.getServerType());
// }
// int index = getIndex(serverTypeArray, routerInfo.getHost(), routerInfo.getPort());
// if (index == -1) {
// throw new RouterInfoOperateException("partyId : " + routerInfo.getPartyId() + ", serverType : " + routerInfo.getServerType()
// + ", Network Access : " + routerInfo.getHost() + ":" + routerInfo.getPort() + " is not exists");
// }
// serverTypeArray.remove(index);
// partyIdRouter.add(routerInfo.getServerType(), serverTypeArray);
// }
// routerJson.add("route_table", route_table);
// if (writeRouterFile(JsonUtil.formatJson(routerJson.toString()))) {
// logger.error("write route_table.json error");
// throw new RouterInfoOperateException("write route_table.json error");
// }
// } catch (RouterInfoOperateException routerEx) {
// throw new RouterInfoOperateException(routerEx.getMessage());
// } catch (Exception e) {
// logger.error("parse router table error");
// throw new RouterInfoOperateException("parse router table error");
// }
// }
public static void saveRouter(String routerInfo){
try {
if (!RouteTableJsonValidator.isJSON(routerInfo)) {
logger.error("validate route_table.json format error");
}
} catch (Exception e) {
throw new RouterInfoOperateException("validate route_table.json format error:" + e.getMessage());
}
try {
if (writeRouterFile(JsonUtil.formatJson(routerInfo))) {
logger.error("write route_table.json fail");
}
} catch (Exception e) {
throw new RouterInfoOperateException("route_table.json : " + e.getMessage());
}
}
public static boolean writeRouterFile(String context) throws Exception {
String filePath = getRouterFile();
logger.info("write router table file {} {}",filePath,context);
// return !FileUtils.writeFile(context, new File(filePath));
return !FileUtils.writeStr2ReplaceFileSync(context, filePath);
}
public static List<RouterTableResponseRecord> parseJson2RouterInfoList(JsonObject routerTableJson) {
List<RouterTableResponseRecord> routerTableInfoList = new ArrayList<>();
if (routerTableJson == null) {
return routerTableInfoList;
}
for (Map.Entry<String, JsonElement> tableEntry : routerTableJson.entrySet()) {
JsonObject routerInfos;
routerInfos = tableEntry.getValue().getAsJsonObject();
if (routerInfos == null) {
continue;
}
RouterTableResponseRecord responseRecord = new RouterTableResponseRecord();
responseRecord.setPartyId(tableEntry.getKey());
List<RouterTableResponseRecord.RouterTable> routerList = new ArrayList<>();
for (Map.Entry<String, JsonElement> routerInfosEntry : routerInfos.entrySet()) {
String serverType = routerInfosEntry.getKey();
switch (serverType) {
case "createTime":
responseRecord.setCreateTime(routerInfosEntry.getValue().getAsLong());
break;
case "updateTime":
responseRecord.setUpdateTime(routerInfosEntry.getValue().getAsLong());
break;
default:
JsonArray routerInfosArr = routerInfosEntry.getValue().getAsJsonArray();
if (routerInfosArr == null) {
continue;
}
for (JsonElement jsonElement : routerInfosArr) {
JsonObject routerTableSignleJson = jsonElement.getAsJsonObject();
routerTableSignleJson.addProperty("serverType", serverType);
routerList.add(JsonUtil.json2Object(routerTableSignleJson, RouterTableResponseRecord.RouterTable.class));
}
break;
}
}
responseRecord.setRouterList(routerList);
responseRecord.setCount(routerList.size());
routerTableInfoList.add(responseRecord);
}
return routerTableInfoList;
}
public static int getIndex(JsonArray sourceArr, String host, int port) {
int result = -1;
String new_address = host + ":" + port;
for (int i = 0; i < sourceArr.size(); i++) {
JsonElement jsonElement = sourceArr.get(i);
String old_address = jsonElement.getAsJsonObject().get("ip").getAsString() + ":" + jsonElement.getAsJsonObject().get("port").toString();
if (new_address.equals(old_address)) {
result = i;
}
}
return result;
}
public static final class RouteTableJsonValidator {
/**
* 数组指针
*/
private static int index;
/**
* 字符串
*/
private static String value;
/**
* 指针当前字符
*/
private static char curchar;
/**
* 工具类非公有构造函数
*/
private RouteTableJsonValidator() {
}
/**
* @param rawValue 字符串参数
* @return boolean 是否是JSON
*/
public static boolean isJSON(String rawValue) throws Exception {
index = 0;
value = rawValue;
switch (nextClean()) {
case '[':
if (nextClean() == ']') {
return true;
}
back();
return validateArray();
case '{':
if (nextClean() == '}') {
return true;
}
back();
return validateObject();
default:
return false;
}
}
/**
* @return char 下一个有效实义字符 char<=' ' char!=127
* @throws JSONException 自定义JSON异常
*/
public static char nextClean() throws JSONException {
skipComment:
do {
next();
if (curchar == '/') { // 跳过//类型与/*类型注释 遇回车或者null为注释内容结束
switch (next()) {
case 47: // '/'
do {
curchar = next();
} while (curchar != '\n' && curchar != '\r' && curchar != 0);
continue;
case 42: // '*'
do {
do {
next();
if (curchar == 0) {
throw syntaxError("Unclosed comment");
}
} while (curchar != '*');
if (next() == '/') {
continue skipComment;
}
back();
} while (true);
}
back();
return '/';
}
if (curchar != '#') { //跳过#类型注释 遇回车或者null为注释内容结束
break;
}
do {
next();
} while (curchar != '\n' && curchar != '\r' && curchar != 0);
} while (true);
if (curchar != 0 && (curchar <= ' ' || curchar == 127)) {
throw syntaxError("JSON can not contain control character!");
}
return curchar;
}
/**
* @return char 下一个字符
*/
public static char next() {
if (index < 0 || index >= value.length()) {
return '\0';
}
curchar = value.charAt(index);
if (curchar <= 0) {
return '\0';
} else {
index++;
return curchar;
}
}
/**
* 将指针移至上一个字符,回退一位
*/
public static void back() { //异常在next中进行返回null
index--;
}
/**
* @param message 异常自定义信息
* @return JSONException 自定义JSON异常
*/
public static JSONException syntaxError(String message) {
return new JSONException((new StringBuilder(String.valueOf(message))).toString());
}
/**
* @return boolean 是否是JSONArray
* @throws JSONException 自定义JSON异常
*/
public static boolean validateArray() throws JSONException {
do {
//入口为合法 [ array 起点
nextClean(); //下一位有效字符,跳过注释
if (curchar == ']') { //空array 直接闭合返回
return true;
} else if (curchar == ',') { //null
continue;
} else if (curchar == '"') { //String
validateString();
} else if (curchar == '-' || (curchar >= 48 && curchar <= 57)) { // number
validateNumber();
} else if (curchar == '{') { // object
if (!validateObject()) { //递归校验
return false;
}
} else if (curchar == '[') { // array
if (!validateArray()) { //递归校验
return false;
}
} else if (curchar == 't' || curchar == 'f' || curchar == 'n') { // boolean and JSONNull
validateBooleanAndNull();
} else {
return false;
}
switch (nextClean()) {
case ',':
continue;
case ']':
return true;
default:
return false;
}
} while (true);
}
/**
* @return boolean 是否是JSONObject
* @throws JSONException 自定义JSON异常
*/
public static boolean validateObject() throws JSONException {
do {
nextClean();
if (curchar == '}') {
return true;
} else if (curchar == '"') { //String
validateString();
} else {
return false;
}
if (nextClean() != ':') {
return false;
}
nextClean();
if (curchar == ',') { //null
throw syntaxError("Missing value");
} else if (curchar == '"') { //String
validateString();
} else if (curchar == '-' || (curchar >= 48 && curchar <= 57)) { // number
validateNumber();
} else if (curchar == '{') { // object
if (!validateObject()) {
return false;
}
} else if (curchar == '[') { // array
if (!validateArray()) {
return false;
}
} else if (curchar == 't' || curchar == 'f' || curchar == 'n') { // boolean and JSONNull
validateBooleanAndNull();
} else {
return false;
}
switch (nextClean()) {
case ',':
continue;
case '}':
return true;
default:
return false;
}
} while (true);
}
/**
* @throws JSONException 自定义JSON异常
*/
public static void validateString() throws JSONException {
// StringBuilder sb = new StringBuilder();
// do {
// curchar = next(); //JSON对字符串中的转义项有严格规定
// sb.append(curchar);
// if (curchar == '\\') {
// if ("\"\\/bfnrtu".indexOf(next()) < 0) {
// throw syntaxError("Invalid escape string");
// }
// if (curchar == 'u') { //校验unicode格式 后跟4位16进制 0-9 a-f A-F
// for (int i = 0; i < 4; i++) {
// next();
// if (curchar < 48 || (curchar > 57 && curchar < 65) || (curchar > 70 && curchar < 97)
// || curchar > 102) {
// throw syntaxError("Invalid hexadecimal digits");
// }
// }
// }
// }
// } while (curchar >= ' ' && "\":{[,#/".indexOf(curchar)< 0 && curchar != 127);
// if (curchar == 0) { //仅正常闭合双引号可通过
// throw syntaxError("Unclosed quot");
// } else if (curchar != '"') {
// throw syntaxError("Invalid string {\""+ sb +"}, missing quot ");
// } else if (value.charAt(index)=='"') {
// throw syntaxError("Missing comma after string: \"" + sb);
// } else if (value.charAt(index)==':' ) {
// String str = sb.substring(0, sb.length() - 1);
//// if (!validateRouteTableKey(sb.charAt(0), str)) {
//// throw syntaxError("Invalid RouteTable KEY:\"" + sb);
//// }
// validateRouteTableValue(str);
// }
}
/**
* @throws JSONException 自定义JSON异常
*/
public static void validateNumber() throws JSONException {
StringBuilder sb = new StringBuilder();
if (curchar == '-') { //可选负号
curchar = next();
}
if (curchar > 48 && curchar <= 57) { //整数部分
do {
sb.append(curchar);
curchar = next();
} while (curchar >= 48 && curchar <= 57);
} else if (curchar == 48) {
curchar = next();
} else {
throw syntaxError("Invalid number");
}
if (curchar == '.') { //小数部分
do { //.后可不跟数字 如 5. 为合法数字
curchar = next();
} while (curchar >= 48 && curchar <= 57);
}
if (curchar == 'e' || curchar == 'E') { //科学计数部分
curchar = next();
if (curchar == '+' || curchar == '-') {
curchar = next();
}
if (curchar < 48 || curchar > 57) {
throw syntaxError("Invalid number");
}
do {
curchar = next();
} while (curchar >= 48 && curchar <= 57);
}
if (curchar == '"') {
throw syntaxError("Missing comma after number: " + sb);
}
back(); //指针移至数字值最后一位,取下一位即判断是,或者],或者是合法注释
}
public static void validateRouteTableValue(String key) throws JSONException {
int a = index;
char c,d ;
List<String> num_list = Arrays.asList("port");
List<String> boolean_list = Arrays.asList("useSSL", "default_allow");
do {
++a;
c = value.charAt(a);
} while (c == ' ' || c == '"');
StringBuilder sb = new StringBuilder();
do {
d = value.charAt(a);
sb.append(d);
a++;
} while (d !=' ' && ",]}\"".indexOf(d) <0);
String str = sb.substring(0,sb.length()-1);
if (num_list.contains(key) && !(c == '-' || (c >= 48 && c <= 57))) {
throw syntaxError("RouteTable KEY:" + key + " match NumberType");
}
if (boolean_list.contains(key) && !(c == 't' || c == 'f' || c == 'n')) {
throw syntaxError("RouteTable KEY:" + key + " match BooleanType");
}
String port_reg = "^([0-5]?\\d{0,4}|6[0-4]\\d{3}|65[0-4]\\d{2}|655[0-2]\\d|6553[0-5])$";
if("port".equals(key) && !str.matches(port_reg)){
throw syntaxError("Invalid Port : " + str);
}
// String ip_reg = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$";
// if("ip".equals(key) && !str.matches(ip_reg)){
// throw syntaxError("Invalid ip : " + str);
// }
}
public static boolean validateRouteTableKey(char firstChar, String str) throws JSONException {
if ("".equals(str)) return false;
List<String> a_list = Arrays.asList("allow");
List<String> c_list = Arrays.asList("certChainFile","caFile","coordinator");
List<String> d_list = Arrays.asList("default", "default_allow","deny");
List<String> f_list = Arrays.asList("from");
List<String> h_list = Arrays.asList("host");
List<String> i_list = Arrays.asList("ip");
List<String> n_list = Arrays.asList("negotiationType","caFile");
List<String> p_list = Arrays.asList("permission", "port", "privateKeyFile");
List<String> r_list = Arrays.asList("route_table","role");
List<String> s_list = Arrays.asList("serving");
List<String> t_list = Arrays.asList("to");
List<String> u_list = Arrays.asList("useSSL");
switch (firstChar) {
case ' ':
return false;
case 'a':
return a_list.contains(str);
case 'f':
return f_list.contains(str);
case 't':
return t_list.contains(str);
case 'i':
return i_list.contains(str);
case 'h':
return h_list.contains(str);
case 's':
return s_list.contains(str);
case 'u':
return u_list.contains(str);
case 'c':
return c_list.contains(str);
case 'n':
return n_list.contains(str);
case 'r':
return r_list.contains(str);
case 'd':
return d_list.contains(str);
case 'p':
return p_list.contains(str);
default:
return true;
}
}
/**
* @throws JSONException 自定义JSON异常
*/
public static void validateBooleanAndNull() throws JSONException {
StringBuilder sb = new StringBuilder();
do {
sb.append(curchar);
curchar = next();
} while (curchar >= ' ' && "\",]#/}".indexOf(curchar) < 0 && curchar != 127);
if (!"null".equals(sb.toString()) && !"true".equals(sb.toString()) && !"false".equals(sb.toString())) {
throw syntaxError("Boolean/null spelling errors : " + sb);
}
if (curchar == '"') {
throw syntaxError("Missing comma after Boolean: " + sb);
}
back();
}
}
public static void main(String[] args) {
// String str = "{\"route_table\": {\"default\":{\"default\":[{\"ip\":\"127.0.0.1\",\"port\":9999,\"useSSL\":false}]},\"10000\":{\"default\":[{\"ip\":\"127.0.0.1\",\"port\":8889}],\"serving\":[{\"ip\":\"127.0.0.1\",\"port\":8080}]},\"123\":[{\"host\":\"10.35.27.23\",\"port\":8888,\"useSSL\":false,\"negotiationType\":\"\",\"certChainFile\":\"\",\"privateKeyFile\":\"\",\"caFile\":\"\"}]},\"permission\":{\"default_allow\":true}}";
String str = "{\"route_table\":{\"default\":{\"default\":[{\"ip\":\"127.0.0.1\",\"port\":2345}]},\"10000\":{\"default\":[{\"ip\":\"127.0.0.1\",\"port\":8889}],\"serving\":[{\"ip\":\"127.0.0.1\",\"port\":8080}]}},\"permission\":{\"default_allow\":true,\"allow\":[{\"from\":{\"coordinator\":\"9999\",\"role\":\"guest\"},\"to\":{\"coordinator\":\"10000\",\"role\":\"host\"}}],\"deny\":[{\"from\":{\"coordinator\":\"9999\",\"role\":\"guest\"},\"to\":{\"coordinator\":\"10000\",\"role\":\"host\"}}]}}";
try {
if (RouteTableJsonValidator.isJSON(str)) {
String s = JsonUtil.formatJson(str);
System.out.println(s);
}
} catch (Exception e) {
System.out.println(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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/common/GlobalResponseController.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/common/GlobalResponseController.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.proxy.common;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* 全局的http结果返回处理器
*/
@RestControllerAdvice
public class GlobalResponseController implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter methodParameter, Class converterType) {
Boolean isRest = AnnotationUtils.isAnnotationDeclaredLocally(RestController.class, methodParameter.getContainingClass());
ResponseBody responseBody = AnnotationUtils.findAnnotation(methodParameter.getMethod(), ResponseBody.class);
if (responseBody != null || isRest) {
return true;
} else {
return false;
}
}
@Nullable
@Override
public Object beforeBodyWrite(@Nullable Object body,
MethodParameter methodParameter,
MediaType mediaType,
Class<? extends HttpMessageConverter<?>> aClass,
ServerHttpRequest serverHttpRequest,
ServerHttpResponse serverHttpResponse) {
return body;
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/event/ErrorEventHandler.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/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.proxy.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.core.bean.Dict;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
@Service
public class ErrorEventHandler extends AbstractAsyncMessageProcessor implements InitializingBean {
@Subscribe(value = Dict.EVENT_ERROR)
public void handleMetricsEvent(AsyncMessageEvent event) {
}
@Override
public void afterPropertiesSet() 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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/bean/RouteTableWrapper.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/bean/RouteTableWrapper.java | package com.webank.ai.fate.serving.proxy.bean;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class RouteTableWrapper {
private static final String ROUTE_TABLE = "route_table";
private static final String PERMISSION = "permission";
private static final String IP = "ip";
private static final String PORT = "port";
private static final String DEFAULT_ALLOW = "default_allow";
private static final String ALLOW = "allow";
private static final String DENY = "deny";
public static void main(String[] args) {
String json = "{\"route_table\":{\"default\":{\"default\":[{\"ip\":\"127.0.0.1\",\"port\":12345}]},\"10000\":{\"default\":[{\"ip\":\"127.0.0.1\",\"port\":8889}],\"serving\":[{\"ip\":\"127.0.0.1\",\"port\":8080}]}},\"permission\":{\"default_allow\":true,\"allow\":[{\"from\":{\"coordinator\":\"9999\",\"role\":\"guest\"},\"to\":{\"coordinator\":\"10000\",\"role\":\"host\"}}],\"deny\":[{\"from\":{\"coordinator\":\"9999\",\"role\":\"guest\"},\"to\":{\"coordinator\":\"10000\",\"role\":\"host\"}}]}}";
Map wrapper = JsonUtil.json2Object(json, Map.class);
System.out.println(JsonUtil.object2Json(wrapper));
RouteTableWrapper wrapper1 = new RouteTableWrapper().parse(JsonUtil.object2Json(wrapper));
System.out.println(JsonUtil.object2Json(wrapper1));
wrapper1.getRouteTable().getService("default").getNodes("default").get(0).setPort(6666);
System.out.println(wrapper1.toString());
}
/**
* json to RouteTable
* @param json
* @return
*/
public RouteTableWrapper parse(String json) {
try {
Map map = JsonUtil.json2Object(json, Map.class);
Map routeTableMap = (Map) map.get(ROUTE_TABLE);
Map permissionMap = (Map) map.get(PERMISSION);
RouteTableWrapper wrapper = new RouteTableWrapper();
RouteTable routeTable = new RouteTable();
Permission permission = new Permission();
for (Object e : routeTableMap.entrySet()) {
Map.Entry entry = (Map.Entry) e;
String partner = (String) entry.getKey(); // 10000
Map serviceMap = (Map) entry.getValue();
Service service = routeTable.getPartnerServiceMap().computeIfAbsent(partner, k -> new Service());
for (Object se : serviceMap.entrySet()) {
Map.Entry serviceEntry = (Map.Entry) se;
String serviceName = (String) serviceEntry.getKey();// serving
List<Map> nodes = (List<Map>) serviceEntry.getValue();
List<Node> nodeList = service.getServiceNodesMap().computeIfAbsent(serviceName, k -> new ArrayList<>());
for (Map nodeMap : nodes) {
String ip = (String) nodeMap.get(IP);
int port = (int) nodeMap.get(PORT);
nodeList.add(new Node(ip, port));
}
}
}
permission.setDefaultAllow((Boolean) permissionMap.get(DEFAULT_ALLOW));
permission.setAllow((List<Map>) permissionMap.get(ALLOW));
permission.setDeny((List<Map>) permissionMap.get(DENY));
wrapper.setRouteTable(routeTable);
wrapper.setPermission(permission);
return wrapper;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* routeTable to json
* @return
*/
@Override
public String toString() {
Map resultMap = new HashMap();
// route_table
HashMap routeTableMap = (HashMap) resultMap.computeIfAbsent(ROUTE_TABLE, k -> new HashMap<>());
for (Map.Entry<String, Service> partnerServiceEntry : routeTable.getPartnerServiceMap().entrySet()) {
// partnerServiceEntry.getKey() == 10000 partner => service
HashMap serviceNodesMap = (HashMap) routeTableMap.computeIfAbsent(partnerServiceEntry.getKey(), k -> new HashMap<>());
Service service = partnerServiceEntry.getValue();
for (Map.Entry<String, List<Node>> serviceNodeEntry : service.getServiceNodesMap().entrySet()) {
// serving => ip:port
List<Node> nodeList = (List<Node>) serviceNodesMap.computeIfAbsent(serviceNodeEntry.getKey(), k -> new ArrayList<>());
nodeList.addAll(serviceNodeEntry.getValue());
}
}
// permission
HashMap permissionMap = (HashMap) resultMap.computeIfAbsent(PERMISSION, k -> new HashMap<>());
permissionMap.putIfAbsent(DEFAULT_ALLOW, this.getPermission().isDefaultAllow());
permissionMap.putIfAbsent(ALLOW, this.getPermission().getAllow());
permissionMap.putIfAbsent(DENY, this.getPermission().getDeny());
return JsonUtil.object2Json(resultMap);
}
public final static String DEFAULT_NODE = "default";
public final static String DEFAULT_SERVICE = "default";
@JsonProperty("route_table")
private RouteTable routeTable;
private Permission permission;
public RouteTable getRouteTable() {
return routeTable;
}
public void setRouteTable(RouteTable routeTable) {
this.routeTable = routeTable;
}
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
class RouteTable {
@JsonIgnore
private ConcurrentMap<String, Service> partnerServiceMap = new ConcurrentHashMap<>();
public ConcurrentMap<String, Service> getPartnerServiceMap() {
return partnerServiceMap;
}
public Service getService(String partner) {
return this.partnerServiceMap.get(partner);
}
public void setService(String partner, Service service) {
this.partnerServiceMap.put(partner, service);
}
}
class Service {
@JsonIgnore
private ConcurrentMap<String, List<Node>> serviceNodesMap = new ConcurrentHashMap<>();
public ConcurrentMap<String, List<Node>> getServiceNodesMap() {
return serviceNodesMap;
}
public List<Node> getNodes(String serviceName) {
return this.serviceNodesMap.get(serviceName);
}
public void setNodes(String serviceName, List<Node> nodes) {
this.serviceNodesMap.put(serviceName, nodes);
}
}
class Node {
public Node(String ip, int port) {
this.ip = ip;
this.port = port;
}
private String ip;
private int port;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
class Permission {
@JsonProperty("default_allow")
private boolean defaultAllow = Boolean.TRUE;
// allow, json array
private List<Map> allow;
// allow, json array
private List<Map> deny;
public Permission() {
}
public boolean isDefaultAllow() {
return defaultAllow;
}
public void setDefaultAllow(boolean defaultAllow) {
this.defaultAllow = defaultAllow;
}
public List<Map> getAllow() {
return allow;
}
public void setAllow(List<Map> allow) {
this.allow = allow;
}
public List<Map> getDeny() {
return deny;
}
public void setDeny(List<Map> deny) {
this.deny = deny;
}
}
/**
* {
* "route_table": {
* "default": {
* "default": [
* {
* "ip": "127.0.0.1",
* "port": 12345
* }
* ]
* },
* "10000": {
* "default": [
* {
* "ip": "127.0.0.1",
* "port": 8889
* }
* ],
* "serving": [
* {
* "ip": "127.0.0.1",
* "port": 8080
* }
* ]
* }
* },
* "permission": {
* "default_allow": true,
* "allow": [{
* "from": {
* "coordinator": "9999",
* "role": "guest"
* },
* "to": {
* "coordinator": "10000",
* "role": "host"
* }* }],
* "allow": [{
* "from": {
* "coordinator": "9999",
* "role": "guest"
* } ,
* "to": {
* "coordinator": "10000",
* "role": "host"
* }
* }]
* }
* }
*/
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/DefaultAuthentication.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/DefaultAuthentication.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.proxy.security;
import com.webank.ai.fate.api.networking.proxy.Proxy;
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.ProxyAuthException;
import com.webank.ai.fate.serving.core.rpc.grpc.GrpcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 检查用户权限
*/
@Service
public class DefaultAuthentication implements Interceptor {
Logger logger = LoggerFactory.getLogger(DefaultAuthentication.class);
@Autowired
private AuthUtils authUtils;
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
if (GrpcType.INTRA_GRPC == context.getGrpcType()) {
return;
}
Proxy.Packet sourcePackage = (Proxy.Packet) inboundPackage.getBody();
boolean isAuthPass = authUtils.checkAuthentication(sourcePackage);
if (!isAuthPass) {
logger.error("check authentication failed");
throw new ProxyAuthException("check authentication failed");
}
}
@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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/RequestOverloadBreaker.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/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.proxy.security;
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());
}
}
@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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/InferenceParamValidator.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/InferenceParamValidator.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.proxy.security;
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.exceptions.GuestInvalidParamException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
/**
* @Description TODO
* @Author
**/
@Service
public class InferenceParamValidator implements Interceptor {
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
try {
Preconditions.checkArgument(StringUtils.isNotEmpty(context.getCaseId()), "case id is null");
Preconditions.checkArgument(null != inboundPackage.getHead(), Dict.HEAD + " is null");
//Preconditions.checkArgument(null != inboundPackage.getBody(),Dict.BODY + " is null");
//Preconditions.checkArgument(StringUtils.isNotEmpty((String) inboundPackage.getHead().get(Dict.SERVICE_ID)), Dict.SERVICE_ID + " is null");
Preconditions.checkArgument(Dict.SERVICENAME_INFERENCE.equals(context.getCallName())
|| Dict.SERVICENAME_BATCH_INFERENCE.equals(context.getCallName()),"invalid call name") ;
} catch (Exception e){
throw new GuestInvalidParamException(e.getMessage());
}
}
@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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/AuthUtils.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/AuthUtils.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.proxy.security;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import com.webank.ai.fate.api.networking.proxy.Proxy;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.utils.EncryptUtils;
import com.webank.ai.fate.serving.proxy.utils.FileUtils;
import com.webank.ai.fate.serving.proxy.utils.ToStringUtils;
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.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
@Component
public class AuthUtils implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(AuthUtils.class);
private static Map<String, String> KEY_SECRET_MAP = new HashMap<>();
private static Map<String, String> PARTYID_KEY_MAP = new HashMap<>();
private static int validRequestTimeoutSecond = 10;
private static boolean ifUseAuth = false;
private static String applyId = "";
private final String userDir = System.getProperty(Dict.PROPERTY_USER_DIR);
private final String DEFAULT_AUTH_FILE = "conf" + System.getProperty(Dict.PROPERTY_FILE_SEPARATOR) + "auth_config.json";
private final String fileSeparator = System.getProperty(Dict.PROPERTY_FILE_SEPARATOR);
@Autowired
private ToStringUtils toStringUtils;
private String selfPartyId;
private String lastFileMd5 = "";
@Scheduled(fixedRate = 10000)
public void loadConfig() {
if (Boolean.valueOf(MetaInfo.PROPERTY_AUTH_OPEN)) {
String filePath = "";
if (StringUtils.isNotEmpty(MetaInfo.PROPERTY_AUTH_FILE)) {
filePath = MetaInfo.PROPERTY_AUTH_FILE;
} else {
filePath = userDir + this.fileSeparator + DEFAULT_AUTH_FILE;
}
logger.info("start refreshed auth config ,file path is {}", filePath);
String fileMd5 = FileUtils.fileMd5(filePath);
if (null != fileMd5 && fileMd5.equals(lastFileMd5)) {
return;
}
File file = new File(filePath);
if (!file.exists()) {
logger.error("auth table {} is not exist", filePath);
return;
}
JsonParser jsonParser = new JsonParser();
JsonReader jsonReader = null;
JsonObject jsonObject = null;
try {
jsonReader = new JsonReader(new FileReader(filePath));
jsonObject = jsonParser.parse(jsonReader).getAsJsonObject();
} catch (FileNotFoundException e) {
logger.error("auth file not found: {}", filePath);
throw new RuntimeException(e);
} finally {
if (jsonReader != null) {
try {
jsonReader.close();
} catch (IOException ignore) {
}
}
}
selfPartyId = jsonObject.get("self_party_id").getAsString();
applyId = jsonObject.get("apply_id") != null ? jsonObject.get("apply_id").getAsString() : "";
ifUseAuth = jsonObject.get("if_use_auth").getAsBoolean();
validRequestTimeoutSecond = jsonObject.get("request_expire_seconds").getAsInt();
JsonArray jsonArray = jsonObject.getAsJsonArray("access_keys");
Gson gson = new Gson();
List<Map> allowKeys = gson.fromJson(jsonArray, ArrayList.class);
KEY_SECRET_MAP.clear();
for (Map allowKey : allowKeys) {
KEY_SECRET_MAP.put(allowKey.get("app_key").toString(), allowKey.get("app_secret").toString());
PARTYID_KEY_MAP.put(allowKey.get("party_id").toString(), allowKey.get("app_key").toString());
}
if (logger.isDebugEnabled()) {
logger.debug("refreshed auth cfg using file {}.", filePath);
}
lastFileMd5 = fileMd5;
}
}
private String getSecret(String appKey) {
return KEY_SECRET_MAP.get(appKey);
}
private String getAppKey(String partyId) {
return PARTYID_KEY_MAP.get(partyId);
}
private String calSignature(Proxy.Metadata header, Proxy.Data body, long timestamp, String appKey) throws Exception {
String signature = "";
String appSecret = getSecret(appKey);
if (StringUtils.isEmpty(appSecret)) {
logger.error("appSecret not found");
return signature;
}
String encryptText = String.valueOf(timestamp) + "\n"
+ toStringUtils.toOneLineString(header) + "\n"
+ toStringUtils.toOneLineString(body);
encryptText = new String(encryptText.getBytes(), EncryptUtils.UTF8);
signature = Base64.getEncoder().encodeToString(EncryptUtils.hmacSha1Encrypt(encryptText, appSecret));
return signature;
}
public Proxy.Packet addAuthInfo(Proxy.Packet packet) throws Exception {
if (Boolean.valueOf(MetaInfo.PROPERTY_AUTH_OPEN) && !StringUtils.equals(selfPartyId, packet.getHeader().getDst().getPartyId())) {
Proxy.Packet.Builder packetBuilder = packet.toBuilder();
Proxy.AuthInfo.Builder authBuilder = packetBuilder.getAuthBuilder();
long timestamp = System.currentTimeMillis();
authBuilder.setTimestamp(timestamp);
String appKey = getAppKey(selfPartyId);
authBuilder.setAppKey(appKey);
String signature = calSignature(packet.getHeader(), packet.getBody(), timestamp, appKey);
authBuilder.setSignature(signature);
authBuilder.setServiceId(packet.getAuth().getServiceId());
if (!("".equals(packet.getAuth().getApplyId()))) {
authBuilder.setApplyId(packet.getAuth().getApplyId());
} else {
authBuilder.setApplyId(applyId);
}
packetBuilder.setAuth(authBuilder.build());
return packetBuilder.build();
}
return packet;
}
public boolean checkAuthentication(Proxy.Packet packet) throws Exception {
if (Boolean.valueOf(MetaInfo.PROPERTY_AUTH_OPEN)) {
// check timestamp
long currentTimeMillis = System.currentTimeMillis();
long requestTimeMillis = packet.getAuth().getTimestamp();
if (currentTimeMillis >= (requestTimeMillis + validRequestTimeoutSecond * 1000)) {
logger.error("receive an expired request, currentTimeMillis:{}, requestTimeMillis{}.", currentTimeMillis, requestTimeMillis);
return false;
}
// check signature
String reqSignature = packet.getAuth().getSignature();
String validSignature = calSignature(packet.getHeader(), packet.getBody(), requestTimeMillis, packet.getAuth().getAppKey());
if (!StringUtils.equals(reqSignature, validSignature)) {
logger.error("invalid signature, request:{}, valid:{}", reqSignature, validSignature);
return false;
}
}
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
try {
loadConfig();
} catch (Throwable e) {
logger.error("load authentication keys fail. ", e);
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/FederationParamValidator.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/FederationParamValidator.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.proxy.security;
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 org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
/**
* @Description TODO
* @Author
**/
@Service
public class FederationParamValidator implements Interceptor {
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
Preconditions.checkArgument(StringUtils.isNotEmpty(context.getHostAppid()), "host id is null");
Preconditions.checkArgument(StringUtils.isNotEmpty(context.getGuestAppId()), "guest id is null");
Preconditions.checkArgument(StringUtils.isNotEmpty(context.getCaseId()), "case id is null");
}
@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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/MonitorInterceptor.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/security/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.proxy.security;
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 org.springframework.stereotype.Service;
@Service
public class MonitorInterceptor implements Interceptor {
@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-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/GrpcConfigration.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/GrpcConfigration.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.proxy.config;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class GrpcConfigration {
@Bean(name = "grpcExecutorPool")
public Executor asyncServiceExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(MetaInfo.PROPERTY_PROXY_GRPC_THREADPOOL_CORESIZE);
executor.setMaxPoolSize(MetaInfo.PROPERTY_PROXY_GRPC_THREADPOOL_MAXSIZE);
executor.setQueueCapacity(MetaInfo.PROPERTY_PROXY_GRPC_THREADPOOL_QUEUESIZE);
executor.setThreadNamePrefix("grpc-service");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
executor.initialize();
return executor;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/CharacterEncodingFilter.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/CharacterEncodingFilter.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.proxy.config;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/WebConfiguration.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/WebConfiguration.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.proxy.config;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.context.request.async.TimeoutCallableProcessingInterceptor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
int processors = Runtime.getRuntime().availableProcessors();
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(MetaInfo.PROPERTY_PROXY_ASYNC_CORESIZE > 0 ? MetaInfo.PROPERTY_PROXY_ASYNC_CORESIZE : processors);
executor.setMaxPoolSize(MetaInfo.PROPERTY_PROXY_ASYNC_MAXSIZE > 0 ? MetaInfo.PROPERTY_PROXY_ASYNC_MAXSIZE : 2 * processors);
executor.setThreadNamePrefix("ProxyAsync");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
executor.initialize();
configurer.setTaskExecutor(executor);
configurer.setDefaultTimeout(MetaInfo.PROPERTY_PROXY_ASYNC_TIMEOUT);
configurer.registerCallableInterceptors(new TimeoutCallableProcessingInterceptor());
}
@Bean
public TimeoutCallableProcessingInterceptor timeoutCallableProcessingInterceptor() {
return new TimeoutCallableProcessingInterceptor();
}
@Bean
public FilterRegistrationBean initUserServletFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
registration.setFilter(characterEncodingFilter);
registration.addUrlPatterns("/*");
registration.setName("CharacterEncodingFilter");
registration.setOrder(Integer.MAX_VALUE);
return registration;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/ProxyConfig.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/ProxyConfig.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.proxy.config;
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 com.webank.ai.fate.serving.common.flow.FlowCounterManager;
import com.webank.ai.fate.serving.core.bean.Dict;
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 ProxyConfig implements ApplicationContextAware {
Logger logger = LoggerFactory.getLogger(ProxyConfig.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());
};
}
@Bean(destroyMethod = "destroy")
public FlowCounterManager flowCounterManager() {
FlowCounterManager flowCounterManager = new FlowCounterManager(Dict.SERVICE_PROXY);
flowCounterManager.startReport();
return flowCounterManager;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/UseZkCondition.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/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.proxy.config;
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_ZK_ROUTER;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/RegistryConfig.java | fate-serving-proxy/src/main/java/com/webank/ai/fate/serving/proxy/config/RegistryConfig.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.proxy.config;
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.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 RegistryConfig {
private static final Logger logger = LoggerFactory.getLogger(RegistryConfig.class);
@Bean(destroyMethod = "destroy")
@Conditional(UseZkCondition.class)
public ZookeeperRegistry zookeeperRegistry() {
if (logger.isDebugEnabled()) {
logger.info("prepare to create zookeeper registry ,use zk {}", MetaInfo.PROPERTY_USE_ZK_ROUTER);
}
if (StringUtils.isEmpty(MetaInfo.PROPERTY_ZK_URL)) {
logger.error("useZkRouter is true,but zkUrl is empty,please check zk.url in the config file");
throw new RuntimeException("wrong zk url");
}
ZookeeperRegistry zookeeperRegistry = ZookeeperRegistry.createRegistry(MetaInfo.PROPERTY_ZK_URL, Dict.SERVICE_PROXY,
Dict.ONLINE_ENVIRONMENT, MetaInfo.PROPERTY_PROXY_GRPC_INTRA_PORT);
zookeeperRegistry.subProject(Dict.SERVICE_SERVING);
return zookeeperRegistry;
}
@Bean
@Conditional(UseZkCondition.class)
@ConditionalOnBean(ZookeeperRegistry.class)
public ApplicationListener<ApplicationReadyEvent> registerComponent(ZookeeperRegistry zookeeperRegistry) {
return applicationReadyEvent -> zookeeperRegistry.registerComponent();
}
@Bean
@ConditionalOnBean(ZookeeperRegistry.class)
public RouterService routerService(ZookeeperRegistry zookeeperRegistry) {
DefaultRouterService defaultRouterService = new DefaultRouterService();
defaultRouterService.setRegistry(zookeeperRegistry);
return defaultRouterService;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/Node.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/Node.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.interfaces;
import com.webank.ai.fate.register.url.URL;
public interface Node {
URL getUrl();
boolean isAvailable();
void destroy();
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/Timer.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/Timer.java | ///*
// * Copyright 2019 The FATE Authors. All Rights Reserved.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//
//package com.webank.ai.fate.register.interfaces;
//
//import com.webank.ai.fate.register.common.TimerTask;
//
//import java.util.Set;
//import java.util.concurrent.TimeUnit;
//
//
//public interface Timer {
//
//
// Timeout newTimeout(TimerTask task, long delay, TimeUnit unit);
//
//
// Set<Timeout> stop();
//
//
// boolean isStop();
//} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/Registry.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/Registry.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.interfaces;
public interface Registry extends Node, RegistryService {
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/NotifyListener.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/NotifyListener.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.interfaces;
import com.webank.ai.fate.register.url.URL;
import java.util.List;
public interface NotifyListener {
void notify(List<URL> urls);
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/Timeout.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/Timeout.java | ///*
// * Copyright 2019 The FATE Authors. All Rights Reserved.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//
//package com.webank.ai.fate.register.interfaces;
//
//
//import com.webank.ai.fate.register.common.TimerTask;
//
//public interface Timeout {
//
//
// Timer timer();
//
//
// TimerTask task();
//
//
// boolean isExpired();
//
//
// boolean isCancelled();
//
//
// boolean cancel();
//} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/RegistryService.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/interfaces/RegistryService.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.interfaces;
import com.webank.ai.fate.register.url.URL;
import java.util.List;
public interface RegistryService {
void register(URL url);
void unregister(URL url);
void subscribe(URL url, NotifyListener listener);
void unsubscribe(URL url, NotifyListener listener);
List<URL> lookup(URL url);
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/url/URL.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/url/URL.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.url;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.webank.ai.fate.register.common.Constants.*;
public class URL implements Serializable {
private static final long serialVersionUID = -1985165475234910535L;
private final String protocol;
private final String host;
private final int port;
private final String path;
private final Map<String, String> parameters;
private String environment;
private String project;
private volatile transient Map<String, Number> numbers;
private volatile transient Map<String, URL> urls;
private volatile transient String ip;
private volatile transient String full;
// ==== cache ====
private volatile transient String identity;
private volatile transient String parameter;
private volatile transient String string;
public URL() {
this.protocol = null;
this.environment = null;
this.project = null;
this.host = null;
this.port = 0;
this.path = null;
this.parameters = null;
}
public URL(String path, Map<String, String> parameters) {
this.protocol = null;
this.environment = null;
this.project = null;
this.host = null;
this.port = 0;
this.path = path;
this.parameters = parameters;
}
public URL(String protocol, String host, int port) {
this(protocol, null, null, host, port, null, (Map<String, String>) null);
}
public URL(String protocol, String host, int port, String[] pairs) { // varargs ... conflict with the following path argument, use array instead.
this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs));
}
public URL(String protocol, String host, int port, Map<String, String> parameters) {
this(protocol, null, null, host, port, null, parameters);
}
public URL(String protocol, String host, int port, String path) {
this(protocol, null, null, host, port, path, (Map<String, String>) null);
}
public URL(String protocol, String host, int port, String path, String... pairs) {
this(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs));
}
public URL(String protocol, String host, int port, String path, Map<String, String> parameters) {
this(protocol, null, null, host, port, path, parameters);
}
public URL(String protocol, String project, String environment, String host, int port, String path) {
this(protocol, project, environment, host, port, path, (Map<String, String>) null);
}
public URL(String protocol, String project, String environment, String host, int port, String path, String... pairs) {
this(protocol, project, environment, host, port, path, CollectionUtils.toStringMap(pairs));
}
public URL(String protocol, String project, String environment, String host, int port, String path, Map<String, String> parameters) {
this.protocol = protocol;
this.project = project;
this.environment = environment;
this.host = host;
this.port = (port < 0 ? 0 : port);
// trim the beginning "/"
while (path != null && path.startsWith("/")) {
path = path.substring(1);
}
this.path = path;
if (parameters == null) {
parameters = new HashMap<>();
} else {
parameters = new HashMap<>(parameters);
}
this.parameters = parameters;
}
public static URL valueOf(String url, String project, String environment) {
//grpc://fateserving/fate-cmd_fate-test")
if (url == null || (url = url.trim()).length() == 0) {
throw new IllegalArgumentException("url == null");
}
String protocol = null;
String username = null;
String password = null;
String host = null;
int port = 0;
String path = null;
Map<String, String> parameters = null;
// separator between body and parameters
int i = url.indexOf("?");
if (i >= 0) {
String[] parts = url.substring(i + 1).split("&");
parameters = new HashMap<>(8);
for (String part : parts) {
part = part.trim();
if (part.length() > 0) {
int j = part.indexOf('=');
if (j >= 0) {
parameters.put(part.substring(0, j), part.substring(j + 1));
} else {
parameters.put(part, part);
}
}
}
url = url.substring(0, i);
}
i = url.indexOf("://");
if (i >= 0) {
if (i == 0) {
throw new IllegalStateException("url missing protocol: \"" + url + "\"");
}
protocol = url.substring(0, i);
url = url.substring(i + 3);
} else {
// case: file:/path/to/file.txt
i = url.indexOf(":/");
if (i >= 0) {
if (i == 0) {
throw new IllegalStateException("url missing protocol: \"" + url + "\"");
}
protocol = url.substring(0, i);
url = url.substring(i + 1);
}
}
i = url.lastIndexOf("/");
if (i >= 0) {
path = url.substring(i + 1);
url = url.substring(0, i);
}
// i = url.lastIndexOf("@");
// if (i >= 0) {
// username = url.substring(0, i);
// int j = username.indexOf(":");
// if (j >= 0) {
// password = username.substring(j + 1);
// username = username.substring(0, j);
// }
// url = url.substring(i + 1);
// }
i = url.lastIndexOf(":");
if (i >= 0 && i < url.length() - 1) {
if (url.lastIndexOf("%") > i) {
// ipv6 address with scope id
// e.g. fe80:0:0:0:894:aeec:f37d:23e1%en0
// see https://howdoesinternetwork.com/2013/ipv6-zone-id
// ignore
} else {
int x = url.indexOf("/");
if (x > 0) {
port = Integer.parseInt(url.substring(i + 1, x));
} else {
port = Integer.parseInt(url.substring(i + 1));
}
host = url.substring(0, i);
url = url.substring(x + 1);
}
}
// i=url.lastIndexOf("/");
// if(i>0){
// project = url.substring(0,i);
// environment = url.substring(i+1);
// }
// if (url.length() > 0) {
// host = url;
// }
return new URL(protocol, project, environment, host, port, path, parameters);
}
/**
* Parse url string
*
* @param url URL string
* @return URL instance
* @see URL
*/
public static URL valueOf(String url) {
//grpc://fateserving/fate-cmd_fate-test")
if (url == null || (url = url.trim()).length() == 0) {
throw new IllegalArgumentException("url == null");
}
String protocol = null;
String username = null;
String password = null;
String host = null;
String project = null;
String environment = null;
int port = 0;
String path = null;
Map<String, String> parameters = null;
// separator between body and parameters
int i = url.indexOf("?");
if (i >= 0) {
String[] parts = url.substring(i + 1).split("&");
parameters = new HashMap<>(8);
for (String part : parts) {
part = part.trim();
if (part.length() > 0) {
int j = part.indexOf('=');
if (j >= 0) {
parameters.put(part.substring(0, j), part.substring(j + 1));
} else {
parameters.put(part, part);
}
}
}
url = url.substring(0, i);
}
i = url.indexOf("://");
if (i >= 0) {
if (i == 0) {
throw new IllegalStateException("url missing protocol: \"" + url + "\"");
}
protocol = url.substring(0, i);
url = url.substring(i + 3);
} else {
// case: file:/path/to/file.txt
i = url.indexOf(":/");
if (i >= 0) {
if (i == 0) {
throw new IllegalStateException("url missing protocol: \"" + url + "\"");
}
protocol = url.substring(0, i);
url = url.substring(i + 1);
}
}
i = url.lastIndexOf("/");
if (i >= 0) {
path = url.substring(i + 1);
url = url.substring(0, i);
}
// i = url.lastIndexOf("@");
// if (i >= 0) {
// username = url.substring(0, i);
// int j = username.indexOf(":");
// if (j >= 0) {
// password = username.substring(j + 1);
// username = username.substring(0, j);
// }
// url = url.substring(i + 1);
// }
i = url.lastIndexOf(":");
if (i >= 0 && i < url.length() - 1) {
if (url.lastIndexOf("%") > i) {
// ipv6 address with scope id
// e.g. fe80:0:0:0:894:aeec:f37d:23e1%en0
// see https://howdoesinternetwork.com/2013/ipv6-zone-id
// ignore
} else {
int x = url.indexOf("/");
if (x > 0) {
port = Integer.parseInt(url.substring(i + 1, x));
} else {
port = Integer.parseInt(url.substring(i + 1));
}
host = url.substring(0, i);
url = url.substring(x + 1);
}
}
i = url.lastIndexOf("/");
if (i > 0) {
project = url.substring(0, i);
environment = url.substring(i + 1);
}
// if (url.length() > 0) {
// host = url;
// }
return new URL(protocol, project, environment, host, port, path, parameters);
}
public static URL valueOf(String url, String... reserveParams) {
URL result = valueOf(url);
if (reserveParams == null || reserveParams.length == 0) {
return result;
}
Map<String, String> newMap = new HashMap<>(reserveParams.length);
Map<String, String> oldMap = result.getParameters();
for (String reserveParam : reserveParams) {
String tmp = oldMap.get(reserveParam);
if (StringUtils.isNotEmpty(tmp)) {
newMap.put(reserveParam, tmp);
}
}
return result.clearParameters().addParameters(newMap);
}
public static URL valueOf(URL url, String[] reserveParams, String[] reserveParamPrefixs) {
Map<String, String> newMap = new HashMap<>(8);
Map<String, String> oldMap = url.getParameters();
if (reserveParamPrefixs != null && reserveParamPrefixs.length != 0) {
for (Map.Entry<String, String> entry : oldMap.entrySet()) {
for (String reserveParamPrefix : reserveParamPrefixs) {
if (entry.getKey().startsWith(reserveParamPrefix) && StringUtils.isNotEmpty(entry.getValue())) {
newMap.put(entry.getKey(), entry.getValue());
}
}
}
}
if (reserveParams != null) {
for (String reserveParam : reserveParams) {
String tmp = oldMap.get(reserveParam);
if (StringUtils.isNotEmpty(tmp)) {
newMap.put(reserveParam, tmp);
}
}
}
return newMap.isEmpty() ? new URL(url.getProtocol(), url.getProject(), url.getEnvironment(), url.getHost(), url.getPort(), url.getPath())
: new URL(url.getProtocol(), url.getProject(), url.getEnvironment(), url.getHost(), url.getPort(), url.getPath(), newMap);
}
public static String encode(String value) {
if (StringUtils.isEmpty(value)) {
return "";
}
try {
return URLEncoder.encode(value, UTF_8);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static String decode(String value) {
if (StringUtils.isEmpty(value)) {
return "";
}
try {
return URLDecoder.decode(value, UTF_8);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
static String appendDefaultPort(String address, int defaultPort) {
if (address != null && address.length() > 0 && defaultPort > 0) {
int i = address.indexOf(':');
if (i < 0) {
return address + ":" + defaultPort;
} else if (Integer.parseInt(address.substring(i + 1)) == 0) {
return address.substring(0, i + 1) + defaultPort;
}
}
return address;
}
public static void main(String[] args) {
}
public static URL parseJMXServiceUrl(String url) {
if (url == null || (url = url.trim()).length() == 0) {
throw new IllegalArgumentException("url == null");
}
String protocol = null;
String project = null;
String environment = null;
String host = null;
int port = 0;
String path = null;
// diffent
int i = url.lastIndexOf("://");
if (i >= 0) {
if (i == 0) {
throw new IllegalStateException("url missing protocol: \"" + url + "\"");
}
protocol = url.substring(0, i);
url = url.substring(i + 3);
} else {
i = url.indexOf(":/");
if (i >= 0) {
if (i == 0) {
throw new IllegalStateException("url missing protocol: \"" + url + "\"");
}
protocol = url.substring(0, i);
url = url.substring(i + 1);
}
}
i = url.lastIndexOf("/");
if (i >= 0) {
path = url.substring(i + 1);
url = url.substring(0, i);
}
i = url.lastIndexOf(":");
if (i >= 0 && i < url.length() - 1) {
int x = url.indexOf("/");
if (x > 0) {
port = Integer.parseInt(url.substring(i + 1, x));
} else {
port = Integer.parseInt(url.substring(i + 1));
}
host = url.substring(0, i);
}
return new URL(protocol, project, environment, host, port, path, new HashMap<>(8));
}
public String getEnvironment() {
return environment;
}
public URL setEnvironment(String environment) {
return new URL(protocol, project, environment, host, port, path, this.parameters);
}
public String getProject() {
return project;
}
public URL setProject(String project) {
return new URL(protocol, project, environment, host, port, path, this.parameters);
}
public String getProtocol() {
return protocol;
}
public URL setProtocol(String protocol) {
return new URL(protocol, project, environment, host, port, path, getParameters());
}
public URL setPassword(String password) {
return new URL(protocol, project, password, host, port, path, getParameters());
}
public String getHost() {
return host;
}
public URL setHost(String host) {
return new URL(protocol, project, environment, host, port, path, getParameters());
}
/**
* Fetch IP address for this URL.
* <p>
* Pls. note that IP should be used instead of Host when to compare with socket's address or to search in a map
* which use address as its key.
*
* @return ip in string format
*/
public String getIp() {
return ip;
}
public int getPort() {
return port;
}
public URL setPort(int port) {
return new URL(protocol, project, environment, host, port, path, getParameters());
}
public int getPort(int defaultPort) {
return port <= 0 ? defaultPort : port;
}
public String getAddress() {
return port <= 0 ? host : host + ":" + port;
}
public URL setAddress(String address) {
int i = address.lastIndexOf(':');
String host;
int port = this.port;
if (i >= 0) {
host = address.substring(0, i);
port = Integer.parseInt(address.substring(i + 1));
} else {
host = address;
}
return new URL(protocol, project, environment, host, port, path, getParameters());
}
public String getBackupAddress() {
return getBackupAddress(0);
}
public String getBackupAddress(int defaultPort) {
StringBuilder address = new StringBuilder(appendDefaultPort(getAddress(), defaultPort));
String[] backups = getParameter(BACKUP_KEY, new String[0]);
if (ArrayUtils.isNotEmpty(backups)) {
for (String backup : backups) {
address.append(",");
address.append(appendDefaultPort(backup, defaultPort));
}
}
return address.toString();
}
public List<URL> getBackupUrls() {
List<URL> urls = new ArrayList<>();
urls.add(this);
String[] backups = getParameter(BACKUP_KEY, new String[0]);
if (backups != null && backups.length > 0) {
for (String backup : backups) {
urls.add(this.setAddress(backup));
}
}
return urls;
}
public String getPath() {
return path;
}
public URL setPath(String path) {
return new URL(protocol, project, environment, host, port, path, getParameters());
}
public String getAbsolutePath() {
if (path != null && !path.startsWith("/")) {
return "/" + path;
}
return path;
}
public Map<String, String> getParameters() {
return parameters;
}
public String getParameterAndDecoded(String key) {
return getParameterAndDecoded(key, null);
}
public String getParameterAndDecoded(String key, String defaultValue) {
return decode(getParameter(key, defaultValue));
}
public String getParameter(String key) {
String value = parameters.get(key);
return StringUtils.isEmpty(value) ? parameters.get(DEFAULT_KEY_PREFIX + key) : value;
}
public String getParameter(String key, String defaultValue) {
String value = getParameter(key);
return StringUtils.isEmpty(value) ? defaultValue : value;
}
public String[] getParameter(String key, String[] defaultValue) {
String value = getParameter(key);
return StringUtils.isEmpty(value) ? defaultValue : COMMA_SPLIT_PATTERN.split(value);
}
public List<String> getParameter(String key, List<String> defaultValue) {
String value = getParameter(key);
if (value == null || value.length() == 0) {
return defaultValue;
}
String[] strArray = COMMA_SPLIT_PATTERN.split(value);
return Arrays.asList(strArray);
}
private Map<String, Number> getNumbers() {
// concurrent initialization is tolerant
return numbers == null ? new ConcurrentHashMap<>(8) : numbers;
}
private Map<String, URL> getUrls() {
// concurrent initialization is tolerant
return urls == null ? new ConcurrentHashMap<>(8) : urls;
}
public URL getUrlParameter(String key) {
URL u = getUrls().get(key);
if (u != null) {
return u;
}
String value = getParameterAndDecoded(key);
if (StringUtils.isEmpty(value)) {
return null;
}
u = URL.valueOf(value);
getUrls().put(key, u);
return u;
}
public double getParameter(String key, double defaultValue) {
Number n = getNumbers().get(key);
if (n != null) {
return n.doubleValue();
}
String value = getParameter(key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
double d = Double.parseDouble(value);
getNumbers().put(key, d);
return d;
}
public float getParameter(String key, float defaultValue) {
Number n = getNumbers().get(key);
if (n != null) {
return n.floatValue();
}
String value = getParameter(key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
float f = Float.parseFloat(value);
getNumbers().put(key, f);
return f;
}
public long getParameter(String key, long defaultValue) {
Number n = getNumbers().get(key);
if (n != null) {
return n.longValue();
}
String value = getParameter(key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
long l = Long.parseLong(value);
getNumbers().put(key, l);
return l;
}
public int getParameter(String key, int defaultValue) {
Number n = getNumbers().get(key);
if (n != null) {
return n.intValue();
}
String value = getParameter(key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
int i = Integer.parseInt(value);
getNumbers().put(key, i);
return i;
}
public short getParameter(String key, short defaultValue) {
Number n = getNumbers().get(key);
if (n != null) {
return n.shortValue();
}
String value = getParameter(key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
short s = Short.parseShort(value);
getNumbers().put(key, s);
return s;
}
public byte getParameter(String key, byte defaultValue) {
Number n = getNumbers().get(key);
if (n != null) {
return n.byteValue();
}
String value = getParameter(key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
byte b = Byte.parseByte(value);
getNumbers().put(key, b);
return b;
}
public float getPositiveParameter(String key, float defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
float value = getParameter(key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public double getPositiveParameter(String key, double defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
double value = getParameter(key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public long getPositiveParameter(String key, long defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
long value = getParameter(key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public int getPositiveParameter(String key, int defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
int value = getParameter(key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public short getPositiveParameter(String key, short defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
short value = getParameter(key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public byte getPositiveParameter(String key, byte defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
byte value = getParameter(key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public char getParameter(String key, char defaultValue) {
String value = getParameter(key);
return StringUtils.isEmpty(value) ? defaultValue : value.charAt(0);
}
public boolean getParameter(String key, boolean defaultValue) {
String value = getParameter(key);
return StringUtils.isEmpty(value) ? defaultValue : Boolean.parseBoolean(value);
}
public boolean hasParameter(String key) {
String value = getParameter(key);
return value != null && value.length() > 0;
}
public String getMethodParameterAndDecoded(String method, String key) {
return URL.decode(getMethodParameter(method, key));
}
public String getMethodParameterAndDecoded(String method, String key, String defaultValue) {
return URL.decode(getMethodParameter(method, key, defaultValue));
}
public String getMethodParameter(String method, String key) {
String value = parameters.get(method + "." + key);
return StringUtils.isEmpty(value) ? getParameter(key) : value;
}
public String getMethodParameter(String method, String key, String defaultValue) {
String value = getMethodParameter(method, key);
return StringUtils.isEmpty(value) ? defaultValue : value;
}
public double getMethodParameter(String method, String key, double defaultValue) {
String methodKey = method + "." + key;
Number n = getNumbers().get(methodKey);
if (n != null) {
return n.doubleValue();
}
String value = getMethodParameter(method, key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
double d = Double.parseDouble(value);
getNumbers().put(methodKey, d);
return d;
}
public float getMethodParameter(String method, String key, float defaultValue) {
String methodKey = method + "." + key;
Number n = getNumbers().get(methodKey);
if (n != null) {
return n.floatValue();
}
String value = getMethodParameter(method, key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
float f = Float.parseFloat(value);
getNumbers().put(methodKey, f);
return f;
}
public long getMethodParameter(String method, String key, long defaultValue) {
String methodKey = method + "." + key;
Number n = getNumbers().get(methodKey);
if (n != null) {
return n.longValue();
}
String value = getMethodParameter(method, key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
long l = Long.parseLong(value);
getNumbers().put(methodKey, l);
return l;
}
public int getMethodParameter(String method, String key, int defaultValue) {
String methodKey = method + "." + key;
Number n = getNumbers().get(methodKey);
if (n != null) {
return n.intValue();
}
String value = getMethodParameter(method, key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
int i = Integer.parseInt(value);
getNumbers().put(methodKey, i);
return i;
}
public short getMethodParameter(String method, String key, short defaultValue) {
String methodKey = method + "." + key;
Number n = getNumbers().get(methodKey);
if (n != null) {
return n.shortValue();
}
String value = getMethodParameter(method, key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
short s = Short.parseShort(value);
getNumbers().put(methodKey, s);
return s;
}
public byte getMethodParameter(String method, String key, byte defaultValue) {
String methodKey = method + "." + key;
Number n = getNumbers().get(methodKey);
if (n != null) {
return n.byteValue();
}
String value = getMethodParameter(method, key);
if (StringUtils.isEmpty(value)) {
return defaultValue;
}
byte b = Byte.parseByte(value);
getNumbers().put(methodKey, b);
return b;
}
public double getMethodPositiveParameter(String method, String key, double defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
double value = getMethodParameter(method, key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public float getMethodPositiveParameter(String method, String key, float defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
float value = getMethodParameter(method, key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public long getMethodPositiveParameter(String method, String key, long defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
long value = getMethodParameter(method, key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public int getMethodPositiveParameter(String method, String key, int defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
int value = getMethodParameter(method, key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public short getMethodPositiveParameter(String method, String key, short defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
short value = getMethodParameter(method, key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public byte getMethodPositiveParameter(String method, String key, byte defaultValue) {
if (defaultValue <= 0) {
throw new IllegalArgumentException("defaultValue <= 0");
}
byte value = getMethodParameter(method, key, defaultValue);
return value <= 0 ? defaultValue : value;
}
public char getMethodParameter(String method, String key, char defaultValue) {
String value = getMethodParameter(method, key);
return StringUtils.isEmpty(value) ? defaultValue : value.charAt(0);
}
public boolean getMethodParameter(String method, String key, boolean defaultValue) {
String value = getMethodParameter(method, key);
return StringUtils.isEmpty(value) ? defaultValue : Boolean.parseBoolean(value);
}
public boolean hasMethodParameter(String method, String key) {
if (method == null) {
String suffix = "." + key;
for (String fullKey : parameters.keySet()) {
if (fullKey.endsWith(suffix)) {
return true;
}
}
return false;
}
if (key == null) {
String prefix = method + ".";
for (String fullKey : parameters.keySet()) {
if (fullKey.startsWith(prefix)) {
return true;
}
| 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-register/src/main/java/com/webank/ai/fate/register/url/CollectionUtils.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/url/CollectionUtils.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.url;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
public class CollectionUtils {
private static final Comparator<String> SIMPLE_NAME_COMPARATOR = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
if (s1 == null && s2 == null) {
return 0;
}
if (s1 == null) {
return -1;
}
if (s2 == null) {
return 1;
}
int i1 = s1.lastIndexOf('.');
if (i1 >= 0) {
s1 = s1.substring(i1 + 1);
}
int i2 = s2.lastIndexOf('.');
if (i2 >= 0) {
s2 = s2.substring(i2 + 1);
}
return s1.compareToIgnoreCase(s2);
}
};
public CollectionUtils() {
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> List<T> sort(List<T> list) {
if (isNotEmpty(list)) {
Collections.sort((List) list);
}
return list;
}
public static List<String> sortSimpleName(List<String> list) {
if (list != null && list.size() > 0) {
Collections.sort(list, SIMPLE_NAME_COMPARATOR);
}
return list;
}
public static Map<String, Map<String, String>> splitAll(Map<String, List<String>> list, String separator) {
if (list == null) {
return null;
}
Map<String, Map<String, String>> result = new HashMap<>();
for (Map.Entry<String, List<String>> entry : list.entrySet()) {
result.put(entry.getKey(), split(entry.getValue(), separator));
}
return result;
}
public static Map<String, List<String>> joinAll(Map<String, Map<String, String>> map, String separator) {
if (map == null) {
return null;
}
Map<String, List<String>> result = new HashMap<>();
for (Map.Entry<String, Map<String, String>> entry : map.entrySet()) {
result.put(entry.getKey(), join(entry.getValue(), separator));
}
return result;
}
public static Map<String, String> split(List<String> list, String separator) {
if (list == null) {
return null;
}
Map<String, String> map = new HashMap<>();
if (list.isEmpty()) {
return map;
}
for (String item : list) {
int index = item.indexOf(separator);
if (index == -1) {
map.put(item, "");
} else {
map.put(item.substring(0, index), item.substring(index + 1));
}
}
return map;
}
public static List<String> join(Map<String, String> map, String separator) {
if (map == null) {
return null;
}
List<String> list = new ArrayList<>();
if (map.size() == 0) {
return list;
}
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (StringUtils.isEmpty(value)) {
list.add(key);
} else {
list.add(key + separator + value);
}
}
return list;
}
public static String join(List<String> list, String separator) {
StringBuilder sb = new StringBuilder();
for (String ele : list) {
if (sb.length() > 0) {
sb.append(separator);
}
sb.append(ele);
}
return sb.toString();
}
public static boolean mapEquals(Map<?, ?> map1, Map<?, ?> map2) {
if (map1 == null && map2 == null) {
return true;
}
if (map1 == null || map2 == null) {
return false;
}
if (map1.size() != map2.size()) {
return false;
}
for (Map.Entry<?, ?> entry : map1.entrySet()) {
Object key = entry.getKey();
Object value1 = entry.getValue();
Object value2 = map2.get(key);
if (!objectEquals(value1, value2)) {
return false;
}
}
return true;
}
private static boolean objectEquals(Object obj1, Object obj2) {
if (obj1 == null && obj2 == null) {
return true;
}
if (obj1 == null || obj2 == null) {
return false;
}
return obj1.equals(obj2);
}
public static Map<String, String> toStringMap(String... pairs) {
Map<String, String> parameters = new HashMap<>();
if (pairs.length > 0) {
if (pairs.length % 2 != 0) {
throw new IllegalArgumentException("pairs must be even.");
}
for (int i = 0; i < pairs.length; i = i + 2) {
parameters.put(pairs[i], pairs[i + 1]);
}
}
return parameters;
}
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> toMap(Object... pairs) {
Map<K, V> ret = new HashMap<>();
if (pairs == null || pairs.length == 0) {
return ret;
}
if (pairs.length % 2 != 0) {
throw new IllegalArgumentException("Map pairs can not be odd number.");
}
int len = pairs.length / 2;
for (int i = 0; i < len; i++) {
ret.put((K) pairs[2 * i], (V) pairs[2 * i + 1]);
}
return ret;
}
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
public static boolean isNotEmpty(Collection<?> collection) {
return !isEmpty(collection);
}
public static boolean isEmptyMap(Map map) {
return map == null || map.size() == 0;
}
public static boolean isNotEmptyMap(Map map) {
return !isEmptyMap(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-register/src/main/java/com/webank/ai/fate/register/url/UrlUtils.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/url/UrlUtils.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.url;
import com.webank.ai.fate.register.utils.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static com.webank.ai.fate.register.common.Constants.*;
public class UrlUtils {
/**
* in the url string,mark the param begin
*/
private final static String URL_PARAM_STARTING_SYMBOL = "?";
public static URL parseUrl(String address, Map<String, String> defaults) {
if (address == null || address.length() == 0) {
return null;
}
String url;
if (address.contains("://") || address.contains(URL_PARAM_STARTING_SYMBOL)) {
url = address;
} else {
String[] addresses = COMMA_SPLIT_PATTERN.split(address);
url = addresses[0];
if (addresses.length > 1) {
StringBuilder backup = new StringBuilder();
for (int i = 1; i < addresses.length; i++) {
if (i > 1) {
backup.append(",");
}
backup.append(addresses[i]);
}
url += URL_PARAM_STARTING_SYMBOL + BACKUP_KEY + "=" + backup.toString();
}
}
String defaultProtocol = defaults == null ? null : defaults.get(PROTOCOL_KEY);
if (defaultProtocol == null || defaultProtocol.length() == 0) {
defaultProtocol = GRPC;
}
String defaultProject = defaults == null ? null : defaults.get(PROJECT_KEY);
String defaultEnvironment = defaults == null ? null : defaults.get(ENVIRONMENT_KEY);
int defaultPort = StringUtils.parseInteger(defaults == null ? null : defaults.get(PORT_KEY));
String defaultPath = defaults == null ? null : defaults.get(PATH_KEY);
Map<String, String> defaultParameters = defaults == null ? null : new HashMap<String, String>(defaults);
if (defaultParameters != null) {
defaultParameters.remove(PROTOCOL_KEY);
defaultParameters.remove(PROJECT_KEY);
defaultParameters.remove(ENVIRONMENT_KEY);
defaultParameters.remove(HOST_KEY);
defaultParameters.remove(PORT_KEY);
defaultParameters.remove(PATH_KEY);
}
URL u = URL.valueOf(url);
boolean changed = false;
String protocol = u.getProtocol();
String project = u.getProject();
String environment = u.getEnvironment();
String host = u.getHost();
int port = u.getPort();
String path = u.getPath();
Map<String, String> parameters = new HashMap<String, String>(u.getParameters());
if ((protocol == null || protocol.length() == 0) && defaultProtocol != null && defaultProtocol.length() > 0) {
changed = true;
protocol = defaultProtocol;
}
// if ((project == null || username.length() == 0) && defaultUsername != null && defaultUsername.length() > 0) {
// changed = true;
// username = defaultUsername;
// }
// if ((password == null || password.length() == 0) && defaultPassword != null && defaultPassword.length() > 0) {
// changed = true;
// password = defaultPassword;
// }
/*if (u.isAnyHost() || u.isLocalHost()) {
changed = true;
host = NetUtils.getLocalHost();
}*/
if (port <= 0) {
if (defaultPort > 0) {
changed = true;
port = defaultPort;
} else {
changed = true;
port = 9090;
}
}
if (path == null || path.length() == 0) {
if (defaultPath != null && defaultPath.length() > 0) {
changed = true;
path = defaultPath;
}
}
if (defaultParameters != null && defaultParameters.size() > 0) {
for (Map.Entry<String, String> entry : defaultParameters.entrySet()) {
String key = entry.getKey();
String defaultValue = entry.getValue();
if (defaultValue != null && defaultValue.length() > 0) {
String value = parameters.get(key);
if (StringUtils.isEmpty(value)) {
changed = true;
parameters.put(key, defaultValue);
}
}
}
}
// if (changed) {
// u = new URL(protocol, pro, password, host, port, path, parameters);
// }
return u;
}
public static List<URL> parseUrls(String address, Map<String, String> defaults) {
if (address == null || address.length() == 0) {
return null;
}
String[] addresses = REGISTRY_SPLIT_PATTERN.split(address);
if (addresses == null || addresses.length == 0) {
//here won't be empty
return null;
}
List<URL> registries = new ArrayList<URL>();
for (String addr : addresses) {
registries.add(parseUrl(addr, defaults));
}
return registries;
}
public static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register) {
Map<String, Map<String, String>> newRegister = new HashMap<String, Map<String, String>>();
for (Map.Entry<String, Map<String, String>> entry : register.entrySet()) {
String serviceName = entry.getKey();
Map<String, String> serviceUrls = entry.getValue();
if (!serviceName.contains(":") && !serviceName.contains("/")) {
for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) {
String serviceUrl = entry2.getKey();
String serviceQuery = entry2.getValue();
Map<String, String> params = StringUtils.parseQueryString(serviceQuery);
String group = params.get(GROUP_KEY);
String version = params.get(VERSION_KEY);
//params.remove("group");
//params.remove("version");
String name = serviceName;
if (group != null && group.length() > 0) {
name = group + "/" + name;
}
if (version != null && version.length() > 0) {
name = name + ":" + version;
}
Map<String, String> newUrls = newRegister.get(name);
if (newUrls == null) {
newUrls = new HashMap<String, String>();
newRegister.put(name, newUrls);
}
newUrls.put(serviceUrl, StringUtils.toQueryString(params));
}
} else {
newRegister.put(serviceName, serviceUrls);
}
}
return newRegister;
}
public static Map<String, String> convertSubscribe(Map<String, String> subscribe) {
Map<String, String> newSubscribe = new HashMap<String, String>();
for (Map.Entry<String, String> entry : subscribe.entrySet()) {
String serviceName = entry.getKey();
String serviceQuery = entry.getValue();
if (!serviceName.contains(":") && !serviceName.contains("/")) {
Map<String, String> params = StringUtils.parseQueryString(serviceQuery);
String group = params.get(GROUP_KEY);
String version = params.get(VERSION_KEY);
//params.remove("group");
//params.remove("version");
String name = serviceName;
if (group != null && group.length() > 0) {
name = group + "/" + name;
}
if (version != null && version.length() > 0) {
name = name + ":" + version;
}
newSubscribe.put(name, StringUtils.toQueryString(params));
} else {
newSubscribe.put(serviceName, serviceQuery);
}
}
return newSubscribe;
}
public static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register) {
Map<String, Map<String, String>> newRegister = new HashMap<String, Map<String, String>>();
for (Map.Entry<String, Map<String, String>> entry : register.entrySet()) {
String serviceName = entry.getKey();
Map<String, String> serviceUrls = entry.getValue();
if (serviceName.contains(":") || serviceName.contains("/")) {
for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) {
String serviceUrl = entry2.getKey();
String serviceQuery = entry2.getValue();
Map<String, String> params = StringUtils.parseQueryString(serviceQuery);
String name = serviceName;
int i = name.indexOf('/');
if (i >= 0) {
params.put(GROUP_KEY, name.substring(0, i));
name = name.substring(i + 1);
}
i = name.lastIndexOf(':');
if (i >= 0) {
params.put(VERSION_KEY, name.substring(i + 1));
name = name.substring(0, i);
}
Map<String, String> newUrls = newRegister.get(name);
if (newUrls == null) {
newUrls = new HashMap<String, String>();
newRegister.put(name, newUrls);
}
newUrls.put(serviceUrl, StringUtils.toQueryString(params));
}
} else {
newRegister.put(serviceName, serviceUrls);
}
}
return newRegister;
}
public static Map<String, String> revertSubscribe(Map<String, String> subscribe) {
Map<String, String> newSubscribe = new HashMap<String, String>();
for (Map.Entry<String, String> entry : subscribe.entrySet()) {
String serviceName = entry.getKey();
String serviceQuery = entry.getValue();
if (serviceName.contains(":") || serviceName.contains("/")) {
Map<String, String> params = StringUtils.parseQueryString(serviceQuery);
String name = serviceName;
int i = name.indexOf('/');
if (i >= 0) {
params.put(GROUP_KEY, name.substring(0, i));
name = name.substring(i + 1);
}
i = name.lastIndexOf(':');
if (i >= 0) {
params.put(VERSION_KEY, name.substring(i + 1));
name = name.substring(0, i);
}
newSubscribe.put(name, StringUtils.toQueryString(params));
} else {
newSubscribe.put(serviceName, serviceQuery);
}
}
return newSubscribe;
}
public static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify) {
if (notify != null && notify.size() > 0) {
Map<String, Map<String, String>> newNotify = new HashMap<String, Map<String, String>>();
for (Map.Entry<String, Map<String, String>> entry : notify.entrySet()) {
String serviceName = entry.getKey();
Map<String, String> serviceUrls = entry.getValue();
if (!serviceName.contains(":") && !serviceName.contains("/")) {
if (serviceUrls != null && serviceUrls.size() > 0) {
for (Map.Entry<String, String> entry2 : serviceUrls.entrySet()) {
String url = entry2.getKey();
String query = entry2.getValue();
Map<String, String> params = StringUtils.parseQueryString(query);
String group = params.get(GROUP_KEY);
String version = params.get(VERSION_KEY);
// params.remove("group");
// params.remove("version");
String name = serviceName;
if (group != null && group.length() > 0) {
name = group + "/" + name;
}
if (version != null && version.length() > 0) {
name = name + ":" + version;
}
Map<String, String> newUrls = newNotify.get(name);
if (newUrls == null) {
newUrls = new HashMap<String, String>();
newNotify.put(name, newUrls);
}
newUrls.put(url, StringUtils.toQueryString(params));
}
}
} else {
newNotify.put(serviceName, serviceUrls);
}
}
return newNotify;
}
return notify;
}
public static URL getEmptyUrl(String service, String category) {
String group = null;
String version = null;
int i = service.indexOf('/');
if (i > 0) {
group = service.substring(0, i);
service = service.substring(i + 1);
}
i = service.lastIndexOf(':');
if (i > 0) {
version = service.substring(i + 1);
service = service.substring(0, i);
}
return URL.valueOf(EMPTY_PROTOCOL + "://" + ANYHOST_VALUE + "/" + service + URL_PARAM_STARTING_SYMBOL
+ CATEGORY_KEY + "=" + category
+ (group == null ? "" : "&" + GROUP_KEY + "=" + group)
+ (version == null ? "" : "&" + VERSION_KEY + "=" + version));
}
public static boolean isMatchCategory(String category, String categories) {
if (categories == null || categories.length() == 0) {
return DEFAULT_CATEGORY.equals(category);
} else if (categories.contains(ANY_VALUE)) {
return true;
} else if (categories.contains(REMOVE_VALUE_PREFIX)) {
return !categories.contains(REMOVE_VALUE_PREFIX + category);
} else {
return categories.contains(category);
}
}
public static boolean isMatch(URL consumerUrl, URL providerUrl) {
String consumerInterface = consumerUrl.getServiceInterface();
String providerInterface = providerUrl.getServiceInterface();
//FIXME accept providerUrl with '*' as interface name, after carefully thought about all possible scenarios I think it's ok to add this condition.
if (!(ANY_VALUE.equals(consumerInterface)
|| ANY_VALUE.equals(providerInterface)
|| (consumerInterface.equals(providerInterface)))) {
return false;
}
if (!isMatchCategory(providerUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY),
consumerUrl.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY))) {
return false;
}
if (!providerUrl.getParameter(ENABLED_KEY, true)
&& !ANY_VALUE.equals(consumerUrl.getParameter(ENABLED_KEY))) {
return false;
}
String consumerGroup = consumerUrl.getParameter(GROUP_KEY);
// String consumerVersion = consumerUrl.getParameter(VERSION_KEY);
String consumerClassifier = consumerUrl.getParameter(CLASSIFIER_KEY, ANY_VALUE);
String providerGroup = providerUrl.getParameter(GROUP_KEY);
// String providerVersion = providerUrl.getParameter(VERSION_KEY);
String providerClassifier = providerUrl.getParameter(CLASSIFIER_KEY, ANY_VALUE);
return (ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup))
// && (ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion))
&& (consumerClassifier == null || ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier));
}
public static boolean isMatchGlobPattern(String pattern, String value, URL param) {
if (param != null && pattern.startsWith("$")) {
pattern = param.getRawParameter(pattern.substring(1));
}
return isMatchGlobPattern(pattern, value);
}
public static boolean isMatchGlobPattern(String pattern, String value) {
if ("*".equals(pattern)) {
return true;
}
if (StringUtils.isEmpty(pattern) && StringUtils.isEmpty(value)) {
return true;
}
if (StringUtils.isEmpty(pattern) || StringUtils.isEmpty(value)) {
return false;
}
int i = pattern.lastIndexOf('*');
// doesn't find "*"
if (i == -1) {
return value.equals(pattern);
}
// "*" is at the end
else if (i == pattern.length() - 1) {
return value.startsWith(pattern.substring(0, i));
}
// "*" is at the beginning
else if (i == 0) {
return value.endsWith(pattern.substring(i + 1));
}
// "*" is in the middle
else {
String prefix = pattern.substring(0, i);
String suffix = pattern.substring(i + 1);
return value.startsWith(prefix) && value.endsWith(suffix);
}
}
public static boolean isServiceKeyMatch(URL pattern, URL value) {
return pattern.getParameter(INTERFACE_KEY).equals(
value.getParameter(INTERFACE_KEY))
&& isItemMatch(pattern.getParameter(GROUP_KEY),
value.getParameter(GROUP_KEY))
&& isItemMatch(pattern.getParameter(VERSION_KEY),
value.getParameter(VERSION_KEY));
}
public static List<URL> classifyUrls(List<URL> urls, Predicate<URL> predicate) {
return urls.stream().filter(predicate).collect(Collectors.toList());
}
public static boolean isConfigurator(URL url) {
return OVERRIDE_PROTOCOL.equals(url.getProtocol()) ||
CONFIGURATORS_CATEGORY.equals(url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY));
}
public static boolean isRoute(URL url) {
return ROUTE_PROTOCOL.equals(url.getProtocol()) ||
ROUTERS_CATEGORY.equals(url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY));
}
public static boolean isProvider(URL url) {
return !OVERRIDE_PROTOCOL.equals(url.getProtocol()) &&
!ROUTE_PROTOCOL.equals(url.getProtocol()) &&
PROVIDERS_CATEGORY.equals(url.getParameter(CATEGORY_KEY, PROVIDERS_CATEGORY));
}
/**
* Check if the given value matches the given pattern. The pattern supports wildcard "*".
*
* @param pattern pattern
* @param value value
* @return true if match otherwise false
*/
static boolean isItemMatch(String pattern, String value) {
if (pattern == null) {
return value == null;
} else {
return "*".equals(pattern) || pattern.equals(value);
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/utils/StringUtils.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/utils/StringUtils.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.utils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.webank.ai.fate.register.common.Constants.*;
/**
* StringUtils
*/
public final class StringUtils {
public static final String EMPTY = "";
public static final int INDEX_NOT_FOUND = -1;
public static final String[] EMPTY_STRING_ARRAY = new String[0];
/**
* key value pair pattern.
*/
private static final Pattern KVP_PATTERN = Pattern.compile("([_.a-zA-Z0-9][-_.a-zA-Z0-9]*)[=](.*)");
private static final Pattern INT_PATTERN = Pattern.compile("^\\d+$");
private static final int PAD_LIMIT = 8192;
private StringUtils() {
}
/**
* Gets a CharSequence length or {@code 0} if the CharSequence is
* {@code null}.
*
* @param cs a CharSequence or {@code null}
* @return CharSequence length or {@code 0} if the CharSequence is
* {@code null}.
*/
public static int length(final CharSequence cs) {
return cs == null ? 0 : cs.length();
}
/**
* <p>Repeat a String {@code repeat} times to form a
* new String.</p>
* <p>
* <pre>
* StringUtils.repeat(null, 2) = null
* StringUtils.repeat("", 0) = ""
* StringUtils.repeat("", 2) = ""
* StringUtils.repeat("a", 3) = "aaa"
* StringUtils.repeat("ab", 2) = "abab"
* StringUtils.repeat("a", -2) = ""
* </pre>
*
* @param str the String to repeat, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* {@code null} if null String input
*/
public static String repeat(final String str, final int repeat) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
if (repeat <= 0) {
return EMPTY;
}
final int inputLength = str.length();
if (repeat == 1 || inputLength == 0) {
return str;
}
if (inputLength == 1 && repeat <= PAD_LIMIT) {
return repeat(str.charAt(0), repeat);
}
final int outputLength = inputLength * repeat;
switch (inputLength) {
case 1:
return repeat(str.charAt(0), repeat);
case 2:
final char ch0 = str.charAt(0);
final char ch1 = str.charAt(1);
final char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default:
final StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
}
return buf.toString();
}
}
/**
* <p>Repeat a String {@code repeat} times to form a
* new String, with a String separator injected each time. </p>
* <p>
* <pre>
* StringUtils.repeat(null, null, 2) = null
* StringUtils.repeat(null, "x", 2) = null
* StringUtils.repeat("", null, 0) = ""
* StringUtils.repeat("", "", 2) = ""
* StringUtils.repeat("", "x", 3) = "xxx"
* StringUtils.repeat("?", ", ", 3) = "?, ?, ?"
* </pre>
*
* @param str the String to repeat, may be null
* @param separator the String to inject, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* {@code null} if null String input
* @since 2.5
*/
public static String repeat(final String str, final String separator, final int repeat) {
if (str == null || separator == null) {
return repeat(str, repeat);
}
// given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it
final String result = repeat(str + separator, repeat);
return removeEnd(result, separator);
}
/**
* <p>Removes a substring only if it is at the end of a source string,
* otherwise returns the source string.</p>
* <p>
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
* <p>
* <pre>
* StringUtils.removeEnd(null, *) = null
* StringUtils.removeEnd("", *) = ""
* StringUtils.removeEnd(*, null) = *
* StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEnd("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
*/
public static String removeEnd(final String str, final String remove) {
if (isAnyEmpty(str, remove)) {
return str;
}
if (str.endsWith(remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
* <p>
* <pre>
* StringUtils.repeat('e', 0) = ""
* StringUtils.repeat('e', 3) = "eee"
* StringUtils.repeat('e', -2) = ""
* </pre>
* <p>
* <p>Note: this method doesn't not support padding with
* <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a>
* as they require a pair of {@code char}s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param ch character to repeat
* @param repeat number of times to repeat char, negative treated as zero
* @return String with repeated character
* @see #repeat(String, int)
*/
public static String repeat(final char ch, final int repeat) {
final char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
/**
* <p>Strips any of a set of characters from the end of a String.</p>
* <p>
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
* <p>
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
* <p>
* <pre>
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
* StringUtils.stripEnd("abc", "") = "abc"
* StringUtils.stripEnd("abc", null) = "abc"
* StringUtils.stripEnd(" abc", null) = " abc"
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
* StringUtils.stripEnd("120.00", ".0") = "12"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the set of characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String stripEnd(final String str, final String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) {
end--;
}
}
return str.substring(0, end);
}
/**
* <p>Replaces all occurrences of a String within another String.</p>
* <p>
* <p>A {@code null} reference passed to this method is a no-op.</p>
* <p>
* <pre>
* StringUtils.replace(null, *, *) = null
* StringUtils.replace("", *, *) = ""
* StringUtils.replace("any", null, *) = "any"
* StringUtils.replace("any", *, null) = "any"
* StringUtils.replace("any", "", *) = "any"
* StringUtils.replace("aba", "a", null) = "aba"
* StringUtils.replace("aba", "a", "") = "b"
* StringUtils.replace("aba", "a", "z") = "zbz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
* @see #replace(String text, String searchString, String replacement, int max)
*/
public static String replace(final String text, final String searchString, final String replacement) {
return replace(text, searchString, replacement, -1);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String.</p>
* <p>
* <p>A {@code null} reference passed to this method is a no-op.</p>
* <p>
* <pre>
* StringUtils.replace(null, *, *, *) = null
* StringUtils.replace("", *, *, *) = ""
* StringUtils.replace("any", null, *, *) = "any"
* StringUtils.replace("any", *, null, *) = "any"
* StringUtils.replace("any", "", *, *) = "any"
* StringUtils.replace("any", *, *, 0) = "any"
* StringUtils.replace("abaa", "a", null, -1) = "abaa"
* StringUtils.replace("abaa", "a", "", -1) = "b"
* StringUtils.replace("abaa", "a", "z", 0) = "abaa"
* StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtils.replace("abaa", "a", "z", 2) = "zbza"
* StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or {@code -1} if no maximum
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replace(final String text, final String searchString, final String replacement, int max) {
if (isAnyEmpty(text, searchString) || replacement == null || max == 0) {
return text;
}
int start = 0;
int end = text.indexOf(searchString, start);
if (end == INDEX_NOT_FOUND) {
return text;
}
final int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = increase < 0 ? 0 : increase;
increase *= max < 0 ? 16 : max > 64 ? 64 : max;
final StringBuilder buf = new StringBuilder(text.length() + increase);
while (end != INDEX_NOT_FOUND) {
buf.append(text.substring(start, end)).append(replacement);
start = end + replLength;
if (--max == 0) {
break;
}
end = text.indexOf(searchString, start);
}
buf.append(text.substring(start));
return buf.toString();
}
public static boolean isBlank(String str) {
return isEmpty(str);
}
/**
* is empty string.
*
* @param str source string.
* @return is empty.
*/
public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
/**
* <p>Checks if the strings contain empty or null elements. <p/>
* <p>
* <pre>
* StringUtils.isNoneEmpty(null) = false
* StringUtils.isNoneEmpty("") = false
* StringUtils.isNoneEmpty(" ") = true
* StringUtils.isNoneEmpty("abc") = true
* StringUtils.isNoneEmpty("abc", "def") = true
* StringUtils.isNoneEmpty("abc", null) = false
* StringUtils.isNoneEmpty("abc", "") = false
* StringUtils.isNoneEmpty("abc", " ") = true
* </pre>
*
* @param ss the strings to check
* @return {@code true} if all strings are not empty or null
*/
public static boolean isNoneEmpty(final String... ss) {
if (ArrayUtils.isEmpty(ss)) {
return false;
}
for (final String s : ss) {
if (isEmpty(s)) {
return false;
}
}
return true;
}
/**
* <p>Checks if the strings contain at least on empty or null element. <p/>
* <p>
* <pre>
* StringUtils.isAnyEmpty(null) = true
* StringUtils.isAnyEmpty("") = true
* StringUtils.isAnyEmpty(" ") = false
* StringUtils.isAnyEmpty("abc") = false
* StringUtils.isAnyEmpty("abc", "def") = false
* StringUtils.isAnyEmpty("abc", null) = true
* StringUtils.isAnyEmpty("abc", "") = true
* StringUtils.isAnyEmpty("abc", " ") = false
* </pre>
*
* @param ss the strings to check
* @return {@code true} if at least one in the strings is empty or null
*/
public static boolean isAnyEmpty(final String... ss) {
return !isNoneEmpty(ss);
}
/**
* is not empty string.
*
* @param str source string.
* @return is not empty.
*/
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
/**
* @param s1
* @param s2
* @return equals
*/
public static boolean isEquals(String s1, String s2) {
if (s1 == null && s2 == null) {
return true;
}
if (s1 == null || s2 == null) {
return false;
}
return s1.equals(s2);
}
/**
* is integer string.
*
* @param str
* @return is integer
*/
public static boolean isInteger(String str) {
return isNotEmpty(str) && INT_PATTERN.matcher(str).matches();
}
public static int parseInteger(String str) {
return isInteger(str) ? Integer.parseInt(str) : 0;
}
/**
* Returns true if s is a legal Java identifier.<p>
* <a href="http://www.exampledepot.com/egs/java.lang/IsJavaId.html">more info.</a>
*/
public static boolean isJavaIdentifier(String s) {
if (isEmpty(s) || !Character.isJavaIdentifierStart(s.charAt(0))) {
return false;
}
for (int i = 1; i < s.length(); i++) {
if (!Character.isJavaIdentifierPart(s.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isContains(String values, String value) {
return isNotEmpty(values) && isContains(COMMA_SPLIT_PATTERN.split(values), value);
}
/**
* @param values
* @param value
* @return contains
*/
public static boolean isContains(String[] values, String value) {
if (isNotEmpty(value) && ArrayUtils.isNotEmpty(values)) {
for (String v : values) {
if (value.equals(v)) {
return true;
}
}
}
return false;
}
public static boolean isNumeric(String str, boolean allowDot) {
if (str == null || str.isEmpty()) {
return false;
}
boolean hasDot = false;
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (str.charAt(i) == '.') {
if (hasDot || !allowDot) {
return false;
}
hasDot = true;
continue;
}
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
// /**
// * @param e
// * @return string
// */
// public static String toString(Throwable e) {
// UnsafeStringWriter w = new UnsafeStringWriter();
// PrintWriter p = new PrintWriter(w);
// p.print(e.getClass().getName());
// if (e.getMessage() != null) {
// p.print(": " + e.getMessage());
// }
// p.println();
// try {
// e.printStackTrace(p);
// return w.toString();
// } finally {
// p.close();
// }
// }
// /**
// * @param msg
// * @param e
// * @return string
// */
// public static String toString(String msg, Throwable e) {
// UnsafeStringWriter w = new UnsafeStringWriter();
// w.write(msg + "\n");
// PrintWriter p = new PrintWriter(w);
// try {
// e.printStackTrace(p);
// return w.toString();
// } finally {
// p.close();
// }
// }
/**
* translate.
*
* @param src source string.
* @param from src char table.
* @param to target char table.
* @return String.
*/
public static String translate(String src, String from, String to) {
if (isEmpty(src)) {
return src;
}
StringBuilder sb = null;
int ix;
char c;
for (int i = 0, len = src.length(); i < len; i++) {
c = src.charAt(i);
ix = from.indexOf(c);
if (ix == -1) {
if (sb != null) {
sb.append(c);
}
} else {
if (sb == null) {
sb = new StringBuilder(len);
sb.append(src, 0, i);
}
if (ix < to.length()) {
sb.append(to.charAt(ix));
}
}
}
return sb == null ? src : sb.toString();
}
/**
* split.
*
* @param ch char.
* @return string array.
*/
public static String[] split(String str, char ch) {
List<String> list = null;
char c;
int ix = 0, len = str.length();
for (int i = 0; i < len; i++) {
c = str.charAt(i);
if (c == ch) {
if (list == null) {
list = new ArrayList<String>();
}
list.add(str.substring(ix, i));
ix = i + 1;
}
}
if (ix > 0) {
list.add(str.substring(ix));
}
return list == null ? EMPTY_STRING_ARRAY : (String[]) list.toArray(EMPTY_STRING_ARRAY);
}
/**
* join string.
*
* @param array String array.
* @return String.
*/
public static String join(String[] array) {
if (ArrayUtils.isEmpty(array)) {
return EMPTY;
}
StringBuilder sb = new StringBuilder();
for (String s : array) {
sb.append(s);
}
return sb.toString();
}
/**
* join string like javascript.
*
* @param array String array.
* @param split split
* @return String.
*/
public static String join(String[] array, char split) {
if (ArrayUtils.isEmpty(array)) {
return EMPTY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0) {
sb.append(split);
}
sb.append(array[i]);
}
return sb.toString();
}
/**
* join string like javascript.
*
* @param array String array.
* @param split split
* @return String.
*/
public static String join(String[] array, String split) {
if (ArrayUtils.isEmpty(array)) {
return EMPTY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0) {
sb.append(split);
}
sb.append(array[i]);
}
return sb.toString();
}
public static String join(Collection<String> coll, String split) {
if (CollectionUtils.isEmpty(coll)) {
return EMPTY;
}
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (String s : coll) {
if (isFirst) {
isFirst = false;
} else {
sb.append(split);
}
sb.append(s);
}
return sb.toString();
}
/**
* parse key-value pair.
*
* @param str string.
* @param itemSeparator item separator.
* @return key-value map;
*/
private static Map<String, String> parseKeyValuePair(String str, String itemSeparator) {
String[] tmp = str.split(itemSeparator);
Map<String, String> map = new HashMap<String, String>(tmp.length);
for (int i = 0; i < tmp.length; i++) {
Matcher matcher = KVP_PATTERN.matcher(tmp[i]);
if (!matcher.matches()) {
continue;
}
map.put(matcher.group(1), matcher.group(2));
}
return map;
}
public static String getQueryStringValue(String qs, String key) {
Map<String, String> map = StringUtils.parseQueryString(qs);
return map.get(key);
}
/**
* parse query string to Parameters.
*
* @param qs query string.
* @return Parameters instance.
*/
public static Map<String, String> parseQueryString(String qs) {
if (isEmpty(qs)) {
return new HashMap<String, String>();
}
return parseKeyValuePair(qs, "\\&");
}
// public static String getServiceKey(Map<String, String> ps) {
// StringBuilder buf = new StringBuilder();
// String group = ps.get(GROUP_KEY);
// if (isNotEmpty(group)) {
// buf.append(group).append("/");
// }
// buf.append(ps.get(INTERFACE_KEY));
// String version = ps.get(VERSION_KEY);
// if (isNotEmpty(group)) {
// buf.append(":").append(version);
// }
// return buf.toString();
// }
public static String toQueryString(Map<String, String> ps) {
StringBuilder buf = new StringBuilder();
if (ps != null && ps.size() > 0) {
for (Map.Entry<String, String> entry : new TreeMap<String, String>(ps).entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (isNoneEmpty(key, value)) {
if (buf.length() > 0) {
buf.append("&");
}
buf.append(key);
buf.append("=");
buf.append(value);
}
}
}
return buf.toString();
}
public static String camelToSplitName(String camelName, String split) {
if (isEmpty(camelName)) {
return camelName;
}
StringBuilder buf = null;
for (int i = 0; i < camelName.length(); i++) {
char ch = camelName.charAt(i);
if (ch >= 'A' && ch <= 'Z') {
if (buf == null) {
buf = new StringBuilder();
if (i > 0) {
buf.append(camelName.substring(0, i));
}
}
if (i > 0) {
buf.append(split);
}
buf.append(Character.toLowerCase(ch));
} else if (buf != null) {
buf.append(ch);
}
}
return buf == null ? camelName : buf.toString();
}
// public static String toArgumentString(Object[] args) {
// StringBuilder buf = new StringBuilder();
// for (Object arg : args) {
// if (buf.length() > 0) {
// buf.append(COMMA_SEPARATOR);
// }
// if (arg == null || ReflectUtils.isPrimitives(arg.getClass())) {
// buf.append(arg);
// } else {
// try {
// buf.append(JSON.toJSONString(arg));
// } catch (Exception e) {
// logger.warn(e.getMessage(), e);
// buf.append(arg);
// }
// }
// }
// return buf.toString();
// }
public static String trim(String str) {
return str == null ? null : str.trim();
}
public static String toUrlKey(String key) {
return key.toLowerCase().replaceAll(SEPARATOR_REGEX, HIDE_KEY_PREFIX);
}
public static boolean isAllUpperCase(String str) {
if (str != null && !isEmpty(str)) {
int sz = str.length();
for (int i = 0; i < sz; ++i) {
if (!Character.isUpperCase(str.charAt(i))) {
return false;
}
}
return true;
} else {
return false;
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/utils/URLBuilder.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/utils/URLBuilder.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.utils;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.url.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static com.webank.ai.fate.register.common.Constants.DEFAULT_KEY_PREFIX;
public final class URLBuilder {
private String protocol;
private String username;
private String password;
// by default, host to registry
private String host;
// by default, port to registry
private int port;
private String path;
private Map<String, String> parameters;
public URLBuilder() {
protocol = null;
username = null;
password = null;
host = null;
port = 0;
path = null;
parameters = new HashMap<>();
}
public URLBuilder(String protocol, String host, int port) {
this(protocol, null, null, host, port, null, null);
}
public URLBuilder(String protocol, String host, int port, String[] pairs) {
this(protocol, null, null, host, port, null, CollectionUtils.toStringMap(pairs));
}
public URLBuilder(String protocol, String host, int port, Map<String, String> parameters) {
this(protocol, null, null, host, port, null, parameters);
}
public URLBuilder(String protocol, String host, int port, String path) {
this(protocol, null, null, host, port, path, null);
}
public URLBuilder(String protocol, String host, int port, String path, String... pairs) {
this(protocol, null, null, host, port, path, CollectionUtils.toStringMap(pairs));
}
public URLBuilder(String protocol, String host, int port, String path, Map<String, String> parameters) {
this(protocol, null, null, host, port, path, parameters);
}
public URLBuilder(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) {
this.protocol = protocol;
this.username = username;
this.password = password;
this.host = host;
this.port = port;
this.path = path;
this.parameters = parameters != null ? parameters : new HashMap<>();
}
public static URLBuilder from(URL url) {
String protocol = url.getProtocol();
String project = url.getProject();
String enviroment = url.getEnvironment();
String host = url.getHost();
int port = url.getPort();
String path = url.getPath();
Map<String, String> parameters = new HashMap<>(url.getParameters());
return new URLBuilder(
protocol,
project,
enviroment,
host,
port,
path,
parameters);
}
public URL build() {
if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) {
throw new IllegalArgumentException("Invalid url, password without username!");
}
port = port < 0 ? 0 : port;
// trim the leading "/"
int firstNonSlash = 0;
if (path != null) {
while (firstNonSlash < path.length() && path.charAt(firstNonSlash) == '/') {
firstNonSlash++;
}
if (firstNonSlash >= path.length()) {
path = "";
} else if (firstNonSlash > 0) {
path = path.substring(firstNonSlash);
}
}
return new URL(protocol, username, password, host, port, path, parameters);
}
public URLBuilder setProtocol(String protocol) {
this.protocol = protocol;
return this;
}
public URLBuilder setUsername(String username) {
this.username = username;
return this;
}
public URLBuilder setPassword(String password) {
this.password = password;
return this;
}
public URLBuilder setHost(String host) {
this.host = host;
return this;
}
public URLBuilder setPort(int port) {
this.port = port;
return this;
}
public URLBuilder setAddress(String address) {
int i = address.lastIndexOf(':');
String host;
int port = this.port;
if (i >= 0) {
host = address.substring(0, i);
port = Integer.parseInt(address.substring(i + 1));
} else {
host = address;
}
this.host = host;
this.port = port;
return this;
}
public URLBuilder setPath(String path) {
this.path = path;
return this;
}
public URLBuilder addParameterAndEncoded(String key, String value) {
if (StringUtils.isEmpty(value)) {
return this;
}
return addParameter(key, URL.encode(value));
}
public URLBuilder addParameter(String key, boolean value) {
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, char value) {
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, byte value) {
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, short value) {
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, int value) {
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, long value) {
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, float value) {
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, double value) {
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, Enum<?> value) {
if (value == null) {
return this;
}
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, Number value) {
if (value == null) {
return this;
}
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, CharSequence value) {
if (value == null || value.length() == 0) {
return this;
}
return addParameter(key, String.valueOf(value));
}
public URLBuilder addParameter(String key, String value) {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
return this;
}
// if value doesn't change, return immediately
if (value.equals(parameters.get(key))) { // value != null
return this;
}
parameters.put(key, value);
return this;
}
public URLBuilder addParameterIfAbsent(String key, String value) {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
return this;
}
if (hasParameter(key)) {
return this;
}
parameters.put(key, value);
return this;
}
public URLBuilder addParameters(Map<String, String> parameters) {
if (CollectionUtils.isEmptyMap(parameters)) {
return this;
}
boolean hasAndEqual = true;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
String oldValue = this.parameters.get(entry.getKey());
String newValue = entry.getValue();
if (!Objects.equals(oldValue, newValue)) {
hasAndEqual = false;
break;
}
}
// return immediately if there's no change
if (hasAndEqual) {
return this;
}
this.parameters.putAll(parameters);
return this;
}
public URLBuilder addParametersIfAbsent(Map<String, String> parameters) {
if (CollectionUtils.isEmptyMap(parameters)) {
return this;
}
this.parameters.putAll(parameters);
return this;
}
public URLBuilder addParameters(String... pairs) {
if (pairs == null || pairs.length == 0) {
return this;
}
if (pairs.length % 2 != 0) {
throw new IllegalArgumentException("Map pairs can not be odd number.");
}
Map<String, String> map = new HashMap<>();
int len = pairs.length / 2;
for (int i = 0; i < len; i++) {
map.put(pairs[2 * i], pairs[2 * i + 1]);
}
return addParameters(map);
}
public URLBuilder addParameterString(String query) {
if (StringUtils.isEmpty(query)) {
return this;
}
return addParameters(StringUtils.parseQueryString(query));
}
public URLBuilder removeParameter(String key) {
if (StringUtils.isEmpty(key)) {
return this;
}
return removeParameters(key);
}
public URLBuilder removeParameters(Collection<String> keys) {
if (CollectionUtils.isEmpty(keys)) {
return this;
}
return removeParameters(keys.toArray(new String[0]));
}
public URLBuilder removeParameters(String... keys) {
if (keys == null || keys.length == 0) {
return this;
}
for (String key : keys) {
parameters.remove(key);
}
return this;
}
public URLBuilder clearParameters() {
parameters.clear();
return this;
}
public boolean hasParameter(String key) {
String value = getParameter(key);
return value != null && value.length() > 0;
}
public String getParameter(String key) {
String value = parameters.get(key);
if (StringUtils.isEmpty(value)) {
value = parameters.get(DEFAULT_KEY_PREFIX + key);
}
return value;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/ConfigChangeType.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/ConfigChangeType.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
public enum ConfigChangeType {
/**
* add config
*/
ADDED,
/**
* modify config
*/
MODIFIED,
/**
* delete
*/
DELETED
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/AbstractZookeeperTransporter.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/AbstractZookeeperTransporter.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.zookeeper.ZookeeperClient;
import com.webank.ai.fate.register.zookeeper.ZookeeperTransporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.webank.ai.fate.register.common.Constants.BACKUP_KEY;
import static com.webank.ai.fate.register.common.Constants.TIMEOUT_KEY;
public abstract class AbstractZookeeperTransporter implements ZookeeperTransporter {
private static final Logger logger = LoggerFactory.getLogger(AbstractZookeeperTransporter.class);
private final Map<String, ZookeeperClient> zookeeperClientMap = new ConcurrentHashMap<>();
/**
* share connnect for registry, metadata, etc..
* <p>
* Make sure the connection is connected.
*
* @param url
* @return
*/
@Override
public ZookeeperClient connect(URL url) {
ZookeeperClient zookeeperClient;
List<String> addressList = getURLBackupAddress(url);
// The field define the zookeeper server , including protocol, host, port, username, password
if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null && zookeeperClient.isConnected()) {
logger.info("find valid zookeeper client from the cache for address: " + url);
return zookeeperClient;
}
// avoid creating too many connections, so add lock
synchronized (zookeeperClientMap) {
if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null && zookeeperClient.isConnected()) {
logger.info("find valid zookeeper client from the cache for address: " + url);
return zookeeperClient;
}
zookeeperClient = createZookeeperClient(toClientURL(url));
logger.info("No valid zookeeper client found from cache, therefore create a new client for url. " + url);
writeToClientMap(addressList, zookeeperClient);
}
return zookeeperClient;
}
protected abstract ZookeeperClient createZookeeperClient(URL url);
ZookeeperClient fetchAndUpdateZookeeperClientCache(List<String> addressList) {
ZookeeperClient zookeeperClient = null;
for (String address : addressList) {
if ((zookeeperClient = zookeeperClientMap.get(address)) != null && zookeeperClient.isConnected()) {
break;
}
}
if (zookeeperClient != null && zookeeperClient.isConnected()) {
writeToClientMap(addressList, zookeeperClient);
}
return zookeeperClient;
}
/**
* get all zookeeper urls (such as :zookeeper://127.0.0.1:2181?127.0.0.1:8989,127.0.0.1:9999)
*
* @param url such as:zookeeper://127.0.0.1:2181?127.0.0.1:8989,127.0.0.1:9999
* @return such as 127.0.0.1:2181,127.0.0.1:8989,127.0.0.1:9999
*/
List<String> getURLBackupAddress(URL url) {
List<String> addressList = new ArrayList<String>();
addressList.add(url.getAddress());
addressList.addAll(url.getParameter(BACKUP_KEY, Collections.EMPTY_LIST));
return addressList;
}
/**
* write address-ZookeeperClient relationship to Map
*
* @param addressList
* @param zookeeperClient
*/
void writeToClientMap(List<String> addressList, ZookeeperClient zookeeperClient) {
for (String address : addressList) {
zookeeperClientMap.put(address, zookeeperClient);
}
}
/**
* redefine the url for zookeeper. just keep protocol, username, password, host, port, and individual parameter.
*
* @param url
* @return
*/
URL toClientURL(URL url) {
Map<String, String> parameterMap = new HashMap<>();
// for CuratorZookeeperClient
if (url.getParameter(TIMEOUT_KEY) != null) {
parameterMap.put(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY));
}
if (url.getParameter(BACKUP_KEY) != null) {
parameterMap.put(BACKUP_KEY, url.getParameter(BACKUP_KEY));
}
return new URL(url.getProtocol(), url.getProject(), url.getEnvironment(), url.getHost(), url.getPort(),
ZookeeperTransporter.class.getName(), parameterMap);
}
Map<String, ZookeeperClient> getZookeeperClientMap() {
return zookeeperClientMap;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/RouterMode.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/RouterMode.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
public enum RouterMode {
/**
* VERSION_BIGER
*/
VERSION_BIGER,
/**
* VERSION_BIGTHAN_OR_EQUAL
*/
VERSION_BIGTHAN_OR_EQUAL,
/**
* VERSION_SMALLER
*/
VERSION_SMALLER,
/**
* VERSION_EQUALS
*/
VERSION_EQUALS,
/**
* ALL_ALLOWED
*/
ALL_ALLOWED;
public static boolean contains(String routerMode) {
RouterMode[] values = RouterMode.values();
for (RouterMode value : values) {
if (String.valueOf(value).equals(routerMode)) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/CuratorZookeeperTransporter.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/CuratorZookeeperTransporter.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.zookeeper.ZookeeperClient;
public class CuratorZookeeperTransporter extends AbstractZookeeperTransporter {
@Override
public ZookeeperClient createZookeeperClient(URL url) {
return new CuratorZookeeperClient(url);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/CuratorZookeeperClient.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/CuratorZookeeperClient.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.utils.StringUtils;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import static com.webank.ai.fate.register.common.Constants.TIMEOUT_KEY;
import static com.webank.ai.fate.register.common.Constants.UTF_8;
public class CuratorZookeeperClient extends AbstractZookeeperClient<CuratorZookeeperClient.CuratorWatcherImpl, CuratorZookeeperClient.CuratorWatcherImpl> {
static final Charset CHARSET = Charset.forName(UTF_8);
private static final Logger logger = LoggerFactory.getLogger(CuratorZookeeperClient.class);
private static final String SCHEME = "digest";
private final CuratorFramework client;
private Map<String, TreeCache> treeCacheMap = new ConcurrentHashMap<>();
private boolean aclEnable;
private String aclUsername;
private String aclPassword;
private List<ACL> acls = new ArrayList<>();
public CuratorZookeeperClient(URL url) {
super(url);
try {
int timeout = url.getParameter(TIMEOUT_KEY, 5000);
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString(url.getBackupAddress())
.retryPolicy(new RetryNTimes(1, 1000))
.connectionTimeoutMs(timeout);
aclEnable = MetaInfo.PROPERTY_ACL_ENABLE;
if (aclEnable) {
aclUsername = MetaInfo.PROPERTY_ACL_USERNAME;
aclPassword = MetaInfo.PROPERTY_ACL_PASSWORD;
if (StringUtils.isBlank(aclUsername) || StringUtils.isBlank(aclPassword)) {
aclEnable = false;
MetaInfo.PROPERTY_ACL_ENABLE = false;
} else {
builder.authorization(SCHEME, (aclUsername + ":" + aclPassword).getBytes());
Id allow = new Id(SCHEME, DigestAuthenticationProvider.generateDigest(aclUsername + ":" + aclPassword));
// add more
acls.add(new ACL(ZooDefs.Perms.ALL, allow));
}
}
client = builder.build();
client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
@Override
public void stateChanged(CuratorFramework client, ConnectionState state) {
if (state == ConnectionState.LOST) {
CuratorZookeeperClient.this.stateChanged(StateListener.DISCONNECTED);
} else if (state == ConnectionState.CONNECTED) {
CuratorZookeeperClient.this.stateChanged(StateListener.CONNECTED);
} else if (state == ConnectionState.RECONNECTED) {
CuratorZookeeperClient.this.stateChanged(StateListener.RECONNECTED);
}
}
});
client.start();
if (aclEnable) {
client.setACL().withACL(acls).forPath("/");
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public void createPersistent(String path) {
try {
if (logger.isDebugEnabled()) {
logger.debug("createPersistent {}", path);
}
if (aclEnable) {
client.create().withACL(acls).forPath(path);
} else {
client.create().forPath(path);
}
} catch (NodeExistsException e) {
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public void createEphemeral(String path) {
try {
if (logger.isDebugEnabled()) {
logger.debug("createEphemeral {}", path);
}
if (aclEnable) {
client.create().withMode(CreateMode.EPHEMERAL).withACL(acls).forPath(path);
} else {
client.create().withMode(CreateMode.EPHEMERAL).forPath(path);
}
} catch (NodeExistsException e) {
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void createPersistent(String path, String data) {
byte[] dataBytes = data.getBytes(CHARSET);
try {
if (logger.isDebugEnabled()) {
logger.debug("createPersistent {} data {}", path, data);
}
if (aclEnable) {
client.create().withACL(acls).forPath(path, dataBytes);
} else {
client.create().forPath(path, dataBytes);
}
} catch (NodeExistsException e) {
try {
if (aclEnable) {
Stat stat = client.checkExists().forPath(path);
client.setData().withVersion(stat.getAversion()).forPath(path, dataBytes);
} else {
client.setData().forPath(path, dataBytes);
}
} catch (Exception e1) {
throw new IllegalStateException(e.getMessage(), e1);
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void createEphemeral(String path, String data) {
byte[] dataBytes = data.getBytes(CHARSET);
try {
if (logger.isDebugEnabled()) {
logger.debug("createEphemeral {} data {}", path, data);
}
if (aclEnable) {
client.create().withMode(CreateMode.EPHEMERAL).withACL(acls).forPath(path, dataBytes);
} else {
client.create().withMode(CreateMode.EPHEMERAL).forPath(path, dataBytes);
}
} catch (NodeExistsException e) {
try {
if (aclEnable) {
Stat stat = client.checkExists().forPath(path);
client.setData().withVersion(stat.getAversion()).forPath(path, dataBytes);
} else {
client.setData().forPath(path, dataBytes);
}
} catch (Exception e1) {
throw new IllegalStateException(e.getMessage(), e1);
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public void delete(String path) {
try {
if (aclEnable) {
// Stat stat = client.checkExists().forPath(path);
// client.delete().withVersion(stat.getAversion()).forPath(path);
this.clearAcl(path);
}
client.delete().forPath(path);
} catch (NoNodeException e) {
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public List<String> getChildren(String path) {
try {
return client.getChildren().forPath(path);
} catch (NoNodeException e) {
return null;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public boolean checkExists(String path) {
try {
if (client.checkExists().forPath(path) != null) {
return true;
}
} catch (Exception e) {
}
return false;
}
@Override
public boolean isConnected() {
return client.getZookeeperClient().isConnected();
}
@Override
public String doGetContent(String path) {
try {
byte[] dataBytes = client.getData().forPath(path);
return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, CHARSET);
} catch (NoNodeException e) {
// ignore NoNode Exception.
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
return null;
}
@Override
public void doClose() {
if (aclEnable) {
this.clearAcl("/");
}
client.close();
}
@Override
public CuratorZookeeperClient.CuratorWatcherImpl createTargetChildListener(String path, ChildListener listener) {
return new CuratorZookeeperClient.CuratorWatcherImpl(client, listener);
}
@Override
public List<String> addTargetChildListener(String path, CuratorWatcherImpl listener) {
try {
return client.getChildren().usingWatcher(listener).forPath(path);
} catch (NoNodeException e) {
return null;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected CuratorZookeeperClient.CuratorWatcherImpl createTargetDataListener(String path, DataListener listener) {
return new CuratorWatcherImpl(client, listener);
}
@Override
protected void addTargetDataListener(String path, CuratorZookeeperClient.CuratorWatcherImpl treeCacheListener) {
this.addTargetDataListener(path, treeCacheListener, null);
}
@Override
protected void addTargetDataListener(String path, CuratorZookeeperClient.CuratorWatcherImpl treeCacheListener, Executor executor) {
try {
TreeCache treeCache = TreeCache.newBuilder(client, path).setCacheData(false).build();
treeCacheMap.putIfAbsent(path, treeCache);
if (executor == null) {
treeCache.getListenable().addListener(treeCacheListener);
} else {
treeCache.getListenable().addListener(treeCacheListener, executor);
}
treeCache.start();
} catch (Exception e) {
throw new IllegalStateException("Add treeCache listener for path:" + path, e);
}
}
@Override
protected void removeTargetDataListener(String path, CuratorZookeeperClient.CuratorWatcherImpl treeCacheListener) {
TreeCache treeCache = treeCacheMap.get(path);
if (treeCache != null) {
treeCache.getListenable().removeListener(treeCacheListener);
}
treeCacheListener.dataListener = null;
}
@Override
public void removeTargetChildListener(String path, CuratorWatcherImpl listener) {
listener.unwatch();
}
@Override
public void clearAcl(String path) {
if (aclEnable) {
if (logger.isDebugEnabled()) {
logger.debug("clear acl {}", path);
}
try {
client.setACL().withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE).forPath(path);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* just for unit test
*
* @return
*/
CuratorFramework getClient() {
return client;
}
public static class CuratorWatcherImpl implements CuratorWatcher, TreeCacheListener {
private CuratorFramework client;
private volatile ChildListener childListener;
private volatile DataListener dataListener;
public CuratorWatcherImpl(CuratorFramework client, ChildListener listener) {
this.client = client;
this.childListener = listener;
}
public CuratorWatcherImpl(CuratorFramework client, DataListener dataListener) {
this.dataListener = dataListener;
}
protected CuratorWatcherImpl() {
}
public void unwatch() {
this.childListener = null;
}
@Override
public void process(WatchedEvent event) throws Exception {
if (childListener != null) {
String path = event.getPath() == null ? "" : event.getPath();
childListener.childChanged(path,
// if path is null, curator using watcher will throw NullPointerException.
// if client connect or disconnect to server, zookeeper will queue
// watched event(Watcher.Event.EventType.None, .., path = null).
StringUtils.isNotEmpty(path)
? client.getChildren().usingWatcher(this).forPath(path)
: Collections.<String>emptyList());
}
}
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
if (dataListener != null) {
if (logger.isDebugEnabled()) {
logger.debug("listen the zookeeper changed. The changed data:" + event.getData());
}
TreeCacheEvent.Type type = event.getType();
EventType eventType = null;
String content = null;
String path = null;
switch (type) {
case NODE_ADDED:
eventType = EventType.NodeCreated;
path = event.getData().getPath();
content = event.getData().getData() == null ? "" : new String(event.getData().getData(), CHARSET);
break;
case NODE_UPDATED:
eventType = EventType.NodeDataChanged;
path = event.getData().getPath();
content = event.getData().getData() == null ? "" : new String(event.getData().getData(), CHARSET);
break;
case NODE_REMOVED:
path = event.getData().getPath();
eventType = EventType.NodeDeleted;
break;
case INITIALIZED:
eventType = EventType.INITIALIZED;
break;
case CONNECTION_LOST:
eventType = EventType.CONNECTION_LOST;
break;
case CONNECTION_RECONNECTED:
eventType = EventType.CONNECTION_RECONNECTED;
break;
case CONNECTION_SUSPENDED:
eventType = EventType.CONNECTION_SUSPENDED;
break;
default:
break;
}
dataListener.dataChanged(path, content, eventType);
}
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/NamedThreadFactory.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/NamedThreadFactory.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import static com.webank.ai.fate.register.common.Constants.POOL_PREFIX;
import static com.webank.ai.fate.register.common.Constants.POOL_PREFIX_THREAD;
public class NamedThreadFactory implements ThreadFactory {
protected static final AtomicInteger POOL_SEQ = new AtomicInteger(1);
protected final AtomicInteger mThreadNum = new AtomicInteger(1);
protected final String mPrefix;
protected final boolean mDaemon;
protected final ThreadGroup mGroup;
public NamedThreadFactory() {
this(POOL_PREFIX + POOL_SEQ.getAndIncrement(), false);
}
public NamedThreadFactory(String prefix) {
this(prefix, false);
}
public NamedThreadFactory(String prefix, boolean daemon) {
mPrefix = prefix + POOL_PREFIX_THREAD;
mDaemon = daemon;
SecurityManager s = System.getSecurityManager();
mGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
}
@Override
public Thread newThread(Runnable runnable) {
String name = mPrefix + mThreadNum.getAndIncrement();
Thread ret = new Thread(mGroup, runnable, name, 0);
ret.setDaemon(mDaemon);
return ret;
}
public ThreadGroup getThreadGroup() {
return mGroup;
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/DataListener.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/DataListener.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
public interface DataListener {
void dataChanged(String path, Object value, EventType eventType);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/FailbackRegistry.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/FailbackRegistry.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import com.webank.ai.fate.register.interfaces.NotifyListener;
import com.webank.ai.fate.register.task.*;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.serving.core.timer.HashedWheelTimer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import static com.webank.ai.fate.register.common.Constants.*;
public abstract class FailbackRegistry extends AbstractRegistry {
private static final Logger logger = LoggerFactory.getLogger(FailbackRegistry.class);
private final ConcurrentMap<URL, FailedRegisteredTask> failedRegistered = new ConcurrentHashMap<URL, FailedRegisteredTask>();
private final ConcurrentMap<URL, FailedUnregisteredTask> failedUnregistered = new ConcurrentHashMap<URL, FailedUnregisteredTask>();
private final ConcurrentMap<Holder, FailedSubscribedTask> failedSubscribed = new ConcurrentHashMap<Holder, FailedSubscribedTask>();
private final ConcurrentMap<Holder, FailedUnsubscribedTask> failedUnsubscribed = new ConcurrentHashMap<Holder, FailedUnsubscribedTask>();
private final ConcurrentMap<Holder, FailedNotifiedTask> failedNotified = new ConcurrentHashMap<Holder, FailedNotifiedTask>();
private final ConcurrentMap<String, FailedSubProjectTask> failedSubProject = new ConcurrentHashMap<>();
private final ConcurrentMap<String, FailedRegisterComponentTask> failedRegisterComponent = new ConcurrentHashMap<>();
private final int retryPeriod;
private final HashedWheelTimer retryTimer;
protected URL componentUrl ;
public FailbackRegistry(URL url) {
super(url);
this.retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, 5000);
// since the retry task will not be very much. 128 ticks is enough.
retryTimer = new HashedWheelTimer(new NamedThreadFactory(REFIX_FATE_REGISTRY_RETRY_TIMER, true), retryPeriod, TimeUnit.MILLISECONDS, 128);
}
@Override
public void subProject(String project) {
if (logger.isDebugEnabled()) {
logger.debug("try to subProject: {}", project);
}
super.subProject(project);
failedSubProject.remove(project);
try {
doSubProject(project);
} catch (Exception e) {
addFailedSubscribedProjectTask(project);
}
}
public void removeFailedRegisteredTask(URL url) {
failedRegistered.remove(url);
}
public void removeFailedUnregisteredTask(URL url) {
failedUnregistered.remove(url);
}
public void removeFailedSubscribedProjectTask(String project) {
failedSubProject.remove(project);
}
public void removeFailedSubscribedTask(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
failedSubscribed.remove(h);
}
public void removeFailedUnsubscribedTask(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
failedUnsubscribed.remove(h);
}
public void removeFailedNotifiedTask(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
failedNotified.remove(h);
}
public void addFailedSubscribedProjectTask(String project) {
if (logger.isDebugEnabled()) {
logger.debug("try to add failed subscribed project {}", project);
}
FailedSubProjectTask oldOne = failedSubProject.get(project);
if (oldOne != null) {
return;
}
URL url = new URL();
URL newUrl = url.setProject(project);
FailedSubProjectTask newTask = new FailedSubProjectTask(newUrl, this);
oldOne = failedSubProject.putIfAbsent(project, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
public void addFailedRegisterComponentTask(URL url) {
if(url!=null) {
String instanceId = AbstractRegistry.INSTANCE_ID;
FailedRegisterComponentTask oldOne = this.failedRegisterComponent.get(instanceId);
if (oldOne != null) {
return;
}
FailedRegisterComponentTask newTask = new FailedRegisterComponentTask(url, this);
oldOne = failedRegisterComponent.putIfAbsent(instanceId, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
}
public void removeFailedRegisterComponentTask(URL url) {
String instanceId = AbstractRegistry.INSTANCE_ID;
FailedRegisterComponentTask oldOne = this.failedRegisterComponent.remove(instanceId);
if (oldOne != null) {
oldOne.cancel();
}
}
private void addFailedRegistered(URL url) {
if (logger.isDebugEnabled()) {
logger.debug("try to add failed registed url {}", url);
}
FailedRegisteredTask oldOne = failedRegistered.get(url);
if (oldOne != null) {
return;
}
FailedRegisteredTask newTask = new FailedRegisteredTask(url, this);
oldOne = failedRegistered.putIfAbsent(url, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
// private void addFailedSubProject(String url) {
// FailedSubProjectTask oldOne = failedSubProject.get(url);
// if (oldOne != null) {
// return;
// }
// FailedSubProjectTask newTask = new FailedSubProjectTask(url, this);
// oldOne = failedRegistered.putIfAbsent(url, newTask);
// if (oldOne == null) {
// // never has a retry task. then start a new task for retry.
// retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
// }
// }
private void removeFailedRegistered(URL url) {
FailedRegisteredTask f = failedRegistered.remove(url);
if (f != null) {
f.cancel();
}
}
private void addFailedUnregistered(URL url) {
FailedUnregisteredTask oldOne = failedUnregistered.get(url);
if (oldOne != null) {
return;
}
FailedUnregisteredTask newTask = new FailedUnregisteredTask(url, this);
oldOne = failedUnregistered.putIfAbsent(url, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
private void removeFailedUnregistered(URL url) {
FailedUnregisteredTask f = failedUnregistered.remove(url);
if (f != null) {
f.cancel();
}
}
private void addFailedSubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedSubscribedTask oldOne = failedSubscribed.get(h);
if (oldOne != null) {
return;
}
FailedSubscribedTask newTask = new FailedSubscribedTask(url, this, listener);
oldOne = failedSubscribed.putIfAbsent(h, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
private void removeFailedSubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedSubscribedTask f = failedSubscribed.remove(h);
if (f != null) {
f.cancel();
}
removeFailedUnsubscribed(url, listener);
removeFailedNotified(url, listener);
}
private void addFailedUnsubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedUnsubscribedTask oldOne = failedUnsubscribed.get(h);
if (oldOne != null) {
return;
}
FailedUnsubscribedTask newTask = new FailedUnsubscribedTask(url, this, listener);
oldOne = failedUnsubscribed.putIfAbsent(h, newTask);
if (oldOne == null) {
// never has a retry task. then start a new task for retry.
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
}
}
private void removeFailedUnsubscribed(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedUnsubscribedTask f = failedUnsubscribed.remove(h);
if (f != null) {
f.cancel();
}
}
private void addFailedNotified(URL url, NotifyListener listener, List<URL> urls) {
Holder h = new Holder(url, listener);
FailedNotifiedTask newTask = new FailedNotifiedTask(url, listener);
FailedNotifiedTask f = failedNotified.putIfAbsent(h, newTask);
if (f == null) {
// never has a retry task. then start a new task for retry.
newTask.addUrlToRetry(urls);
retryTimer.newTimeout(newTask, retryPeriod, TimeUnit.MILLISECONDS);
} else {
// just add urls which needs retry.
newTask.addUrlToRetry(urls);
}
}
private void removeFailedNotified(URL url, NotifyListener listener) {
Holder h = new Holder(url, listener);
FailedNotifiedTask f = failedNotified.remove(h);
if (f != null) {
f.cancel();
}
}
ConcurrentMap<URL, FailedRegisteredTask> getFailedRegistered() {
return failedRegistered;
}
ConcurrentMap<URL, FailedUnregisteredTask> getFailedUnregistered() {
return failedUnregistered;
}
ConcurrentMap<Holder, FailedSubscribedTask> getFailedSubscribed() {
return failedSubscribed;
}
ConcurrentMap<Holder, FailedUnsubscribedTask> getFailedUnsubscribed() {
return failedUnsubscribed;
}
ConcurrentMap<Holder, FailedNotifiedTask> getFailedNotified() {
return failedNotified;
}
@Override
public void register(URL url) {
super.register(url);
removeFailedRegistered(url);
removeFailedUnregistered(url);
try {
// Sending a registration request to the server side
doRegister(url);
} catch (Exception e) {
Throwable t = e;
addFailedRegistered(url);
}
}
@Override
public void unregister(URL url) {
super.unregister(url);
removeFailedRegistered(url);
removeFailedUnregistered(url);
try {
// Sending a cancellation request to the server side
doUnregister(url);
} catch (Exception e) {
Throwable t = e;
// If the startup detection is opened, the Exception is thrown directly.
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true)
&& !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol());
// boolean skipFailback = t instanceof SkipFailbackWrapperException;
// if (check || skipFailback) {
// if (skipFailback) {
// t = t.getCause();
// }
// throw new IllegalStateException("Failed to unregister " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t);
// } else {
// logger.error("Failed to unregister " + url + ", waiting for retry, cause: " + t.getMessage(), t);
// }
// Record a failed registration request to a failed list, retry regularly
addFailedUnregistered(url);
}
}
@Override
public void subscribe(URL url, NotifyListener listener) {
if (logger.isDebugEnabled()) {
logger.debug("prepare to subscribe " + url);
}
super.subscribe(url, listener);
removeFailedSubscribed(url, listener);
try {
// Sending a subscription request to the server side
doSubscribe(url, listener);
} catch (Exception e) {
Throwable t = e;
List<URL> urls = getCacheUrls(url);
if (CollectionUtils.isNotEmpty(urls)) {
notify(url, listener, urls);
logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(FILE_KEY, System.getProperty(USER_HOME) + "/fate-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t);
} else {
// If the startup detection is opened, the Exception is thrown directly.
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true);
// boolean skipFailback = t instanceof SkipFailbackWrapperException;
// if (check || skipFailback) {
// if (skipFailback) {
// t = t.getCause();
// }
// throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t);
// } else {
// logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t);
// }
}
// Record a failed registration request to a failed list, retry regularly
addFailedSubscribed(url, listener);
}
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
super.unsubscribe(url, listener);
removeFailedSubscribed(url, listener);
try {
// Sending a canceling subscription request to the server side
doUnsubscribe(url, listener);
} catch (Exception e) {
Throwable t = e;
// If the startup detection is opened, the Exception is thrown directly.
boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
&& url.getParameter(Constants.CHECK_KEY, true);
// boolean skipFailback = t instanceof SkipFailbackWrapperException;
// if (check || skipFailback) {
// if (skipFailback) {
// t = t.getCause();
// }
// throw new IllegalStateException("Failed to unsubscribe " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t);
// } else {
// logger.error("Failed to unsubscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t);
// }
// Record a failed registration request to a failed list, retry regularly
addFailedUnsubscribed(url, listener);
}
}
@Override
protected void notify(URL url, NotifyListener listener, List<URL> urls) {
if (url == null) {
throw new IllegalArgumentException("notify url == null");
}
if (listener == null) {
throw new IllegalArgumentException("notify listener == null");
}
try {
doNotify(url, listener, urls);
} catch (Exception t) {
// Record a failed registration request to a failed list, retry regularly
addFailedNotified(url, listener, urls);
logger.error("Failed to notify for subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t);
}
}
protected void doNotify(URL url, NotifyListener listener, List<URL> urls) {
super.notify(url, listener, urls);
}
@Override
protected void recover() throws Exception {
// register
if (logger.isDebugEnabled()) {
logger.debug("prepare to recover registed......{}", getRegistered());
}
Set<URL> recoverRegistered = new HashSet<URL>(getRegistered());
if (!recoverRegistered.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover register url " + recoverRegistered);
}
for (URL url : recoverRegistered) {
addFailedRegistered(url);
}
}
if (logger.isDebugEnabled()) {
logger.debug("prepare to recover registed.project.....{}", projectSets);
}
Set<String> subjectSets = new HashSet(this.projectSets);
if (!subjectSets.isEmpty()) {
subjectSets.forEach(project -> {
try {
this.addFailedSubscribedProjectTask(project);
} catch (Exception e) {
logger.error("recover addFailedSubscribedProjectTask error", e);
}
});
}
if (logger.isDebugEnabled()) {
logger.debug("prepare to recover subscribed......{}", getSubscribed());
}
// subscribe
Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<URL, Set<NotifyListener>>(getSubscribed());
if (!recoverSubscribed.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover subscribe url " + recoverSubscribed.keySet());
}
for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
addFailedSubscribed(url, listener);
}
}
}
if(this.componentUrl!=null) {
this.addFailedRegisterComponentTask(this.componentUrl);
}else{
this.addFailedRegisterComponentTask(null);
}
if (logger.isDebugEnabled()) {
logger.debug("recover over !!!!!!");
}
}
@Override
public void destroy() {
super.destroy();
retryTimer.stop();
}
public abstract void doRegister(URL url);
public abstract void doUnregister(URL url);
public abstract void doSubscribe(URL url, NotifyListener listener);
public abstract void doUnsubscribe(URL url, NotifyListener listener);
static class Holder {
private final URL url;
private final NotifyListener notifyListener;
Holder(URL url, NotifyListener notifyListener) {
if (url == null || notifyListener == null) {
throw new IllegalArgumentException();
}
this.url = url;
this.notifyListener = notifyListener;
}
@Override
public int hashCode() {
return url.hashCode() + notifyListener.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Holder) {
Holder h = (Holder) obj;
return this.url.equals(h.url) && this.notifyListener.equals(h.notifyListener);
} else {
return false;
}
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/ServiceWrapper.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/ServiceWrapper.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
public class ServiceWrapper {
private Integer weight;
// private Long version;
private String routerMode;
public ServiceWrapper() {
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
public String getRouterMode() {
return routerMode;
}
public void setRouterMode(String routerMode) {
this.routerMode = routerMode;
}
public void update(ServiceWrapper wrapper) {
if (wrapper.getRouterMode() != null) {
this.setRouterMode(wrapper.getRouterMode());
}
if (wrapper.getWeight() != null) {
this.setWeight(wrapper.getWeight());
}
// if (wrapper.getVersion() != null) {
// this.setVersion(wrapper.getVersion());
// }
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/EventType.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/EventType.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import org.apache.zookeeper.Watcher;
/**
* 2019-02-26
*/
public enum EventType {
None(-1),
NodeCreated(1),
NodeDeleted(2),
NodeDataChanged(3),
NodeChildrenChanged(4),
CONNECTION_SUSPENDED(11),
CONNECTION_RECONNECTED(12),
CONNECTION_LOST(12),
INITIALIZED(10);
/**
* Integer representation of value
*/
private final int intValue;
// for sending over wire
EventType(int intValue) {
this.intValue = intValue;
}
public static Watcher.Event.EventType fromInt(int intValue) {
switch (intValue) {
case -1:
return Watcher.Event.EventType.None;
case 1:
return Watcher.Event.EventType.NodeCreated;
case 2:
return Watcher.Event.EventType.NodeDeleted;
case 3:
return Watcher.Event.EventType.NodeDataChanged;
case 4:
return Watcher.Event.EventType.NodeChildrenChanged;
default:
throw new RuntimeException("Invalid integer value for conversion to EventType");
}
}
public int getIntValue() {
return intValue;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/ChildListener.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/ChildListener.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import java.util.List;
public interface ChildListener {
void childChanged(String path, List<String> children);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/StateListener.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/StateListener.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
public interface StateListener {
int DISCONNECTED = 0;
int CONNECTED = 1;
int RECONNECTED = 2;
void stateChanged(int connected);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/Role.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/Role.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
public enum Role {
COMMON,
GUEST,
HOST;
public static boolean contains(String routerMode) {
Role[] values = Role.values();
for (Role value : values) {
if (String.valueOf(value).equals(routerMode)) {
return true;
}
}
return false;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/ServiceVersionUtil.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/ServiceVersionUtil.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
public class ServiceVersionUtil {
static final String BIGER = "BIGER";
static final String BIGER_OR_EQUAL = "BIGTHAN_OR_EQUAL";
static final String SMALLER = "SMALLER";
static final String EQUALS = "EQUALS";
public static boolean march(String versionModel, String serverVersion, String clientVersion) {
Integer serverVersionInteger = new Integer(serverVersion);
Integer clientVersionInteger = new Integer(clientVersion);
switch (versionModel) {
case BIGER_OR_EQUAL:
if (clientVersionInteger >= serverVersionInteger) {
return true;
}
case BIGER:
if (clientVersionInteger > serverVersionInteger) {
return true;
}
case SMALLER:
if (clientVersionInteger < serverVersionInteger) {
return true;
}
default:
return false;
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/AbstractZookeeperClient.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/AbstractZookeeperClient.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.zookeeper.ZookeeperClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;
public abstract class AbstractZookeeperClient<TargetDataListener, TargetChildListener> implements ZookeeperClient {
private static final Logger logger = LoggerFactory.getLogger(AbstractZookeeperClient.class);
private final URL url;
private final Set<StateListener> stateListeners = new CopyOnWriteArraySet<StateListener>();
private final ConcurrentMap<String, ConcurrentMap<ChildListener, TargetChildListener>> childListeners = new ConcurrentHashMap<String, ConcurrentMap<ChildListener, TargetChildListener>>();
private final ConcurrentMap<String, ConcurrentMap<DataListener, TargetDataListener>> listeners = new ConcurrentHashMap<String, ConcurrentMap<DataListener, TargetDataListener>>();
private volatile boolean closed = false;
public AbstractZookeeperClient(URL url) {
this.url = url;
}
@Override
public URL getUrl() {
return url;
}
@Override
public void create(String path, boolean ephemeral) {
if (!ephemeral) {
if (checkExists(path)) {
return;
}
}
int i = path.lastIndexOf('/');
if (i > 0) {
create(path.substring(0, i), false);
}
if (ephemeral) {
createEphemeral(path);
} else {
createPersistent(path);
}
}
@Override
public void addStateListener(StateListener listener) {
stateListeners.add(listener);
}
@Override
public void removeStateListener(StateListener listener) {
stateListeners.remove(listener);
}
public Set<StateListener> getSessionListeners() {
return stateListeners;
}
@Override
public List<String> addChildListener(String path, final ChildListener listener) {
ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
if (listeners == null) {
childListeners.putIfAbsent(path, new ConcurrentHashMap<ChildListener, TargetChildListener>());
listeners = childListeners.get(path);
}
TargetChildListener targetListener = listeners.get(listener);
if (targetListener == null) {
listeners.putIfAbsent(listener, createTargetChildListener(path, listener));
targetListener = listeners.get(listener);
}
return addTargetChildListener(path, targetListener);
}
@Override
public void addDataListener(String path, DataListener listener) {
this.addDataListener(path, listener, null);
}
@Override
public void addDataListener(String path, DataListener listener, Executor executor) {
ConcurrentMap<DataListener, TargetDataListener> dataListenerMap = listeners.get(path);
if (dataListenerMap == null) {
listeners.putIfAbsent(path, new ConcurrentHashMap<DataListener, TargetDataListener>());
dataListenerMap = listeners.get(path);
}
TargetDataListener targetListener = dataListenerMap.get(listener);
if (targetListener == null) {
dataListenerMap.putIfAbsent(listener, createTargetDataListener(path, listener));
targetListener = dataListenerMap.get(listener);
}
addTargetDataListener(path, targetListener, executor);
}
@Override
public void removeDataListener(String path, DataListener listener) {
ConcurrentMap<DataListener, TargetDataListener> dataListenerMap = listeners.get(path);
if (dataListenerMap != null) {
TargetDataListener targetListener = dataListenerMap.remove(listener);
if (targetListener != null) {
removeTargetDataListener(path, targetListener);
}
}
}
@Override
public void removeChildListener(String path, ChildListener listener) {
ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
if (listeners != null) {
TargetChildListener targetListener = listeners.remove(listener);
if (targetListener != null) {
removeTargetChildListener(path, targetListener);
}
}
}
protected void stateChanged(int state) {
for (StateListener sessionListener : getSessionListeners()) {
sessionListener.stateChanged(state);
}
}
@Override
public void close() {
if (closed) {
return;
}
closed = true;
try {
doClose();
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
}
}
@Override
public void create(String path, String content, boolean ephemeral) {
if (checkExists(path)) {
delete(path);
}
int i = path.lastIndexOf('/');
if (i > 0) {
create(path.substring(0, i), false);
}
if (ephemeral) {
createEphemeral(path, content);
} else {
createPersistent(path, content);
}
}
@Override
public String getContent(String path) {
if (!checkExists(path)) {
return null;
}
return doGetContent(path);
}
protected abstract void doClose();
protected abstract void createPersistent(String path);
protected abstract void createEphemeral(String path);
protected abstract void createPersistent(String path, String data);
protected abstract void createEphemeral(String path, String data);
protected abstract boolean checkExists(String path);
protected abstract TargetChildListener createTargetChildListener(String path, ChildListener listener);
protected abstract List<String> addTargetChildListener(String path, TargetChildListener listener);
protected abstract TargetDataListener createTargetDataListener(String path, DataListener listener);
protected abstract void addTargetDataListener(String path, TargetDataListener listener);
protected abstract void addTargetDataListener(String path, TargetDataListener listener, Executor executor);
protected abstract void removeTargetDataListener(String path, TargetDataListener listener);
protected abstract void removeTargetChildListener(String path, TargetChildListener listener);
protected abstract String doGetContent(String path);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/TimerTask.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/TimerTask.java | ///*
// * Copyright 2019 The FATE Authors. All Rights Reserved.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//
//package com.webank.ai.fate.register.common;
//
//import com.webank.ai.fate.register.interfaces.Timeout;
//
//
//public interface TimerTask {
//
// void run(Timeout timeout) throws Exception;
//} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/AbstractRegistryFactory.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/AbstractRegistryFactory.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import com.webank.ai.fate.register.interfaces.Registry;
import com.webank.ai.fate.register.interfaces.RegistryService;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.utils.URLBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import static com.webank.ai.fate.register.common.Constants.INTERFACE_KEY;
public abstract class AbstractRegistryFactory implements RegistryFactory {
// Log output
private static final Logger logger = LoggerFactory.getLogger(AbstractRegistryFactory.class);
// The lock for the acquisition process of the registry
private static final ReentrantLock LOCK = new ReentrantLock();
// Registry Collection Map<RegistryAddress, Registry>
private static final Map<String, Registry> REGISTRIES = new HashMap<>();
public static Collection<Registry> getRegistries() {
return Collections.unmodifiableCollection(REGISTRIES.values());
}
/**
* Close all created registries
*/
public static void destroyAll() {
if (logger.isInfoEnabled()) {
logger.info("Close all registries " + getRegistries());
}
// Lock up the registry shutdown process
LOCK.lock();
try {
for (Registry registry : getRegistries()) {
try {
registry.destroy();
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
}
REGISTRIES.clear();
} finally {
// Release the lock
LOCK.unlock();
}
}
@Override
public Registry getRegistry(URL url) {
url = URLBuilder.from(url)
.setPath(RegistryService.class.getName())
.addParameter(INTERFACE_KEY, RegistryService.class.getName())
.build();
String key = url.toServiceStringWithoutResolving();
// Lock the registry access process to ensure a single instance of the registry
LOCK.lock();
try {
Registry registry = REGISTRIES.get(key);
if (registry != null) {
return registry;
}
//create registry by spi/ioc
registry = createRegistry(url);
if (registry == null) {
throw new IllegalStateException("Can not create registry " + url);
}
REGISTRIES.put(key, registry);
return registry;
} finally {
// Release the lock
LOCK.unlock();
}
}
protected abstract Registry createRegistry(URL url);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/HashedWheelTimer.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/HashedWheelTimer.java | ///*
// * Copyright 2019 The FATE Authors. All Rights Reserved.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//
//package com.webank.ai.fate.register.common;
//
//
//import com.webank.ai.fate.register.interfaces.Timeout;
//import com.webank.ai.fate.register.interfaces.Timer;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.util.*;
//import java.util.concurrent.*;
//import java.util.concurrent.atomic.AtomicBoolean;
//import java.util.concurrent.atomic.AtomicInteger;
//import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
//import java.util.concurrent.atomic.AtomicLong;
//
//import static com.webank.ai.fate.register.common.Constants.OS_NAME;
//import static com.webank.ai.fate.register.common.Constants.OS_NAME_WIN;
//
//
//public class HashedWheelTimer implements Timer {
//
// public static final String NAME = "hased";
// private static final Logger logger = LoggerFactory.getLogger(HashedWheelTimer.class);
//
// private static final AtomicInteger INSTANCE_COUNTER = new AtomicInteger();
// private static final AtomicBoolean WARNED_TOO_MANY_INSTANCES = new AtomicBoolean();
// private static final int INSTANCE_COUNT_LIMIT = 64;
// private static final AtomicIntegerFieldUpdater<HashedWheelTimer> WORKER_STATE_UPDATER =
// AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimer.class, "workerState");
// private static final int WORKER_STATE_INIT = 0;
// private static final int WORKER_STATE_STARTED = 1;
// private static final int WORKER_STATE_SHUTDOWN = 2;
// private final Worker worker = new Worker();
// private final Thread workerThread;
// private final long tickDuration;
// private final HashedWheelBucket[] wheel;
// private final int mask;
// private final CountDownLatch startTimeInitialized = new CountDownLatch(1);
// private final Queue<HashedWheelTimeout> timeouts = new LinkedBlockingQueue<>();
// private final Queue<HashedWheelTimeout> cancelledTimeouts = new LinkedBlockingQueue<>();
// private final AtomicLong pendingTimeouts = new AtomicLong(0);
// private final long maxPendingTimeouts;
// /**
// * 0 - init, 1 - started, 2 - shut down
// */
// @SuppressWarnings({"unused", "FieldMayBeFinal"})
// private volatile int workerState;
// private volatile long startTime;
//
//
// public HashedWheelTimer() {
// this(Executors.defaultThreadFactory());
// }
//
//
// public HashedWheelTimer(long tickDuration, TimeUnit unit) {
// this(Executors.defaultThreadFactory(), tickDuration, unit);
// }
//
//
// public HashedWheelTimer(long tickDuration, TimeUnit unit, int ticksPerWheel) {
// this(Executors.defaultThreadFactory(), tickDuration, unit, ticksPerWheel);
// }
//
//
// public HashedWheelTimer(ThreadFactory threadFactory) {
// this(threadFactory, 100, TimeUnit.MILLISECONDS);
// }
//
//
// public HashedWheelTimer(
// ThreadFactory threadFactory, long tickDuration, TimeUnit unit) {
// this(threadFactory, tickDuration, unit, 512);
// }
//
//
// public HashedWheelTimer(
// ThreadFactory threadFactory,
// long tickDuration, TimeUnit unit, int ticksPerWheel) {
// this(threadFactory, tickDuration, unit, ticksPerWheel, -1);
// }
//
//
// public HashedWheelTimer(
// ThreadFactory threadFactory,
// long tickDuration, TimeUnit unit, int ticksPerWheel,
// long maxPendingTimeouts) {
//
// if (threadFactory == null) {
// throw new NullPointerException("threadFactory");
// }
// if (unit == null) {
// throw new NullPointerException("unit");
// }
// if (tickDuration <= 0) {
// throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration);
// }
// if (ticksPerWheel <= 0) {
// throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel);
// }
//
// // Normalize ticksPerWheel to power of two and initialize the wheel.
// wheel = createWheel(ticksPerWheel);
// mask = wheel.length - 1;
//
// // Convert tickDuration to nanos.
// this.tickDuration = unit.toNanos(tickDuration);
//
// // Prevent overflow.
// if (this.tickDuration >= Long.MAX_VALUE / wheel.length) {
// throw new IllegalArgumentException(String.format(
// "tickDuration: %d (expected: 0 < tickDuration in nanos < %d",
// tickDuration, Long.MAX_VALUE / wheel.length));
// }
// workerThread = threadFactory.newThread(worker);
//
// this.maxPendingTimeouts = maxPendingTimeouts;
//
// if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT &&
// WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) {
// reportTooManyInstances();
// }
// }
//
// private static HashedWheelBucket[] createWheel(int ticksPerWheel) {
// if (ticksPerWheel <= 0) {
// throw new IllegalArgumentException(
// "ticksPerWheel must be greater than 0: " + ticksPerWheel);
// }
// if (ticksPerWheel > 1073741824) {
// throw new IllegalArgumentException(
// "ticksPerWheel may not be greater than 2^30: " + ticksPerWheel);
// }
//
// ticksPerWheel = normalizeTicksPerWheel(ticksPerWheel);
// HashedWheelBucket[] wheel = new HashedWheelBucket[ticksPerWheel];
// for (int i = 0; i < wheel.length; i++) {
// wheel[i] = new HashedWheelBucket();
// }
// return wheel;
// }
//
// private static int normalizeTicksPerWheel(int ticksPerWheel) {
// int normalizedTicksPerWheel = ticksPerWheel - 1;
// normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 1;
// normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 2;
// normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 4;
// normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 8;
// normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 16;
// return normalizedTicksPerWheel + 1;
// }
//
// private static void reportTooManyInstances() {
// String resourceType = HashedWheelTimer.class.getName();
// logger.error("You are creating too many " + resourceType + " instances. " +
// resourceType + " is a shared resource that must be reused across the JVM," +
// "so that only a few instances are created.");
// }
//
// @Override
// protected void finalize() throws Throwable {
// try {
// super.finalize();
// } finally {
// // This object is going to be GCed and it is assumed the ship has sailed to do a proper shutdown. If
// // we have not yet shutdown then we want to make sure we decrement the active instance count.
// if (WORKER_STATE_UPDATER.getAndSet(this, WORKER_STATE_SHUTDOWN) != WORKER_STATE_SHUTDOWN) {
// INSTANCE_COUNTER.decrementAndGet();
// }
// }
// }
//
// public void start() {
// switch (WORKER_STATE_UPDATER.get(this)) {
// case WORKER_STATE_INIT:
// if (WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_INIT, WORKER_STATE_STARTED)) {
// workerThread.start();
// }
// break;
// case WORKER_STATE_STARTED:
// break;
// case WORKER_STATE_SHUTDOWN:
// throw new IllegalStateException("cannot be started once stopped");
// default:
// throw new Error("Invalid WorkerState");
// }
//
// // Wait until the startTime is initialized by the worker.
// while (startTime == 0) {
// try {
// startTimeInitialized.await();
// } catch (InterruptedException ignore) {
// // Ignore - it will be ready very soon.
// }
// }
// }
//
// @Override
// public Set<Timeout> stop() {
// if (Thread.currentThread() == workerThread) {
// throw new IllegalStateException(
// HashedWheelTimer.class.getSimpleName() +
// ".stop() cannot be called from " +
// com.webank.ai.fate.register.common.TimerTask.class.getSimpleName());
// }
//
// if (!WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_STARTED, WORKER_STATE_SHUTDOWN)) {
// // workerState can be 0 or 2 at this moment - let it always be 2.
// if (WORKER_STATE_UPDATER.getAndSet(this, WORKER_STATE_SHUTDOWN) != WORKER_STATE_SHUTDOWN) {
// INSTANCE_COUNTER.decrementAndGet();
// }
//
// return Collections.emptySet();
// }
//
// try {
// boolean interrupted = false;
// while (workerThread.isAlive()) {
// workerThread.interrupt();
// try {
// workerThread.join(100);
// } catch (InterruptedException ignored) {
// interrupted = true;
// }
// }
//
// if (interrupted) {
// Thread.currentThread().interrupt();
// }
// } finally {
// INSTANCE_COUNTER.decrementAndGet();
// }
// return worker.unprocessedTimeouts();
// }
//
// @Override
// public boolean isStop() {
// return WORKER_STATE_SHUTDOWN == WORKER_STATE_UPDATER.get(this);
// }
//
// @Override
// public Timeout newTimeout(com.webank.ai.fate.register.common.TimerTask task, long delay, TimeUnit unit) {
// if (task == null) {
// throw new NullPointerException("task");
// }
// if (unit == null) {
// throw new NullPointerException("unit");
// }
//
// long pendingTimeoutsCount = pendingTimeouts.incrementAndGet();
//
// if (maxPendingTimeouts > 0 && pendingTimeoutsCount > maxPendingTimeouts) {
// pendingTimeouts.decrementAndGet();
// throw new RejectedExecutionException("Number of pending timeouts ("
// + pendingTimeoutsCount + ") is greater than or equal to maximum allowed pending "
// + "timeouts (" + maxPendingTimeouts + ")");
// }
//
// start();
//
// // Add the timeout to the timeout queue which will be processed on the next tick.
// // During processing all the queued HashedWheelTimeouts will be added to the correct HashedWheelBucket.
// long deadline = System.nanoTime() + unit.toNanos(delay) - startTime;
//
// // Guard against overflow.
// if (delay > 0 && deadline < 0) {
// deadline = Long.MAX_VALUE;
// }
// HashedWheelTimeout timeout = new HashedWheelTimeout(this, task, deadline);
// timeouts.add(timeout);
// return timeout;
// }
//
// public long pendingTimeouts() {
// return pendingTimeouts.get();
// }
//
// private boolean isWindows() {
// return System.getProperty(OS_NAME, "").toLowerCase(Locale.US).contains(OS_NAME_WIN);
// }
//
// private static final class HashedWheelTimeout implements Timeout {
//
// private static final int ST_INIT = 0;
// private static final int ST_CANCELLED = 1;
// private static final int ST_EXPIRED = 2;
// private static final AtomicIntegerFieldUpdater<HashedWheelTimeout> STATE_UPDATER =
// AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimeout.class, "state");
//
// private final HashedWheelTimer timer;
// private final com.webank.ai.fate.register.common.TimerTask task;
// private final long deadline;
// /**
// * RemainingRounds will be calculated and set by Worker.transferTimeoutsToBuckets() before the
// * HashedWheelTimeout will be added to the correct HashedWheelBucket.
// */
// long remainingRounds;
// /**
// * This will be used to chain timeouts in HashedWheelTimerBucket via a double-linked-list.
// * As only the workerThread will act on it there is no need for synchronization / volatile.
// */
// HashedWheelTimeout next;
// HashedWheelTimeout prev;
// /**
// * The bucket to which the timeout was added
// */
// HashedWheelBucket bucket;
// @SuppressWarnings({"unused", "FieldMayBeFinal", "RedundantFieldInitialization"})
// private volatile int state = ST_INIT;
//
// HashedWheelTimeout(HashedWheelTimer timer, com.webank.ai.fate.register.common.TimerTask task, long deadline) {
// this.timer = timer;
// this.task = task;
// this.deadline = deadline;
// }
//
// @Override
// public com.webank.ai.fate.register.interfaces.Timer timer() {
// return timer;
// }
//
// @Override
// public com.webank.ai.fate.register.common.TimerTask task() {
// return task;
// }
//
// @Override
// public boolean cancel() {
// // only update the state it will be removed from HashedWheelBucket on next tick.
// if (!compareAndSetState(ST_INIT, ST_CANCELLED)) {
// return false;
// }
// // If a task should be canceled we put this to another queue which will be processed on each tick.
// // So this means that we will have a GC latency of max. 1 tick duration which is good enough. This way
// // we can make again use of our MpscLinkedQueue and so minimize the locking / overhead as much as possible.
// timer.cancelledTimeouts.add(this);
// return true;
// }
//
// void remove() {
// HashedWheelBucket bucket = this.bucket;
// if (bucket != null) {
// bucket.remove(this);
// } else {
// timer.pendingTimeouts.decrementAndGet();
// }
// }
//
// public boolean compareAndSetState(int expected, int state) {
// return STATE_UPDATER.compareAndSet(this, expected, state);
// }
//
// public int state() {
// return state;
// }
//
// @Override
// public boolean isCancelled() {
// return state() == ST_CANCELLED;
// }
//
// @Override
// public boolean isExpired() {
// return state() == ST_EXPIRED;
// }
//
// public void expire() {
// if (!compareAndSetState(ST_INIT, ST_EXPIRED)) {
// return;
// }
//
// try {
// task.run(this);
// } catch (Throwable t) {
// if (logger.isWarnEnabled()) {
// logger.warn("An exception was thrown by " + com.webank.ai.fate.register.common.TimerTask.class.getSimpleName() + '.', t);
// }
// }
// }
//
// @Override
// public String toString() {
// final long currentTime = System.nanoTime();
// long remaining = deadline - currentTime + timer.startTime;
// // String simpleClassName = ClassUtils.simpleClassName(this.getClass());
//
// StringBuilder buf = new StringBuilder(192)
//
// .append('(')
// .append("deadline: ");
// if (remaining > 0) {
// buf.append(remaining)
// .append(" ns later");
// } else if (remaining < 0) {
// buf.append(-remaining)
// .append(" ns ago");
// } else {
// buf.append("now");
// }
//
// if (isCancelled()) {
// buf.append(", cancelled");
// }
//
// return buf.append(", task: ")
// .append(task())
// .append(')')
// .toString();
// }
// }
//
// /**
// * Bucket that stores HashedWheelTimeouts. These are stored in a linked-list like datastructure to allow easy
// * removal of HashedWheelTimeouts in the middle. Also the HashedWheelTimeout act as nodes themself and so no
// * extra object creation is needed.
// */
// private static final class HashedWheelBucket {
//
// /**
// * Used for the linked-list datastructure
// */
// private HashedWheelTimeout head;
// private HashedWheelTimeout tail;
//
// /**
// * Add {@link HashedWheelTimeout} to this bucket.
// */
// void addTimeout(HashedWheelTimeout timeout) {
// assert timeout.bucket == null;
// timeout.bucket = this;
// if (head == null) {
// head = tail = timeout;
// } else {
// tail.next = timeout;
// timeout.prev = tail;
// tail = timeout;
// }
// }
//
// /**
// * Expire all {@link HashedWheelTimeout}s for the given {@code deadline}.
// */
// void expireTimeouts(long deadline) {
// HashedWheelTimeout timeout = head;
//
// // process all timeouts
// while (timeout != null) {
// HashedWheelTimeout next = timeout.next;
// if (timeout.remainingRounds <= 0) {
// next = remove(timeout);
// if (timeout.deadline <= deadline) {
// timeout.expire();
// } else {
// // The timeout was placed into a wrong slot. This should never happen.
// throw new IllegalStateException(String.format(
// "timeout.deadline (%d) > deadline (%d)", timeout.deadline, deadline));
// }
// } else if (timeout.isCancelled()) {
// next = remove(timeout);
// } else {
// timeout.remainingRounds--;
// }
// timeout = next;
// }
// }
//
// public HashedWheelTimeout remove(HashedWheelTimeout timeout) {
// HashedWheelTimeout next = timeout.next;
// // remove timeout that was either processed or cancelled by updating the linked-list
// if (timeout.prev != null) {
// timeout.prev.next = next;
// }
// if (timeout.next != null) {
// timeout.next.prev = timeout.prev;
// }
//
// if (timeout == head) {
// // if timeout is also the tail we need to adjust the entry too
// if (timeout == tail) {
// tail = null;
// head = null;
// } else {
// head = next;
// }
// } else if (timeout == tail) {
// // if the timeout is the tail modify the tail to be the prev node.
// tail = timeout.prev;
// }
// // null out prev, next and bucket to allow for GC.
// timeout.prev = null;
// timeout.next = null;
// timeout.bucket = null;
// timeout.timer.pendingTimeouts.decrementAndGet();
// return next;
// }
//
// /**
// * Clear this bucket and return all not expired / cancelled {@link Timeout}s.
// */
// void clearTimeouts(Set<Timeout> set) {
// for (; ; ) {
// HashedWheelTimeout timeout = pollTimeout();
// if (timeout == null) {
// return;
// }
// if (timeout.isExpired() || timeout.isCancelled()) {
// continue;
// }
// set.add(timeout);
// }
// }
//
// private HashedWheelTimeout pollTimeout() {
// HashedWheelTimeout head = this.head;
// if (head == null) {
// return null;
// }
// HashedWheelTimeout next = head.next;
// if (next == null) {
// tail = this.head = null;
// } else {
// this.head = next;
// next.prev = null;
// }
//
// // null out prev and next to allow for GC.
// head.next = null;
// head.prev = null;
// head.bucket = null;
// return head;
// }
// }
//
// private final class Worker implements Runnable {
// private final Set<Timeout> unprocessedTimeouts = new HashSet<Timeout>();
//
// private long tick;
//
// @Override
// public void run() {
// // Initialize the startTime.
// startTime = System.nanoTime();
// if (startTime == 0) {
// // We use 0 as an indicator for the uninitialized value here, so make sure it's not 0 when initialized.
// startTime = 1;
// }
//
// // Notify the other threads waiting for the initialization at start().
// startTimeInitialized.countDown();
//
// do {
// final long deadline = waitForNextTick();
// if (deadline > 0) {
// int idx = (int) (tick & mask);
// processCancelledTasks();
// HashedWheelBucket bucket =
// wheel[idx];
// transferTimeoutsToBuckets();
// bucket.expireTimeouts(deadline);
// tick++;
// }
// } while (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_STARTED);
//
// // Fill the unprocessedTimeouts so we can return them from stop() method.
// for (HashedWheelBucket bucket : wheel) {
// bucket.clearTimeouts(unprocessedTimeouts);
// }
// for (; ; ) {
// HashedWheelTimeout timeout = timeouts.poll();
// if (timeout == null) {
// break;
// }
// if (!timeout.isCancelled()) {
// unprocessedTimeouts.add(timeout);
// }
// }
// processCancelledTasks();
// }
//
// private void transferTimeoutsToBuckets() {
// // transfer only max. 100000 timeouts per tick to prevent a thread to stale the workerThread when it just
// // adds new timeouts in a loop.
// for (int i = 0; i < 100000; i++) {
// HashedWheelTimeout timeout = timeouts.poll();
// if (timeout == null) {
// // all processed
// break;
// }
// if (timeout.state() == HashedWheelTimeout.ST_CANCELLED) {
// // Was cancelled in the meantime.
// continue;
// }
//
// long calculated = timeout.deadline / tickDuration;
// timeout.remainingRounds = (calculated - tick) / wheel.length;
//
// // Ensure we don't schedule for past.
// final long ticks = Math.max(calculated, tick);
// int stopIndex = (int) (ticks & mask);
//
// HashedWheelBucket bucket = wheel[stopIndex];
// bucket.addTimeout(timeout);
// }
// }
//
// private void processCancelledTasks() {
// for (; ; ) {
// HashedWheelTimeout timeout = cancelledTimeouts.poll();
// if (timeout == null) {
// // all processed
// break;
// }
// try {
// timeout.remove();
// } catch (Throwable t) {
// if (logger.isWarnEnabled()) {
// logger.warn("An exception was thrown while process a cancellation task", t);
// }
// }
// }
// }
//
// /**
// * calculate goal nanoTime from startTime and current tick number,
// * then wait until that goal has been reached.
// *
// * @return Long.MIN_VALUE if received a shutdown request,
// * current time otherwise (with Long.MIN_VALUE changed by +1)
// */
// private long waitForNextTick() {
// long deadline = tickDuration * (tick + 1);
//
// for (; ; ) {
// final long currentTime = System.nanoTime() - startTime;
// long sleepTimeMs = (deadline - currentTime + 999999) / 1000000;
//
// if (sleepTimeMs <= 0) {
// if (currentTime == Long.MIN_VALUE) {
// return -Long.MAX_VALUE;
// } else {
// return currentTime;
// }
// }
// if (isWindows()) {
// sleepTimeMs = sleepTimeMs / 10 * 10;
// }
//
// try {
// Thread.sleep(sleepTimeMs);
// } catch (InterruptedException ignored) {
// if (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_SHUTDOWN) {
// return Long.MIN_VALUE;
// }
// }
// }
// }
//
// Set<Timeout> unprocessedTimeouts() {
// return Collections.unmodifiableSet(unprocessedTimeouts);
// }
// }
//}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/Constants.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/Constants.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import java.util.regex.Pattern;
public interface Constants {
public static String ZOOKEEPER_REGISTER = "zookeeper_register";
public static String PARTY_ID = "party_id";
public static String ROUTER_MODE = "router_mode";
public static String VERSION = "version";
public static String RETRY_PERID_KEY = "retry_period_key";
public static String REGISTRY_FILESAVE_SYNC_KEY = "registry_filesave_sync_key";
public static String FILE_KEY = "file";
public static String APPLICATION_KEY = "application";
public static String BACKUP_KEY = "backup";
public static String PROTOCOL_KEY = "protocol";
public static String PROJECT_KEY = "project";
public static String ENVIRONMENT_KEY = "environment";
public static String SERVER_PORT = "server_port";
public static String INSTANCE_ID = "instance_id";
public static String HOST_KEY = "host";
public static String PORT_KEY = "port";
public static String PATH_KEY = "path";
public static String PATH_JMX = "jmx";
public static String JMX_PROTOCOL_KEY = "service:jmx:rmi:///jndi/rmi";
String PROVIDER = "com/webank/ai/fate/register/provider";
String CONSUMER = "consumer";
String CHECK_KEY = "check";
String REMOTE_APPLICATION_KEY = "remote.application";
String ENABLED_KEY = "enabled";
String DISABLED_KEY = "disabled";
String ENVIRONMENT = "environment";
String ANY_VALUE = "*";
String COMMA_SEPARATOR = ",";
String DOT_SEPARATOR = ".";
Pattern COMMA_SPLIT_PATTERN = Pattern.compile("\\s*[,]+\\s*");
String PATH_SEPARATOR = "/";
String PROTOCOL_SEPARATOR = "://";
String REGISTRY_SEPARATOR = "|";
Pattern REGISTRY_SPLIT_PATTERN = Pattern.compile("\\s*[|;]+\\s*");
String SEMICOLON_SEPARATOR = ";";
Pattern SEMICOLON_SPLIT_PATTERN = Pattern.compile("\\s*[;]+\\s*");
Pattern EQUAL_SPLIT_PATTERN = Pattern.compile("\\s*[=]+\\s*");
String DEFAULT_PROXY = "javassist";
int DEFAULT_CORE_THREADS = 0;
int DEFAULT_THREADS = 200;
String THREADPOOL_KEY = "threadpool";
String THREAD_NAME_KEY = "threadname";
String CORE_THREADS_KEY = "corethreads";
String THREADS_KEY = "threads";
String QUEUES_KEY = "queues";
String ALIVE_KEY = "alive";
String DEFAULT_THREADPOOL = "limited";
String DEFAULT_CLIENT_THREADPOOL = "cached";
String IO_THREADS_KEY = "iothreads";
int DEFAULT_QUEUES = 0;
int DEFAULT_ALIVE = 60 * 1000;
String TIMEOUT_KEY = "timeout";
int DEFAULT_TIMEOUT = 1000;
String REMOVE_VALUE_PREFIX = "-";
String PROPERTIES_CHAR_SEPERATOR = "-";
String UNDERLINE_SEPARATOR = "_";
String SEPARATOR_REGEX = "_|-";
String GROUP_CHAR_SEPERATOR = ":";
String HIDE_KEY_PREFIX = ".";
String DOT_REGEX = "\\.";
String DEFAULT_KEY_PREFIX = "default.";
String DEFAULT_KEY = "default";
/**
* Default timeout value in milliseconds for server shutdown
*/
int DEFAULT_SERVER_SHUTDOWN_TIMEOUT = 10000;
String SIDE_KEY = "side";
String PROVIDER_SIDE = "com/webank/ai/fate/register/provider";
String CONSUMER_SIDE = "consumer";
String ANYHOST_KEY = "anyhost";
String ANYHOST_VALUE = "0.0.0.0";
String LOCALHOST_KEY = "localhost";
String LOCALHOST_VALUE = "127.0.0.1";
String METHODS_KEY = "methods";
String METHOD_KEY = "method";
String PID_KEY = "pid";
String TIMESTAMP_KEY = "timestamp";
String GROUP_KEY = "group";
String INTERFACE_KEY = "interface";
String DUMP_DIRECTORY = "dump.directory";
String CLASSIFIER_KEY = "classifier";
String VERSION_KEY = "version";
String REVISION_KEY = "revision";
/**
* package version in the manifest
*/
String RELEASE_KEY = "release";
int MAX_PROXY_COUNT = 65535;
String MONITOR_KEY = "monitor";
String CLUSTER_KEY = "cluster";
String REGISTRY_KEY = "registry";
String REGISTRY_PROTOCOL = "registry";
String DYNAMIC_KEY = "dynamic";
String CATEGORY_KEY = "category";
String PROVIDERS_CATEGORY = "providers";
String CONSUMERS_CATEGORY = "consumers";
String ROUTERS_CATEGORY = "routers";
String DYNAMIC_ROUTERS_CATEGORY = "dynamicrouters";
String DEFAULT_CATEGORY = PROVIDERS_CATEGORY;
String CONFIGURATORS_CATEGORY = "configurators";
String DYNAMIC_CONFIGURATORS_CATEGORY = "dynamicconfigurators";
String APP_DYNAMIC_CONFIGURATORS_CATEGORY = "appdynamicconfigurators";
String ROUTERS_SUFFIX = ".routers";
String EMPTY_PROTOCOL = "empty";
String ROUTE_PROTOCOL = "route";
String OVERRIDE_PROTOCOL = "override";
String WEIGHT_KEY = "weight";
String COMPATIBLE_CONFIG_KEY = "compatible_config";
String REGISTER_IP_KEY = "register.ip";
String REGISTER_KEY = "register";
String SUBSCRIBE_KEY = "subscribe";
String DEFAULT_REGISTRY = "fate";
String REGISTER = "register";
String UNREGISTER = "unregister";
String SUBSCRIBE = "subscribe";
String UNSUBSCRIBE = "unsubscribe";
String CONFIGURATORS_SUFFIX = ".configurators";
String ADMIN_PROTOCOL = "admin";
String PROVIDER_PROTOCOL = "com/webank/ai/fate/register/provider";
String CONSUMER_PROTOCOL = "consumer";
String SCRIPT_PROTOCOL = "script";
String CONDITION_PROTOCOL = "condition";
String TRACE_PROTOCOL = "trace";
String SIMPLIFIED_KEY = "simplified";
String EXTRA_KEYS_KEY = "extra-keys";
String REGISTRY_RECONNECT_PERIOD_KEY = "reconnect.period";
int DEFAULT_SESSION_TIMEOUT = 60 * 1000;
int DEFAULT_REGISTRY_RETRY_TIMES = 3;
int DEFAULT_REGISTRY_RECONNECT_PERIOD = 3 * 1000;
int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000;
String REGISTRY_RETRY_TIMES_KEY = "retry.times";
String REGISTRY_RETRY_PERIOD_KEY = "retry.period";
String SESSION_TIMEOUT_KEY = "session";
String UTF_8 = "UTF-8";
String GRPC = "grpc";
String POOL_PREFIX = "pool-";
String POOL_PREFIX_THREAD = "-thread-";
String REFIX_FATE_REGISTRY_RETRY_TIMER = "FateRegistryRetryTimer";
String OS_NAME = "os.name";
String USER_HOME = "user.home";
String OS_NAME_WIN = "win";
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/RegistryFactory.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/RegistryFactory.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import com.webank.ai.fate.register.interfaces.Registry;
import com.webank.ai.fate.register.url.URL;
public interface RegistryFactory {
Registry getRegistry(URL url);
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/ConfigChangeEvent.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/ConfigChangeEvent.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
public class ConfigChangeEvent {
private final String key;
private final String value;
private final ConfigChangeType changeType;
public ConfigChangeEvent(String key, String value) {
this(key, value, ConfigChangeType.MODIFIED);
}
public ConfigChangeEvent(String key, String value, ConfigChangeType changeType) {
this.key = key;
this.value = value;
this.changeType = changeType;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
public ConfigChangeType getChangeType() {
return changeType;
}
@Override
public String toString() {
return "ConfigChangeEvent{" +
"key='" + key + '\'' +
", value='" + value + '\'' +
", changeType=" + changeType +
'}';
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/common/AbstractRegistry.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/common/AbstractRegistry.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.common;
import com.google.common.collect.Sets;
import com.webank.ai.fate.register.interfaces.NotifyListener;
import com.webank.ai.fate.register.interfaces.Registry;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.url.UrlUtils;
import com.webank.ai.fate.register.utils.StringUtils;
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.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.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static com.webank.ai.fate.register.common.Constants.*;
public abstract class AbstractRegistry implements Registry {
public final static String INSTANCE_ID = UUID.randomUUID().toString();
private static final Logger logger = LoggerFactory.getLogger(AbstractRegistry.class);
private static final char URL_SEPARATOR = ' ';
private static final String URL_SPLIT = "\\s+";
private static final int MAX_RETRY_TIMES_SAVE_PROPERTIES = 3;
private final Properties properties = new Properties();
private final ExecutorService registryCacheExecutor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
new NamedThreadFactory("FateSaveRegistryCache", true));
private final boolean syncSaveFile;
private final AtomicLong lastCacheChanged = new AtomicLong();
private final AtomicInteger savePropertiesRetryTimes = new AtomicInteger();
private final Set<URL> registered = new HashSet<>();
private final ConcurrentMap<URL, Set<NotifyListener>> subscribed = new ConcurrentHashMap<>();
private final ConcurrentMap<URL, Map<String, List<URL>>> notified = new ConcurrentHashMap<>();
// environment + serviceName => ServiceWrapper
protected ConcurrentMap<String, ServiceWrapper> serviceCacheMap = new ConcurrentHashMap<>();
protected File serviceCacheFile;
protected Set<String> projectSets = Sets.newHashSet();
private URL registryUrl;
// Local disk cache file
private File file;
public AbstractRegistry(URL url) {
setUrl(url);
// Start file save timer
syncSaveFile = url.getParameter(REGISTRY_FILESAVE_SYNC_KEY, false);
String filename = url.getParameter(FILE_KEY, System.getProperty(USER_HOME) + "/.fate/fate-registry-" + url.getParameter(PROJECT_KEY) + "-" + url.getHost() + "-" + url.getPort() + ".cache");
File file = null;
if (StringUtils.isNotEmpty(filename)) {
file = new File(filename);
if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
throw new IllegalArgumentException("Invalid registry cache file " + file + ", cause: Failed to create directory " + file.getParentFile() + "!");
}
}
}
this.file = file;
loadProperties();
notify(url.getBackupUrls());
String serviceCacheFileName = System.getProperty(Dict.PROPERTY_USER_HOME) + "/.fate/fate-service-" + url.getParameter(PROJECT_KEY) + "-" + url.getHost() + "-" + url.getPort() + ".cache";
if (StringUtils.isNotEmpty(serviceCacheFileName)) {
serviceCacheFile = new File(serviceCacheFileName);
if (!serviceCacheFile.exists() && serviceCacheFile.getParentFile() != null && !serviceCacheFile.getParentFile().exists()) {
if (!serviceCacheFile.getParentFile().mkdirs()) {
throw new IllegalArgumentException("Invalid service cache file " + serviceCacheFile + ", cause: Failed to create directory " + serviceCacheFile.getParentFile() + "!");
}
}
}
loadServiceCache(serviceCacheMap, serviceCacheFile);
}
protected static List<URL> filterEmpty(URL url, List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
List<URL> result = new ArrayList<>(1);
result.add(url.setProtocol(EMPTY_PROTOCOL));
return result;
}
return urls;
}
public void saveServiceCache(Map data, File file) {
if (file == null) {
logger.error("save cache file error , file is 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 model 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)) {
byte[] serialize = Base64.getEncoder().encode(JsonUtil.object2Json(data).getBytes());
outputFile.write(serialize);
}
} finally {
lock.release();
}
}
logger.info("save cache file {} success", file.getAbsolutePath());
} catch (Throwable e) {
logger.error("Failed to save model cache file, will retry, cause: " + e.getMessage(), e);
}
}
public void loadServiceCache(Map data, File file) {
if (file != null && file.exists()) {
try (InputStream in = new FileInputStream(file)) {
Long length = file.length();
byte[] bytes = new byte[length.intValue()];
int readCount = in.read(bytes);
if (readCount > 0) {
data.clear();
ConcurrentHashMap deserialize = JsonUtil.json2Object(Base64.getDecoder().decode(bytes), ConcurrentHashMap.class);
if (deserialize != null) {
deserialize.forEach((k, v) -> {
ServiceWrapper serviceWrapper = JsonUtil.json2Object(JsonUtil.object2Json(v), ServiceWrapper.class);
data.put(k, serviceWrapper);
});
}
}
} catch (Throwable e) {
logger.error("failed to doLoadCache file {}", file, e);
}
}
}
public ConcurrentMap<String, ServiceWrapper> getServiceCacheMap() {
return serviceCacheMap;
}
public void setServiceCacheMap(ConcurrentMap<String, ServiceWrapper> serviceCacheMap) {
this.serviceCacheMap = serviceCacheMap;
}
public void subProject(String project) {
projectSets.add(project);
}
public abstract void doRegisterComponent(URL url);
public abstract void doSubProject(String project);
@Override
public URL getUrl() {
return registryUrl;
}
protected void setUrl(URL url) {
if (url == null) {
throw new IllegalArgumentException("registry url == null");
}
this.registryUrl = url;
}
public Set<URL> getRegistered() {
return Collections.unmodifiableSet(registered);
}
public Map<URL, Set<NotifyListener>> getSubscribed() {
return Collections.unmodifiableMap(subscribed);
}
public Map<URL, Map<String, List<URL>>> getNotified() {
return Collections.unmodifiableMap(notified);
}
public File getCacheFile() {
return file;
}
public Properties getCacheProperties() {
return properties;
}
public AtomicLong getLastCacheChanged() {
return lastCacheChanged;
}
public void doSaveProperties(long version) {
if (logger.isDebugEnabled()) {
logger.debug("doSaveProperties {} {}", version, properties);
}
if (version < lastCacheChanged.get()) {
return;
}
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");
}
// Save
try {
if (!file.exists()) {
file.createNewFile();
}
try (FileOutputStream outputFile = new FileOutputStream(file)) {
properties.store(outputFile, "Fate Registry Cache");
}
} finally {
lock.release();
}
}
} catch (Throwable e) {
savePropertiesRetryTimes.incrementAndGet();
if (savePropertiesRetryTimes.get() >= MAX_RETRY_TIMES_SAVE_PROPERTIES) {
logger.warn("Failed to save registry cache file after retrying " + MAX_RETRY_TIMES_SAVE_PROPERTIES + " times, cause: " + e.getMessage(), e);
savePropertiesRetryTimes.set(0);
return;
}
if (version < lastCacheChanged.get()) {
savePropertiesRetryTimes.set(0);
return;
} else {
registryCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet()));
}
logger.warn("Failed to save registry cache file, will retry, cause: " + e.getMessage(), e);
}
}
private void loadProperties() {
if (file != null && file.exists()) {
InputStream in = null;
try {
in = new FileInputStream(file);
properties.load(in);
if (logger.isDebugEnabled()) {
logger.debug("Load registry cache file " + file + ", data: " + properties);
}
} catch (Throwable e) {
logger.warn("Failed to load registry cache file " + file, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
}
}
}
}
public List<URL> getCacheUrls(URL url) {
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (key != null && key.length() > 0 && key.equals(url.getServiceKey())
&& (Character.isLetter(key.charAt(0)) || key.charAt(0) == '_')
&& value != null && value.length() > 0) {
String[] arr = value.trim().split(URL_SPLIT);
List<URL> urls = new ArrayList<>();
for (String u : arr) {
// for jmx url
if (u.startsWith(JMX_PROTOCOL_KEY)) {
urls.add(URL.parseJMXServiceUrl(u));
} else {
urls.add(URL.valueOf(u));
}
}
return urls;
}
}
return null;
}
@Override
public List<URL> lookup(URL url) {
List<URL> result = new ArrayList<>();
Map<String, List<URL>> notifiedUrls = getNotified().get(url);
if (notifiedUrls != null && notifiedUrls.size() > 0) {
for (List<URL> urls : notifiedUrls.values()) {
for (URL u : urls) {
if (!EMPTY_PROTOCOL.equals(u.getProtocol())) {
result.add(u);
}
}
}
} else {
final AtomicReference<List<URL>> reference = new AtomicReference<>();
NotifyListener listener = reference::set;
subscribe(url, listener); // Subscribe logic guarantees the first notify to return
List<URL> urls = reference.get();
if (CollectionUtils.isNotEmpty(urls)) {
for (URL u : urls) {
if (!EMPTY_PROTOCOL.equals(u.getProtocol())) {
result.add(u);
}
}
}
}
return result;
}
@Override
public void register(URL url) {
if (url == null) {
throw new IllegalArgumentException("register url == null");
}
if (logger.isInfoEnabled()) {
logger.info("Register: " + url);
}
registered.add(url);
}
@Override
public void unregister(URL url) {
if (url == null) {
throw new IllegalArgumentException("unregister url == null");
}
if (logger.isInfoEnabled()) {
logger.info("Unregister: " + url);
}
registered.remove(url);
}
@Override
public void subscribe(URL url, NotifyListener listener) {
if (url == null) {
throw new IllegalArgumentException("subscribe url == null");
}
if (listener == null) {
throw new IllegalArgumentException("subscribe listener == null");
}
if (logger.isDebugEnabled()) {
logger.debug("Subscribe: " + url);
}
Set<NotifyListener> listeners = subscribed.computeIfAbsent(url, n -> new HashSet<>());
listeners.add(listener);
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
if (url == null) {
throw new IllegalArgumentException("unsubscribe url == null");
}
if (listener == null) {
throw new IllegalArgumentException("unsubscribe listener == null");
}
if (logger.isDebugEnabled()) {
logger.debug("Unsubscribe: " + url);
}
Set<NotifyListener> listeners = subscribed.get(url);
if (listeners != null) {
listeners.remove(listener);
}
}
protected void recover() throws Exception {
for (String project : this.projectSets) {
logger.info("Recover project {} ", project);
subProject(project);
}
// register
Set<URL> recoverRegistered = new HashSet<>(getRegistered());
if (!recoverRegistered.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover register url " + recoverRegistered);
}
for (URL url : recoverRegistered) {
register(url);
}
}
// subscribe
Map<URL, Set<NotifyListener>> recoverSubscribed = new HashMap<>(getSubscribed());
if (!recoverSubscribed.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("Recover subscribe url " + recoverSubscribed.keySet());
}
for (Map.Entry<URL, Set<NotifyListener>> entry : recoverSubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
subscribe(url, listener);
}
}
}
}
protected void notify(List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
return;
}
for (Map.Entry<URL, Set<NotifyListener>> entry : getSubscribed().entrySet()) {
URL url = entry.getKey();
if (!UrlUtils.isMatch(url, urls.get(0))) {
continue;
}
Set<NotifyListener> listeners = entry.getValue();
if (listeners != null) {
for (NotifyListener listener : listeners) {
try {
notify(url, listener, filterEmpty(url, urls));
} catch (Throwable t) {
logger.error("Failed to notify registry event, urls: " + urls + ", cause: " + t.getMessage(), t);
}
}
}
}
}
protected void notify(URL url, NotifyListener listener, List<URL> urls) {
if (url == null) {
throw new IllegalArgumentException("notify url == null");
}
if (listener == null) {
throw new IllegalArgumentException("notify listener == null");
}
if ((CollectionUtils.isEmpty(urls))
&& !ANY_VALUE.equals(url.getServiceInterface())) {
logger.warn("Ignore empty notify urls for subscribe url " + url);
return;
}
if (logger.isInfoEnabled()) {
logger.info("Notify urls for subscribe url " + url + ", urls: " + urls);
}
// keep every provider's category.
Map<String, List<URL>> result = new HashMap<>(8);
for (URL u : urls) {
if (UrlUtils.isMatch(url, u)) {
String category = u.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY);
List<URL> categoryList = result.computeIfAbsent(category, k -> new ArrayList<>());
categoryList.add(u);
}
}
if (result.size() == 0) {
return;
}
Map<String, List<URL>> categoryNotified = notified.computeIfAbsent(url, u -> new ConcurrentHashMap<>(8));
for (Map.Entry<String, List<URL>> entry : result.entrySet()) {
String category = entry.getKey();
List<URL> categoryList = entry.getValue();
categoryNotified.put(category, categoryList);
listener.notify(categoryList);
// We will update our cache file after each notification.
// When our Registry has a subscribe failure due to network jitter, we can return at least the existing cache URL.
saveProperties(url);
}
}
private void saveProperties(URL url) {
if (logger.isDebugEnabled()) {
logger.debug("saveProperties url {}", url);
}
if (file == null) {
return;
}
try {
StringBuilder buf = new StringBuilder();
Map<String, List<URL>> categoryNotified = notified.get(url);
if (categoryNotified != null) {
for (List<URL> us : categoryNotified.values()) {
for (URL u : us) {
if (buf.length() > 0) {
buf.append(URL_SEPARATOR);
}
buf.append(u.toFullString());
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("properties set property key {} value {}", url.getServiceKey(), buf.toString());
}
properties.setProperty(url.getServiceKey(), buf.toString());
long version = lastCacheChanged.incrementAndGet();
if (syncSaveFile) {
doSaveProperties(version);
} else {
registryCacheExecutor.execute(new SaveProperties(version));
}
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
}
}
@Override
public void destroy() {
if (logger.isInfoEnabled()) {
logger.info("Destroy registry:" + getUrl());
}
Set<URL> destroyRegistered = new HashSet<>(getRegistered());
if (!destroyRegistered.isEmpty()) {
for (URL url : new HashSet<>(getRegistered())) {
if (url.getParameter(DYNAMIC_KEY, true)) {
try {
unregister(url);
if (logger.isInfoEnabled()) {
logger.info("Destroy unregister url " + url);
}
} catch (Throwable t) {
logger.warn("Failed to unregister url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t);
}
}
}
}
Map<URL, Set<NotifyListener>> destroySubscribed = new HashMap<>(getSubscribed());
if (!destroySubscribed.isEmpty()) {
for (Map.Entry<URL, Set<NotifyListener>> entry : destroySubscribed.entrySet()) {
URL url = entry.getKey();
for (NotifyListener listener : entry.getValue()) {
try {
unsubscribe(url, listener);
if (logger.isInfoEnabled()) {
logger.info("Destroy unsubscribe url " + url);
}
} catch (Throwable t) {
logger.warn("Failed to unsubscribe url " + url + " to registry " + getUrl() + " on destroy, cause: " + t.getMessage(), t);
}
}
}
}
}
@Override
public String toString() {
return getUrl().toString();
}
private class SaveProperties implements Runnable {
private long version;
private SaveProperties(long version) {
this.version = version;
}
@Override
public void run() {
doSaveProperties(version);
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/annotions/RegisterService.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/annotions/RegisterService.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.annotions;
import com.webank.ai.fate.register.common.Role;
import com.webank.ai.fate.register.common.RouterMode;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RegisterService {
String serviceName();
long version() default MetaInfo.CURRENT_VERSION;
boolean useDynamicEnvironment() default false;
RouterMode routerMode() default RouterMode.ALL_ALLOWED;
Role role() default Role.COMMON;
String protocol() default "grpc";
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/zookeeper/ZookeeperRegistry.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/zookeeper/ZookeeperRegistry.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.zookeeper;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.webank.ai.fate.register.annotions.RegisterService;
import com.webank.ai.fate.register.common.*;
import com.webank.ai.fate.register.interfaces.NotifyListener;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.url.UrlUtils;
import com.webank.ai.fate.register.utils.StringUtils;
import com.webank.ai.fate.register.utils.URLBuilder;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.core.utils.NetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static com.webank.ai.fate.register.common.Constants.*;
import static org.apache.curator.utils.ZKPaths.PATH_SEPARATOR;
public class ZookeeperRegistry extends FailbackRegistry {
private static final Logger logger = LoggerFactory.getLogger(ZookeeperRegistry.class);
private final static int DEFAULT_ZOOKEEPER_PORT = 2181;
private final static String DEFAULT_COMPONENT_ROOT = "FATE-COMPONENTS";
private final static String ROOT_KEY = "root";
public static ConcurrentMap<URL, ZookeeperRegistry> registeryMap = new ConcurrentHashMap();
private static String DYNAMIC_KEY = "dynamic";
private final String root;
private final ConcurrentMap<URL, ConcurrentMap<NotifyListener, ChildListener>> zkListeners = new ConcurrentHashMap<>();
private final ZookeeperClient zkClient;
Set<String> registedString = Sets.newHashSet();
Set<String> anyServices = new HashSet<String>();
private String environment;
private Set<String> dynamicEnvironments = new HashSet<String>();
private String project;
private int port;
public ZookeeperRegistry(URL url, ZookeeperTransporter zookeeperTransporter) {
super(url);
String group = url.getParameter(ROOT_KEY, Dict.DEFAULT_FATE_ROOT);
if (!group.startsWith(PATH_SEPARATOR)) {
group = PATH_SEPARATOR + group;
}
this.environment = url.getParameter(ENVIRONMENT_KEY, "online");
project = url.getParameter(PROJECT_KEY);
port = url.getParameter(SERVER_PORT) != null ? new Integer(url.getParameter(SERVER_PORT)) : 0;
this.root = group;
zkClient = zookeeperTransporter.connect(url);
zkClient.addStateListener(state -> {
if (state == StateListener.RECONNECTED) {
logger.error("state listener reconnected");
try {
recover();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
});
}
public static synchronized ZookeeperRegistry createRegistry(String host, String project, String environment, int port) {
String url = URL.generateZkUrl(host);
return getRegistry(url, project, environment, port);
}
public static synchronized ZookeeperRegistry getRegistry(String url, String project, String environment, int port) {
if (url == null) {
return null;
}
URL registryUrl = URL.valueOf(url);
registryUrl = registryUrl.addParameter(Constants.ENVIRONMENT_KEY, environment);
registryUrl = registryUrl.addParameter(Constants.SERVER_PORT, port);
registryUrl = registryUrl.addParameter(Constants.PROJECT_KEY, project);
List<URL> backups = registryUrl.getBackupUrls();
if (registeryMap.get(registryUrl) == null) {
URL finalRegistryUrl = registryUrl;
registeryMap.computeIfAbsent(registryUrl, n -> {
CuratorZookeeperTransporter curatorZookeeperTransporter = new CuratorZookeeperTransporter();
ZookeeperRegistryFactory zookeeperRegistryFactory = new ZookeeperRegistryFactory();
zookeeperRegistryFactory.setZookeeperTransporter(curatorZookeeperTransporter);
ZookeeperRegistry zookeeperRegistry = (ZookeeperRegistry) zookeeperRegistryFactory.createRegistry(finalRegistryUrl);
return zookeeperRegistry;
});
}
return registeryMap.get(registryUrl);
}
public ZookeeperClient getZkClient() {
return this.zkClient;
}
@Override
public void doRegisterComponent(URL url) {
if(url == null) {
String hostAddress = NetUtils.getLocalIp();
String path = PATH_SEPARATOR + DEFAULT_COMPONENT_ROOT + PATH_SEPARATOR + project + PATH_SEPARATOR + hostAddress + ":" + port;
url = new URL(path, Maps.newHashMap());
//url=url.addParameter(Constants.INSTANCE_ID, AbstractRegistry.INSTANCE_ID);
}
String path = url.getPath();
Map content = new HashMap();
content.put(Constants.INSTANCE_ID, AbstractRegistry.INSTANCE_ID);
content.put(Constants.TIMESTAMP_KEY, System.currentTimeMillis());
content.put(Dict.VERSION, MetaInfo.CURRENT_VERSION);
this.zkClient.create(path, JsonUtil.object2Json(content), true);
this.componentUrl = url;
logger.info("register component {} ", path);
}
public void registerComponent() {
try {
doRegisterComponent(null);
} catch (Exception e) {
logger.error("registerComponent error",e);
addFailedRegisterComponentTask(null);
}
}
public void unRegisterComponent() {
if(componentUrl!=null) {
System.err.println("delete component "+this.componentUrl.getPath());
zkClient.delete(this.componentUrl.getPath());
}else{
System.err.println("componentUrl is null");
}
}
public boolean tryUnregister(URL url) {
try {
CuratorZookeeperClient client = (CuratorZookeeperClient) zkClient;
boolean exists = client.checkExists(toUrlPath(url));
String urlPath = toUrlPath(url);
if (exists) {
if (logger.isDebugEnabled()) {
logger.debug("delete zk path " + urlPath);
}
zkClient.delete(toUrlPath(url));
registedString.remove(url.getServiceInterface() + url.getEnvironment());
syncServiceCacheFile();
return true;
} else {
logger.error(urlPath + " is not exist");
}
} catch (Throwable e) {
throw new RuntimeException("Failed to unregister " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
return false;
}
private void syncServiceCacheFile() {
super.saveServiceCache(serviceCacheMap, serviceCacheFile);
}
@Override
public void doSubProject(String project) {
String path = root + Constants.PATH_SEPARATOR + project;
List<String> environments = zkClient.addChildListener(path, (parent, childrens) -> {
if (StringUtils.isNotEmpty(parent)) {
logger.info("fire environments changes {}", childrens);
subEnvironments(path, project, childrens);
}
});
if (logger.isDebugEnabled()) {
logger.debug("environments {}", environments);
}
if (environments == null) {
if (logger.isDebugEnabled()) {
logger.debug("path {} is not exist in zk", path);
}
throw new RuntimeException("environment is null");
}
subEnvironments(path, project, environments);
}
private void subEnvironments(String path, String project, List<String> environments) {
if (environments != null) {
for (String environment : environments) {
String tempPath = path + Constants.PATH_SEPARATOR + environment;
List<String> services = zkClient.addChildListener(tempPath, (parent, childrens) -> {
if (StringUtils.isNotEmpty(parent)) {
if (logger.isDebugEnabled()) {
logger.debug("fire services changes {}", childrens);
}
subServices(project, environment, childrens);
}
});
subServices(project, environment, services);
}
}
}
private void subServices(String project, String environment, List<String> services) {
if (services != null) {
for (String service : services) {
String subString = project + Constants.PATH_SEPARATOR + environment + Constants.PATH_SEPARATOR + service;
if (logger.isDebugEnabled()) {
logger.debug("subServices sub {}", subString);
}
subscribe(URL.valueOf(subString), urls -> {
if (logger.isDebugEnabled()) {
logger.debug("change services urls =" + urls);
}
});
}
}
}
private String parseRegisterService(String serviceName, RegisterService registerService) {
long version = registerService.version();
String param = "?";
RouterMode routerMode = registerService.routerMode();
param = param + Constants.ROUTER_MODE + "=" + routerMode.name();
param = param + "&";
param = param + Constants.TIMESTAMP_KEY + "=" + System.currentTimeMillis();
String key = serviceName;
if (version != 0) {
param = param + "&" + Constants.VERSION + "=" + version;
}
key = key + param;
return key;
}
private void loadCacheParams(URL url) {
Map<String, String> parameters = url.getParameters();
ServiceWrapper serviceWrapper = this.getServiceCacheMap().get(url.getEnvironment() + "/" + url.getPath());
if (serviceWrapper != null) {
if (serviceWrapper.getRouterMode() != null) {
parameters.put(Constants.ROUTER_MODE, serviceWrapper.getRouterMode());
}
if (serviceWrapper.getWeight() != null) {
parameters.put(Constants.WEIGHT_KEY, String.valueOf(serviceWrapper.getWeight()));
}
} else {
serviceWrapper = new ServiceWrapper();
serviceWrapper.setRouterMode(parameters.get(Constants.ROUTER_MODE));
serviceWrapper.setWeight(parameters.get(Constants.WEIGHT_KEY) != null ? Integer.valueOf(parameters.get(Constants.WEIGHT_KEY)) : null);
this.getServiceCacheMap().put(url.getEnvironment() + "/" + url.getPath(), serviceWrapper);
}
}
public synchronized void register(Set<RegisterService> sets,Collection<String> dynamicEnvironments){
String hostAddress = NetUtils.getLocalIp();
for (RegisterService service : sets) {
URL url = generateUrl(hostAddress, service);
URL serviceUrl = url.setProject(project);
if (service.useDynamicEnvironment()) {
if (CollectionUtils.isNotEmpty(dynamicEnvironments)) {
dynamicEnvironments.forEach(environment -> {
URL newServiceUrl = serviceUrl.setEnvironment(environment);
// use cache service params
loadCacheParams(newServiceUrl);
String serviceName = service.serviceName() + environment;
if (!registedString.contains(serviceName)) {
this.register(newServiceUrl);
this.registedString.add(serviceName);
} else {
logger.info("url {} is already registed, will not do anything ", newServiceUrl);
}
});
}
}
}
syncServiceCacheFile();
}
public synchronized void register(Set<RegisterService> sets) {
if (logger.isDebugEnabled()) {
logger.debug("prepare to register {}", sets);
}
String hostAddress = NetUtils.getLocalIp();
Preconditions.checkArgument(port != 0);
Preconditions.checkArgument(StringUtils.isNotEmpty(environment));
Set<URL> registered = this.getRegistered();
for (RegisterService service : sets) {
try {
URL url = generateUrl(hostAddress, service);
URL serviceUrl = url.setProject(project);
if (service.useDynamicEnvironment()) {
if (CollectionUtils.isNotEmpty(dynamicEnvironments)) {
dynamicEnvironments.forEach(environment -> {
URL newServiceUrl = service.protocol().equals(Dict.HTTP) ? url : serviceUrl.setEnvironment(environment);
// use cache service params
loadCacheParams(newServiceUrl);
String serviceName = service.serviceName() + environment;
if (!registedString.contains(serviceName)) {
this.register(newServiceUrl);
this.registedString.add(serviceName);
} else {
logger.info("url {} is already registed, will not do anything ", newServiceUrl);
}
});
}
} else {
if (!registedString.contains(service.serviceName() + environment)) {
URL newServiceUrl = service.protocol().equals(Dict.HTTP) ? url : serviceUrl.setEnvironment(environment);
if (logger.isDebugEnabled()) {
logger.debug("try to register url {}", newServiceUrl);
}
// use cache service params
loadCacheParams(newServiceUrl);
this.register(newServiceUrl);
this.registedString.add(service.serviceName() + environment);
} else {
logger.info("url {} is already registed, will not do anything ", service.serviceName());
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("try to register service {} failed", service);
}
}
syncServiceCacheFile();
if (logger.isDebugEnabled()) {
logger.debug("registed urls {}", registered);
}
}
private URL generateUrl(String hostAddress, RegisterService service) {
String protocol , serviceName ;
int hostPort;
protocol = service.protocol();
if (MetaInfo.PROPERTY_SERVER_PORT == null) {
logger.error("Failed to register service:{} ,acquire server.port is null", service);
throw new RuntimeException("Failed to register service:"+ service +" ,acquire server.port is null");
}
hostPort = service.protocol().equals(Dict.HTTP)?MetaInfo.PROPERTY_SERVER_PORT:port;
serviceName = service.serviceName();
if (StringUtils.isBlank(serviceName)) {
logger.error("Failed to register service:{} ,acquire serviceName is blank", service);
throw new RuntimeException("Failed to register service:"+ service +" ,acquire serviceName is blank");
}
return URL.valueOf(protocol + "://" + hostAddress + ":" + hostPort + Constants.PATH_SEPARATOR + parseRegisterService(serviceName, service));
}
public void addDynamicEnvironment(String environment) {
dynamicEnvironments.add(environment);
}
public void addDynamicEnvironment(Collection collection) {
if (collection != null && !collection.isEmpty()) {
dynamicEnvironments.addAll(collection);
}
}
@Override
public boolean isAvailable() {
return zkClient.isConnected();
}
@Override
public void destroy() {
System.err.println("try to destroy zookeeper registry !");
this.unRegisterComponent();
super.destroy();
try {
zkClient.close();
} catch (Exception e) {
logger.warn("Failed to close zookeeper client " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doRegister(URL url) {
try {
String urlPath = toUrlPath(url);
if (logger.isDebugEnabled()) {
logger.debug("create urlpath {} ", urlPath);
}
zkClient.create(urlPath, true);
} catch (Throwable e) {
throw new RuntimeException("Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doUnregister(URL url) {
try {
zkClient.delete(toUrlPath(url));
registedString.remove(url.getServiceInterface() + url.getEnvironment());
} catch (Throwable e) {
throw new RuntimeException("Failed to unregister " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doSubscribe(final URL url, final NotifyListener listener) {
try {
List<URL> urls = new ArrayList<>();
if (ANY_VALUE.equals(url.getEnvironment())) {
String root = toRootPath();
ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url);
if (listeners == null) {
zkListeners.putIfAbsent(url, new ConcurrentHashMap<>());
listeners = zkListeners.get(url);
}
ChildListener zkListener = listeners.get(listener);
if (zkListener == null) {
listeners.putIfAbsent(listener, (parentPath, currentChilds) -> {
if (parentPath.equals(Constants.PROVIDERS_CATEGORY)) {
for (String child : currentChilds) {
child = URL.decode(child);
if (!anyServices.contains(child)) {
anyServices.add(child);
subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child,
Constants.CHECK_KEY, String.valueOf(false)), listener);
}
}
}
});
zkListener = listeners.get(listener);
}
StringBuilder sb = new StringBuilder(root);
sb.append("/").append(url.getProject());
List<String> children = zkClient.addChildListener(sb.toString(), zkListener);
for (String environment : children) {
sb.append("/").append(environment);
List<String> interfaces = zkClient.addChildListener(sb.toString(), zkListener);
if (interfaces != null) {
for (String inter : interfaces) {
sb.append("/").append(inter).append("/").append(Constants.PROVIDERS_CATEGORY);
List<String> services = zkClient.addChildListener(sb.toString(), zkListener);
if (services != null) {
urls.addAll(toUrlsWithEmpty(url, sb.toString(), services));
}
}
}
}
notify(url, listener, urls);
} else {
for (String path : toCategoriesPath(url)) {
ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url);
if (listeners == null) {
zkListeners.putIfAbsent(url, new ConcurrentHashMap<>());
listeners = zkListeners.get(url);
}
ChildListener zkListener = listeners.get(listener);
if (zkListener == null) {
listeners.putIfAbsent(listener, (parentPath, currentChilds) -> {
if (StringUtils.isNotEmpty(parentPath)) {
ZookeeperRegistry.this.notify(url, listener,
toUrlsWithEmpty(url, parentPath, currentChilds));
}
}
);
zkListener = listeners.get(listener);
}
zkClient.create(path, false);
List<String> children = zkClient.addChildListener(path, zkListener);
if (children != null) {
urls.addAll(toUrlsWithEmpty(url, path, children));
}
}
notify(url, listener, urls);
}
} catch (Throwable e) {
throw new RuntimeException("Failed to subscribe " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url);
if (listeners != null) {
ChildListener zkListener = listeners.get(listener);
if (zkListener != null) {
for (String path : toCategoriesPath(url)) {
zkClient.removeChildListener(path, zkListener);
}
}
}
}
@Override
public List<URL> lookup(URL url) {
if (url == null) {
throw new IllegalArgumentException("lookup url == null");
}
try {
List<String> providers = new ArrayList<>();
for (String path : toCategoriesPath(url)) {
List<String> children = zkClient.getChildren(path);
if (children != null) {
providers.addAll(children);
}
}
return toUrlsWithoutEmpty(url, providers);
} catch (Throwable e) {
throw new RuntimeException("Failed to lookup " + url + " from zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
private String toRootDir() {
if (root.equals(PATH_SEPARATOR)) {
return root;
}
return root + PATH_SEPARATOR;
}
private String toRootPath() {
return root;
}
private String toServicePath(URL url) {
String project = url.getProject() != null ? url.getProject() : this.project;
String environment = url.getEnvironment() != null ? url.getEnvironment() : this.environment;
String name = url.getServiceInterface();
if (ANY_VALUE.equals(name)) {
return toRootPath();
}
return toRootDir() + project + Constants.PATH_SEPARATOR + environment + Constants.PATH_SEPARATOR + URL.encode(name);
}
private String[] toCategoriesPath(URL url) {
String[] categories;
if (ANY_VALUE.equals(url.getParameter(CATEGORY_KEY))) {
categories = new String[]{PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY};
} else {
categories = url.getParameter(CATEGORY_KEY, new String[]{DEFAULT_CATEGORY});
}
String[] paths = new String[categories.length];
for (int i = 0; i < categories.length; i++) {
paths[i] = toServicePath(url) + PATH_SEPARATOR + categories[i];
}
return paths;
}
private String toCategoryPath(URL url) {
String servicePath = toServicePath(url);
String category = url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY);
return servicePath + PATH_SEPARATOR + category;
}
private String toUrlPath(URL url) {
return toCategoryPath(url) + PATH_SEPARATOR + URL.encode(url.toFullString());
}
private List<URL> toUrlsWithoutEmpty(URL consumer, List<String> providers) {
List<URL> urls = new ArrayList<>();
if (CollectionUtils.isNotEmpty(providers)) {
for (String provider : providers) {
provider = URL.decode(provider);
if (provider.contains(PROTOCOL_SEPARATOR)) {
URL url;
// for jmx url
if (provider.startsWith(JMX_PROTOCOL_KEY)) {
url = URL.parseJMXServiceUrl(provider);
} else {
url = URL.valueOf(provider);
}
if (UrlUtils.isMatch(consumer, url)) {
urls.add(url);
}
}
}
}
return urls;
}
private List<URL> toUrlsWithEmpty(URL consumer, String path, List<String> providers) {
List<URL> urls = toUrlsWithoutEmpty(consumer, providers);
if (urls.isEmpty()) {
int i = path.lastIndexOf(PATH_SEPARATOR);
String category = i < 0 ? path : path.substring(i + 1);
URL empty = URLBuilder.from(consumer)
.setProtocol(EMPTY_PROTOCOL)
.addParameter(CATEGORY_KEY, category)
.build();
urls.add(empty);
}
return urls;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/zookeeper/ZookeeperTransporter.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/zookeeper/ZookeeperTransporter.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.zookeeper;
import com.webank.ai.fate.register.url.URL;
public interface ZookeeperTransporter {
ZookeeperClient connect(URL url);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/zookeeper/ZookeeperClient.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/zookeeper/ZookeeperClient.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.zookeeper;
import com.webank.ai.fate.register.common.ChildListener;
import com.webank.ai.fate.register.common.DataListener;
import com.webank.ai.fate.register.common.StateListener;
import com.webank.ai.fate.register.url.URL;
import java.util.List;
import java.util.concurrent.Executor;
public interface ZookeeperClient {
void create(String path, boolean ephemeral);
void delete(String path);
List<String> getChildren(String path);
List<String> addChildListener(String path, ChildListener listener);
void addDataListener(String path, DataListener listener);
void addDataListener(String path, DataListener listener, Executor executor);
void removeDataListener(String path, DataListener listener);
void removeChildListener(String path, ChildListener listener);
void addStateListener(StateListener listener);
void removeStateListener(StateListener listener);
boolean isConnected();
void close();
URL getUrl();
void create(String path, String content, boolean ephemeral);
String getContent(String path);
void clearAcl(String path);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/zookeeper/ZookeeperRegistryFactory.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/zookeeper/ZookeeperRegistryFactory.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.zookeeper;
import com.webank.ai.fate.register.common.AbstractRegistryFactory;
import com.webank.ai.fate.register.interfaces.Registry;
import com.webank.ai.fate.register.url.URL;
/**
* ZookeeperRegistryFactory.
*/
public class ZookeeperRegistryFactory extends AbstractRegistryFactory {
private ZookeeperTransporter zookeeperTransporter;
public void setZookeeperTransporter(ZookeeperTransporter zookeeperTransporter) {
this.zookeeperTransporter = zookeeperTransporter;
}
@Override
public Registry createRegistry(URL url) {
return new ZookeeperRegistry(url, zookeeperTransporter);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/provider/FateServer.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/provider/FateServer.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.provider;
import com.webank.ai.fate.register.annotions.RegisterService;
import com.webank.ai.fate.register.interfaces.Registry;
import io.grpc.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class FateServer extends Server {
private static final Logger logger = LoggerFactory.getLogger(FateServer.class);
public static Set<RegisterService> serviceSets = new HashSet<>();
public static Set<RegisterService> guestServiceSets = new HashSet<>();
public static Set<RegisterService> hostServiceSets = new HashSet<>();
public static Set<RegisterService> commonServiceSets = new HashSet<>();
public String project;
Server server;
private String environment;
private Registry registry;
public FateServer() {
}
public FateServer(Server server) {
this();
this.server = server;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
@Override
public Server start() throws IOException {
Server server = this.server.start();
// register();
return this;
}
@Override
public Server shutdown() {
logger.info("grpc server prepare shutdown");
// registry.destroy();
this.server.shutdown();
logger.info("grpc server shutdown!!!!!!!");
return this;
}
@Override
public Server shutdownNow() {
this.server.shutdownNow();
return this;
}
@Override
public boolean isShutdown() {
return this.server.isShutdown();
}
@Override
public boolean isTerminated() {
return this.server.isTerminated();
}
@Override
public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException {
return this.server.awaitTermination(l, timeUnit);
}
@Override
public void awaitTermination() throws InterruptedException {
this.server.awaitTermination();
}
// public static void main(String[] args){
//
// FateServer fateServer = new FateServer();
//
// FateServer.serviceRegister.put("test1","");
// FateServer.serviceRegister.put("test2","");
//
// FateServer.register();
// FateServer.lookup("test2");
//
// List<URL> cacheUrls = ((AbstractRegistry)registry).getCacheUrls(URL.valueOf("/test1"));
//
// System.err.println("cacheUrls==================="+cacheUrls);
//
//
// while(true){
//
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
//
// }
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/provider/FateNettyServerProvider.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/provider/FateNettyServerProvider.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.provider;
import io.grpc.ServerBuilder;
import io.grpc.ServerProvider;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
public class FateNettyServerProvider extends ServerProvider {
public FateNettyServerProvider() {
}
@Override
protected boolean isAvailable() {
return true;
}
@Override
protected int priority() {
return 10;
}
@Override
protected ServerBuilder<?> builderForPort(int port) {
ServerBuilder<?> serverBuilder = NettyServerBuilder.forPort(port);
FateServerBuilder fateServerBuilder = new FateServerBuilder(serverBuilder);
return fateServerBuilder;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/provider/FateServerBuilder.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/provider/FateServerBuilder.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.provider;
import com.webank.ai.fate.register.annotions.RegisterService;
import io.grpc.*;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext;
import javax.annotation.Nullable;
import java.io.File;
import java.lang.reflect.Method;
import java.net.SocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
public class FateServerBuilder extends ServerBuilder {
ServerBuilder serverBuilder;
private String partyId;
private String version;
private String project;
private String environment;
private String application;
private String zkRegisterLocation;
public FateServerBuilder(ServerBuilder serverBuilder) {
this.serverBuilder = serverBuilder;
}
public static FateServerBuilder forNettyServerBuilderAddress(SocketAddress socketAddress) {
return new FateServerBuilder(NettyServerBuilder.forAddress(socketAddress));
}
public String getPartyId() {
return partyId;
}
public FateServerBuilder setPartyId(String partyId) {
this.partyId = partyId;
return this;
}
public String getVersion() {
return version;
}
public FateServerBuilder setVersion(String version) {
this.version = version;
return this;
}
public String getProject() {
return project;
}
public FateServerBuilder setProject(String project) {
this.project = project;
return this;
}
public String getEnvironment() {
return environment;
}
public FateServerBuilder setEnvironment(String environment) {
this.environment = environment;
return this;
}
public String getApplication() {
return application;
}
public FateServerBuilder setApplication(String application) {
this.application = application;
return this;
}
public FateServerBuilder maxConcurrentCallsPerConnection(int count) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).maxConcurrentCallsPerConnection(count);
}
return this;
}
@Override
public FateServerBuilder maxInboundMessageSize(int count) {
//
// if(this.serverBuilder instanceof NettyServerBuilder){
//
// this.serverBuilder = ((NettyServerBuilder)this.serverBuilder).maxInboundMessageSize(count);
// }
this.serverBuilder.maxInboundMessageSize(count);
return this;
}
public FateServerBuilder sslContext(SslContext sslContext) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).sslContext(sslContext);
}
return this;
}
public FateServerBuilder flowControlWindow(int count) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).flowControlWindow(count);
}
return this;
}
public FateServerBuilder keepAliveTime(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).keepAliveTime(count, timeUnit);
}
return this;
}
public FateServerBuilder keepAliveTimeout(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).keepAliveTimeout(count, timeUnit);
}
return this;
}
public FateServerBuilder permitKeepAliveTime(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).permitKeepAliveTime(count, timeUnit);
}
return this;
}
public FateServerBuilder permitKeepAliveWithoutCalls(boolean permit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).permitKeepAliveWithoutCalls(permit);
}
return this;
}
public FateServerBuilder maxConnectionAge(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).maxConnectionAge(count, timeUnit);
}
return this;
}
public FateServerBuilder maxConnectionAgeGrace(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).maxConnectionAgeGrace(count, timeUnit);
}
return this;
}
@Override
public ServerBuilder directExecutor() {
serverBuilder.directExecutor();
return this;
}
@Override
public FateServerBuilder executor(@Nullable Executor executor) {
serverBuilder.executor(executor);
return this;
}
@Override
public FateServerBuilder addService(ServerServiceDefinition serverServiceDefinition) {
prepareRegister(serverServiceDefinition);
serverBuilder.addService(serverServiceDefinition);
return this;
}
public FateServerBuilder maxConnectionIdle(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).maxConnectionIdle(count, timeUnit);
}
return this;
}
public FateServerBuilder addService(ServerServiceDefinition serverServiceDefinition, Class clazz) {
prepareRegister(clazz);
serverBuilder.addService(serverServiceDefinition);
return this;
}
@Override
public FateServerBuilder addService(BindableService bindableService) {
prepareRegister(bindableService);
serverBuilder.addService(bindableService);
return this;
}
private void prepareRegister(Object service) {
Method[] methods;
if (service instanceof Class) {
methods = ((Class) service).getMethods();
} else {
methods = service.getClass().getMethods();
}
for (Method method : methods) {
doRegister(method);
}
}
private void doRegister(Method method) {
RegisterService registerService = method.getAnnotation(RegisterService.class);
if (registerService != null) {
FateServer.serviceSets.add(registerService);
switch(registerService.role()){
case HOST: FateServer.hostServiceSets.add(registerService);break;
case COMMON: FateServer.commonServiceSets.add(registerService);break;
case GUEST: FateServer.guestServiceSets.add(registerService);break;
}
}
}
@Override
public ServerBuilder fallbackHandlerRegistry(@Nullable HandlerRegistry handlerRegistry) {
serverBuilder.fallbackHandlerRegistry(handlerRegistry);
return this;
}
@Override
public ServerBuilder useTransportSecurity(File file, File file1) {
serverBuilder.useTransportSecurity(file, file1);
return this;
}
@Override
public ServerBuilder decompressorRegistry(@Nullable DecompressorRegistry decompressorRegistry) {
serverBuilder.decompressorRegistry(decompressorRegistry);
return this;
}
@Override
public ServerBuilder compressorRegistry(@Nullable CompressorRegistry compressorRegistry) {
serverBuilder.compressorRegistry(compressorRegistry);
return this;
}
public String getZkRegisterLocation() {
return zkRegisterLocation;
}
public FateServerBuilder setZkRegisterLocation(String zkRegisterLocation) {
this.zkRegisterLocation = zkRegisterLocation;
return this;
}
@Override
public Server build() {
Server server = serverBuilder.build();
FateServer fateServer = new FateServer(server);
fateServer.setEnvironment(environment);
fateServer.setProject(project);
return fateServer;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/provider/FateNameResolver.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/provider/FateNameResolver.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.provider;
import io.grpc.NameResolver;
public class FateNameResolver extends NameResolver {
@Override
public String getServiceAuthority() {
return null;
}
@Override
public void start(Listener listener) {
}
@Override
public void shutdown() {
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/AbstractLoadBalancer.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/AbstractLoadBalancer.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.loadbalance;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.url.URL;
import java.util.List;
import static com.webank.ai.fate.register.common.Constants.WEIGHT_KEY;
public abstract class AbstractLoadBalancer implements LoadBalancer {
public static int DEFAULT_WEIGHT = 100;
@Override
public List<URL> select(List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
return null;
}
if (urls.size() == 1) {
return urls;
}
return doSelect(urls);
}
protected abstract List<URL> doSelect(List<URL> url);
protected int getWeight(URL url) {
int weight = url.getParameter(WEIGHT_KEY, DEFAULT_WEIGHT);
return weight;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/LoadBalancer.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/LoadBalancer.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.loadbalance;
import com.webank.ai.fate.register.url.URL;
import java.util.List;
public interface LoadBalancer {
public List<URL> select(List<URL> urls);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/LoadBalanceModel.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/LoadBalanceModel.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.loadbalance;
public enum LoadBalanceModel {
/**
* random
*/
random,
/**
* random_with_weight
*/
random_with_weight
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/RandomLoadBalance.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/RandomLoadBalance.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.loadbalance;
import com.webank.ai.fate.register.url.URL;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class RandomLoadBalance extends AbstractLoadBalancer {
public static final String NAME = "random";
@Override
protected List<URL> doSelect(List<URL> urls) {
int length = urls.size();
boolean sameWeight = true;
int[] weights = new int[length];
int firstWeight = getWeight(urls.get(0));
weights[0] = firstWeight;
int totalWeight = firstWeight;
for (int i = 1; i < length; i++) {
int weight = getWeight(urls.get(i));
weights[i] = weight;
totalWeight += weight;
if (sameWeight && weight != firstWeight) {
sameWeight = false;
}
}
if (totalWeight > 0 && !sameWeight) {
int offset = ThreadLocalRandom.current().nextInt(totalWeight);
for (int i = 0; i < length; i++) {
offset -= weights[i];
if (offset < 0) {
return Lists.newArrayList(urls.get(i));
}
}
}
return Lists.newArrayList(urls.get(ThreadLocalRandom.current().nextInt(length)));
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/DefaultLoadBalanceFactory.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/DefaultLoadBalanceFactory.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.loadbalance;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class DefaultLoadBalanceFactory implements LoadBalancerFactory {
private static ConcurrentMap<LoadBalanceModel, LoadBalancer> loaderBalanceRegister;
static {
loaderBalanceRegister = new ConcurrentHashMap();
loaderBalanceRegister.put(LoadBalanceModel.random_with_weight, new RandomLoadBalance());
loaderBalanceRegister.put(LoadBalanceModel.random, new RandomLoadBalance());
}
@Override
public LoadBalancer getLoaderBalancer(LoadBalanceModel model) {
return loaderBalanceRegister.get(model);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/LoadBalancerFactory.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/loadbalance/LoadBalancerFactory.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.loadbalance;
public interface LoadBalancerFactory {
LoadBalancer getLoaderBalancer(LoadBalanceModel model);
}
| 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.