Exemple #1
0
        /**
         * @param e Edge to close
         * @param cm message to send to other node
         * This method is used if we want to use a particular CloseMessage
         * If not, we can use the method with the same name with one fewer
         * parameters
         */
        public void GracefullyClose(Edge e, string message)
        {
            /**
             * Close any connection on this edge, and
             * put the edge into the list of unconnected edges
             */
            _connection_table.Disconnect(e);

            ListDictionary close_info = new ListDictionary();
            string         reason     = message;

            if (reason != String.Empty)
            {
                close_info["reason"] = reason;
            }
            ProtocolLog.WriteIf(ProtocolLog.EdgeClose, String.Format(
                                    "GracefulCLose - " + e + ": " + reason));

            var          results  = new BCon.Channel(1);
            EventHandler close_eh = delegate(object o, EventArgs args) {
                e.Close();
            };

            results.CloseEvent += close_eh;
            try {
                _rpc.Invoke(e, results, "sys:link.Close", close_info);
            }
            catch { Close(e); }
        }
Exemple #2
0
        static void TraceRoute(IList nodes)
        {
            Random     my_r    = new Random();
            int        idx0    = my_r.Next(0, nodes.Count);
            int        idx1    = my_r.Next(0, nodes.Count);
            Node       n0      = (Node)nodes[idx0];
            Node       n1      = (Node)nodes[idx1];
            RpcManager pinger  = n0.Rpc;
            Channel    results = new Channel();

            Console.WriteLine("Traceroute: {0} -> {1}", n0.Address, n1.Address);
            results.EnqueueEvent += delegate(object q, EventArgs a) {
                object    result = results.Dequeue();
                RpcResult r      = (RpcResult)result;
                IList     data   = (IList)r.Result;
                int       hop    = 0;
                foreach (IDictionary d in data)
                {
                    Console.WriteLine("Hop: {0} :: {1}\n  :: {2}", hop, d["node"], d["next_con"]);
                    hop++;
                }
            };
            try {
                pinger.Invoke(n0, results, "trace.GetRouteTo", n1.Address.ToString());
            }
            catch (Exception x) {
                Console.WriteLine("Exception: {0}", x);
            }
        }
        /**
         * Compute candidate scores for a shortcut connection.
         * @param start address computed by the SCO.
         * @param range nunber of candidate nodes.
         * @param cb callback function when candidate scores are available.
         * @param current current selection of the optimal in the provided range.
         */
        public override void ComputeCandidates(Address start, int range, TargetSelectorDelegate cb, Address current)
        {
            Channel      q  = null;
            RequestState rs = null;

            lock (_sync) {
#if VTS_DEBUG
                Console.Error.WriteLine("VTS local: {0}, start: {1}, range: {2}, count: {3}", _node.Address, start, range, _num_requests);
#endif
                if (_num_requests == MAX_REQUESTS)
                {
                    return; //do nothing and return;
                }
                _num_requests++;
                q  = new Channel();
                rs = new RequestState(start, range, cb, current);
                _channel_to_state[q] = rs;
            }

            //create a new request state
            ISender s = new ForwardingSender(_node,
                                             start,
                                             AHHeader.Options.Greedy,
                                             new DirectionalAddress(DirectionalAddress.Direction.Left),
                                             (short)range,
                                             AHHeader.Options.Path
                                             );

            q.EnqueueEvent += new EventHandler(EnqueueHandler);
            q.CloseEvent   += new EventHandler(CloseHandler);
            RpcManager rpc = _node.Rpc;
            rpc.Invoke(s, q, "ncserver.EchoVivaldiState", new object[] {});
        }
Exemple #4
0
 public override void Start()
 {
     //Make sure the Node is listening to this node
     try {
         //This will throw an exception if _e is already closed:
         _e.CloseEvent += this.CloseHandler;
         //_e must not be closed, let's start listening to it:
         _e.Subscribe(_node, _e);
         /* Make the call */
         Channel results = new Channel();
         results.CloseAfterEnqueue();
         results.CloseEvent += this.LinkCloseHandler;
         RpcManager rpc = _node.Rpc;
         if (ProtocolLog.LinkDebug.Enabled)
         {
             ProtocolLog.Write(ProtocolLog.LinkDebug,
                               String.Format("LPS target: {0} Invoking Start() over edge: {1}", _linker.Target, _e));
         }
         rpc.Invoke(_e, results, "sys:link.Start", MakeLM().ToDictionary());
     }
     catch (Exception e) {
         //The Edge must have closed, move on to the next TA
         if (ProtocolLog.LinkDebug.Enabled)
         {
             ProtocolLog.Write(ProtocolLog.LinkDebug,
                               String.Format("LPS target: {0} Start() over edge: {1}, hit exception: {2}",
                                             _linker.Target, _e, e));
         }
         Finish(Result.MoveToNextTA);
     }
 }
