Beispiel #1
0
        protected override async Task <Response> OnExecute(ExecutionContext context, Request request)
        {
            var branch = await context.Branch().ConfigureAwait(false);

            using var transaction = branch.BeginTransaction();

            var serviceNode = new ServiceNode()
            {
                Id        = NodeId.Create <ServiceNode>(request.Id),
                ServiceId = request.Id,
                Metadata  = NodeMetadata.Create(context.TimeProvider())
            };

            if (await branch.Services.PutIfAbsentAsync(serviceNode.Id, serviceNode)
                .ConfigureAwait(false))
            {
                await transaction.CommitAsync().ConfigureAwait(false);

                return(new Response()
                {
                    Service = serviceNode.ToOutput()
                });
            }

            throw new ExecutionException(ExecutionErrorType.Conflict, $"Service {request.Id} already exist");
        }
Beispiel #2
0
        private BoilerDataType GetBoilerModel()
        {
            var nodeId = NodeId.Create(BoilerModel.Variables.Boiler1_BoilerStatus, OpcPlc.Namespaces.OpcPlcBoiler, Session.NamespaceUris);
            var value  = Session.ReadValue(nodeId).Value;

            return(value.Should().BeOfType <ExtensionObject>().Which.Body.Should().BeOfType <BoilerDataType>().Subject);
        }
        public async Task Create(string branchId, string?sourceBranchId)
        {
            var node = CreateNode();

            node.Id       = NodeId.Create <TBranchNode>(branchId);
            node.Metadata = NodeMetadata.Create(timeProvider);
            node.SourceId = sourceBranchId;

            if (await branchCache.PutIfAbsentAsync(node.Id, node).ConfigureAwait(false))
            {
                Schema.Create(Ignite, branchId);

                if (sourceBranchId != null)
                {
                    if (await Exists(sourceBranchId).ConfigureAwait(false))
                    {
                        await Schema.Copy(Ignite, sourceBranchId, branchId).ConfigureAwait(false);
                    }
                    else
                    {
                        throw new IgniteException($"Branch {sourceBranchId} does not exist");
                    }
                }
            }
        }
Beispiel #4
0
    public void AddState()
    {
        List <int> conditions = new List <int>();
        Node       _node      = new Node(NodeId.Create(), 310, 20, 1, Constants.S_INIT, conditions);

        nodes[current_type].Add(_node.id, _node);
    }
 public void Setup()
 {
     listener = new TestListener();
     node     = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Any, 0));
     engine   = new DhtEngine(listener);
     //engine.Add(node);
 }
        public override void Execute()
        {
            if (Active)
            {
                return;
            }

            Active = true;

            // If we were given a list of nodes to load at the start, use them
            if (initialNodes.Count > 0)
            {
                foreach (Node node in initialNodes)
                {
                    engine.Add(node);
                }
                SendFindNode(initialNodes);
            }
            else
            {
                try
                {
                    Node utorrent = new Node(NodeId.Create(), new System.Net.IPEndPoint(Dns.GetHostEntry("router.bittorrent.com").AddressList[0], 6881));
                    SendFindNode(new Node[] { utorrent });
                }
                catch
                {
                    RaiseComplete(new TaskCompleteEventArgs(this));
                }
            }
        }
Beispiel #7
0
        private void SendFindNode(Node node)
        {
            FindNode msg = new FindNode(GetNeighborId(node.Id), NodeId.Create());

            //FindNode msg = new FindNode(LocalId, NodeId.Create());
            Send(msg, node.EndPoint);
        }
Beispiel #8
0
        public override void Execute()
        {
            if (Active)
            {
                return;
            }

            Active = true;

            // If we were given a list of nodes to load at the start, use them
            if (_initialNodes.Count > 0)
            {
                foreach (var node in _initialNodes)
                {
                    _engine.Add(node);
                }
                SendFindNode(_initialNodes);
            }
            else
            {
                try
                {
                    var utorrent = new Node(NodeId.Create(),
                                            new IPEndPoint(Dns.ResolveAddress("router.bittorrent.com"), 6881));
                    SendFindNode(new[] { utorrent });
                }
                catch
                {
                    RaiseComplete(new TaskCompleteEventArgs(this));
                }
            }
        }
