public void testSPInterface() { SimulatorLibrary.setHash(true); SimulatorLibrary.setUtilityComputation(UtilityComputationType.outgoing); Console.WriteLine("Welcome to the short paths testing interface: "); bool exitNow = false; while (!exitNow) { Console.Write(">>"); string command = Console.ReadLine().ToLower(); string[] pieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (command.IndexOf("input") == 0) { g = input(pieces); } else if (command.IndexOf("getpath") == 0) { getpath(pieces); } else if (command.IndexOf("setstate") == 0) S = setstate(pieces); else if (command.IndexOf("init") == 0) { List<UInt32> ea = new List<uint>(); ea.Add(1239); gs = SimulatorLibrary.initGlobalState(g, ea); } else if (command.IndexOf("iterate") == 0) { List<MiniDestination> miniDs = new List<MiniDestination>(); foreach (var AS in g.GetAllNodes()) { miniDs.Add(SimulatorLibrary.initMiniDestinationSP(g,AS.NodeNum,false)); Console.WriteLine("initialized AS " + AS.NodeNum); } List<Message> results= new List<Message>(); foreach(var mD in miniDs) { results.Add(SimulatorLibrary.ComputeOnDestination(mD,gs)); Console.WriteLine("computed on: " + mD.destination); } Console.WriteLine("updating global state."); Int64[] Before = new Int64[Constants._numASNs]; Int64[] After = new Int64[Constants._numASNs]; SimulatorLibrary.updateGlobalState(ref gs, results,(float)0,ref Before,ref After); for (int i = 0; i < gs.S.Length; i++) if (gs.S[i]) Console.WriteLine("AS " + i + " is on."); } } }
public static void traverseDoD(NetworkGraph g) { //starting at 721 print out providers to DoD people. AsNode DoDMain = g.GetNode(721); List<UInt32> DoDProviders = new List<UInt32>(); List<UInt32> DoDPeers = new List<UInt32>(); List<UInt32> DoDASNs = new List<UInt32>(); Queue<UInt32> ASesToProcess = new Queue<UInt32>(); DoDASNs.Add(721); ASesToProcess.Enqueue(721); while (ASesToProcess.Count > 0) { AsNode curr = g.GetNode(ASesToProcess.Dequeue()); Console.WriteLine("Processing: " + curr.NodeNum); foreach (var provider in curr.GetNeighborsByType(RelationshipType.CustomerOf)) { if (!DoDASNs.Contains(provider.NodeNum) && !DoDProviders.Contains(provider.NodeNum)) { DoDProviders.Add(provider.NodeNum); Console.WriteLine(curr.NodeNum + " has non-DoD provider: " + provider.NodeNum); Console.ReadLine(); } } foreach (var customer in curr.GetNeighborsByType(RelationshipType.ProviderTo)) { if (!DoDASNs.Contains(customer.NodeNum) && !ASesToProcess.Contains(customer.NodeNum)) { ASesToProcess.Enqueue(customer.NodeNum); DoDASNs.Add(customer.NodeNum); } } foreach (var peer in curr.GetNeighborsByType(RelationshipType.PeerOf)) { if (!DoDASNs.Contains(peer.NodeNum)) DoDPeers.Add(peer.NodeNum); } } Console.WriteLine("DoDProviders: "); foreach (var provider in DoDProviders) { if(!DoDASNs.Contains(provider)) Console.Write(provider + ", "); } Console.WriteLine(); Console.WriteLine("DoDPeers: "); foreach (var peer in DoDPeers) Console.Write(peer + ", "); Console.WriteLine(); }
/// <summary> /// Copy constructor creates a copy of a given network graph /// </summary> public NetworkGraph(NetworkGraph otherGraph) { AsNodes = new Dictionary<UInt32, AsNode>(); EdgeCount = 0; BfsTreeDepth = 0; foreach (AsNode node in otherGraph.GetAllNodes()) { foreach (AsNode neighbor in node.GetAllNeighbors()) { AddEdge(node.NodeNum, neighbor.NodeNum, node.GetRelationshipTypeOfNeighbor(neighbor)); } } }
/// <summary> /// ADDED BY SHARON /// Looks at the path this node has in the BFS /// and returns the relationship with the first hop on this path /// /// </summary> public static RelationshipType GetPathTypeFromBfsRoot(NetworkGraph graph, UInt32 nodeNum) { AsNode node = graph.GetNode(nodeNum); // first check that the node has a path to the root if (node.BfsDepth == Int32.MaxValue) { return(RelationshipType.NullRelationship); } else // return the relationship it has with its BFS parent { return(node.BfsParentNode.GetRelationshipTypeOfNeighbor(node)); } }
/// <summary> /// Copy constructor creates a copy of a given network graph /// </summary> public NetworkGraph(NetworkGraph otherGraph) { AsNodes = new Dictionary <UInt32, AsNode>(); EdgeCount = 0; BfsTreeDepth = 0; foreach (AsNode node in otherGraph.GetAllNodes()) { foreach (AsNode neighbor in node.GetAllNeighbors()) { AddEdge(node.NodeNum, neighbor.NodeNum, node.GetRelationshipTypeOfNeighbor(neighbor)); } } }
/// <summary> /// Builds the honest tree! /// </summary> public static NetworkGraph RoutingTreeAlg(NetworkGraph graph, UInt32 rootNodeNum, ref List <UInt32>[] Best, ref List <UInt32>[] BestNew, ref List <UInt32>[][] BucketTable, ref List <UInt32>[] ChosenPath, ref UInt32[] ChosenParent, ref byte[] L, ref byte[] BestRelation) { //BFS to create the honest tree List <UInt32> nodeList = new List <UInt32>(); nodeList.Add(rootNodeNum); ExecuteBfs(graph, nodeList, false, true, RelationshipType.CustomerOf | RelationshipType.SiblingOf, ref Best, ref BestNew, ref BucketTable, ref ChosenPath, ref ChosenParent, ref L, ref BestRelation); // first stage BFS, customers and siblings ExecuteBfs(graph, nodeList, true, false, RelationshipType.PeerOf, ref Best, ref BestNew, ref BucketTable, ref ChosenPath, ref ChosenParent, ref L, ref BestRelation); // second stage BFS, peers ExecuteBfs(graph, nodeList, false, true, RelationshipType.ProviderTo | RelationshipType.SiblingOf, ref Best, ref BestNew, ref BucketTable, ref ChosenPath, ref ChosenParent, ref L, ref BestRelation); // third stage BFS, providers and siblings /* OutputLog.LogMessageNoNewline( * LogLevelType.LogLevelInfo, * "\n Routing tree algorithm on destination {0} complete. \n", rootNodeNum);*/ return(graph); }
/// <summary> /// Builds the SHORTEST PATH tree! /// </summary> public static NetworkGraph ShortestRoutingTreeAlg(NetworkGraph graph, UInt32 rootNodeNum, ref List <UInt32>[] Best, ref List <UInt32>[][] BucketTable, ref List <UInt32>[] ChosenPath, ref UInt32[] ChosenParent, ref byte[] L, ref byte[] BestRelation) { //BFS to create the honest tree List <UInt32> nodeList = new List <UInt32>(); List <UInt32>[] BestNew; BestNew = new List <UInt32> [Constants._numASNs]; nodeList.Add(rootNodeNum); ExecuteBfs(graph, nodeList, false, true, RelationshipType.NullRelationship, ref Best, ref BestNew, ref BucketTable, ref ChosenPath, ref ChosenParent, ref L, ref BestRelation); // first stage BFS, customers and siblings /* OutputLog.LogMessageNoNewline( * LogLevelType.LogLevelInfo, * "\n Routing tree algorithm on destination {0} complete. \n", rootNodeNum);*/ return(graph); }
/// <summary> /// Retrieves a path from the BFS root to the specified start node. /// The path is returned as a list of AsNode objects. /// If there is no path from the BFS root, this function returns null. /// </summary> public static List <AsNode> GetPathFromBfsRoot(NetworkGraph graph, UInt32 srcNodeNum) { // Check the input AsNode currNode = graph.GetNode(srcNodeNum); if ((currNode == null) || (currNode.BfsDepth == Int32.MaxValue)) { return(null); } // Start a list of nodes in the path List <AsNode> nodeList = new List <AsNode>(); nodeList.Insert(0, currNode); // Keep adding parents to the list until we get to the root while (currNode.BfsParentNode != null) { currNode = currNode.BfsParentNode; nodeList.Insert(0, currNode); } return(nodeList); }
/// <summary> /// ADDED BY SHARON /// Checks if a particular other node (usually the attacker) is on the path /// from the source node to the BFS root. Returns true if it is, false otherwise /// If there is no path to the BFS root, this function returns false /// </summary> public static bool isNodeOnPathFromBfsRoot(NetworkGraph graph, UInt32 srcNodeNum, UInt32 attackerNodeNum) { AsNode currNode = graph.GetNode(srcNodeNum); AsNode attackerNode = graph.GetNode(attackerNodeNum); // Check the input if ((currNode == null) || (attackerNode == null) || (currNode.BfsDepth == Int32.MaxValue)) { return(false); } //walk down path to root, checking for attacker while (currNode != null) { if (currNode.NodeNum == attackerNode.NodeNum) { return(true); } currNode = currNode.BfsParentNode; } return(false); }
/// <summary> /// Examines the BFS subtree rooted at the node specified by nodeNum and returns a list of the /// nodes in the tree. /// </summary> public static List <AsNode> GetNodesInBfsSubtree(NetworkGraph graph, UInt32 nodeNum) { // Make sure the node exists and is in the BFS tree AsNode rootNode = graph.GetNode(nodeNum); if ((rootNode == null) || (rootNode.BfsDepth == Int32.MaxValue)) { return(null); } // Running node count & list List <AsNode> nodeList = new List <AsNode>(); // Similar to BFS, but we're only going to follow edges that are BFS children Queue <AsNode> nodeQueue = new Queue <AsNode>(); nodeQueue.Enqueue(rootNode); // While there's still nodes in the sub-tree to be examined... while (nodeQueue.Count > 0) { // Dequeue a node and iterate through its BFS children AsNode currentNode = nodeQueue.Dequeue(); foreach (AsNode oppositeNode in currentNode.GetNeighborsByType(RelationshipType.BfsParentOf)) { nodeQueue.Enqueue(oppositeNode); nodeList.Add(oppositeNode); // Sanity check... current node should be the BFS parent of opposite node if (oppositeNode.BfsParentNode != currentNode) { throw new Exception("Expected current node to be parent of child node"); } } } return(nodeList); }
/// <summary> /// debugging function to give us a string representation of the path for /// a node n. /// </summary> /// <param name="n"></param> /// <returns></returns> public string GetPath(UInt32 n, NetworkGraph g) { string toreturn = ""; if (ChosenPath[n] == null) { return("no path found for this node, are you sure it exists?"); } toreturn = Convert.ToString(ChosenPath[n][0]);//first element is this node with no annotations. UInt32 lastASN = ChosenPath[n][0]; for (int i = 1; i < ChosenPath[n].Count; i++) { UInt32 ASN; int col; unjoin(ChosenPath[n][i], out ASN, out col); RelationshipType rt = g.GetNode(ASN).GetRelationshipTypeOfNeighbor(g.GetNode(lastASN)); switch (rt) { case RelationshipType.CustomerOf: toreturn = toreturn + " <- "; break; case RelationshipType.PeerOf: toreturn = toreturn + " -- "; break; case RelationshipType.ProviderTo: toreturn = toreturn + " -> "; break; } lastASN = ASN; toreturn = toreturn + ASN; } return(toreturn); }
/// <summary> /// Extension method on the NetworkGraph class that performs a [modified] BFS on the /// specified graph from the specified source ndoe. The allowedRelationships specifies /// which edges may be traversed during the BFS. /// This algorithm breaks ties by picking the node with the lower node number. /// This algorithm allows you to execute multiple BFS iterations on a single graph, with the /// constraint that any previous BFS trees created in a prior BFS run will not be modified (only /// added to). /// If limitedDiscovery is true, the BFS will only find new nodes that are 1 edge away from any existing /// BFS tree. /// If includeSibling is true, then ties are broken by first taking non-siblings over siblings. /// /// Modified by PGill Oct. 2010 to take in references to the Best, BucketTable and ChosenPaths sets. The function /// was also modified to populate these for our new sims. /// </summary> public static void ExecuteBfs(NetworkGraph graph, List<UInt32> srcNodeNums, bool limitedDiscovery, bool includeSibling, RelationshipType allowedRelationships, ref List<UInt32>[] Best, ref List<UInt32>[] BestNew, ref List<UInt32>[][] BucketTable, ref List<UInt32>[] ChosenPath, ref UInt32[] ChosenParent, ref byte[] L, ref byte[] BestRelation) { Destination utility = new Destination(); // Initialize some stuff... Queue<AsNode> nodeQueue = new Queue<AsNode>(graph.NodeCount); graph.BfsTreeNodeCount = 0; // "Visit" the source nodes foreach (UInt32 srcNodeNum in srcNodeNums) { AsNode currentNode = graph.GetNode(srcNodeNum); currentNode.InProcessBfsStatus = NodeInProcessBfsStatus.SeenInCurrentRun; currentNode.BfsDepth = 0; nodeQueue.Enqueue(currentNode); graph.BfsTreeNodeCount++; //init the destination's path to itself ChosenPath[srcNodeNum] = new List<UInt32>(); ChosenPath[srcNodeNum].Add(srcNodeNum); Best[srcNodeNum] = new List<UInt32>(); Best[srcNodeNum].Add(srcNodeNum); //if (allowedRelationships.HasFlag(RelationshipType.CustomerOf)) if ((allowedRelationships & RelationshipType.CustomerOf) == RelationshipType.CustomerOf || allowedRelationships==RelationshipType.NullRelationship) { BucketTable[0][ Destination._CUSTOMERCOLUMN] = new List<UInt32>(); BucketTable[0][ Destination._CUSTOMERCOLUMN].Add(srcNodeNum); } } // While there's still nodes to be examined... while (nodeQueue.Count > 0) { // Dequeue a node to examine. Iterate through all of its neighbors of the specified type (plus // existing BFS children) and visit them. AsNode currentNode = nodeQueue.Dequeue(); foreach (AsNode oppositeNode in currentNode.GetNeighborsByType(allowedRelationships | RelationshipType.BfsParentOf).Distinct()) { bool addedtoBest = false; // If this is the first time we've see this node, mark it and possibly enqueue it for later examination if (oppositeNode.InProcessBfsStatus == NodeInProcessBfsStatus.UnseenInCurrentRun) { // Case 1: oppositeNode is a newly discovered node, also unseen in any previous BFS runs if (oppositeNode.PriorBfsStatus == NodePriorBfsStatus.NotDiscoveredInPriorBfs) { oppositeNode.InProcessBfsStatus = NodeInProcessBfsStatus.SeenInCurrentRun; oppositeNode.BfsDepth = currentNode.BfsDepth + 1; oppositeNode.BfsParentNode = currentNode; currentNode.AddBfsChild(oppositeNode); graph.BfsTreeDepth = Math.Max(graph.BfsTreeDepth, oppositeNode.BfsDepth); graph.BfsTreeNodeCount++; if (!oppositeNode.isStub() || !OnlyNonStubs) { L[oppositeNode.NodeNum] = (byte)oppositeNode.BfsDepth; /*** add this node to the buckettable and update its chosen path, parent and BFS depth***/ //if (allowedRelationships.HasFlag(RelationshipType.CustomerOf)) -- this is .NET 4, downgraded to make comptabilte with .NET 3.5 if ((allowedRelationships & RelationshipType.CustomerOf) == RelationshipType.CustomerOf || allowedRelationships == RelationshipType.NullRelationship) { //init this spot in the bucket table (if needed) if (BucketTable[oppositeNode.BfsDepth][Destination._CUSTOMERCOLUMN] == null) BucketTable[oppositeNode.BfsDepth][Destination._CUSTOMERCOLUMN] = new List<UInt32>(); BestRelation[oppositeNode.NodeNum] = Destination._CUSTOMERCOLUMN; BucketTable[oppositeNode.BfsDepth][Destination._CUSTOMERCOLUMN].Add(oppositeNode.NodeNum); utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._CUSTOMERCOLUMN, ref ChosenPath); } //else if (allowedRelationships.HasFlag(RelationshipType.ProviderTo)) -- this is .NET 4, downgraded to make comptabilte with .NET 3.5 else if ((allowedRelationships & RelationshipType.ProviderTo) == RelationshipType.ProviderTo) { //init this spot in the bucket table (if needed) if (BucketTable[oppositeNode.BfsDepth][Destination._PROVIDERCOLUMN] == null) BucketTable[oppositeNode.BfsDepth][Destination._PROVIDERCOLUMN] = new List<UInt32>(); BestRelation[oppositeNode.NodeNum] = Destination._PROVIDERCOLUMN; BucketTable[oppositeNode.BfsDepth][Destination._PROVIDERCOLUMN].Add(oppositeNode.NodeNum); utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._PROVIDERCOLUMN, ref ChosenPath); } //else if (allowedRelationships.HasFlag(RelationshipType.PeerOf)) -- this is .NET 4, downgraded to make comptabilte with .NET 3.5 else if ((allowedRelationships & RelationshipType.PeerOf) == RelationshipType.PeerOf) { //init this spot in the bucket table (if needed) if (BucketTable[oppositeNode.BfsDepth][Destination._PEERCOLUMN] == null) BucketTable[oppositeNode.BfsDepth][Destination._PEERCOLUMN] = new List<UInt32>(); BestRelation[oppositeNode.NodeNum] = Destination._PEERCOLUMN; BucketTable[oppositeNode.BfsDepth][Destination._PEERCOLUMN].Add(oppositeNode.NodeNum); utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._PEERCOLUMN, ref ChosenPath); } /*** update this node's Best set ***/ if (Best[oppositeNode.NodeNum] == null) Best[oppositeNode.NodeNum] = new List<UInt32>(); Best[oppositeNode.NodeNum].Add(currentNode.NodeNum); ChosenParent[oppositeNode.NodeNum] = currentNode.NodeNum; if (BestNew[oppositeNode.NodeNum] == null) BestNew[oppositeNode.NodeNum] = new List<UInt32>(); UInt32 encoded = 0; UInt32 NodeNumx = currentNode.NodeNum; if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.ProviderTo) { encoded = (UInt32)((NodeNumx << 3) + Destination._PROVIDERCOLUMN); } else if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.CustomerOf || allowedRelationships == RelationshipType.NullRelationship) { encoded = (UInt32)((NodeNumx << 3) + Destination._CUSTOMERCOLUMN); } else if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.PeerOf) { encoded = (UInt32)((NodeNumx << 3) + Destination._PEERCOLUMN); } BestNew[oppositeNode.NodeNum].Add(encoded); } // If we want to continue discovering past this newly found node, enqueue it if (!limitedDiscovery) { nodeQueue.Enqueue(oppositeNode); } } // Case 2: oppositeNode was found in a prior BFS run, and the path to oppositeNode went through currentNode else if (oppositeNode.BfsParentNode == currentNode) { // Don't need to do any marking of the opposite node because it's already in the BFS tree. // Just enqueue it so we can continue our BFS from that node at some later time. oppositeNode.InProcessBfsStatus = NodeInProcessBfsStatus.SeenInCurrentRun; nodeQueue.Enqueue(oppositeNode); graph.BfsTreeDepth = Math.Max(graph.BfsTreeDepth, oppositeNode.BfsDepth); graph.BfsTreeNodeCount++; // Sanity check... the depth should be the same, right? if (oppositeNode.BfsDepth != currentNode.BfsDepth + 1) { throw new Exception("Unexpected BFS depth during BFS re-run"); } } // Case 3: oppositeNode was found in a prior BFS run, and the path to oppositeNode did NOT go through currentNode // No action necessary. We can't process oppositeNode now because we aren't allow to follow this edge. // Eventually we will hit the already-existing edge that's part of a prior BFS run, and we'll enter Case 2 above. } // We've seen this node before... else { // Did we find an alternate route to the opposite node? // We cannot change the route if this node was found in a prior BFS run. // This is where tie-breaking happens... if ((oppositeNode.InProcessBfsStatus == NodeInProcessBfsStatus.SeenInCurrentRun) && (oppositeNode.BfsDepth == (currentNode.BfsDepth + 1)) && (oppositeNode.PriorBfsStatus != NodePriorBfsStatus.DiscoveredInPriorBfs)) { // This is an alternate route... break the tie //note that current node is a potential parent of opposite node here. //equivalent to current node being one of the nodes in the tiebreak set //Console.WriteLine("Ties Breaker"); //UPDATED CONDITION TO DEAL WITH HASH FLAG if ((Hash && NewRouteWinsTieBreak(currentNode, oppositeNode, includeSibling)) || (!Hash && NewRouteWinsTieBreakOriginal(currentNode, oppositeNode, includeSibling))) { // Tie-break algorithm says we have a new, better route to this node. // We need to switch the route through the current node instead. oppositeNode.BfsParentNode.RemoveBfsChild(oppositeNode); oppositeNode.BfsParentNode = currentNode; currentNode.AddBfsChild(oppositeNode); if (!oppositeNode.isStub() || !OnlyNonStubs) { /*** update chosen parent***/ ChosenParent[oppositeNode.NodeNum] = currentNode.NodeNum; /*** update its chosen path ***/ //if (allowedRelationships.HasFlag(RelationshipType.CustomerOf)) if ((allowedRelationships & RelationshipType.CustomerOf) == RelationshipType.CustomerOf || allowedRelationships == RelationshipType.NullRelationship) utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._CUSTOMERCOLUMN, ref ChosenPath); //else if (allowedRelationships.HasFlag(RelationshipType.ProviderTo)) else if ((allowedRelationships & RelationshipType.ProviderTo) == RelationshipType.ProviderTo) utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._PROVIDERCOLUMN, ref ChosenPath); //else if (allowedRelationships.HasFlag(RelationshipType.PeerOf)) else if ((allowedRelationships & RelationshipType.PeerOf) == RelationshipType.PeerOf) utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._PEERCOLUMN, ref ChosenPath); } } /*** NEED TO UPDATE BEST SET WHETHER OR NOT THIS WINS THE TIE BREAK!! **/ if (!oppositeNode.isStub() || !OnlyNonStubs) { Best[oppositeNode.NodeNum].Add(currentNode.NodeNum); addedtoBest = true; } } } if ((Best[oppositeNode.NodeNum] != null))// && addedtoBest)// && //(oppositeNode.PriorBfsStatus != NodePriorBfsStatus.DiscoveredInPriorBfs)) { if (BestNew[oppositeNode.NodeNum] == null) BestNew[oppositeNode.NodeNum] = new List<UInt32>(); UInt32 encoded = 0; UInt32 NodeNumx = currentNode.NodeNum; if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.ProviderTo) { encoded = (UInt32)((NodeNumx << 3) + Destination._PROVIDERCOLUMN); } else if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.CustomerOf || allowedRelationships == RelationshipType.NullRelationship) { encoded = (UInt32)((NodeNumx << 3) + Destination._CUSTOMERCOLUMN); } else if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.PeerOf) { encoded = (UInt32)((NodeNumx << 3) + Destination._PEERCOLUMN); } UInt32 encoded0 = (UInt32)((NodeNumx << 3) + Destination._PROVIDERCOLUMN); UInt32 encoded1 = (UInt32)((NodeNumx << 3) + Destination._CUSTOMERCOLUMN); UInt32 encoded2 = (UInt32)((NodeNumx << 3) + Destination._PEERCOLUMN); if (!((BestNew[oppositeNode.NodeNum].Exists(element => element == encoded0)) || (BestNew[oppositeNode.NodeNum].Exists(element => element == encoded1)) || (BestNew[oppositeNode.NodeNum].Exists(element => element == encoded2)))) { //Console.WriteLine(oppositeNode.NodeNum + "--> Entered for: " + ((UInt32)(((uint)encoded) >> 3) + " relation: " + (int)(encoded & 7))); //Console.WriteLine("encoded = " + encoded); if (encoded != 0) { //Console.WriteLine(oppositeNode.NodeNum + "--> Entered for: " + ((UInt32)(((uint)encoded) >> 3) + " relation: " + (int)(encoded & 7))); //if ((((allowedRelationships & RelationshipType.ProviderTo) == RelationshipType.ProviderTo) && oppositeNode.InProcessBfsStatus == NodeInProcessBfsStatus.ProcessedInCurrentRun)) //{ // Console.Write("Rel: " + allowedRelationships + " & Node status: " + oppositeNode.InProcessBfsStatus + "\n"); //} //else { BestNew[oppositeNode.NodeNum].Add(encoded); } } } } } // Update the in-process BFS status currentNode.InProcessBfsStatus = NodeInProcessBfsStatus.ProcessedInCurrentRun; } // Finished the BFS... lock the discovered nodes into the BFS tree foreach (AsNode node in graph.GetAllNodes()) { // FYI In limitedDiscovery mode, some nodes may have been left in the SeenInCurrentRun state // (instead of ProcessedInCurrentRun). if (node.InProcessBfsStatus != NodeInProcessBfsStatus.UnseenInCurrentRun) { node.PriorBfsStatus = NodePriorBfsStatus.DiscoveredInPriorBfs; } node.InProcessBfsStatus = NodeInProcessBfsStatus.UnseenInCurrentRun; } }
/// <summary> /// Builds the honest tree! /// </summary> public static NetworkGraph RoutingTreeAlg(NetworkGraph graph, UInt32 rootNodeNum, ref List<UInt32>[] Best, ref List<UInt32>[] BestNew, ref List<UInt32>[][] BucketTable, ref List<UInt32>[] ChosenPath, ref UInt32[] ChosenParent, ref byte[] L, ref byte[] BestRelation) { //BFS to create the honest tree List<UInt32> nodeList = new List<UInt32>(); nodeList.Add(rootNodeNum); ExecuteBfs(graph, nodeList, false, true, RelationshipType.CustomerOf | RelationshipType.SiblingOf, ref Best, ref BestNew, ref BucketTable, ref ChosenPath, ref ChosenParent, ref L, ref BestRelation); // first stage BFS, customers and siblings ExecuteBfs(graph, nodeList, true, false, RelationshipType.PeerOf, ref Best, ref BestNew, ref BucketTable, ref ChosenPath, ref ChosenParent, ref L, ref BestRelation); // second stage BFS, peers ExecuteBfs(graph, nodeList, false, true, RelationshipType.ProviderTo | RelationshipType.SiblingOf, ref Best, ref BestNew, ref BucketTable, ref ChosenPath, ref ChosenParent, ref L, ref BestRelation); // third stage BFS, providers and siblings /* OutputLog.LogMessageNoNewline( LogLevelType.LogLevelInfo, "\n Routing tree algorithm on destination {0} complete. \n", rootNodeNum);*/ return graph; }
/// <summary> /// Builds the SHORTEST PATH tree! /// </summary> public static NetworkGraph ShortestRoutingTreeAlg(NetworkGraph graph, UInt32 rootNodeNum, ref List<UInt32>[] Best, ref List<UInt32>[][] BucketTable, ref List<UInt32>[] ChosenPath, ref UInt32[] ChosenParent, ref byte[] L, ref byte[] BestRelation) { //BFS to create the honest tree List<UInt32> nodeList = new List<UInt32>(); List<UInt32>[] BestNew; BestNew = new List<UInt32>[Constants._numASNs]; nodeList.Add(rootNodeNum); ExecuteBfs(graph, nodeList, false, true, RelationshipType.NullRelationship, ref Best, ref BestNew, ref BucketTable, ref ChosenPath, ref ChosenParent, ref L, ref BestRelation); // first stage BFS, customers and siblings /* OutputLog.LogMessageNoNewline( LogLevelType.LogLevelInfo, "\n Routing tree algorithm on destination {0} complete. \n", rootNodeNum);*/ return graph; }
public void CLI(bool script) { bool debug = false; bool decoy_sim = false; string resp; List<Destination> d = new List<Destination>(); NetworkGraph g = new NetworkGraph(); Worker w = new Worker(); bool[] S = new bool[Constants._numASNs]; for (int i = 0; i < S.Length; i++) S[i] = false; GlobalState globalState = new GlobalState(); globalState.S = S; StreamReader input = new StreamReader( Console.OpenStandardInput()); if (script) { Console.WriteLine("You have selected to run a script, please enter the file name:"); string scriptfile = Console.ReadLine(); if (!File.Exists(scriptfile)) Console.WriteLine("script file: " + scriptfile + " did not exist, entering interactive mode"); else input = new StreamReader(scriptfile); } globalState.W = new UInt16[Constants._numASNs]; for (int i = 0; i < globalState.W.Length; i++) globalState.W[i] = 1; Console.WriteLine("Welcome to the testing interface: (type help for help) Haseeb Mac"); bool exitNow = false; //Automatcally load Cyclops_caida.txt if (decoy_sim) { String load = "inputfile decoy/Cyclops_poison.txt"; initGraph(ref g, load); globalState.nonStubs = g.getNonStubs(); Console.WriteLine("Cyclops_poison.txt Loaded!"); } else { String load = "inputfile Cyclops_caida_new.txt"; initGraph(ref g, load); globalState.nonStubs = g.getNonStubs(); Console.WriteLine("Cyclops_caida_new.txt Loaded!"); } //DEBUG if (debug) { String debugC = "analysepathfile test.txt"; analysePathfile (ref g, debugC); exitNow = true; } else if (decoy_sim) { string dst; using (StreamReader reader = new StreamReader("decoy/helper.txt")) { dst = reader.ReadLine(); } String decoyC = "all_path_info " + dst; all_path_info(ref d, ref g, decoyC); exitNow = true; } while(!exitNow) { if (input.EndOfStream) { input.Close(); input = new StreamReader(Console.OpenStandardInput()); Console.WriteLine("script has ended, now in interactive mode"); } Console.Write(">>"); string command = input.ReadLine().ToLower(); if (command.IndexOf ("input") == 0) { initGraph (ref g, command); globalState.nonStubs = g.getNonStubs (); } else if (command.IndexOf ("destination") == 0) { if (command.IndexOf ("all") < 0) { Destination newD = new Destination (); if (initDestination (ref g, ref newD, command)) { d.Add (newD); Console.WriteLine ("initialized and added " + newD.destination); } } else { IEnumerable<AsNode> allASes = g.GetAllNodes (); foreach (AsNode AS in allASes) { Destination newD = new Destination (); if (initDestination (ref g, ref newD, "destination " + AS.NodeNum)) { d.Add (newD); Console.WriteLine ("initialized and added " + newD.destination); } } } } else if (command.IndexOf ("resultsexplorer") == 0) { ResultsExplorer res = new ResultsExplorer (); res.ResultsInterface (); } else if (command.IndexOf ("setstate") == 0) initS (ref globalState.S, command); else if (command.IndexOf ("addedges") == 0) addEdges (command, ref g); else if (command.IndexOf ("getlink") == 0) getLink (command, ref g); else if (command.IndexOf ("flipallu") == 0) flipallU (ref d, ref g, ref globalState, command); else if (command.IndexOf ("printstate") == 0) printState (ref globalState.S, command); else if (command.IndexOf ("printsecp") == 0) printSecP (ref d, command); else if (command.IndexOf ("getl") == 0) getL (ref d, command); else if (command.IndexOf ("getw") == 0) getW (ref globalState.W, command); else if (command.IndexOf ("printw") == 0) printWeight (ref globalState.W, command); else if (command.IndexOf ("setw") == 0) setW (ref globalState.W, command); else if (command.IndexOf ("getbestnew") == 0) getBestNew (ref d, command); else if (command.IndexOf ("getbest") == 0) getBest (ref d, command); else if (command.IndexOf ("all_path_info") == 0) all_path_info (ref d, ref g, command); else if (command.IndexOf ("getpath") == 0) getPath (ref d, ref g, command); else if (command.IndexOf ("analysepathfile") == 0) analysePathfile (ref g, command); else if (command.IndexOf ("analysepath") == 0) analysePath (ref g, command); else if (command.IndexOf ("serialise") == 0) serialisePathArrays (ref g, command); else if (command.IndexOf ("getallpathsoflength") == 0) getAllPathsoflength (ref d, ref g, command); else if (command.IndexOf ("getallpathsto") == 0) getAllPathsTo (ref d, ref g, command); else if (command.IndexOf ("getallpaths") == 0) getAllPaths (ref d, ref g, command); else if (command.IndexOf("getsecp") == 0) getSecP(ref d, command); else if (command.IndexOf("getutility") == 0) getUtility(ref d, command); else if (command.IndexOf("onlynonstubs") == 0) SimulatorLibrary.setOnlyStubs(true); else if (command.IndexOf("notonlynonstubs") == 0) SimulatorLibrary.setOnlyStubs(false); else if (command.IndexOf("iterateall") == 0) iterateAll(ref d, ref g, ref globalState, command); else if (command.IndexOf("iterate") == 0) iterate(ref d, ref globalState, command); else if (command.IndexOf("not") == 0) computeNotN(ref d, ref globalState, ref w, command); else if (command.IndexOf("wgetsecp") == 0) getWorkerSecP(ref w, command); else if (command.IndexOf("checkpath") == 0) checkPath(command); else if (command.IndexOf("initglobalstate") == 0) initGlobalState(command, ref g, ref globalState); else if (command.IndexOf("wgetpath") == 0) getWorkerPath(ref w, command); else if (command.IndexOf("wgetparent") == 0) getWorkerParent(ref w, command); else if (command.IndexOf("printbuckettable") == 0) printBucketTable(ref d, command); else if (command.IndexOf("compareu") == 0) compareU(ref d, ref globalState, ref g, command); else if (command.IndexOf("flipu") == 0) flipU(ref d, ref g, ref globalState, command); else if (command.IndexOf("getnonstubs") == 0) printnonstubs(ref g); else if (command.IndexOf("getstubs") == 0) printstubs(ref g); else if (command.IndexOf("turnonstubs") == 0) turnOnStubs(ref g, ref globalState.S); else if (command.IndexOf("getcustomers") == 0) getcustomers(ref g, command); else if (command.IndexOf("getpeers") == 0) getpeers(ref g, command); else if (command.IndexOf("getproviders") == 0) getproviders(ref g, command); else if (command.IndexOf("gets") == 0) //must be tested for after getsecp getS(ref globalState.S, command); else if (command.IndexOf("sets") == 0) //this must be tested for *after* the test for setstate setS(ref globalState.S, command); else if (command.IndexOf("computehash") == 0) computeHash(command); else if (command.IndexOf("setutilitycomputation") == 0) setUtilityComputation(command); else if (command.IndexOf("numberon") == 0) numberOn(ref globalState.S); else if (command.IndexOf("getaveragebest") == 0) getAverageBest(command, ref d); else if (command.IndexOf("nodeswithnopath") == 0) nodesWithNoPath(command, ref d, ref g); else if (command.IndexOf("traversedod") == 0) DoDAnaly.traverseDoD(g); else if (command.IndexOf("clear") == 0) { Console.WriteLine("clearing state of graph, destination, S and worker."); g = new NetworkGraph(); for (int i = 0; i < S.Length; i++) S[i] = false; d = new List<Destination>(); w = new Worker(); } else if (command.IndexOf("help") == 0) help(); else if (command.IndexOf("list") == 0) { Console.WriteLine("printing current directory contents:"); string[] dirContents = Directory.GetFiles("."); foreach (string s in dirContents) Console.WriteLine(s); } else if (command.IndexOf("exit") == 0) exitNow = true; Console.Write(">>"); } input.Close(); }
private bool all_path_info(ref List<Destination> ds, ref NetworkGraph graph, string command) { TextWriter tw = new StreamWriter("decoy/all_path_info.txt"); string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 2) { Console.WriteLine("error: usage all_path_info <dstnum>"); return false; } int dstNum; if (!int.TryParse(cpieces[1],out dstNum)) { Console.WriteLine("invalid destination."); return false; } Destination newD = new Destination(); if (initDestination (ref graph, ref newD, "destination " + dstNum)) { ds.Add (newD); Console.WriteLine ("HN: initialized and added " + newD.destination); } else { Console.WriteLine ("could not find destination"); return false; } var lines = File.ReadAllLines("decoy/all_asn.txt"); foreach (var line in lines) { UInt32 ASN = Convert.ToUInt32(line); tw.WriteLine(ASN + " " + newD.GetPath(ASN)); } return true; }
private static void printDiamond(UInt32 pointASN, UInt32 stub, List <UInt32> competitors, SecureSimulator.NetworkGraph g, StreamWriter output) { SecureSimulator.AsNode pointASNode = g.GetNode(pointASN); SecureSimulator.AsNode stubASNode = g.GetNode(stub); foreach (UInt32 c in competitors) { SecureSimulator.AsNode cASNode = g.GetNode(c); output.WriteLine("{0} {1} {2} {3} {4}", pointASN, relationshipToString(cASNode.GetRelationshipTypeOfNeighbor(pointASNode)), c, relationshipToString(stubASNode.GetRelationshipTypeOfNeighbor(cASNode)), stub); } }
/// <summary> /// this is hardcoded to be like fig. 20 in the Feb version of the sigcomm 2010 paper. /// </summary> /// <returns></returns> public NetworkGraph getTestGraph() { NetworkGraph testGraph = new NetworkGraph(); testGraph.AddEdge(1, 2, RelationshipType.PeerOf); testGraph.AddEdge(2, 1, RelationshipType.PeerOf); testGraph.AddEdge(1, 3, RelationshipType.CustomerOf); testGraph.AddEdge(3, 1, RelationshipType.ProviderTo); testGraph.AddEdge(1, 9, RelationshipType.ProviderTo); testGraph.AddEdge(9, 1, RelationshipType.CustomerOf); testGraph.AddEdge(1, 4, RelationshipType.PeerOf); testGraph.AddEdge(4, 1, RelationshipType.PeerOf); testGraph.AddEdge(3, 4, RelationshipType.ProviderTo); testGraph.AddEdge(4, 3, RelationshipType.CustomerOf); testGraph.AddEdge(3, 7, RelationshipType.ProviderTo); testGraph.AddEdge(7, 3, RelationshipType.CustomerOf); testGraph.AddEdge(7, 4, RelationshipType.PeerOf); testGraph.AddEdge(4, 7, RelationshipType.PeerOf); testGraph.AddEdge(4, 8, RelationshipType.ProviderTo); testGraph.AddEdge(8, 4, RelationshipType.CustomerOf); testGraph.AddEdge(2, 9, RelationshipType.ProviderTo); testGraph.AddEdge(9, 2, RelationshipType.CustomerOf); testGraph.AddEdge(2, 5, RelationshipType.PeerOf); testGraph.AddEdge(5, 2, RelationshipType.PeerOf); testGraph.AddEdge(2, 6, RelationshipType.ProviderTo); testGraph.AddEdge(6, 2, RelationshipType.CustomerOf); testGraph.AddEdge(5, 6, RelationshipType.ProviderTo); testGraph.AddEdge(6, 5, RelationshipType.CustomerOf); return testGraph; }
private bool getAllPathsoflength(ref List<Destination> ds, ref NetworkGraph graph, string command) { string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 4) { Console.WriteLine("error: usage getallpathsoflength <length> <as#> <dstnum>"); return false; } int dstNum, length; UInt32 ASN; if (!UInt32.TryParse(cpieces[2], out ASN) || !int.TryParse(cpieces[3], out dstNum) || !int.TryParse(cpieces[1], out length)) { Console.WriteLine("invalid ASN or destination or length."); return false; } Destination newD = new Destination(); if (initDestination(ref graph, ref newD, "destination " + dstNum)) { ds.Add(newD); Console.WriteLine("HN: initialized and added " + newD.destination); } foreach (Destination d in ds) { if (d.destination == dstNum) { if (d.BestNew[ASN] != null) { //d.Best[0]++; List<List<UInt32>> allPaths = new List<List<UInt32>>(); List<UInt32> pathNew = new List<UInt32>(); UInt32 first = (UInt32)((ASN << 3) + Destination._NOREL); pathNew.Add(first); //Console.Write("First: " + (UInt32)(((uint)first) >> 3) + "\n"); string fileName = "all_paths_of_length_"+ length + "_" + ASN + "-" + d.destination + ".txt"; //if (!Directory.Exists(d.destination + "\\")) //{ // Try to create the directory. // DirectoryInfo di = Directory.CreateDirectory(d.destination + "\\"); //} TextWriter tw = new StreamWriter(fileName); int count = 0; int counter = 0; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); d.GetAllPaths(ASN, (UInt32)dstNum, ref allPaths, pathNew, ref tw, ref count); for (int j = 0; j < allPaths.Count; j++) { if (allPaths [j].Count == length) { tw.WriteLine (pathString (allPaths [j])); counter++; } } allPaths.Clear(); Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); stopwatch.Reset(); tw.Close(); d.totalCount = d.totalCount + count; if (count == 0) { File.Delete(fileName); } //writePathsToFile(allPaths); Console.WriteLine(counter + " Number of paths found from " + ASN + " to " + dstNum); return true; } else { Console.WriteLine("No path from " + ASN); } } } Console.WriteLine("could not find destination"); return false; }
private bool getAllPathsTo(ref List<Destination> ds, ref NetworkGraph graph, string command) { string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 2) { Console.WriteLine("error: usage getallpathsto <dstnum>"); return false; } int dstNum; if (!int.TryParse(cpieces[1], out dstNum)) { Console.WriteLine("invalid destination."); return false; } Destination newD = new Destination(); if (initDestination(ref graph, ref newD, "destination " + dstNum)) { newD.totalCount = 0; ds.Add(newD); Console.WriteLine("HN: initialized and added " + newD.destination); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = Constants._numASNs-1; i >= 0 ; i--) { if (i != newD.destination) { string com = "getallpaths " + i + " " + dstNum; getAllPaths(ref ds, ref graph, com); Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); } } TextWriter tw = new StreamWriter("time.txt"); // write a line of text to the file tw.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); tw.WriteLine("Total Paths Computed: " + newD.totalCount); stopwatch.Reset(); // close the stream tw.Close(); ds.Remove(newD); return true; } Console.WriteLine("could not find destination"); return false; }
private bool flipallU(ref List<Destination> ds, ref NetworkGraph g, ref GlobalState globalState, string command) { Console.WriteLine("Flipping state:"); string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 1) { Console.WriteLine("usage: flipallu <quiet?>"); return false; } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); List<UInt32> toflip = new List<UInt32>(); bool quiet = false; if (command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length > 1) { quiet = true; Console.WriteLine("you have selected quiet mode"); } List<UInt32> nonstubs = g.getNonStubs(); Int64[] deltaU = new Int64[Constants._numASNs]; for (int i = 0; i < deltaU.Length; i++) deltaU[i] = 0; foreach (Destination d in ds) { foreach (UInt32 ASN in nonstubs) { if (d.Best[ASN] != null)//make sure this AS has a route to our destination { Worker w = new Worker(); int notASN = w.ComputeUtility(d.BucketTable, d.Best, d.ChosenParent, d.SecP, globalState.S, ASN, d.L[ASN], d.BestRelation[ASN], globalState.W); deltaU[ASN] += (notASN - d.U[ASN]); } } } int flipped = 0; for (int ASN = 0; ASN < deltaU.Length;ASN++ ) { if (deltaU[ASN] > 0)//positive change in utility for this ASN { flipped++; if (globalState.S[ASN]) Console.WriteLine("AS: " + ASN + " is rolling back!!!"); globalState.S[ASN] = !globalState.S[ASN]; if (!quiet) { Console.WriteLine("AS: " + ASN + " had change in utility of " + deltaU[ASN]); } } } stopwatch.Stop(); Console.WriteLine("flip u took " + stopwatch.ElapsedMilliseconds + " ms"); Console.WriteLine("it flipped " + flipped + " ASes"); return true; }
private bool flipU(ref List<Destination> ds, ref NetworkGraph g, ref GlobalState globalState,string command) { Console.WriteLine("Flipping state:"); string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 2) { Console.WriteLine("usage: flipu <d> <quiet?>"); return false; } Destination d = new Destination(); UInt32 destNum; if (!UInt32.TryParse(cpieces[1], out destNum)) { Console.WriteLine("invalid destination number"); return false; } foreach (Destination curr in ds) { if (curr.destination == destNum) d = curr; } if (d.BucketTable == null) { Console.WriteLine("null bucket table!"); return false; } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); List<UInt32> toflip = new List<UInt32>(); bool quiet = false; if (command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length > 2) { quiet = true; Console.WriteLine("you have selected quiet mode"); } List<UInt32> nonstubs = g.getNonStubs(); foreach (UInt32 ASN in nonstubs) { if (d.Best[ASN] != null)//make sure this AS has a route to our destination { Worker w = new Worker(); int notASN = w.ComputeUtility(d.BucketTable, d.Best, d.ChosenParent, d.SecP, globalState.S, ASN, d.L[ASN], d.BestRelation[ASN], globalState.W); if (d.U[ASN] < notASN) { if (!quiet) Console.WriteLine("AS: " + ASN + " from " + globalState.S[ASN] + " to " + !globalState.S[ASN]); toflip.Add(ASN);//don't flip on the fly it messes up everyones calculations, do it at the end. } } } foreach (int ASN in toflip) { if (globalState.S[ASN]) Console.WriteLine("AS: " + ASN + " is rolling back!!!"); globalState.S[ASN] = !globalState.S[ASN]; } stopwatch.Stop(); Console.WriteLine("flip u took " + stopwatch.ElapsedMilliseconds + " ms"); Console.WriteLine("it flipped " + toflip.Count + " ASes"); return true; }
private bool compareU(ref List<Destination> ds, ref GlobalState globalState,ref NetworkGraph g,string command) { string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 2) { Console.WriteLine("usage: compareu <d> <onlybenefit?>"); return false; } /** first off try to parse out a specific destination (or all) **/ UInt32 destNum; if (!UInt32.TryParse(cpieces[1], out destNum) && !cpieces[1].Equals("all")) { Console.WriteLine("invalid destination number"); return false; } List<Destination> destinationsToCompare = new List<Destination>(); if (cpieces[1].Equals("all")) { //want to run on all destinations. destinationsToCompare = ds; } else { foreach (Destination curr in ds) { if (curr.destination == destNum) destinationsToCompare.Add(curr); } } /** next see if we have been asked only for nodes that benefit **/ bool onlybenefit = false; if (command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length > 2) { Console.WriteLine("you've chosen to only display ASes that benefit"); onlybenefit = true; } List<UInt32> nonstubs = g.getNonStubs(); Worker w = new Worker(); foreach (Destination d in destinationsToCompare) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Console.WriteLine("Destination : " + d.destination); Console.WriteLine("ASN :: U(before) : U(flipped)"); runCompareU(nonstubs, d, ref w, onlybenefit,ref globalState); stopwatch.Stop(); Console.WriteLine("compare u took " + stopwatch.ElapsedMilliseconds + " ms"); } return true; }
private void analysePathfile(ref NetworkGraph graph, string command) { string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 2) { Console.WriteLine("error: usage analysepathfile <filename>"); return; } TextWriter tw = new StreamWriter("result_bucket.txt"); TextWriter twViolation = new StreamWriter("violation_bucket.txt"); TextWriter twMissing = new StreamWriter("missing_bucket.txt"); TextWriter twRandom = new StreamWriter("random_file.txt"); //for (int i = 0; i < allPaths.Count; i++) //{ // tw.WriteLine(pathString(allPaths[i])); //} //tw.Close(); using (var reader = new StreamReader(cpieces[1])) { PathChecker pathChecker = new PathChecker(); Destination newD2 = new Destination(); initDestination(ref graph, ref newD2, "destination " + "1"); string line; while ((line = reader.ReadLine()) != null) { string[] lpieces = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (lpieces.Length == 2) { int dstNum; string path = lpieces[1]; if (!int.TryParse(lpieces[0], out dstNum)) { Console.WriteLine("invalid destination. " + lpieces[0]); continue; } if (dstNum > Constants._numASNs) { continue; } if (dstNum != newD2.destination) { try { initDestination(ref graph, ref newD2, "destination " + dstNum); } catch (Exception x) { Console.Out.WriteLine("Exception computing dest: " + dstNum); continue; } } try { string result = pathChecker.pathAnalysis(path, ref newD2, ref twMissing, ref twRandom, ref twViolation); tw.WriteLine(result); tw.Flush(); } catch (Exception y) { Console.Out.WriteLine("Exception analysing path: " + path); continue; } } } } tw.Close(); twMissing.Close(); twRandom.Close(); }
private bool analysePath(ref NetworkGraph graph, string command) { string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 3) { Console.WriteLine("error: usage analysepath <dstnum> <path>"); return false; } int dstNum; string path = cpieces[2]; if (!int.TryParse(cpieces[1], out dstNum)) { Console.WriteLine("invalid destination."); return false; } PathChecker pathChecker = new PathChecker(); if (dstNum > Constants._numASNs) { return false; } Destination newD2 = new Destination(); if (initDestination(ref graph, ref newD2, "destination " + dstNum)) { Console.WriteLine("HN: initialized " + newD2.destination); pathChecker.pathAnalysis(path, ref newD2); return true; } return false; }
private NetworkGraph input(string[] pieces) { if (pieces.Length < 2) { return null; } NetworkGraph g = new NetworkGraph(); if (!File.Exists(pieces[1])) pieces[1] = "C:\\Users\\phillipa\\Desktop\\adoptTraffic\\AugmentedGraphs\\" + pieces[1]; if (File.Exists(pieces[1])) { InputFileReader ifr = new InputFileReader(pieces[1], g); ifr.ProcessFile(); Console.WriteLine("read graph: " + g.EdgeCount + " edges " + g.NodeCount + " nodes"); return g; } return null; }
/// <summary> /// Extension method on the NetworkGraph class that performs a [modified] BFS on the /// specified graph from the specified source ndoe. The allowedRelationships specifies /// which edges may be traversed during the BFS. /// This algorithm breaks ties by picking the node with the lower node number. /// This algorithm allows you to execute multiple BFS iterations on a single graph, with the /// constraint that any previous BFS trees created in a prior BFS run will not be modified (only /// added to). /// If limitedDiscovery is true, the BFS will only find new nodes that are 1 edge away from any existing /// BFS tree. /// If includeSibling is true, then ties are broken by first taking non-siblings over siblings. /// /// Modified by PGill Oct. 2010 to take in references to the Best, BucketTable and ChosenPaths sets. The function /// was also modified to populate these for our new sims. /// </summary> public static void ExecuteBfs(NetworkGraph graph, List <UInt32> srcNodeNums, bool limitedDiscovery, bool includeSibling, RelationshipType allowedRelationships, ref List <UInt32>[] Best, ref List <UInt32>[] BestNew, ref List <UInt32>[][] BucketTable, ref List <UInt32>[] ChosenPath, ref UInt32[] ChosenParent, ref byte[] L, ref byte[] BestRelation) { Destination utility = new Destination(); // Initialize some stuff... Queue <AsNode> nodeQueue = new Queue <AsNode>(graph.NodeCount); graph.BfsTreeNodeCount = 0; // "Visit" the source nodes foreach (UInt32 srcNodeNum in srcNodeNums) { AsNode currentNode = graph.GetNode(srcNodeNum); currentNode.InProcessBfsStatus = NodeInProcessBfsStatus.SeenInCurrentRun; currentNode.BfsDepth = 0; nodeQueue.Enqueue(currentNode); graph.BfsTreeNodeCount++; //init the destination's path to itself ChosenPath[srcNodeNum] = new List <UInt32>(); ChosenPath[srcNodeNum].Add(srcNodeNum); Best[srcNodeNum] = new List <UInt32>(); Best[srcNodeNum].Add(srcNodeNum); //if (allowedRelationships.HasFlag(RelationshipType.CustomerOf)) if ((allowedRelationships & RelationshipType.CustomerOf) == RelationshipType.CustomerOf || allowedRelationships == RelationshipType.NullRelationship) { BucketTable[0][Destination._CUSTOMERCOLUMN] = new List <UInt32>(); BucketTable[0][Destination._CUSTOMERCOLUMN].Add(srcNodeNum); } } // While there's still nodes to be examined... while (nodeQueue.Count > 0) { // Dequeue a node to examine. Iterate through all of its neighbors of the specified type (plus // existing BFS children) and visit them. AsNode currentNode = nodeQueue.Dequeue(); foreach (AsNode oppositeNode in currentNode.GetNeighborsByType(allowedRelationships | RelationshipType.BfsParentOf).Distinct()) { bool addedtoBest = false; // If this is the first time we've see this node, mark it and possibly enqueue it for later examination if (oppositeNode.InProcessBfsStatus == NodeInProcessBfsStatus.UnseenInCurrentRun) { // Case 1: oppositeNode is a newly discovered node, also unseen in any previous BFS runs if (oppositeNode.PriorBfsStatus == NodePriorBfsStatus.NotDiscoveredInPriorBfs) { oppositeNode.InProcessBfsStatus = NodeInProcessBfsStatus.SeenInCurrentRun; oppositeNode.BfsDepth = currentNode.BfsDepth + 1; oppositeNode.BfsParentNode = currentNode; currentNode.AddBfsChild(oppositeNode); graph.BfsTreeDepth = Math.Max(graph.BfsTreeDepth, oppositeNode.BfsDepth); graph.BfsTreeNodeCount++; if (!oppositeNode.isStub() || !OnlyNonStubs) { L[oppositeNode.NodeNum] = (byte)oppositeNode.BfsDepth; /*** add this node to the buckettable and update its chosen path, parent and BFS depth***/ //if (allowedRelationships.HasFlag(RelationshipType.CustomerOf)) -- this is .NET 4, downgraded to make comptabilte with .NET 3.5 if ((allowedRelationships & RelationshipType.CustomerOf) == RelationshipType.CustomerOf || allowedRelationships == RelationshipType.NullRelationship) { //init this spot in the bucket table (if needed) if (BucketTable[oppositeNode.BfsDepth][Destination._CUSTOMERCOLUMN] == null) { BucketTable[oppositeNode.BfsDepth][Destination._CUSTOMERCOLUMN] = new List <UInt32>(); } BestRelation[oppositeNode.NodeNum] = Destination._CUSTOMERCOLUMN; BucketTable[oppositeNode.BfsDepth][Destination._CUSTOMERCOLUMN].Add(oppositeNode.NodeNum); utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._CUSTOMERCOLUMN, ref ChosenPath); } //else if (allowedRelationships.HasFlag(RelationshipType.ProviderTo)) -- this is .NET 4, downgraded to make comptabilte with .NET 3.5 else if ((allowedRelationships & RelationshipType.ProviderTo) == RelationshipType.ProviderTo) { //init this spot in the bucket table (if needed) if (BucketTable[oppositeNode.BfsDepth][Destination._PROVIDERCOLUMN] == null) { BucketTable[oppositeNode.BfsDepth][Destination._PROVIDERCOLUMN] = new List <UInt32>(); } BestRelation[oppositeNode.NodeNum] = Destination._PROVIDERCOLUMN; BucketTable[oppositeNode.BfsDepth][Destination._PROVIDERCOLUMN].Add(oppositeNode.NodeNum); utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._PROVIDERCOLUMN, ref ChosenPath); } //else if (allowedRelationships.HasFlag(RelationshipType.PeerOf)) -- this is .NET 4, downgraded to make comptabilte with .NET 3.5 else if ((allowedRelationships & RelationshipType.PeerOf) == RelationshipType.PeerOf) { //init this spot in the bucket table (if needed) if (BucketTable[oppositeNode.BfsDepth][Destination._PEERCOLUMN] == null) { BucketTable[oppositeNode.BfsDepth][Destination._PEERCOLUMN] = new List <UInt32>(); } BestRelation[oppositeNode.NodeNum] = Destination._PEERCOLUMN; BucketTable[oppositeNode.BfsDepth][Destination._PEERCOLUMN].Add(oppositeNode.NodeNum); utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._PEERCOLUMN, ref ChosenPath); } /*** update this node's Best set ***/ if (Best[oppositeNode.NodeNum] == null) { Best[oppositeNode.NodeNum] = new List <UInt32>(); } Best[oppositeNode.NodeNum].Add(currentNode.NodeNum); ChosenParent[oppositeNode.NodeNum] = currentNode.NodeNum; if (BestNew[oppositeNode.NodeNum] == null) { BestNew[oppositeNode.NodeNum] = new List <UInt32>(); } UInt32 encoded = 0; UInt32 NodeNumx = currentNode.NodeNum; if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.ProviderTo) { encoded = (UInt32)((NodeNumx << 3) + Destination._PROVIDERCOLUMN); } else if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.CustomerOf || allowedRelationships == RelationshipType.NullRelationship) { encoded = (UInt32)((NodeNumx << 3) + Destination._CUSTOMERCOLUMN); } else if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.PeerOf) { encoded = (UInt32)((NodeNumx << 3) + Destination._PEERCOLUMN); } BestNew[oppositeNode.NodeNum].Add(encoded); } // If we want to continue discovering past this newly found node, enqueue it if (!limitedDiscovery) { nodeQueue.Enqueue(oppositeNode); } } // Case 2: oppositeNode was found in a prior BFS run, and the path to oppositeNode went through currentNode else if (oppositeNode.BfsParentNode == currentNode) { // Don't need to do any marking of the opposite node because it's already in the BFS tree. // Just enqueue it so we can continue our BFS from that node at some later time. oppositeNode.InProcessBfsStatus = NodeInProcessBfsStatus.SeenInCurrentRun; nodeQueue.Enqueue(oppositeNode); graph.BfsTreeDepth = Math.Max(graph.BfsTreeDepth, oppositeNode.BfsDepth); graph.BfsTreeNodeCount++; // Sanity check... the depth should be the same, right? if (oppositeNode.BfsDepth != currentNode.BfsDepth + 1) { throw new Exception("Unexpected BFS depth during BFS re-run"); } } // Case 3: oppositeNode was found in a prior BFS run, and the path to oppositeNode did NOT go through currentNode // No action necessary. We can't process oppositeNode now because we aren't allow to follow this edge. // Eventually we will hit the already-existing edge that's part of a prior BFS run, and we'll enter Case 2 above. } // We've seen this node before... else { // Did we find an alternate route to the opposite node? // We cannot change the route if this node was found in a prior BFS run. // This is where tie-breaking happens... if ((oppositeNode.InProcessBfsStatus == NodeInProcessBfsStatus.SeenInCurrentRun) && (oppositeNode.BfsDepth == (currentNode.BfsDepth + 1)) && (oppositeNode.PriorBfsStatus != NodePriorBfsStatus.DiscoveredInPriorBfs)) { // This is an alternate route... break the tie //note that current node is a potential parent of opposite node here. //equivalent to current node being one of the nodes in the tiebreak set //Console.WriteLine("Ties Breaker"); //UPDATED CONDITION TO DEAL WITH HASH FLAG if ((Hash && NewRouteWinsTieBreak(currentNode, oppositeNode, includeSibling)) || (!Hash && NewRouteWinsTieBreakOriginal(currentNode, oppositeNode, includeSibling))) { // Tie-break algorithm says we have a new, better route to this node. // We need to switch the route through the current node instead. oppositeNode.BfsParentNode.RemoveBfsChild(oppositeNode); oppositeNode.BfsParentNode = currentNode; currentNode.AddBfsChild(oppositeNode); if (!oppositeNode.isStub() || !OnlyNonStubs) { /*** update chosen parent***/ ChosenParent[oppositeNode.NodeNum] = currentNode.NodeNum; /*** update its chosen path ***/ //if (allowedRelationships.HasFlag(RelationshipType.CustomerOf)) if ((allowedRelationships & RelationshipType.CustomerOf) == RelationshipType.CustomerOf || allowedRelationships == RelationshipType.NullRelationship) { utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._CUSTOMERCOLUMN, ref ChosenPath); } //else if (allowedRelationships.HasFlag(RelationshipType.ProviderTo)) else if ((allowedRelationships & RelationshipType.ProviderTo) == RelationshipType.ProviderTo) { utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._PROVIDERCOLUMN, ref ChosenPath); } //else if (allowedRelationships.HasFlag(RelationshipType.PeerOf)) else if ((allowedRelationships & RelationshipType.PeerOf) == RelationshipType.PeerOf) { utility.updatePath(oppositeNode.NodeNum, ChosenPath[currentNode.NodeNum], Destination._PEERCOLUMN, ref ChosenPath); } } } /*** NEED TO UPDATE BEST SET WHETHER OR NOT THIS WINS THE TIE BREAK!! **/ if (!oppositeNode.isStub() || !OnlyNonStubs) { Best[oppositeNode.NodeNum].Add(currentNode.NodeNum); addedtoBest = true; } } } if ((Best[oppositeNode.NodeNum] != null))// && addedtoBest)// && //(oppositeNode.PriorBfsStatus != NodePriorBfsStatus.DiscoveredInPriorBfs)) { if (BestNew[oppositeNode.NodeNum] == null) { BestNew[oppositeNode.NodeNum] = new List <UInt32>(); } UInt32 encoded = 0; UInt32 NodeNumx = currentNode.NodeNum; if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.ProviderTo) { encoded = (UInt32)((NodeNumx << 3) + Destination._PROVIDERCOLUMN); } else if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.CustomerOf || allowedRelationships == RelationshipType.NullRelationship) { encoded = (UInt32)((NodeNumx << 3) + Destination._CUSTOMERCOLUMN); } else if ((allowedRelationships & currentNode.GetRelationshipTypeOfNeighbor(oppositeNode)) == RelationshipType.PeerOf) { encoded = (UInt32)((NodeNumx << 3) + Destination._PEERCOLUMN); } UInt32 encoded0 = (UInt32)((NodeNumx << 3) + Destination._PROVIDERCOLUMN); UInt32 encoded1 = (UInt32)((NodeNumx << 3) + Destination._CUSTOMERCOLUMN); UInt32 encoded2 = (UInt32)((NodeNumx << 3) + Destination._PEERCOLUMN); if (!((BestNew[oppositeNode.NodeNum].Exists(element => element == encoded0)) || (BestNew[oppositeNode.NodeNum].Exists(element => element == encoded1)) || (BestNew[oppositeNode.NodeNum].Exists(element => element == encoded2)))) { //Console.WriteLine(oppositeNode.NodeNum + "--> Entered for: " + ((UInt32)(((uint)encoded) >> 3) + " relation: " + (int)(encoded & 7))); //Console.WriteLine("encoded = " + encoded); if (encoded != 0) { //Console.WriteLine(oppositeNode.NodeNum + "--> Entered for: " + ((UInt32)(((uint)encoded) >> 3) + " relation: " + (int)(encoded & 7))); //if ((((allowedRelationships & RelationshipType.ProviderTo) == RelationshipType.ProviderTo) && oppositeNode.InProcessBfsStatus == NodeInProcessBfsStatus.ProcessedInCurrentRun)) //{ // Console.Write("Rel: " + allowedRelationships + " & Node status: " + oppositeNode.InProcessBfsStatus + "\n"); //} //else { BestNew[oppositeNode.NodeNum].Add(encoded); } } } } } // Update the in-process BFS status currentNode.InProcessBfsStatus = NodeInProcessBfsStatus.ProcessedInCurrentRun; } // Finished the BFS... lock the discovered nodes into the BFS tree foreach (AsNode node in graph.GetAllNodes()) { // FYI In limitedDiscovery mode, some nodes may have been left in the SeenInCurrentRun state // (instead of ProcessedInCurrentRun). if (node.InProcessBfsStatus != NodeInProcessBfsStatus.UnseenInCurrentRun) { node.PriorBfsStatus = NodePriorBfsStatus.DiscoveredInPriorBfs; } node.InProcessBfsStatus = NodeInProcessBfsStatus.UnseenInCurrentRun; } }
private bool initGlobalState(string command, ref NetworkGraph g, ref GlobalState globalState) { if (command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length < 2) { Console.WriteLine("usage: initglobalstate :early adopters:top x:top x%"); Console.WriteLine("e.g., initglobalstate :15169 8075:8075 22822:40 will set security true for 15169 and 8075 and assign 40 % weight total to 8075 and 22822 with remaining 60% divided across other ASs"); return false; } string [] parameters= command.Split(":".ToCharArray(),StringSplitOptions.RemoveEmptyEntries); if (parameters.Length != 4) { Console.WriteLine("usage: initglobalstate :early adopters:top x:top x%"); Console.WriteLine("e.g., initglobalstate :15169 8075:8075 22822:40 will set security true for 15169 and 8075 and assign 40 % weight total to 8075 and 22822 with remaining 60% divided across other ASs"); return false; } List<UInt32> earlyAdopters = new List<UInt32>(); string[] earlyAdopterStrings = parameters[1].Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string eAS in earlyAdopterStrings) { UInt32 currAdopter; if (UInt32.TryParse(eAS, out currAdopter)) { if (g.GetNode(currAdopter) != null) earlyAdopters.Add(currAdopter); else Console.WriteLine(currAdopter + " was not in the graph."); } else Console.WriteLine("could not parse AS: " + eAS); } List<UInt32> topX = new List<UInt32>(); string[] topXStrings = parameters[2].Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string tXS in topXStrings) { UInt32 currTopX; if (UInt32.TryParse(tXS, out currTopX)) { if (g.GetNode(currTopX) != null) topX.Add(currTopX); else Console.WriteLine(currTopX + " was not in the graph."); } else Console.WriteLine("could not parse AS: " + tXS); } short topXPercent; if (!short.TryParse(parameters[3], out topXPercent)) { Console.WriteLine("could not parse your top X percent value!"); return false; } Console.WriteLine("dividing " + topXPercent + " across "); foreach (UInt32 topXAS in topX) Console.Write(topXAS + ", "); Console.WriteLine(); Console.WriteLine("turning on stubs and "); foreach (UInt32 adopter in earlyAdopters) Console.Write(adopter + ", "); Console.WriteLine(); globalState = SimulatorLibrary.initGlobalState(g, earlyAdopters, topX, topXPercent); return true; }
private bool nodesWithNoPath(string command, ref List<Destination> destinations,ref NetworkGraph g) { string[] parameters = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (parameters.Length < 2) { Console.WriteLine("error: usage averagebest [destination]"); return false; } UInt32 ASN; if (!UInt32.TryParse(parameters[1], out ASN)) { Console.WriteLine("error: invalid destination ASN"); return false; } foreach (Destination d in destinations) { if (d.destination == ASN) { Int32 numWithNoPath=0; IEnumerable<AsNode> allNodes = g.GetAllNodes(); foreach (AsNode AS in allNodes) { if (d.Best[AS.NodeNum] == null) numWithNoPath++; } Console.WriteLine(numWithNoPath + " nodes have no path to destination " + d.destination); } } Console.WriteLine("error could not find AS " + ASN + " in the list of destinations"); return false; }
/// <summary> /// Constructor just saves the filename and graph /// </summary> public InputFileReader(string filename, NetworkGraph netGraph) { Filename = filename; NetGraph = netGraph; }
private bool serialisePathArrays(ref NetworkGraph graph, string command) { string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 3) { Console.WriteLine("error: usage serialise <dstnum> <path>"); return false; } int dstNum; string path; if (!int.TryParse(cpieces[1], out dstNum)) { Console.WriteLine("invalid destination."); return false; } PathChecker pathChecker = new PathChecker(); if (dstNum == -1) { for (int i = 0; i < Constants._numASNs; i++) { Destination newD = new Destination(); try { if (initDestination(ref graph, ref newD, "destination " + i)) { pathChecker.serializeBestNew(newD.BestNew, i, cpieces[2]); } } catch(Exception) { } } return true; } Destination newD2 = new Destination(); if (initDestination(ref graph, ref newD2, "destination " + dstNum)) { Console.WriteLine("HN: initialized " + newD2.destination + "\t Calling serialiser"); pathChecker.serializeBestNew(newD2.BestNew, dstNum, cpieces[2]); return true; } return false; }
private bool turnOnStubs(ref NetworkGraph g, ref bool[] S) { //clear S for (int i = 0; i < S.Length; i++) S[i] = false; List<UInt32> stubs = g.getStubs(); foreach (int stub in stubs) { S[stub] = true; } return true; }
/// <summary> /// ADDED BY SHARON /// Checks if a particular other node (usually the attacker) is on the path /// from the source node to the BFS root. Returns true if it is, false otherwise /// If there is no path to the BFS root, this function returns false /// </summary> public static bool isNodeOnPathFromBfsRoot(NetworkGraph graph, UInt32 srcNodeNum, UInt32 attackerNodeNum) { AsNode currNode = graph.GetNode(srcNodeNum); AsNode attackerNode = graph.GetNode(attackerNodeNum); // Check the input if ((currNode == null) || (attackerNode == null) || (currNode.BfsDepth == Int32.MaxValue)) { return false; } //walk down path to root, checking for attacker while (currNode != null) { if (currNode.NodeNum == attackerNode.NodeNum) { return true; } currNode = currNode.BfsParentNode; } return false; }
private static bool initDestination(ref NetworkGraph g, ref Destination d, string dest) { UInt32 destNum; if (!UInt32.TryParse(dest, out destNum)) { /* Console.WriteLine("Invalid ASN!"); */ return false; } if (g.GetNode(destNum) == null) { /* Console.WriteLine("WARNING: Could not retrieve destination " + d + " from the graph."); */ return false; } /* Console.WriteLine("Initializing variables and running RTA"); */ MiniDestination miniDest = SimulatorLibrary.initMiniDestination(g, destNum, false); d = new Destination(miniDest); bool[] tempS = new bool[Constants._numASNs]; for (int i = 0; i < tempS.Length; i++) { tempS[i] = false; } d.UpdatePaths(tempS); /* Console.WriteLine("Done initializing. Current active destination is: " + destNum); */ return true; }
private bool addEdges(string command, ref NetworkGraph g) { string[] pieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (pieces.Length < 4) { Console.WriteLine("usage: addEdges ASN numEdges onlyNonStubs"); return false; } UInt32 ASN; Int32 numEdges; bool onlyNonStubs; if (!UInt32.TryParse(pieces[1], out ASN) || !int.TryParse(pieces[2], out numEdges) || !bool.TryParse(pieces[3], out onlyNonStubs)) { Console.WriteLine("bad inputs!"); return false; } SimulatorLibrary.addEdges(ref g, ASN, numEdges, onlyNonStubs); return true; }
private bool iterateAll(ref List<Destination> d, ref NetworkGraph g, ref GlobalState globalState, string command) { string[] parameters = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); float percentage = 0; if (parameters.Length == 1) Console.WriteLine("no utility percentage specified, using basic condition that U after must be more than U before"); else if (!float.TryParse(parameters[1], out percentage)) { percentage = 0; Console.WriteLine("could not parse the utility percentage. using default condition Uafter > Ubefore to flip"); } bool useMiniDWeight = false; if (parameters.Length > 2 && parameters[2].IndexOf("t")>=0) { useMiniDWeight = true; Console.WriteLine("using mini d weight."); } List<Message> results = new List<Message>(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Reset(); stopwatch.Start(); foreach (Destination dest in d) { //yes this is pretty dumb/inefficient it is just for testing purposes. MiniDestination mD = SimulatorLibrary.initMiniDestination(g, dest.destination, false); results.Add(SimulatorLibrary.ComputeOnDestination(mD, globalState)); } Int64[] Before = new Int64[Constants._numASNs]; Int64[] After = new Int64[Constants._numASNs]; SimulatorLibrary.updateGlobalState(ref globalState, results, percentage,ref Before,ref After); stopwatch.Stop(); Console.WriteLine("iteration took: " + stopwatch.ElapsedMilliseconds); return true; }
private bool printstubs(ref NetworkGraph g) { Console.WriteLine("printing stubs:"); List<UInt32> stubs = g.getStubs(); for (int i = 0; i < stubs.Count; i++) Console.WriteLine(stubs[i]); return true; }
/// <summary> /// Retrieves a path from the BFS root to the specified start node. /// The path is returned as a list of AsNode objects. /// If there is no path from the BFS root, this function returns null. /// </summary> public static List<AsNode> GetPathFromBfsRoot(NetworkGraph graph, UInt32 srcNodeNum) { // Check the input AsNode currNode = graph.GetNode(srcNodeNum); if ((currNode == null) || (currNode.BfsDepth == Int32.MaxValue)) { return null; } // Start a list of nodes in the path List<AsNode> nodeList = new List<AsNode>(); nodeList.Insert(0, currNode); // Keep adding parents to the list until we get to the root while (currNode.BfsParentNode != null) { currNode = currNode.BfsParentNode; nodeList.Insert(0, currNode); } return nodeList; }
/// <summary> /// ADDED BY SHARON /// Looks at the path this node has in the BFS /// and returns the relationship with the first hop on this path /// /// </summary> public static RelationshipType GetPathTypeFromBfsRoot(NetworkGraph graph, UInt32 nodeNum) { AsNode node = graph.GetNode(nodeNum); // first check that the node has a path to the root if (node.BfsDepth == Int32.MaxValue) return RelationshipType.NullRelationship; else // return the relationship it has with its BFS parent return node.BfsParentNode.GetRelationshipTypeOfNeighbor(node); }
/// <summary> /// Examines the BFS subtree rooted at the node specified by nodeNum and returns a list of the /// nodes in the tree. /// </summary> public static List<AsNode> GetNodesInBfsSubtree(NetworkGraph graph, UInt32 nodeNum) { // Make sure the node exists and is in the BFS tree AsNode rootNode = graph.GetNode(nodeNum); if ((rootNode == null) || (rootNode.BfsDepth == Int32.MaxValue)) { return null; } // Running node count & list List<AsNode> nodeList = new List<AsNode>(); // Similar to BFS, but we're only going to follow edges that are BFS children Queue<AsNode> nodeQueue = new Queue<AsNode>(); nodeQueue.Enqueue(rootNode); // While there's still nodes in the sub-tree to be examined... while (nodeQueue.Count > 0) { // Dequeue a node and iterate through its BFS children AsNode currentNode = nodeQueue.Dequeue(); foreach (AsNode oppositeNode in currentNode.GetNeighborsByType(RelationshipType.BfsParentOf)) { nodeQueue.Enqueue(oppositeNode); nodeList.Add(oppositeNode); // Sanity check... current node should be the BFS parent of opposite node if (oppositeNode.BfsParentNode != currentNode) { throw new Exception("Expected current node to be parent of child node"); } } } return nodeList; }
private bool initGraph(ref NetworkGraph g,string command) { g = new NetworkGraph(); string resp; if (command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length > 1) resp = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1]; else { Console.WriteLine("Please enter a file name or \"testgraph\" to use the graph from the routing tree algorithm figure in the Sigcomm 2010 paper"); resp = Console.ReadLine().ToLower(); } if (resp == "testgraph") { Console.WriteLine("loading test graph ..."); g = getTestGraph(); Console.WriteLine("done."); return true; } else { if (File.Exists(resp)) { InputFileReader iFR = new InputFileReader(resp, g); iFR.ProcessFile(); Int32 p2pEdges = 0; Int32 c2pEdges = 0; foreach(var ASNode in g.GetAllNodes()) { p2pEdges += ASNode.GetNeighborTypeCount(RelationshipType.PeerOf); c2pEdges += ASNode.GetNeighborTypeCount(RelationshipType.CustomerOf); c2pEdges += ASNode.GetNeighborTypeCount(RelationshipType.ProviderTo); } Console.WriteLine("read in the graph it has " + g.NodeCount + " nodes and " + g.EdgeCount + " edges"); Console.WriteLine("P2P: " + p2pEdges + " C2P: " + c2pEdges); return true; } else { Console.WriteLine("that file does not exist. Going back to main menu now."); return false; } } }