Exemple #5
0
        override public void Start()
        {
            ProtocolLog.WriteIf(ProtocolLog.LinkDebug,
                                String.Format("{0}: Starting Connector: {1}, {2}",
                                              _local_node.Address, _sender, State));
            AbortCheck ac = _abort.Value;

            if (ac != null)
            {
                if (ac(this))
                {
                    //We are no longer needed:
                    QueueCloseHandler(null, null);
                    return;
                }
            }

            RpcManager rpc = _local_node.Rpc;

            Channel results = new Channel();

            results.EnqueueEvent += this.EnqueueHandler;
            results.CloseEvent   += this.QueueCloseHandler;
            try {
                rpc.Invoke(_sender, results, "sys:ctm.ConnectTo", _ctm.ToDictionary());
            }
            catch {
                //Looks like the _sender had some problem:
                QueueCloseHandler(null, null);
            }
        }
Exemple #6
0
        protected void FriendPing(string address)
        {
            Address addr = AddressParser.Parse(address);
            Channel q    = new Channel();

            q.CloseAfterEnqueue();
            q.CloseEvent += delegate(object obj, EventArgs eargs) {
                try {
                    RpcResult res      = (RpcResult)q.Dequeue();
                    string    result   = (string)res.Result;
                    string[]  parts    = result.Split(DELIM);
                    string    dht_key  = parts[0];
                    string    response = parts[1];
                    if (response == "online")
                    {
                        SocialUser friend = _friends[dht_key];
                        friend.Time = DateTime.Now.ToString();
                    }
                    ProtocolLog.Write(SocialLog.SVPNLog, "PING FRIEND REPLY: " +
                                      result);
                } catch (Exception e) {
                    ProtocolLog.Write(SocialLog.SVPNLog, e.Message);
                    ProtocolLog.Write(SocialLog.SVPNLog, "PING FRIEND FAILURE: " +
                                      address);
                }
            };
            ISender sender = new AHExactSender(_node, addr);

            _rpc.Invoke(sender, q, "SocialVPN.FriendPing", _local_user.DhtKey);
        }
Exemple #7
0
        static void Ping(IList nodes)
        {
            Random     my_r    = new Random();
            int        idx0    = my_r.Next(0, nodes.Count);
            int        idx1    = my_r.Next(0, nodes.Count);
            Node       n0      = (Node)nodes[idx0];
            Node       n1      = (Node)nodes[idx1];
            RpcManager pinger  = n0.Rpc;
            Channel    results = new Channel();

            results.EnqueueEvent += delegate(object q, EventArgs a) {
                object    result = results.Dequeue();
                RpcResult r      = (RpcResult)result;
                try {
                    IDictionary data = (IDictionary)r.Result;
                    Console.WriteLine("target: {0}, rtt: {1}", data["target"], data["musec"]);
                }
                catch (Exception x) {
                    Console.WriteLine("target: {0}, Exception: {1}", n1.Address, x);
                }
            };
            Console.WriteLine("Pinging: {0} -> {1}", n0.Address, n1.Address);
            try {
                pinger.Invoke(n0, results, "trace.GetRttTo", n1.Address.ToString());
            }
            catch (Exception x) {
                Console.WriteLine("Exception: {0}", x);
            }
        }
Exemple #8
0
        public void Test()
        {
            Channel q = new Channel(1);

            rpc.Invoke(null, q, "test.test");
            RpcResult res = (RpcResult)q.Dequeue();
            bool      val = (bool)res.Result;

            Assert.IsTrue(val, "Reflection Test");
        }
Exemple #9
0
        private object[] Proxy(ISender sender, int maxResultsToWait, string method, object[] args)
        {
            BlockingQueue q = new BlockingQueue(maxResultsToWait);

            args = AdrXmlRpcConverter.XmlRpc2AdrParams(args);
            _rpc.Invoke(sender, q, method, args);
            ArrayList allValues = new ArrayList();
            int       counter   = 0;
            ISender   rsSender  = null;

            try {
                do
                {
                    rsSender = null;               //Reset it before the following:
                    RpcResult rpcRs = (RpcResult)q.Dequeue();
                    rsSender = rpcRs.ResultSender; //get it before exception thrown
                    object val = rpcRs.Result;
                    Debug.WriteLine(string.Format("Original Result: {0}", val));
                    object xmlrpc_val = AdrXmlRpcConverter.Adr2XmlRpc(val); //conversion in here
                    counter++;
                    allValues.Add(xmlrpc_val);
                } while (maxResultsToWait < 0 ? true : (counter < maxResultsToWait));
            } catch (Exception e) {
                Debug.WriteLine(e);
                string s = string.Empty;
                if (e is AdrException)
                {
                    if (rsSender != null)
                    {
                        s = AdrXmlRpcConverter.Adr2XmlRpc(rsSender) as string;
                    }
                }
                if (e is InvalidOperationException)
                {
                    /*
                     * this is what we expect at the end of Dequeuing, so just return what we've gotten so far
                     * it could be an empty array
                     */
                    return(allValues.ToArray());
                }
                Exception new_e = AdrXmlRpcConverter.Adr2XmlRpc(e) as Exception;
                throw new Exception(new_e.Message +
                                    (s.Equals(string.Empty) ? string.Empty : string.Format("thrown by: {0}", s)));
            } finally {
                if (!q.Closed)
                {
                    q.Close();
                }
            }
            return(allValues.ToArray());
        }
        /// <summary>Seek TAs.</summary>
        protected override void SeekTAs(DateTime now)
        {
            Channel queue = new Channel();

            queue.EnqueueEvent += HandleSeekTAs;
            try {
                ISender mcs = _iphandler.CreateMulticastSender();
                _rpc.Invoke(mcs, queue, RPC_CLASS + ".SeekTAs", _realm);
            } catch (SendException) {
                /*
                 * On planetlab, it is not uncommon to have a node that does not allow
                 * Multicast, and it will throw an exception here.  We just ignore this
                 * information for now.  If we don't the heartbeatevent in the node
                 * will not execute properly.
                 */
            }
        }