Beispiel #9
0
        public void Start()
        {
            var bootstrap = new Node[]
            {
                new Node
                (
                    NodeId.Create(),
                    new IPEndPoint(Dns.GetHostEntry("router.bittorrent.com").AddressList[0], 6881)
                ),
                new Node
                (
                    NodeId.Create(),
                    new IPEndPoint(Dns.GetHostEntry("dht.transmissionbt.com").AddressList[0], 6881)
                ),
                new Node
                (
                    NodeId.Create(),
                    new IPEndPoint(Dns.GetHostEntry("router.utorrent.com").AddressList[0], 6881)
                ),
                new Node
                (
                    NodeId.Create(),
                    new IPEndPoint(Dns.GetHostEntry("1.a.magnets.im").AddressList[0], 6881)
                )
            };

            Start(bootstrap);
        }
Beispiel #10
0
        private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            List <Node> next = new List <Node>(maxnodes);

            lock (find_queue)
            {
                for (int i = 0; i < maxnodes &&
                     find_queue.Count > 0 &&
                     activities < maxnodes * 10; i++)
                {
                    var n = find_queue.Dequeue();
                    if (!nodes.Contains(n))
                    {
                        next.Add(n);
                        logAdd("Send FindNode");
                    }
                    nodes.Add(n);
                }
            }
            SendFindNode(next, NodeId.Create());

            if (nodes.Count > 10000)
            {
                nodes = new HashSet <Node>();
            }

            Display();
        }
Beispiel #11
0
 public TaskTests()
 {
     _counter  = 0;
     _listener = new TestListener();
     _engine   = new DhtEngine(_listener);
     _node     = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Any, 4));
     _handle   = new ManualResetEvent(false);
 }
 public async Task Delete(string branchId)
 {
     if (await branchCache.RemoveAsync(NodeId.Create <TBranchNode>(branchId))
         .ConfigureAwait(false))
     {
         Schema.Delete(Ignite, branchId);
     }
 }
Beispiel #13
0
 public DHTSpider(IPEndPoint localAddress, IQueue queue)
 {
     LocalId           = NodeId.Create();
     udpSocketListener = new UdpSocketListener(localAddress);
     KTable            = new ConcurrentDictionary <string, Node>();
     TokenManager      = new EasyTokenManager();
     Queue             = queue;
     MessageQueue      = new ConcurrentQueue <KeyValuePair <IPEndPoint, byte[]> >();
 }
Beispiel #14
0
        /// <summary>
        /// Sets value of VC property to OPCUA node
        /// </summary>
        private void vc_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            IProperty vcProperty = (IProperty)sender;

            // Get OPCUA node that will get its value updated
            string nodeNameParent            = String.Format("{0}-{1}", vcProperty.Name, vcProperty.Container);
            NodeId nodeId                    = NodeId.Create(nodeNameParent, Namespaces.vc2opcua, uaServer.NamespaceUris);
            BaseDataVariableState uaProperty = (BaseDataVariableState)nodeManager.FindPredefinedNode(nodeId, typeof(BaseDataVariableState));

            if (uaProperty == null)
            {
                // Unsubscribe to events
                vcProperty.PropertyChanged -= vc_PropertyChanged;
                return;
            }

            if (vcProperty.PropertyType == typeof(String))
            {
                if ((string)uaProperty.Value == (string)vcProperty.Value)
                {
                    return;
                }
                uaProperty.Value = (string)vcProperty.Value;
            }
            else if (vcProperty.PropertyType == typeof(Boolean))
            {
                if ((bool)uaProperty.Value == (bool)vcProperty.Value)
                {
                    return;
                }
                uaProperty.Value = (bool)vcProperty.Value;
            }
            else if (vcProperty.PropertyType == typeof(Double))
            {
                if ((double)uaProperty.Value == (double)vcProperty.Value)
                {
                    return;
                }
                uaProperty.Value = (double)vcProperty.Value;
            }
            else if (vcProperty.PropertyType == typeof(Int32))
            {
                if ((int)uaProperty.Value == (int)vcProperty.Value)
                {
                    return;
                }
                uaProperty.Value = (int)vcProperty.Value;
            }
            else
            {
                _vcUtils.VcWriteWarningMsg("VC property type not supported" + vcProperty.PropertyType.ToString());
                return;
            }

            uaProperty.Timestamp = DateTime.UtcNow;
            uaProperty.ClearChangeMasks(nodeManager.context, true);
        }
