public static void computeUtility(string[] commandPieces, resultObject Result) { //usage computeutility AS d iteration if (commandPieces.Length < 4) { Console.WriteLine("computeutility [ASN] [dest] [iteration]"); return; } UInt32 ASN, dest; Int32 iter; if (!UInt32.TryParse(commandPieces[1], out ASN) || !UInt32.TryParse(commandPieces[2], out dest) || !Int32.TryParse(commandPieces[3], out iter)) { Console.WriteLine("bad params"); return; } if (iter > Result.state.Count) { Console.WriteLine("iteration too large."); return; } bool[] iterState = Result.state[iter]; foreach (var stub in Result.g.getStubs()) iterState[stub] = true;//turn on the stubs as in the sim SimulatorLibrary.setUtilityComputation(UtilityComputationType.outgoing); GlobalState initial = SimulatorLibrary.initGlobalState(Result.g, Result.earlyAdopters, Result.weightedNodes, short.Parse(Result.k)); Destination d = new Destination(SimulatorLibrary.initMiniDestination(Result.g, dest, false)); d.UpdatePaths(iterState); d.ComputeU(initial.W); Console.WriteLine("Utility for " + ASN + " in iteration: " + iter + " is " + d.U[ASN]); Worker w = new Worker(); int afterFlip= w.ComputeUtility(d.BucketTable, d.Best, d.ChosenParent, d.SecP, iterState, ASN, d.L[ASN], d.BestRelation[ASN], initial.W); Console.WriteLine("Utility for " + ASN + " in iteration: " + iter + " if they flip is " +afterFlip); }
public static void destinationToBlob(Destination d, string containerName,string blobName) { //set up streamwriter for the blob. StreamWriter output =new StreamWriter( BlobLibrary.getBlobWriteStream(containerName,blobName)); destinationToStream(d, output); output.Close(); }
/// <summary> /// returns a string of the form: /// #BucketTable num.rows num.cols /// i j AS1 AS2 AS3 AS4 . /// #Best num.rows /// i AS1 AS2 AS3 /// #BestRelation num.rows /// byte1 byte2 byte3 /// /// since we never ended up using L it does not put L in the file /// note: we may need L at somepoint in which case it would need to be in the file too. /// </summary> /// <param name="d"></param> /// <returns></returns> public static void destinationToText(Destination d, string filename) { /*** output * i j as1 as2 as3 * for each non-null element [i,j] in buckettable * ***/ StreamWriter output = new StreamWriter(filename); destinationToStream(d, output); output.Close(); }
public int bestrel(UInt32 AS, ref Destination dst) { int rel = -1; for (int row = 0; row < dst.BucketTable.GetLength(0); row++) { for (int col = 0; col < dst.BucketTable[0].GetLength(0); col++) { if (dst.BucketTable[row][col] != null) { foreach (UInt32 ASN in dst.BucketTable[row][col]) { if (ASN == AS) return col; } } } } return rel; }
public static void trafficThroughSecureProviders(resultObject results) { //get what the simulation state would look like. GlobalState GS = SimulatorLibrary.initGlobalState(results.g, results.earlyAdopters, results.weightedNodes, short.Parse(results.k)); /** First, get a list of multihomed stubs as destinations **/ var stubs=results.g.getStubs(); List<UInt32> multihomedStubs = new List<UInt32>(); foreach(UInt32 stubNum in stubs) { AsNode stub = results.g.GetNode(stubNum); //if this stub is multihomed, init a destination. add it to the list. if (stub.GetNeighborsByType(RelationshipType.CustomerOf).ToArray().Length > 1) multihomedStubs.Add(stubNum); } Console.WriteLine(multihomedStubs.Count + " stubs out of " + stubs.Count + " are multihomed."); StreamWriter output = new StreamWriter("trafficThroughSecureProvider.txt"); /** Second, go through each iteration... **/ int iteration=0; foreach (bool[] S in results.state) { DateTime IterationStart = DateTime.Now; Int32 numDone = 0; foreach (UInt32 multihomedStubNum in multihomedStubs) { /** for this multhomed stub, see how much traffic * goes through secure providers **/ AsNode multihomedStub = results.g.GetNode(multihomedStubNum); Destination multihomedStubDest = new Destination(SimulatorLibrary.initMiniDestination(results.g, multihomedStubNum, false)); //computer the paths and utilities. multihomedStubDest.UpdatePaths(S); multihomedStubDest.ComputeU(GS.W); //get the providers. var Providers = multihomedStub.GetNeighborsByType(RelationshipType.CustomerOf); //count traffic through secure providers (and number of secure providers). Int64 TotalU = 0; Int64 SecureProviderU = 0; Int32 TotalProviders = Providers.Count(); Int32 SecureProviders = 0; foreach (var Provider in Providers) { if (S[Provider.NodeNum]) { SecureProviderU += multihomedStubDest.U[Provider.NodeNum]; SecureProviders++; } TotalU += multihomedStubDest.U[Provider.NodeNum]; } /*write out summary of how much traffic went through secure providers. */ output.WriteLine(iteration + " :: " + multihomedStubNum + " " + SecureProviders + " " + TotalProviders + " " + SecureProviderU + " " + TotalU); numDone++; if ((numDone % 100) == 0) Console.WriteLine("Done " + numDone + " at " + DateTime.Now); } //some benchmarking. Console.WriteLine(DateTime.Now + " done iteration " + iteration + " it started at " + IterationStart); iteration++; } output.Close(); }
/// <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 void getpath(string[] pieces) { if (pieces.Length < 3) return; uint as1, as2; if (!uint.TryParse(pieces[1], out as1) || !uint.TryParse(pieces[2], out as2)) { return; } if (g.GetNode(as1) == null || g.GetNode(as2) == null) return; Destination as2_dst = new Destination(SimulatorLibrary.initMiniDestinationSP(g, as2, false)); bool[] dummyS = new bool[Constants._numASNs]; as2_dst.UpdatePaths(dummyS); Console.WriteLine("shortest path:"); Console.WriteLine(as2_dst.GetPath(as1,g)); Console.WriteLine("regular path:"); as2_dst = new Destination(SimulatorLibrary.initMiniDestination(g, as2, false)); as2_dst.UpdatePaths(dummyS); Console.WriteLine(as2_dst.GetPath(as1)); }
private static Destination destinationFromStream(StreamReader input) { Destination toreturn = new Destination(); //some constants to make this a little nicer. int currentlyReading = -1; const int buckettable = 0; const int best = 1; const int bestrelation = 2; const int l = 3; while (!input.EndOfStream) { string line = input.ReadLine().ToLower(); string[] pieces = line.Split(space, StringSplitOptions.RemoveEmptyEntries); if (line[0] == '#') { if (line.IndexOf("buckettable") >= 0) { currentlyReading = buckettable; int numRows = int.Parse(pieces[1]); int numCols = int.Parse(pieces[2]); toreturn.BucketTable = new List<UInt32>[numRows][]; for(int i =0;i<toreturn.BucketTable.Length;i++) toreturn.BucketTable[i] = new List<UInt32>[numCols]; } else if (line.IndexOf("bestrelation") >= 0) { currentlyReading = bestrelation; int numRows = int.Parse(pieces[1]); toreturn.BestRelation = new byte[numRows]; } else if (line.IndexOf("destination") >= 0) { UInt32 destNum = UInt32.Parse(pieces[1]); toreturn.destination = destNum; } else if (line.IndexOf("best") >= 0) { currentlyReading = best; int numRows = int.Parse(pieces[1]); toreturn.Best = new List<UInt32>[numRows]; } else if (line.IndexOf("l") >= 0) { currentlyReading = l; int numRows = int.Parse(pieces[1]); toreturn.L = new byte[numRows]; } } else { int row, col; switch (currentlyReading) { case buckettable: row = int.Parse(pieces[0]); col = int.Parse(pieces[1]); toreturn.BucketTable[row][col] = new List<UInt32>(); for (int i = 2; i < pieces.Length; i++) toreturn.BucketTable[row][col].Add(UInt32.Parse(pieces[i])); break; case best: row = int.Parse(pieces[0]); toreturn.Best[row] = new List<UInt32>(); for (int i = 1; i < pieces.Length; i++) toreturn.Best[row].Add(UInt32.Parse(pieces[i])); break; case bestrelation: for (int i = 0; i < pieces.Length; i++) toreturn.BestRelation[i] = byte.Parse(pieces[i]); break; case l: for (int i = 0; i < pieces.Length; i++) toreturn.L[i] = byte.Parse(pieces[i]); break; } } } //rehydrate the parts of the object not passed in text. toreturn.ChosenParent = new UInt32[toreturn.Best.Length]; toreturn.ChosenPath = new List<UInt32>[toreturn.Best.Length]; toreturn.SecP = new bool[toreturn.Best.Length]; toreturn.U = new Int64[toreturn.Best.Length]; //init the destination path to itself to kick things off toreturn.SecP[toreturn.destination] = true; toreturn.ChosenPath[toreturn.destination] = new List<UInt32>(); toreturn.ChosenPath[toreturn.destination].Add(toreturn.destination); toreturn.ChosenParent[toreturn.destination]=toreturn.destination; return toreturn; }
private void runCompareU(List<UInt32> nonstubs,Destination d,ref Worker w,bool onlybenefit,ref GlobalState globalState) { if (d.BucketTable == null) { Console.WriteLine("null bucket table!"); return; } Stopwatch stopwatch = new Stopwatch(); stopwatch.Reset(); stopwatch.Start(); d.UpdatePaths(globalState.S); d.ComputeU(globalState.W);//just in case. stopwatch.Stop(); foreach (UInt32 ASN in nonstubs) { if (d.Best[ASN] != null)//nonstub has a path to d { int notASN = w.ComputeUtility(d.BucketTable, d.Best, d.ChosenParent, d.SecP, globalState.S, ASN, d.L[ASN], d.BestRelation[ASN], globalState.W); if (!onlybenefit || d.U[ASN] < notASN) Console.WriteLine(ASN + " :: " + d.U[ASN] + " : " + notASN); } } Console.WriteLine("update paths and compute u took: " + stopwatch.ElapsedMilliseconds + " ms"); }
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; }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("USAGE:"); Console.WriteLine("mono TestingApplication.exe -bulk <input file> <dest1> ... <dstN> -q <src1> <dst1> ... <srcN> <dstN>"); Console.WriteLine("mono TestingApplication.exe -serverPORT <input file> <precomp file> <cache file>"); Console.WriteLine("mono TestingApplication.exe -cmd"); return; } if ("-cmd" == args[0]) { TestingClass test = new TestingClass(); test.CLI(false); return; } // Graph initialization //NetworkGraph g = new NetworkGraph(); // E.g., input Cyclops_caida.txt if (File.Exists(args[1])) { InputFileReader iFR = new InputFileReader(args[1], 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); } else { Console.WriteLine("The file " + args[1] + " does not exist."); return; } if ("-bulk" == args[0]) { // Setting destinations //HashSet<string> dests = new HashSet<string>(); //List<Destination> d = new List<Destination>(); int i = 1; for (i = 1; i < args.Length; ++i) { if ("-q" == args[i]) break; if (dests.Contains(args[i])) continue; dests.Add(args[i]); Destination newD = new Destination(); if (initDestination(ref g, ref newD, args[i])) { d.Add(args[i], newD); Console.WriteLine("Initialized and added " + newD.destination); } } Console.WriteLine("DESTS " + dests.Count); // Approaching queries for (i = i+1; i < args.Length; i += 2) { //StringBuilder res = new StringBuilder(); //int l = getPath(ref d, args[i], args[i+1]); //getAllPathsOfLength(ref d, l, args[i], args[i+1], ref res); List<List<UInt32>> allPaths = new List<List<UInt32>>(); if (d.ContainsKey(args[i+1])) { UInt32 src; UInt32 dst; if (UInt32.TryParse(args[i], out src) && UInt32.TryParse(args[i+1], out dst)) { Console.WriteLine("ASes from " + src + " to " + dst); d[args[i+1]].GetAllBestPaths(src, dst, ref allPaths); } } foreach (List<UInt32> path in allPaths) { for (int j = 0; j < path.Count; ++j) { Console.WriteLine(path[j]); } Console.WriteLine("-"); } } return; } if (args[0].StartsWith("-server")) { if (args.Length > 2) { loadPrecomputation(args[2]); cacheDestinations(args[3]); } String port = args[0].Replace("-server", ""); StartListening(port); } }
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 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 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 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 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 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 static avgBestSizes getAverageBestSizes(Destination d, List<UInt32> stubs, List<UInt32> nonstubs,List<UInt32> ASNs,StreamWriter output) { double allavg = 0; double allpoints = 0; double savg = 0; double spoints = 0; double nsavg = 0; double nspoints = 0; for (int a = 0; a < ASNs.Count; a++) { UInt32 i = ASNs[a]; if (d.Best[i] != null) { double currVal = d.Best[i].Count; allavg += currVal; allpoints++; // output.WriteLine("{0},{1},{2}", currVal, i,d.destination); if (stubs.Contains(i)) { savg += currVal; spoints++; output.WriteLine("stub,{0},{1},{2}", currVal, i, d.destination); } else if (nonstubs.Contains(i)) { output.WriteLine("nonstub,{0},{1},{2}", currVal, i, d.destination); nsavg += currVal; nspoints++; } } } avgBestSizes toreturn = new avgBestSizes(); toreturn.all = allavg / allpoints; toreturn.stubs = savg /spoints; toreturn.nonstubs = nsavg/ nspoints; return toreturn; }
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 static void cacheDestinations(string path) { System.IO.StreamReader file = new System.IO.StreamReader(path); string line; // whois bulk output format file.ReadLine(); while((line = file.ReadLine()) != null) { string[] tmp = line.Split(' '); string asn = tmp[0]; if (dests.Contains(asn)) continue; dests.Add(asn); Destination newD = new Destination(); if (initDestination(ref g, ref newD, asn)) { d.Add(asn, newD); Console.WriteLine("Initialized and added " + newD.destination); } } file.Close(); Console.WriteLine("CACHE: " + dests.Count); }
private bool printBucketTable(ref List<Destination> ds,string command) { string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 2) { Console.WriteLine("usage: printbuckettable <d>"); return false; } UInt32 dstnum; if (!UInt32.TryParse(cpieces[1], out dstnum)) { Console.WriteLine("invalid d!"); return false; } Destination d = new Destination(); foreach (Destination curr in ds) { if (curr.destination == dstnum) d = curr; } if (d.BucketTable == null) Console.WriteLine("null bucket table!"); for (int i = 0; i < d.BucketTable.GetLength(0); i++) { for (int j = 0; j < d.BucketTable[i].GetLength(0); j++) { if (d.BucketTable[i][ j] != null) { string towrite = "BucketTable [" + i + "," + j + "] is < "; for (int k = 0; k < d.BucketTable[i][ j].Count; k++) { if (k < d.BucketTable[i][ j].Count - 1) towrite = towrite + d.BucketTable[i][ j][k] + ", "; else towrite = towrite + d.BucketTable[i][j][k] + " > "; } Console.WriteLine(towrite); } else Console.WriteLine("BucketTable ["+i+","+j+"] is null"); } } return true; }
private static void loadPrecomputation(string path) { System.IO.StreamReader file = new System.IO.StreamReader(path); string line; while((line = file.ReadLine()) != null) { if ("<EOFs>" == line) break; //Console.WriteLine(line); string[] tmp = line.Replace(":", " ").Split(' '); string src = tmp[2]; string dst = tmp[4]; string key = src + "-" + dst; StringBuilder buf = new StringBuilder(line + "\n"); while ((line = file.ReadLine()) != null) { buf.Append(line + "\n"); if ("-" == line) break; } cache.Add(key, buf.ToString()); // + init the destination if (dests.Contains(dst)) continue; dests.Add(dst); Destination newD = new Destination(); if (initDestination(ref g, ref newD, dst)) { d.Add(dst, newD); Console.WriteLine("Initialized and added " + newD.destination); } } file.Close(); Console.WriteLine("PRECOMP: " + cache.Count); }
private bool initDestination(ref NetworkGraph g, ref Destination d,string command) { string resp; if (command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length < 2) { Console.WriteLine("Please enter a destination ASN: "); resp = Console.ReadLine(); } else resp = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1]; UInt32 destNum; if (!UInt32.TryParse(resp, out destNum)) { Console.WriteLine("invalid ASN! "); return false; } if (g.GetNode(destNum) == null) { Console.WriteLine("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);//init paths with S = all false Console.WriteLine("done initializing. Current active destination is: " + destNum); List<UInt32> temp = new List<UInt32>(); temp.Add(d.destination); d.BestNew[d.destination] = temp; //Console.Write("Dest BestNew["+ d.destination + "] = " + d.BestNew[d.destination][0]); return true; }
public static void StartListening(String p) { int port; if (!Int32.TryParse(p, out port)) { port = 11000; } // Data buffer for incoming data. byte[] bytes = new Byte[1000000]; // Establish the local endpoint for the socket. // Dns.GetHostName returns the name of the // host running the application. //IPostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); //IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint localEndPoint = new IPEndPoint(Dns.Resolve("localhost").AddressList[0], port); // Create a TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and // listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(10); // Start listening for connections. while (true) { Console.WriteLine("Waiting for a connection on {0} ...", port); // Program is suspended while waiting for an incoming connection. Socket handler = listener.Accept(); data = null; // An incoming connection needs to be processed. while (true) { bytes = new byte[1000000]; int bytesRec = handler.Receive(bytes); data += Encoding.ASCII.GetString(bytes,0,bytesRec); if (data.IndexOf("<EOFc>") > -1) { break; } } // Show the data on the console. Console.WriteLine("Text received : {0}", data); string[] args = data.Split(' '); int i; for (i = 0; i < args.Length-1; ++i) { if ("-q" == args[i]) break; if (dests.Contains(args[i])) continue; dests.Add(args[i]); Destination newD = new Destination(); if (initDestination(ref g, ref newD, args[i])) { d.Add(args[i], newD); Console.WriteLine("Initialized and added " + newD.destination); } } Console.WriteLine("DESTS " + dests.Count); // Approaching queries StringBuilder res = new StringBuilder(1000000); int k = 0; for (i = i+1; i < args.Length-1; i += 2) { if ("<EOFc>" == args[i]) break; Console.WriteLine(k); string key = args[i] + "-" + args[i+1]; if (cache.ContainsKey(key)) { res.Append(cache[key]); k++; continue; } StringBuilder tmp = new StringBuilder(); /* //int l = getPath(ref d, args[i], args[i+1]); //getAllPathsOfLength(ref d, l, args[i], args[i+1], ref tmp); getPath2(ref d, args[i], args[i+1], ref tmp); */ getBestPaths(ref d, args[i], args[i+1], ref tmp); res.Append(tmp); cache.Add(key, tmp.ToString()); k++; } res.Append("<EOFs>"); // Echo the data back to the client. byte[] msg = Encoding.ASCII.GetBytes(res.ToString()); //Console.WriteLine(res.ToString()); int sent = handler.Send(msg); Console.WriteLine("Sent: " + sent); handler.Shutdown(SocketShutdown.Both); handler.Close(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); }
public string pathAnalysis(string path, ref Destination dest) { int pathExists; int pathViolate = 0; int GR = 0; int bestrln = 0; int shortest = 0; int bucket; List<UInt32> relPath = new List<UInt32>(); //Check if path exists from best new and make a relPath string[] asPath = path.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); UInt32 AS; UInt32.TryParse(asPath[0], out AS); if (dest.BestNew[AS] != null) { pathExists = 1; UInt32 first = (UInt32)((AS << 3) + Destination._NOREL); relPath.Add(first); for (int i = 0; i < (asPath.Length - 1); i++) { int asNum, asTo; int.TryParse(asPath[i], out asNum); int.TryParse(asPath[i + 1], out asTo); if (dest.BestNew[asNum] != null) { UInt32 encoded0 = (UInt32)((asTo << 3) + Destination._PROVIDERCOLUMN); UInt32 encoded1 = (UInt32)((asTo << 3) + Destination._CUSTOMERCOLUMN); UInt32 encoded2 = (UInt32)((asTo << 3) + Destination._PEERCOLUMN); UInt32 encoded3 = (UInt32)((asTo << 3) + Destination._NOREL); if (dest.BestNew[asNum].Exists(element => element == encoded0)) { relPath.Add(encoded0); } else if (dest.BestNew[asNum].Exists(element => element == encoded1)) { relPath.Add(encoded1); } else if (dest.BestNew[asNum].Exists(element => element == encoded2)) { relPath.Add(encoded2); } else if (dest.BestNew[asNum].Exists(element => element == encoded3)) { relPath.Add(encoded3); } else { pathExists = 0; break; } // Now do perform a sanity check int size = relPath.Count; int rel, prevRel; UInt32 temp; dest.unjoin(relPath[size - 1], out temp, out rel); dest.unjoin(relPath[size - 2], out temp, out prevRel); if ((rel == Destination._PEERCOLUMN && prevRel == Destination._CUSTOMERCOLUMN) || (prevRel == Destination._PEERCOLUMN && rel == Destination._PROVIDERCOLUMN) || (prevRel == Destination._PEERCOLUMN && rel == Destination._PEERCOLUMN) || (prevRel == Destination._CUSTOMERCOLUMN && (rel == Destination._PEERCOLUMN || rel == Destination._PROVIDERCOLUMN))) { pathViolate = 1; pathExists = 0; break; } } else { pathExists = 0; break; } } } else { pathExists = 0; } //GR path and compare string GR_string = dest.GetPathCommaSep(AS); if (pathAvailable_GR(path, ref dest.Best) && (pathExists == 1)) { GR = 1; } //if not GR check for best rel if ((GR == 0) && (pathExists == 1)) { bestrln = 1; for (int j = 0; j < (relPath.Count - 1); j++) { UInt32 fromAS, tempAS; int rel, temprel, bestRelation; dest.unjoin(relPath[j], out fromAS, out temprel); dest.unjoin(relPath[j + 1], out tempAS, out rel); bestRelation = bestrel(fromAS, ref dest); if (bestRelation == -1) { throw new Exception(); } if (rel > bestRelation) { bestrln = 0; break; } } } //Check for shortest if ((GR == 0) && (bestrln == 0) && (pathExists == 1)) { shortest = 1; for (int i = 1; i < asPath.Length; i++) { List<List<UInt32>> allPaths = new List<List<UInt32>>(); List<UInt32> pathNew = new List<UInt32>(); UInt32 first = (UInt32)((AS << 3) + Destination._NOREL); pathNew.Add(first); //Console.Out.WriteLine("Checking length: " + i); if (dest.pathoflength(AS, dest.destination, ref allPaths, pathNew, i)) { shortest = 0; //Console.Out.WriteLine(i + " BHORSI KA: " + allPaths.Count + " " + dest.pathString(allPaths[0])); break; } } } //space seperated: path bucket //bucket -1 -> Export Violation //bucket 0 -> Missing Link //bucket 1 -> GR //bucket 2 -> Best Relation //bucket 3 -> Shortest //bucket 4 -> None but doesnt violate export if (pathExists == 1) { if (GR == 1) { bucket = 1; } else if (bestrln == 1) { bucket = 2; } else if (shortest == 1) { bucket = 3; } else { bucket = 4; } } else { if (pathViolate == 1) { bucket = -1; } else { bucket = 0; } } //Console.Out.WriteLine(path + " " + bucket); //Console.WriteLine("Path: " + dest.pathString(relPath) + "\n" + GR_string + " Exitsts: " + pathExists + " GR: " + GR + " BestReln: "+ bestrln + " Shortest: " + shortest + " Violate: " + pathViolate); return path + " " + bucket; }
private static void destinationToStream(Destination d, StreamWriter output) { output.WriteLine("#destination " + d.destination); /*** output * i j as1 as2 as3 * for each non-null element [i,j] in buckettable * ***/ output.WriteLine("#buckettable " + d.BucketTable.GetLength(0) + " " + d.BucketTable[0].GetLength(0)); for (int i = 0; i < d.BucketTable.GetLength(0); i++) { for (int j = 0; j < d.BucketTable[0].GetLength(0); j++) { if (d.BucketTable[i][ j] != null) { output.Write(i + " " + j + " "); for (int k = 0; k < d.BucketTable[i][ j].Count; k++) output.Write(d.BucketTable[i][j][k] + " "); output.Write("\n"); } } } /** output i as1 as2 as3 * for each non-null list in the best[i] array. **/ output.WriteLine("#best " + d.Best.Length); for (int i = 0; i < d.Best.Length; i++) { if (d.Best[i] != null) { output.Write(i + " "); for (int j = 0; j < d.Best[i].Count; j++) output.Write(d.Best[i][j] + " "); output.Write("\n"); } } /*** output 1 line with all the values of bestrelation separated by ' ' since * it is a simple object **/ output.WriteLine("#bestrelation " + d.BestRelation.Length); for (int i = 0; i < d.BestRelation.Length; i++) output.Write(d.BestRelation[i] + " "); output.Write("\n"); output.WriteLine("#L " + d.L.Length); for (int i = 0; i < d.L.Length; i++) output.Write(d.L[i]+ " "); output.Write("\n"); }
private bool printSecP(ref List<Destination> ds, string command) { string resp; if (command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length < 2) { Console.WriteLine("maximum AS #"); resp = Console.ReadLine(); } else { resp = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1]; } string resp2 = ""; if (command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length > 2) resp2 = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[2]; int maxnum; int destNum; if (!int.TryParse(resp, out maxnum)) { Console.WriteLine("invalid maximum."); return false; } if (!int.TryParse(resp2, out destNum)) { Console.WriteLine("you did not specify a destination!"); return false; } Destination d = new Destination(); foreach (Destination curr in ds) { if (curr.destination == destNum) d = curr; } if (d.BucketTable == null) { Console.WriteLine("destination "+destNum+" does not seem to be initialized!"); return false; } Console.WriteLine("---------"); Console.WriteLine("ASN :: SecP"); for (int i = 1; i < d.SecP.Length && i < maxnum; i++) { Console.WriteLine(i + " :: " + d.SecP[i]); } Console.WriteLine("---------"); return true; }
public string pathAnalysis(string path, ref Destination dest, ref TextWriter Missing, ref TextWriter randomFile, ref TextWriter ViolationType) { int pathExists; int pathViolate = 0; int GR = 0; int bestrln = 0; int bestrlnHop = 0; int shortest = 0; int shortestHop = 0; int shortestLen = 0; int bucket; List<UInt32> relPath = new List<UInt32>(); //Check if path exists from best new and make a relPath string[] asPath = path.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); UInt32 AS; UInt32.TryParse(asPath[0], out AS); if (dest.BestNew[AS] != null) { pathExists = 1; UInt32 first = (UInt32)((AS << 3) + Destination._NOREL); relPath.Add(first); for (int i = 0; i < (asPath.Length - 1); i++) { int asNum, asTo; int.TryParse(asPath[i], out asNum); int.TryParse(asPath[i + 1], out asTo); if (dest.BestNew[asNum] != null) { UInt32 encoded0 = (UInt32)((asTo << 3) + Destination._PROVIDERCOLUMN); UInt32 encoded1 = (UInt32)((asTo << 3) + Destination._CUSTOMERCOLUMN); UInt32 encoded2 = (UInt32)((asTo << 3) + Destination._PEERCOLUMN); UInt32 encoded3 = (UInt32)((asTo << 3) + Destination._NOREL); if (dest.BestNew[asNum].Exists(element => element == encoded0)) { relPath.Add(encoded0); } else if (dest.BestNew[asNum].Exists(element => element == encoded1)) { relPath.Add(encoded1); } else if (dest.BestNew[asNum].Exists(element => element == encoded2)) { relPath.Add(encoded2); } else if (dest.BestNew[asNum].Exists(element => element == encoded3)) { relPath.Add(encoded3); } else { pathExists = 0; break; } // Now do perform a sanity check int size = relPath.Count; int rel, prevRel; UInt32 temp; dest.unjoin(relPath[size-1], out temp, out rel); dest.unjoin(relPath[size-2], out temp, out prevRel); if ((rel == Destination._PEERCOLUMN && prevRel == Destination._CUSTOMERCOLUMN) || (prevRel == Destination._PEERCOLUMN && rel == Destination._PROVIDERCOLUMN) || (prevRel == Destination._PEERCOLUMN && rel == Destination._PEERCOLUMN) || (prevRel == Destination._CUSTOMERCOLUMN && (rel == Destination._PEERCOLUMN || rel == Destination._PROVIDERCOLUMN))) { pathViolate = 1; pathExists = 0; ViolationType.WriteLine(pathString(relPath)); ViolationType.Flush(); break; } } else { pathExists = 0; break; } } } else { pathExists = 0; } //Check hop count for missing link /* if(pathExists == 0) { int hopsfromend = 0, hopsfromstart = 0; string tempPath = ""; for (int i = 1; i < asPath.Length; i++) { tempPath = ""; for (int j = asPath.Length - i; j < asPath.Length; j++) { if (j == (asPath.Length - 1)) { tempPath = tempPath + asPath[j]; } else { tempPath = tempPath + asPath[j] + ","; } } //Check if path exists if(!pathAvailable(tempPath, dest.BestNew)) { hopsfromend = i; hopsfromstart = asPath.Length - i; break; } else { hopsfromend = i; hopsfromstart = asPath.Length - i; } } Missing.WriteLine(hopsfromstart + " " + hopsfromend); Missing.Flush(); } */ //GR path and compare string GR_string = dest.GetPathCommaSep(AS); if (pathAvailable_GR(path, ref dest.Best) && (pathExists == 1)) { GR = 1; } //if not GR check for best rel if ((GR == 0) && (pathExists == 1)) { bestrln = 1; for (int j = 0; j < (relPath.Count - 1); j++) { UInt32 fromAS, tempAS; int rel, temprel, bestRelation; dest.unjoin(relPath[j], out fromAS, out temprel); dest.unjoin(relPath[j+1], out tempAS, out rel); bestRelation = bestrel(fromAS, ref dest); if (bestRelation == -1) { throw new Exception(); } if (rel > bestRelation) { bestrln = 0; break; } } } //checking for bestRl for first hop if (1 == 1) { bestrlnHop = 1; UInt32 fromAS, tempAS; int rel, temprel, bestRelation; dest.unjoin (relPath [0], out fromAS, out temprel); dest.unjoin (relPath [1], out tempAS, out rel); bestRelation = bestrel (fromAS, ref dest); if (bestRelation == -1) { throw new Exception (); } if (rel > bestRelation) { bestrlnHop = 0; } } //Check for shortest if ((GR == 0) && (bestrln == 0) && (pathExists == 1)) { shortest = 1; shortestLen = asPath.Length -1; // to correct for the next comment for (int i = 1; i < asPath.Length-1; i++) { //i=1 essentially means checking for path length 2, therefore the -1 List<List<UInt32>> allPaths = new List<List<UInt32>> (); List<UInt32> pathNew = new List<UInt32> (); UInt32 first = (UInt32)((AS << 3) + Destination._NOREL); pathNew.Add (first); //Console.Out.WriteLine("Checking length: " + i); if (dest.pathoflength (AS, dest.destination, ref allPaths, pathNew, i)) { shortest = 0; shortestLen = i; if (shortestLen == 1) { shortest = 1; } //Console.Out.WriteLine ("Path length: " + asPath.Length); //Console.Out.WriteLine(i + " shortest: " + shortest+ " B KA: " + allPaths.Count + " " + dest.pathString(allPaths[0])); break; } } } else { // Added to compute shortest lenght path for all buckets and for per hop shortest shortestLen = asPath.Length-1; for (int i = 1; i < asPath.Length; i++) { List<List<UInt32>> allPaths = new List<List<UInt32>> (); List<UInt32> pathNew = new List<UInt32> (); UInt32 first = (UInt32)((AS << 3) + Destination._NOREL); pathNew.Add (first); //Console.Out.WriteLine ("Checking : " + i); if (dest.pathoflength (AS, dest.destination, ref allPaths, pathNew, i)) { shortestLen = i; break; } } } shortestLen = shortestLen + 1; //shortestLen is now the number of AS in shortest path if (shortestLen == asPath.Length) { shortestHop = 1; } //space seperated: path bucket //bucket -1 -> Export Violation //bucket 0 -> Missing Link //bucket 1 -> GR //bucket 2 -> Best Relation //bucket 3 -> Shortest //bucket 4 -> None but doesnt violate export if (pathExists == 1) { if (GR == 1) { bucket = 1; } else if (bestrln == 1) { bucket = 2; } else if (shortest == 1) { bucket = 3; } else { bucket = 4; //Console.WriteLine("Difference: " + (asPath.Length - shortestLen) + "\n Length: " + asPath.Length + "\nShortest: " + shortestLen); //ShortestDiff.WriteLine((asPath.Length - shortestLen)); //ShortestDiff.Flush(); } } else { if (pathViolate == 1) { bucket = -1; } else { bucket = 0; } } //Console.Out.WriteLine(path + " " + bucket); // Format: Original Path | Bucket | GR Path | Shortest Length | lastHop info : BestRln+Shortest randomFile.WriteLine(dest.pathString(relPath) + "|" + bucket + "|" + dest.GetPath(AS) + "|" + shortestLen + "|" + bestrlnHop + "" + shortestHop); randomFile.Flush(); //Console.WriteLine("Path: " + dest.pathString(relPath) + "\n" + GR_string + " Exitsts: " + pathExists + " GR: " + GR + " BestReln: "+ bestrln + " Shortest: " + shortest + " Violate: " + pathViolate + "\n"); return path + " " + bucket; }
private bool getPath(ref List<Destination> ds, ref NetworkGraph graph, string command) { string[] cpieces = command.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (cpieces.Length < 3) { Console.WriteLine("error: usage getpath <as#> <dstnum>"); return false; } int dstNum; UInt32 ASN; if (!UInt32.TryParse(cpieces[1], out ASN) || !int.TryParse(cpieces[2],out dstNum)) { Console.WriteLine("invalid ASN or destination."); return false; } foreach (Destination d in ds) { if (d.destination == dstNum) { //d.Best[0]++; Console.WriteLine("Path from " + ASN + " to " + d.destination + " is " + d.GetPath(ASN)); return true; } } //Added by Haseeb *Computes destination so getPath doesnt return false if the destination is not initialised before calling getPath Destination newD = new Destination(); if (initDestination(ref graph, ref newD, "destination " + dstNum)) { ds.Add(newD); Console.WriteLine("HN: initialized and added " + newD.destination); //newD.Best[0]++; Console.WriteLine("HN: Path from " + ASN + " to " + newD.destination + " is " + newD.GetPath(ASN)); return true; } Console.WriteLine("could not find destination"); return false; }