Exemple #11
0
        private async void Start()
        {
            while (listener.IsListening)
            {
                try
                {
                    HttpListenerContext context = await listener.GetContextAsync();

                    var requestContent = new StreamReader(context.Request.InputStream).ReadToEnd();

                    Result <object, RpcError> result;
                    MethodCallContext?        call = null;

                    try
                    {
                        call = MethodCallContext.FromJson(requestContent);

                        if (call.JsonRpcVersion != RpcManager.JsonRpcVersion)
                        {
                            result = new Result <object, RpcError>(
                                new InvalidRequest($"Incompatible RPC versions call {call.JsonRpcVersion} vs current {RpcManager.JsonRpcVersion}"));
                        }
                        else
                        {
                            result = RpcManager.Invoke(call.MethodName, call.Params.ToArray());
                        }
                    }
                    catch (Exception e)
                    {
                        result = new Result <object, RpcError>((ParseError)e);
                    }

                    var response = RpcResponse.ToJson(RpcManager.JsonRpcVersion, result, call == null ? 0 : call.Id);

                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(response);

                    context.Response.ContentLength64 = buffer.Length;
                    context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                    context.Response.OutputStream.Close(); // Must close output stream
                }
                catch (ObjectDisposedException)
                {
                    return;
                }
            }
        }
Exemple #12
0
        /**
         * Used to request other nodes existence
         */
        protected void Announce()
        {
            Channel queue = new Channel();

            queue.EnqueueEvent += HandleGetInformation;
            try {
                ISender mcs = _node.IPHandler.CreateMulticastSender();
                _rpc.Invoke(mcs, queue, "LocalCO.GetInformation");
            }
            catch (SendException) {
                /*
                 * On planetlab, it is not uncommon to have a node that
                 * does not allow Multicast, and it will throw an exception
                 * here.  We just ignore this information for now.  If we don't
                 * the heartbeatevent in the node will not execute properly.
                 */
            }
        }
        protected void SendRpcMessage(Address addr, string method,
                                      string query, bool secure)
        {
            DateTime sent = DateTime.Now;

#if !SVPN_NUNIT
            string  meth_call = RPCID + "." + method;
            Channel q         = new Channel();
            q.CloseAfterEnqueue();
            q.CloseEvent += delegate(object obj, EventArgs eargs) {
                try {
                    RpcResult res    = (RpcResult)q.Dequeue();
                    string    result = (string)res.Result;

                    if (method == "Ping")
                    {
                        DateTime recv = DateTime.Now;
                        _times = _times.InsertIntoNew(result, recv);
                        TimeSpan rtt = recv - sent;
                        _ssm.UpdateLatency(result, rtt.TotalMilliseconds);
                    }

                    ProtocolLog.WriteIf(SocialLog.SVPNLog,
                                        String.Format("RPC {0} {1} {2}", addr.ToString(), method,
                                                      query));
                } catch (Exception e) {
                    ProtocolLog.WriteIf(SocialLog.SVPNLog, e.ToString());
                }
            };

            ISender sender;
            if (!secure)
            {
                sender = new AHExactSender(_node.Node, addr);
            }
            else
            {
                sender = _node.Bso.GetSecureSender(addr);
            }
            _rpc.Invoke(sender, q, meth_call, _node.Address, query);
#endif
        }
Exemple #14
0
        /*** Gracefully close this connection, if it is not already disconnected.
         * Idempotent (calling it twice is the same as once).
         * @return the old state, new state pair.
         */
        public Pair <ConnectionState, ConnectionState> Close(RpcManager rpc, string reason)
        {
            var old_new = Abort();

            if (old_new.First.Disconnected != true)
            {
                //Now try to tell the other node:
                var close_info = new ListDictionary();
                if (reason != String.Empty)
                {
                    close_info["reason"] = reason;
                }
                Edge e       = old_new.Second.Edge;
                var  results = new Channel(1);
                //Either the RPC call times out, or we get a response.
                results.CloseEvent += delegate(object o, EventArgs args) {
                    e.Close();
                };
                try { rpc.Invoke(e, results, "sys:link.Close", close_info); }
                catch { e.Close(); }
            }
            return(old_new);
        }