Beispiel #15
0
        public Node FindNode(NodeId nid)
        {
            var node = new Node(NodeId.Create(), LocalAddress);

            if (KTable.TryGetValue(nid.ToString(), out node))
            {
                return(node);
            }
            return(null);
        }
Beispiel #16
0
        public void AnnouncePeerEncode()
        {
            Node n = new Node(NodeId.Create(), null);

            n.Token = _token;
            AnnouncePeer m = new AnnouncePeer(_id, _infohash, 6881, _token);

            m.TransactionId = _transactionId;

            Compare(m, "d1:ad2:id20:abcdefghij01234567899:info_hash20:mnopqrstuvwxyz1234564:porti6881e5:token8:aoeusnthe1:q13:announce_peer1:t2:aa1:y1:qe");
        }
Beispiel #17
0
        public void BucketRefreshTest()
        {
            var nodes = new List <Node>();

            for (var i = 0; i < 5; i++)
            {
                nodes.Add(new Node(NodeId.Create(), new IPEndPoint(IPAddress.Any, i)));
            }

            _engine.TimeOut = TimeSpan.FromMilliseconds(25);
            _engine.BucketRefreshTimeout   = TimeSpan.FromMilliseconds(75);
            _engine.MessageLoop.QuerySent += delegate(object o, SendQueryEventArgs e)
            {
                DhtEngine.MainLoop.Queue(() =>
                {
                    if (!e.TimedOut)
                    {
                        return;
                    }

                    var current = nodes.Find(n => n.EndPoint.Port.Equals(e.EndPoint.Port));
                    if (current == null)
                    {
                        return;
                    }

                    if (e.Query is Ping)
                    {
                        var r = new PingResponse(current.Id, e.Query.TransactionId);
                        _listener.RaiseMessageReceived(r, current.EndPoint);
                    }
                    else if (e.Query is FindNode)
                    {
                        var response = new FindNodeResponse(current.Id,
                                                            e.Query.TransactionId)
                        {
                            Nodes = string.Empty
                        };
                        _listener.RaiseMessageReceived(response, current.EndPoint);
                    }
                });
            };

            _engine.Add(nodes);
            _engine.Start();

            Thread.Sleep(500);

            foreach (var bucket in _engine.RoutingTable.Buckets)
            {
                Assert.IsTrue(bucket.LastChanged > DateTime.UtcNow.AddSeconds(-2));
                Assert.IsTrue(bucket.Nodes.Exists(n => n.LastSeen > DateTime.UtcNow.AddMilliseconds(-900)));
            }
        }
Beispiel #18
0
        public DhtSpider(DhtListener listener)
        {
            if (listener == null)
            {
                throw new ArgumentNullException("listener");
            }

            TokenManager = new EasyTokenManager();
            LocalId      = NodeId.Create();
            MessageLoop  = new MessageLoop(this, listener);
            MessageLoop.ReceivedMessage += MessageLoop_ReceivedMessage;
        }
        public async Task <TBranch> Get(string branchId)
        {
            var node = await branchCache.GetAsyncOrDefault(NodeId.Create <TBranchNode>(branchId))
                       .ConfigureAwait(false);

            if (node != null)
            {
                return(CreateInstance(Ignite, Schema, node));
            }

            throw new IgniteException($"Branch {branchId} does not exist");
        }
Beispiel #20
0
        public void CompactPort()
        {
            var node = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Parse("1.21.121.3"), 511));
            var port = node.CompactPort();

            Assert.AreEqual(1, port.TextBytes[0], "#1");
            Assert.AreEqual(21, port.TextBytes[1], "#1");
            Assert.AreEqual(121, port.TextBytes[2], "#1");
            Assert.AreEqual(3, port.TextBytes[3], "#1");
            Assert.AreEqual(1, port.TextBytes[4], "#1");
            Assert.AreEqual(255, port.TextBytes[5], "#1");
        }
Beispiel #21
0
        public void CompactPort()
        {
            Node           n    = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Parse("1.21.121.3"), 511));
            BEncodedString port = n.CompactAddressPort();

            Assert.Equal(1, port.TextBytes[0]);
            Assert.Equal(21, port.TextBytes[1]);
            Assert.Equal(121, port.TextBytes[2]);
            Assert.Equal(3, port.TextBytes[3]);
            Assert.Equal(1, port.TextBytes[4]);
            Assert.Equal(255, port.TextBytes[5]);
        }
