循环驱动模式的协议只要继承CDProtocol就OK了,peersim会在每一个cycle里在每个节点上执行nextCycle()方法; 为了获取邻接信息,必须配置IdleProtocol( implements Protocol, Linkable),这个协议是peersim.core中的核心代码。
Linkable linkable = (Linkable) node.getProtocol(linkableID) 获取IdleProtocol对象(IdleProtocol实现于linkable接口)。 上面是peersim实现cdsim的类,对于循环驱动协议只需要使用者实现CDProtocol接口就OK了: 1)CDSimulator,中是主要的cdsim实现的过程; 2)CDState,设置和获取当前的cycle即时间; 3)DeamonProtocol,这不是一个真正的protocol,提供一个可以在任何时候运行control类的方法,设置step控制运行时间。 4)FullNextCycle,每个cycle时,控制协议运行(运行协议的nextCycle方法)和更新CDState的状态。 5)NextCycle,与FullNextCycle作用一样,由private static final String PAR_NOMAIN = "simulation.nodefaultcycle";配置使用NextCycle还是FullNextCycle。NextCycle的灵活性要比FullNextCycle好,为精通的使用者使用。 6)Shuffle,顾名思义就是打乱节点在数组中的位置。 下图是CDSIM的主要过程,protocol类封装成FullNextCycle和配置的control类一起运行。 01 public class AverageFunction extends SingleValueHolder implements CDProtocol { 02 /**03 * Creates a new {@link example.aggregation.AverageFunction} protocol 04 * instance. 05 * 06 * @param prefix 07 * the component prefix declared in the configuration file. 08 */ 09 public AverageFunction(String prefix) { 10 super(prefix); 11 } 12 13 /** 14 * Using an underlying {@link Linkable} protocol choses a neighbor and 15 * performs a variance reduction step. 16 * 17 * @param node 18 * the node on which this component is run. 19 * @param protocolID 20 * the id of this protocol in the protocol array. 21 */ 22 public void nextCycle(Node node, int protocolID) { 23 int linkableID = FastConfig.getLinkable(protocolID); 24 Linkable linkable = (Linkable) node.getProtocol(linkableID); 25 if (linkable.degree() > 0) { 26 Node peer = linkable.getNeighbor(CommonState.r.nextInt(linkable 27 .degree())); 28 29 // Failure handling 30 if (!peer.isUp()) 31 return; 32 33 AverageFunction neighbor = (AverageFunction) peer 34 .getProtocol(protocolID); 35 double mean = ( this.value + neighbor.value) / 2; 36 this.value = mean; 37 neighbor.value = mean; 38 } 39 } 40 41 } 看看源码中的这个示例,这个协议实现用gossip获取整个网络中节点平均值,每一个cycle,每个节点和自己的邻居求平局值。nextCycle方法是每个cycle在每个节点中运行的。以上就是主要的CDSIM的主要过程和编程方法。 |