Exemple #15
0
        /**
         * When we get a response to the sys:link method, this handled
         * is called
         */
        protected void LinkCloseHandler(object q, EventArgs args)
        {
            try {
                Channel resq = (Channel)q;
                //If the Channel is empty this will throw an exception:
                RpcResult res = (RpcResult)resq.Dequeue();
                /* Here's the LinkMessage response */
                LinkMessage lm = new LinkMessage((IDictionary)res.Result);

                /**
                 * This will set our LinkMessageReply variable.  It can
                 * only be set once, so all future sets will fail.  It
                 * will also make sure we have the lock on the target.
                 * If we don't, that will throw an exception
                 */
                SetAndCheckLinkReply(lm);
                //If we got here, we have our response and the Lock on _target_address
                StatusMessage sm = _node.GetStatus(_contype, lm.Local.Address);
                /* Make the call */
                Channel results = new Channel();
                results.CloseAfterEnqueue();
                results.CloseEvent += this.StatusCloseHandler;
                RpcManager rpc = _node.Rpc;
                if (ProtocolLog.LinkDebug.Enabled)
                {
                    ProtocolLog.Write(ProtocolLog.LinkDebug,
                                      String.Format(
                                          "LPS target: {0} Invoking GetStatus() over edge: {1}",
                                          _linker.Target, _e));
                }

                /*
                 * This could throw an exception if the Edge is closed
                 */
                rpc.Invoke(_e, results, "sys:link.GetStatus", sm.ToDictionary());
            }
            catch (AdrException x) {
                /*
                 * This happens when the RPC call has some kind of issue,
                 * first we check for common error conditions:
                 */
                _x.Value = x;
                Finish(GetResultForErrorCode(x.Code));
            }
            catch (ConnectionExistsException x) {
                /* We already have a connection */
                _x.Value = x;
                Finish(Result.ProtocolError);
            }
            catch (CTLockException x) {
                //This is thrown when ConnectionTable cannot lock.  Lets try again:
                _x.Value = x;
                Finish(Result.RetryThisTA);
            }
            catch (LinkException x) {
                _x.Value = x;
                if (x.IsCritical)
                {
                    Finish(Result.MoveToNextTA);
                }
                else
                {
                    Finish(Result.RetryThisTA);
                }
            }
            catch (InvalidOperationException) {
                //The queue never got anything
                Finish(Result.MoveToNextTA);
            }
            catch (EdgeException) {
                //The Edge is goofy, let's move on:
                Finish(Result.MoveToNextTA);
            }
            catch (Exception x) {
                //The protocol was not followed correctly by the other node, fail
                _x.Value = x;
                Finish(Result.RetryThisTA);
            }
        }
Exemple #16
0
        /**
         * This starts a linking operation on the given edge
         */
        public IDictionary Start(IDictionary link_message, ISender edge)
        {
            if (ProtocolLog.LinkDebug.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.LinkDebug, String.Format(
                                      "{0} -start- sys:link.Start", _node.Address));
            }

            Edge        from = GetEdge(edge);
            LinkMessage lm   = new LinkMessage(link_message);

            if (ProtocolLog.LinkDebug.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.LinkDebug, String.Format(
                                      "{0} -args- sys:link.Start({1},{2})", _node.Address, lm, from));
            }

            CphState cph = new CphState(from, lm);

            lock ( _sync ) {
                if (!_edge_to_cphstate.ContainsKey(from))
                {
                    _edge_to_cphstate[from] = cph;
                }
                else
                {
                    throw new AdrException((int)ErrorMessage.ErrorCode.InProgress,
                                           "Already have a link in progress on this edge");
                }
            }
            ErrorMessage err = null;

            if (CanConnect(cph, out err))
            {
                try {
                    //If the CloseEvent was already called, this throws an exception
                    from.CloseEvent += this.CloseHandler;
                }
                catch {
                    CloseHandler(from, null);
                    throw new AdrException((int)ErrorMessage.ErrorCode.EdgeClosed,
                                           "Edge Closed after receiving message");
                }
            }
            else
            {
                lock ( _sync ) {
                    _edge_to_cphstate.Remove(from);
                }
            }
            //Now we prepare our response
            LinkMessage lm_resp = null;

            if (err == null)
            {
                //We send a response:
                NodeInfo n_info      = NodeInfo.CreateInstance(_node.Address, from.LocalTA);
                NodeInfo remote_info = NodeInfo.CreateInstance(null, from.RemoteTA);
                System.Collections.Specialized.StringDictionary attrs =
                    new System.Collections.Specialized.StringDictionary();
                attrs["type"]  = String.Intern(lm.ConTypeString);
                attrs["realm"] = String.Intern(_node.Realm);
                lm_resp        = new LinkMessage(attrs, n_info, remote_info, lm.Token);
            }
            else
            {
                if (err.Ec == ErrorMessage.ErrorCode.AlreadyConnected)
                {
                    /**
                     * When we send the ErrorCode.AlreadyConnected,
                     * we could have a stale connection, lets try pinging
                     * the other node, if they are there, but have lost
                     * the Edge, this may trigger the edge to close, causing
                     * us to remove the Connection.
                     * @todo consider putting this address on a "fast track"
                     * to removal if we don't hear from it soon
                     */
                    ConnectionTable tab = _node.ConnectionTable;
                    Connection      c   = tab.GetConnection(lm.ConnectionType,
                                                            lm.Local.Address);
                    if (c != null)
                    {
                        RpcManager rpc = _node.Rpc;
                        rpc.Invoke(c.Edge, null, "sys:link.Ping", String.Empty);
                    }
                }
            }
            if (err != null)
            {
                throw new AdrException((int)err.Ec, err.Message);
            }
            if (ProtocolLog.LinkDebug.Enabled)
            {
                ProtocolLog.Write(ProtocolLog.LinkDebug, String.Format(
                                      "{0} -end- sys:link.Start()->{1}", _node.Address, lm_resp));
            }
            return(lm_resp.ToDictionary());
        }
