JAVA开发
字数统计:
580字
|
阅读时长:
3分
JAVA开发
流程
初始化模型(规则树)
将规则添加到前缀树中
提取前缀树中规则
模型更新
验证
根据端口名获取端口(不存在直接添加)
1 2 3 4 5 6
| Port p = device.getPort("default");
public Port getPort(String name) { nameToPort.putIfAbsent(name, new Port(name, this)); return this.nameToPort.get(name); }
|
规则插入树结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| public IndexedRules traverseSrc(Rule rule, ArrayList<Rule> ret, int size) { IndexedRules t = this; if (ret != null) t.read(rule, ret, size); long srcIp = rule.getSrc(); for (int i = 0; i < rule.getSrcSuffix(); i++) { long bit = (srcIp >> i) & 1;右移i位 并将其结果与1进行and运算 t = t.buildNext(bit == 0 ? 0 : 1); if (ret != null) t.read(rule, ret, size); } if (ret != null) t.exploreSrc(rule, ret, size); return t.traverse(rule, size); }
public void read(Rule rule, ArrayList<Rule> ret, int size) { if (this.dst == null) return; IndexedRules t = this.dst; if (ret != null) ret.addAll(t.getRules()); long dstIp = rule.getMatch().longValue(); for (int i = 0; i < rule.getPrefix() - (32 - size); i++) { long bit = (dstIp >> (size - 1 - i)) & 1; t = (bit == 0) ? t.left : t.right; if (t == null) return; if (ret != null) ret.addAll(t.getRules()); } if (ret != null) t.explore(ret); }
private IndexedRules buildNext(int flag) { if (flag == 0) { if (this.left == null) { this.left = new IndexedRules(); } return this.left; } else { if (this.right == null) { this.right = new IndexedRules(); } return this.right; } }
private void explore(ArrayList<Rule> ret) { if (this.left != null) this.left.explore(ret); if (this.right != null) this.right.explore(ret); ret.addAll(this.getRules()); }
public IndexedRules traverse(Rule rule, int size) { if (this.dst == null) this.dst = new IndexedRules(); IndexedRules t = this.dst;
long dstIp = rule.getMatch().longValue(); for (int i = 0; i < rule.getPrefix() - (32 - size); i++) { long bit = (dstIp >> (size - 1 - i)) & 1; t = t.buildNext(bit == 0 ? 0 : 1); } return t; }
private void exploreSrc(Rule rule, ArrayList<Rule> ret, int size) { if (this.left != null) { this.left.read(rule, ret, size); this.left.exploreSrc(rule, ret, size); } if (this.right != null) { this.right.read(rule, ret, size); this.right.exploreSrc(rule, ret, size); } }
|
模拟测试
假设存在三条转发规则
rule 1 192.168.1.1/24 port1
rule 2 192.168.1.2/16 port2
rule 3 192.168.1.1/25 port3
存在默认规则
rule default 0.0/24 default
过程
1.添加默认规则
调用traverseSrc(default, null, 32)
调用traverse(default,32)
t = t.dst
2.添加规则rule 1 rule 2 rule 3
for循环遍历规则集合[rule 1,rule 2,rule 3]
添加规则rule 1
调用traverseSrc(default, null, 32)
执行