Beispiel #22
0
        public void NodeReplaceTest()
        {
            _engine.TimeOut = TimeSpan.FromMilliseconds(25);
            var handle = new ManualResetEvent(false);
            var b      = new Bucket();

            for (var i = 0; i < Bucket.MaxCapacity; i++)
            {
                var n = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Any, i))
                {
                    LastSeen = DateTime.UtcNow
                };
                b.Add(n);
            }

            b.Nodes[3].LastSeen = DateTime.UtcNow.AddDays(-5);
            b.Nodes[1].LastSeen = DateTime.UtcNow.AddDays(-4);
            b.Nodes[5].LastSeen = DateTime.UtcNow.AddDays(-3);

            _engine.MessageLoop.QuerySent += delegate(object o, SendQueryEventArgs e)
            {
                if (!e.TimedOut)
                {
                    return;
                }

                b.Nodes.Sort();
                if ((e.EndPoint.Port == 3 && _nodeCount == 0) ||
                    (e.EndPoint.Port == 1 && _nodeCount == 1) ||
                    (e.EndPoint.Port == 5 && _nodeCount == 2))
                {
                    var n = b.Nodes.Find(delegate(Node no) { return(no.EndPoint.Port == e.EndPoint.Port); });
                    n.Seen();
                    var response = new PingResponse(n.Id, e.Query.TransactionId);
                    DhtEngine.MainLoop.Queue(delegate
                    {
                        //System.Threading.Thread.Sleep(100);
                        Console.WriteLine("Faking the receive");
                        _listener.RaiseMessageReceived(response, _node.EndPoint);
                    });
                    _nodeCount++;
                }
            };

            var task = new ReplaceNodeTask(_engine, b, null);

            // FIXME: Need to assert that node 0.0.0.0:0 is the one which failed - i.e. it should be replaced
            task.Completed += (o, e) => handle.Set();
            task.Execute();

            Assert.IsTrue(handle.WaitOne(4000, false), "#10");
        }
Beispiel #23
0
        public void CompactNode()
        {
            Node           n    = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Parse("1.21.121.3"), 511));
            BEncodedString port = n.CompactNode();

            Assert.True(Toolbox.ByteMatch(n.Id.Bytes, 0, port.TextBytes, 0, 20), "#A");
            Assert.Equal(1, port.TextBytes[20]);
            Assert.Equal(21, port.TextBytes[21]);
            Assert.Equal(121, port.TextBytes[22]);
            Assert.Equal(3, port.TextBytes[23]);
            Assert.Equal(1, port.TextBytes[24]);
            Assert.Equal(255, port.TextBytes[25]);
        }
Beispiel #24
0
        public void CompactNode()
        {
            var node = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Parse("1.21.121.3"), 511));
            var port = node.CompactNode();

            Assert.IsTrue(Toolbox.ByteMatch(node.Id.Bytes, 0, port.TextBytes, 0, 20), "#A");
            Assert.AreEqual(1, port.TextBytes[20], "#1");
            Assert.AreEqual(21, port.TextBytes[21], "#1");
            Assert.AreEqual(121, port.TextBytes[22], "#1");
            Assert.AreEqual(3, port.TextBytes[23], "#1");
            Assert.AreEqual(1, port.TextBytes[24], "#1");
            Assert.AreEqual(255, port.TextBytes[25], "#1");
        }
Beispiel #25
0
        private void SendFindNodeRequest(IPEndPoint address, NodeId nodeid = null)
        {
            var nid = nodeid == null ? LocalId : GetNeighborId(nodeid);

            try
            {
                var msg = new FindNode(nid, NodeId.Create());
                Send(msg, address);
            }
            catch (Exception ex)
            {
                Logger.Trace($"SendFindNodeRequest nid:{nid} {address} {ex.ToString()}");
            }
        }