Exemple #17
0
        protected void GenTreeHandler(object chano, EventArgs args)
        {
            if (LogEnabled)
            {
                ProtocolLog.Write(ProtocolLog.MapReduce,
                                  String.Format("MapReduce: {0}, GenTreeHandler", _node.Address));
            }
            Channel gtchan = (Channel)chano;

            MapReduceInfo[] children;
            object          gtchan_result = null;

            try {
                gtchan_result = gtchan.Dequeue();
                children      = (MapReduceInfo[])gtchan_result;
            }
            catch (Exception x) {
                //We could fail to return (queue is empty), or get a bad result
                Exception rx = gtchan_result as Exception;
                if (rx != null)
                {
                    x = rx; //x should have been a bad cast
                }
                if (LogEnabled)
                {
                    ProtocolLog.Write(ProtocolLog.MapReduce,
                                      String.Format("MapReduce: {0}, GenTreeHandler exception ({1})", _node.Address, x));
                }
                HandleException(null, x);
                return;
            }
            //The usual transactional bit:
            State state = _state;
            State old_state;
            State new_state;

            do
            {
                old_state = state;
                new_state = old_state.UpdateTree(children);
                state     = Interlocked.CompareExchange <State>(ref _state, new_state, old_state);
            }while(state != old_state);
            if (new_state.Done)
            {
                //We don't need to start calling our children
                if (LogEnabled)
                {
                    ProtocolLog.Write(ProtocolLog.MapReduce,
                                      String.Format("MapReduce: {0}, done on GenTreeHandler", _node.Address));
                }
                SendResult(new_state.ReduceResult);
                return;
            }
            //Now we need to start calling our children:
            foreach (MapReduceInfo mri in children)
            {
                Channel child_q = new Channel(1, mri);
                child_q.CloseEvent += this.ChildCallback;
                try {
                    if (LogEnabled)
                    {
                        ProtocolLog.Write(ProtocolLog.MapReduce,
                                          String.Format("MapReduce: {0}, calling child ({1})", _node.Address, mri.Sender.ToUri()));
                    }
                    _rpc.Invoke(mri.Sender, child_q, "mapreduce.Start", mri.Args.ToHashtable());
                }
                catch (Exception x) {
                    if (LogEnabled)
                    {
                        ProtocolLog.Write(ProtocolLog.MapReduce,
                                          String.Format("MapReduce: {0}, child ({1}) call threw: {2}.", _node.Address, mri.Sender.ToUri(), x));
                    }
                    HandleException(mri.Sender, x);
                }
            }
        }
Exemple #18
0
 public void BenchmarkFragPing(int fsize, int reps) {
   List<int> mu_sec_pings = new List<int>();
   Random my_r = new Random();
   ArrayList nodes = null;
   lock(_sync) {
     //Make a copy
     nodes = new ArrayList(_node_list);
   }
   Stack<Action> pings = new Stack<Action>();
   for(int i = 0; i < reps; i++) {
     int idx0 = my_r.Next(0, nodes.Count);
     int idx1 = my_r.Next(0, nodes.Count);
     Node n0 = (Node)nodes[idx0];
     Node n1 = (Node)nodes[idx1];
     Action ping = delegate() {
       RpcManager pinger = n0.Rpc;
       Channel results = new Channel(1, new WriteOnce<DateTime>());
       results.CloseEvent += delegate(object q, EventArgs a) {
         try {
           results.Dequeue();
           TimeSpan rttts = DateTime.UtcNow - ((WriteOnce<DateTime>)results.State).Value;
           mu_sec_pings.Add((int)(1000 * rttts.TotalMilliseconds));
         }
         catch(Exception x) {
           Console.WriteLine("target: {0}, Exception: {1}", n1.Address, x);
         }
         if( pings.Count > 0 ) {
           var next = pings.Pop();
           next();
         }
         else {
           double ave_rtt = 0;
           foreach(int s in mu_sec_pings) {
             ave_rtt += (double)s;     
           }
           ave_rtt /= mu_sec_pings.Count;
           double var = 0;
           foreach(int s in mu_sec_pings) {
             var += (ave_rtt - (double)s) * (ave_rtt - (double)s);
           }
           var /= mu_sec_pings.Count;
           var stdev = Math.Sqrt(var);
           mu_sec_pings.Sort();
           var median = mu_sec_pings[ mu_sec_pings.Count / 2];
           Console.WriteLine("Average: {0} Median: {1} Stdev: {2} Samples: {3} Reps: {4}",
                             ave_rtt, median, stdev, mu_sec_pings.Count, reps); 
         }
       };
       try {
         var sender = new FragmentingSender(1400, new AHExactSender(n0, n1.Address));
         var data = new byte[fsize];
         my_r.NextBytes(data);
         ((WriteOnce<DateTime>)results.State).Value = DateTime.UtcNow;
         pinger.Invoke(sender, results, "sys:link.Ping", data);
       }
       catch(Exception x) {
         Console.WriteLine("Exception: {0}", x);
         if( pings.Count > 0 ) {
           var next = pings.Pop();
           next();
         }
         else {
           double ave_rtt = 0;
           foreach(int s in mu_sec_pings) {
             ave_rtt += (double)s;     
           }
           ave_rtt /= mu_sec_pings.Count;
           double var = 0;
           foreach(int s in mu_sec_pings) {
             var += (ave_rtt - (double)s) * (ave_rtt - (double)s);
           }
           var /= mu_sec_pings.Count;
           var stdev = Math.Sqrt(var);
           mu_sec_pings.Sort();
           var median = mu_sec_pings[ mu_sec_pings.Count / 2];
           Console.WriteLine("Average: {0} Median: {1} Stdev: {2} Samples: {3} Reps: {4}",
                             ave_rtt, median, stdev, mu_sec_pings.Count, reps); 
         }
       }
     };
     pings.Push(ping);
   }
   //Now pop off the first one and go:
   var first = pings.Pop();
   first();
 }