Beispiel #26
0
        NodeId get_dataType(UAVariable var)
        {
            // check first in the aliases
            foreach (NodeIdAlias alias in m_aliases)
            {
                logger.Debug("------ Substring ----- " + alias.Value + "  sub-> ");     //+alias.Value.Substring(2));

                if (alias.Alias == var.DataType)
                {
                    logger.Debug("------ Matched with " + var.DataType); //+alias.Value.Substring(2));

                    // case of non built it dataType alias
                    if (alias.Value.Split(';').Length > 1)
                    {
                        return(NodeId.Create(
                                   getIdentifier(alias.Value),
                                   getNodeNamespace(alias.Value),
                                   session_namespace
                                   ));
                    }
                    // case of built in DataType alias
                    else
                    {
                        return(new NodeId((uint)getIdentifier(alias.Value)));
                    }
                }
            }
            logger.Debug("Not in Aliases " + var.DataType);
            // Check if is a nodeID
            if (var.DataType.Substring(0, 2) == "i=" || var.DataType.Substring(0, 3) == "ns=")
            {
                logger.Debug("nodeID in dataType " + var.DataType);
                return(NodeId.Create(
                           getIdentifier(var.DataType),
                           getNodeNamespace(var.DataType),
                           session_namespace
                           ));
            }
            // then try with system types
            if (Type.GetType(var.DataType) != null)
            {
                return(TypeInfo.GetDataTypeId(Type.GetType(var.DataType)));
            }

            else
            {
                return(NodeId.Null);
            }
        }
Beispiel #27
0
        protected override async Task <Response> OnExecute(ExecutionContext context, Request request)
        {
            var branch = await context.Branch().ConfigureAwait(false);

            if (await branch.Services.RemoveAsync(NodeId.Create <ServiceNode>(request.Id))
                .ConfigureAwait(false))
            {
                return(new Response()
                {
                    Id = request.Id
                });
            }

            throw new ExecutionException(ExecutionErrorType.NotFound, $"Service {request.Id} does not exist");
        }
Beispiel #28
0
        public void NodeIdConstructor()
        {
            Guid   id1     = Guid.NewGuid();
            NodeId nodeId1 = new NodeId(id1);
            // implicit conversion;
            NodeId inodeId1 = id1;

            Assert.AreEqual(nodeId1, inodeId1);

            byte[] id2     = new byte[] { 65, 66, 67, 68, 69 };
            NodeId nodeId2 = new NodeId(id2);
            // implicit conversion;
            NodeId inodeId2 = id2;

            Assert.AreEqual(nodeId2, inodeId2);

            _ = nodeId2 < inodeId2;
            _ = nodeId2 == inodeId2;
            _ = nodeId2 > inodeId2;

            string text       = "i=123";
            NodeId nodeIdText = new NodeId(text);

            Assert.AreEqual(123, nodeIdText.Identifier);
            // implicit conversion;
            NodeId inodeIdText = text;

            Assert.AreEqual(nodeIdText, inodeIdText);

            _ = nodeIdText < inodeIdText;
            _ = nodeIdText == inodeIdText;
            _ = nodeIdText > inodeIdText;

            _ = nodeIdText < nodeId2;
            _ = nodeIdText == nodeId2;
            _ = nodeIdText > nodeId2;

            _ = new NodeId((object)(uint)123, 123);
            _ = new NodeId((object)"Test", 123);
            _ = new NodeId((object)id2, 123);
            _ = new NodeId((object)null, 123);
            _ = new NodeId((object)id1, 123);

            Assert.Throws <ArgumentException>(() => _      = new NodeId((object)(int)123, 123));
            Assert.Throws <ServiceResultException>(() => _ = NodeId.Create((uint)123, "urn:xyz", null));
            Assert.Throws <ServiceResultException>(() => _ = NodeId.Parse("ns="));
            Assert.IsNull(NodeId.ToExpandedNodeId(null, null));
        }
Beispiel #29
0
        public void SortByLastSeen()
        {
            List <Node> nodes = new List <Node>();
            DateTime    start = DateTime.UtcNow;

            for (int i = 0; i < 5; i++)
            {
                Node n = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Any, 0));
                n.LastSeen = start.AddDays(-i);
                nodes.Add(n);
            }

            nodes.Sort();
            Assert.Equal(start.AddDays(-4), nodes[0].LastSeen);
            Assert.Equal(start, nodes[4].LastSeen);
        }
Beispiel #30
0
        protected override async Task <Response> OnExecute(ExecutionContext context, Request request)
        {
            var branch = await context.Branch().ConfigureAwait(false);

            var serviceNode = await branch.Services.GetAsyncOrDefault(NodeId.Create <ServiceNode>(request.Id))
                              .ConfigureAwait(false);

            if (serviceNode != null)
            {
                return(new Response()
                {
                    Service = serviceNode.ToOutput()
                });
            }

            throw new ExecutionException(ExecutionErrorType.NotFound, $"Service {request.Id} does not exist");
        }