Exemple #19
0
        public static void Main(string [] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("please specify the number edge protocol.");
                Environment.Exit(0);
            }
            if (args.Length < 2)
            {
                Console.WriteLine("please specify the number of p2p nodes.");
                Environment.Exit(0);
            }
            if (args.Length < 3)
            {
                Console.WriteLine("please specify the number of missing edges.");
                Environment.Exit(0);
            }
            string proto = "function";

            try {
                proto = args[0].Trim();
            } catch (Exception) {}

            bool tunnel        = false;
            int  base_port     = 54000;
            int  network_size  = Int32.Parse(args[1]);
            int  missing_count = Int32.Parse(args[2]);

            try {
                tunnel = args[3].Trim().Equals("tunnel");
            } catch (Exception) {}

            Console.WriteLine("use tunnel edges: {0}", tunnel);

            Random rand = new Random();

            ArrayList missing_edges = new ArrayList();

            for (int i = 0; i < missing_count; i++)
            {
                int idx = -1;
                int left, right;
                do
                {
                    idx  = rand.Next(0, network_size);
                    left = (idx + 1) % network_size;
                    if (idx == 0)
                    {
                        right = network_size - 1;
                    }
                    else
                    {
                        right = idx - 1;
                    }
                } while (missing_edges.Contains(idx));// ||
                //missing_edges.Contains(left) ||
                //missing_edges.Contains(right));

                Console.WriteLine("Will drop a left edge on idx {0}: ", idx);
                missing_edges.Add(idx);
            }

            //
            // Sort missing edges.
            //
            missing_edges.Sort();
            SortedList dist = new SortedList();

            //
            // Compute the average distance between missing edges.
            //
            if (missing_count > 1)
            {
                for (int i = 0; i < missing_count; i++)
                {
                    int idx = (int)missing_edges[i];
                    int idx_next;
                    int d;
                    if (i == missing_count - 1)
                    {
                        idx_next = (int)missing_edges[0];
                        d        = (network_size - 1) - idx + idx_next;
                    }
                    else
                    {
                        idx_next = (int)missing_edges[i + 1];
                        d        = idx_next - idx - 1;
                    }
                    if (!dist.Contains(d))
                    {
                        dist[d] = 0;
                    }
                    else
                    {
                        int c = (int)dist[d];
                        dist[d] = c + 1;
                    }
                }
            }
            double sum = 0.0;
            int    num = 0;

            Console.WriteLine("distribution of missing edges separation");
            foreach (DictionaryEntry de in dist)
            {
                int k = (int)de.Key;
                int c = (int)de.Value;
                Console.WriteLine("{0} {1}", k, c);
                sum = sum + k * c;
                num = num + c;
            }

            Console.WriteLine("average separation: {0}", (double)sum / num);
            string brunet_namespace = "testing";

            Console.WriteLine("Initializing...");

            var RemoteTA = new List <TransportAddress>();

            for (int i = 0; i < network_size; i++)
            {
                if (proto.Equals("udp"))
                {
                    RemoteTA.Add(TransportAddressFactory.CreateInstance("brunet.udp://localhost:" + (base_port + i)));
                }
                else if (proto.Equals("function"))
                {
                    RemoteTA.Add(TransportAddressFactory.CreateInstance("brunet.function://localhost:" + (base_port + i)));
                }
            }

            for (int i = 0; i < network_size; i++)
            {
                AHAddress address = new AHAddress(new RNGCryptoServiceProvider());
                Node      node    = new StructuredNode(address, brunet_namespace);
                _sorted_node_list.Add((Address)address, node);
                _node_list.Add(node);
                RouteTestHandler test_handler = new RouteTestHandler();
                node.GetTypeSource(new PType(routing_test)).Subscribe(test_handler, address.ToMemBlock());
                RpcManager rpc_man = node.Rpc;
                rpc_man.AddHandler("rpc_routing_test", new  RpcRoutingTestHandler(node));
            }

            for (int i = 0; i < network_size; i++)
            {
                Node node = (Node)_sorted_node_list.GetByIndex(i);
                Console.WriteLine("Configuring node: {0} ", node.Address);
                TAAuthorizer ta_auth = null;
                if (missing_edges.Contains(i))
                {
                    int remote_port;
                    if (i == network_size - 1)
                    {
                        remote_port = base_port;
                    }
                    else
                    {
                        remote_port = base_port + i + 1;
                    }

                    PortTAAuthorizer port_auth = new PortTAAuthorizer(remote_port);
                    Console.WriteLine("Adding a port TA authorizer at: {0} for remote port: {1}", base_port + i, remote_port);
                    ArrayList arr_tas = new ArrayList();
                    arr_tas.Add(port_auth);
                    arr_tas.Add(new ConstantAuthorizer(TAAuthorizer.Decision.Allow));
                    ta_auth = new SeriesTAAuthorizer(arr_tas);
                }

                if (proto.Equals("udp"))
                {
                    node.AddEdgeListener(new UdpEdgeListener(base_port + i, null, ta_auth));
                }
                else if (proto.Equals("function"))
                {
                    node.AddEdgeListener(new FunctionEdgeListener(base_port + i, -1.00, ta_auth));
                }

                if (tunnel)
                {
                    Console.WriteLine("Adding a tunnel edge listener");
                    node.AddEdgeListener(new Relay.RelayEdgeListener(node));
                }
                _node_to_port[node] = base_port + i;
                node.RemoteTAs      = RemoteTA;
            }

            //start nodes one by one.
            for (int i = 0; i < network_size; i++)
            {
                Node node = (Node)_node_list[i];
                Console.WriteLine("Starting node: {0}, {1}", i, node.Address);
                node.Connect();
                Console.WriteLine("Going to sleep for 2 seconds.");
                System.Threading.Thread.Sleep(2000);
            }

            //wait for 300000 more seconds
            Console.WriteLine("Going to sleep for 300000 seconds.");
            System.Threading.Thread.Sleep(300000);
            bool complete = CheckStatus();

            int count = 0;

            //
            // Send a large number of packets as exact packets to random destinations
            // and make sure exact routing is perfect.
            //

            for (int i = 0; i < network_size; i++)
            {
                for (int j = 0; j < network_size; j++)
                {
                    int  src_idx   = i;
                    int  dest_idx  = j;
                    Node src_node  = (Node)_sorted_node_list.GetByIndex(src_idx);
                    Node dest_node = (Node)_sorted_node_list.GetByIndex(dest_idx);
                    //Console.WriteLine("{0} -> {1}", src_idx, dest_idx);
                    Address  dest_address = (Address)dest_node.Address;
                    ISender  s            = new AHExactSender(src_node, dest_address);
                    MemBlock p            = dest_address.ToMemBlock();
                    s.Send(new CopyList(new PType(routing_test), p));
                    _sent++;
                    //System.Threading.Thread.Sleep(10);
                    s.Send(new CopyList(new PType(routing_test), p));
                    _sent++;
                    //System.Threading.Thread.Sleep(10);
                }
            }
            //wait for 10 more seconds
            Console.WriteLine("Going to sleep for 10 seconds.");
            System.Threading.Thread.Sleep(10000);
            Console.WriteLine("Final statistics");
            lock (_class_lock) {
                Console.WriteLine("Sent: {0}, Received: {1}, Wrongly routed: {2}",
                                  _sent, _received, _wrongly_routed);
            }

            int       missing_rpcs     = 0;
            int       correct_rpcs     = 0;
            int       incorrect_rpcs   = 0;
            Hashtable queue_to_address = new Hashtable();

            for (int i = 0; i < network_size; i++)
            {
                for (int j = 0; j < network_size; j++)
                {
                    int  src_idx   = i;
                    int  dest_idx  = j;
                    Node src_node  = (Node)_sorted_node_list.GetByIndex(src_idx);
                    Node dest_node = (Node)_sorted_node_list.GetByIndex(dest_idx);
                    //Console.WriteLine("{0} -> {1}", src_idx, dest_idx);
                    Address    dest_address = (Address)dest_node.Address;
                    ISender    s            = new AHExactSender(src_node, dest_address);
                    RpcManager rpc_man      = src_node.Rpc;
                    Channel    q            = new Channel();
                    lock (_class_lock) {
                        queue_to_address[q] = dest_address;
                    }
                    q.CloseAfterEnqueue();
                    q.CloseEvent += delegate(object o, EventArgs cargs) {
                        lock (_class_lock) {
                            Channel qu = (Channel)o;
                            if (qu.Count == 0)
                            {
                                missing_rpcs++;
                            }
                            queue_to_address.Remove(qu);
                        }
                    };
                    q.EnqueueEvent += delegate(object o, EventArgs cargs) {
                        lock (_class_lock) {
                            Channel   qu        = (Channel)o;
                            RpcResult rpc_reply = (RpcResult)qu.Peek();
                            byte []   result    = (byte[])rpc_reply.Result;
                            Address   target    = new AHAddress(result);
                            if (target.Equals(queue_to_address[qu]))
                            {
                                correct_rpcs++;
                            }
                            else
                            {
                                incorrect_rpcs++;
                            }
                        }
                    };
                    rpc_man.Invoke(s, q, "rpc_routing_test.GetIdentification", new object[] {});
                }
            }

            //wait for 10 more seconds
            while (true)
            {
                int c = -1;
                lock (_class_lock) {
                    c = incorrect_rpcs + missing_rpcs + correct_rpcs;
                }
                if (c < network_size * network_size)
                {
                    Console.WriteLine("Going to sleep for 10 seconds.");
                    System.Threading.Thread.Sleep(10000);
                }
                else
                {
                    break;
                }
            }

            Console.WriteLine("Final statistics");
            Console.WriteLine("correct rpcs: {0}, incorrect rpcs: {1}, missing rpcs: {2}",
                              correct_rpcs, incorrect_rpcs, missing_rpcs);

            System.Environment.Exit(1);
        }
Exemple #20
0
        public void BenchmarkPing(int reps)
        {
            List <int> mu_sec_pings = new List <int>();
            Random     my_r         = new Random();
            ArrayList  nodes        = null;

            lock (_sync) {
                //Make a copy
                nodes = new ArrayList(_node_list);
            }
            Stack <Action> pings = new Stack <Action>();

            for (int i = 0; i < reps; i++)
            {
                int    idx0 = my_r.Next(0, nodes.Count);
                int    idx1 = my_r.Next(0, nodes.Count);
                Node   n0   = (Node)nodes[idx0];
                Node   n1   = (Node)nodes[idx1];
                Action ping = delegate() {
                    RpcManager pinger  = n0.Rpc;
                    Channel    results = new Channel(1);
                    results.CloseEvent += delegate(object q, EventArgs a) {
                        try {
                            object      result = results.Dequeue();
                            RpcResult   r      = (RpcResult)result;
                            IDictionary data   = (IDictionary)r.Result;
                            int         rtt    = (int)data["musec"];
                            //Console.WriteLine("target: {0}, rtt: {1}", data["target"], data["musec"]);
                            mu_sec_pings.Add(rtt);
                        }
                        catch (Exception x) {
                            Console.WriteLine("target: {0}, Exception: {1}", n1.Address, x);
                        }
                        if (pings.Count > 0)
                        {
                            var next = pings.Pop();
                            next();
                        }
                        else
                        {
                            double ave_rtt = 0;
                            foreach (int s in mu_sec_pings)
                            {
                                ave_rtt += (double)s;
                            }
                            ave_rtt /= mu_sec_pings.Count;
                            double var = 0;
                            foreach (int s in mu_sec_pings)
                            {
                                var += (ave_rtt - (double)s) * (ave_rtt - (double)s);
                            }
                            var /= mu_sec_pings.Count;
                            var stdev = Math.Sqrt(var);
                            mu_sec_pings.Sort();
                            var median = mu_sec_pings[mu_sec_pings.Count / 2];
                            Console.WriteLine("Average: {0} Median: {1} Stdev: {2} Samples: {3} Reps: {4}",
                                              ave_rtt, median, stdev, mu_sec_pings.Count, reps);
                        }
                    };
                    try {
                        pinger.Invoke(n0, results, "trace.GetRttTo", n1.Address.ToString());
                    }
                    catch (Exception x) {
                        Console.WriteLine("Exception: {0}", x);
                        if (pings.Count > 0)
                        {
                            var next = pings.Pop();
                            next();
                        }
                        else
                        {
                            double ave_rtt = 0;
                            foreach (int s in mu_sec_pings)
                            {
                                ave_rtt += (double)s;
                            }
                            ave_rtt /= mu_sec_pings.Count;
                            double var = 0;
                            foreach (int s in mu_sec_pings)
                            {
                                var += (ave_rtt - (double)s) * (ave_rtt - (double)s);
                            }
                            var /= mu_sec_pings.Count;
                            var stdev = Math.Sqrt(var);
                            mu_sec_pings.Sort();
                            var median = mu_sec_pings[mu_sec_pings.Count / 2];
                            Console.WriteLine("Average: {0} Median: {1} Stdev: {2} Samples: {3} Reps: {4}",
                                              ave_rtt, median, stdev, mu_sec_pings.Count, reps);
                        }
                    }
                };
                pings.Push(ping);
            }
            //Now pop off the first one and go:
            var first = pings.Pop();

            first();
        }