public async Task <ActionResult> UpdateNode(int nodeId, [FromBody] NtwkNode node)
 {
     node.Id = nodeId;
     return(ObserveDataOperationStatus(
                await _data.UpdateNode(node)
                ));
 }
Ejemplo n.º 2
0
        public async Task <StatusMessage> UpdateNode(
            NtwkNode node
            )
        {
            StatusMessage nodeIdValidationStatus = await ValidateNodeId(node.Id);

            if (nodeIdValidationStatus.Failure())
            {
                return(nodeIdValidationStatus);
            }

            StatusMessage nodeValidationStatus = _validator.Validate(node);

            if (nodeValidationStatus.Failure())
            {
                return(nodeValidationStatus);
            }

            StatusMessage nameExistsStatus =
                await FailIfNodeNameExists(node.Name, updatingNodeId : node.Id);

            if (nameExistsStatus.Failure())
            {
                return(nameExistsStatus);
            }

            return(await Repo.UpdateNode(_viewToEfConverter.Convert(node)));
        }
Ejemplo n.º 3
0
        public StatusMessage Validate(NtwkNode val)
        {
            StatusMessage nameValidationStatus = ValidationUtils.IsValidName(val.Name);

            if (nameValidationStatus.Failure())
            {
                return(nameValidationStatus);
            }

            StatusMessage ipFormatStatus = StatusMessage.Ok;

            try
            {
                Conversion.ConversionUtils.IpStrToUInt32(val.IpStr);
            }
            catch (ArgumentNullException)
            {
                ipFormatStatus = StatusMessage.IpAddressStringIsNull;
            }
            catch (FormatException)
            {
                ipFormatStatus = StatusMessage.IpAddressStringFormatIsInvalid;
            }

            return(ipFormatStatus);
        }
Ejemplo n.º 4
0
        public async Task <DataActionResult <NtwkNode> > CreateNodeWithParent(
            NtwkNode node,
            int parentId
            )
        {
            StatusMessage nodeIdValidationStatus = await ValidateNodeId(parentId);

            if (nodeIdValidationStatus.Failure())
            {
                return(DataActionResult <NtwkNode> .Failed(nodeIdValidationStatus));
            }

            StatusMessage nodeValidationStatus = _validator.Validate(node);

            if (nodeValidationStatus.Failure())
            {
                return(DataActionResult <NtwkNode> .Failed(nodeValidationStatus));
            }

            StatusMessage nameExistsStatus = await FailIfNodeNameExists(node.Name);

            if (nameExistsStatus.Failure())
            {
                return(DataActionResult <NtwkNode> .Failed(nameExistsStatus));
            }

            return(FailOrConvert(
                       await Repo.CreateNodeWithParent(_viewToEfConverter.Convert(node), parentId),
                       n => _efToViewConverter.Convert(n)
                       ));
        }
        public async Task UpdateNode(NtwkNode newNodeData)
        {
            NtwkNode node = await _context.Nodes.FindAsync(newNodeData.ID);

            node.Name       = newNodeData.Name;
            node.ParentPort = newNodeData.ParentPort;
            node.ip         = newNodeData.ip;
            node.OpenPing   = newNodeData.OpenPing;
            node.OpenSSH    = newNodeData.OpenSSH;
            node.OpenTelnet = newNodeData.OpenTelnet;
            await _context.SaveChangesAsync();
        }
Ejemplo n.º 6
0
 public EFDbModel.NtwkNode Convert(NtwkNode node)
 {
     return(new EFDbModel.NtwkNode()
     {
         ID = node.Id,
         ParentID = node.ParentId,
         ParentPort = node.ParentPort,
         Name = node.Name,
         ip = ConversionUtils.IpStrToUInt32(node.IpStr),
         OpenPing = node.IsOpenPing,
         OpenTelnet = node.IsOpenTelnet,
         OpenSSH = node.IsOpenSsh
     });
 }
        public async Task <NtwkNode> RemoveNode(int nodeId)
        {
            NtwkNode node = await _context.Nodes
                            .Include(n => n.Children)
                            .SingleAsync(n => n.ID == nodeId);

            if (node.Children.Count != 0)
            {
                throw new InvalidOperationException();
            }

            _context.Nodes.Remove(node);
            await _context.SaveChangesAsync();

            return(node);
        }
 public static SerializableNtwkNode IntoSerializable(this NtwkNode node)
 {
     return(new SerializableNtwkNode()
     {
         ID = node.ID,
         Type = node.Type,
         Parent = (node.Parent == null)?(null):(new ParentData()
         {
             ID = node.Parent.ID,
             Name = node.Parent.Name
         }),
         Name = node.Name,
         IsBlackBox = node.IsBlackBox,
         ipStr = UInt32toIP(node.ip).ToString(),
         IsOpenSSH = node.IsOpenSSH,
         IsOpenTelnet = node.IsOpenTelnet,
         IsOpenWeb = node.IsOpenWeb,
         IsOpenPing = node.IsOpenPing
     });
 }
        /// <exception cref="InvalidClientDataException">On invalid client input vales.</exception>
        public SerializableNtwkNode RemoveNode(int id)
        {
            NtwkNode node = db.Nodes
                            .Include(n => n.Parent)
                            .Include(n => n.Children)
                            .SingleOrDefault(n => n.ID == id);

            if (node == null)
            {
                throw new InvalidClientDataException(
                          "Entry specified by ID does not exist.");
            }
            if (node.Children.Any())
            {
                throw new InvalidClientDataException(
                          "Removing entries with child entries is prohibited.");
            }
            db.Nodes.Remove(node);
            db.SaveChanges();
            return(node.IntoSerializable());
        }
 /// <exception cref="InvalidClientDataException">On invalid client input vales.</exception>
 public SerializableNtwkNode CreateNode(SerializableNtwkNode node, int parentID = 0)
 {
     if (node.ID == 0)
     {
         var modelNode = new NtwkNode();
         try {
             modelNode.CopyFromSerializable(node);
         }
         catch (FormatException) {
             throw new InvalidClientDataException("Incorrect ip address format.");
         }
         if (parentID == 0) //root children
         {
             db.Nodes.Add(modelNode);
             db.SaveChanges();
         }
         else
         {
             var bruddas = db.Nodes.Include(n => n.Children)
                           .SingleOrDefault(n => n.ID == parentID)?.Children;
             if (bruddas == null)
             {
                 throw new InvalidClientDataException(
                           "Trying to create node with nonexisting parent.");
             }
             bruddas.Add(modelNode);
             db.SaveChanges();
         }
         return(db.Nodes.AsNoTracking()
                .Include(n => n.Parent)
                .Single(n => n.ID == modelNode.ID)
                .IntoSerializable());
     }
     else
     {
         throw new InvalidClientDataException(
                   "Only entries with ID=0 are accepted.");
     }
 }
 /// <exception cref="FormatException">On invalid ip string.</exception>
 public static void CopyFromSerializable(
     this NtwkNode node, SerializableNtwkNode from)
 {
     node.Type       = from.Type;
     node.Name       = from.Name;
     node.IsBlackBox = from.IsBlackBox;
     if (from.IsBlackBox)
     {
         node.ip                    = 0;
         node.IsOpenPing            =
             node.IsOpenSSH         =
                 node.IsOpenTelnet  =
                     node.IsOpenWeb = false;
     }
     else
     {
         node.ip           = IPtoUInt32(IPAddress.Parse(from.ipStr));
         node.IsOpenPing   = from.IsOpenPing;
         node.IsOpenSSH    = from.IsOpenSSH;
         node.IsOpenTelnet = from.IsOpenTelnet;
         node.IsOpenWeb    = from.IsOpenWeb;
     }
 }
Ejemplo n.º 12
0
        public async Task <NtwkNode> CreateNodeOnRoot(NtwkNode node)
        {
            NtwkNode newNode = new NtwkNode
            {
                ID         = 0,
                Parent     = null,
                ParentPort = node.ParentPort,
                Name       = node.Name,
                ip         = node.ip,
                OpenTelnet = node.OpenTelnet,
                OpenSSH    = node.OpenSSH,
                OpenPing   = node.OpenPing
            };

            _context.Nodes.Add(newNode);
            _context.NodesClosureTable.AddRange(
                await __CreateNewNodeClosures(_context, null, newNode.ID)
                );
            await _context.SaveChangesAsync();

            _context.Entry(newNode).State = EntityState.Detached;
            return(newNode);
        }
 /// <exception cref="InvalidClientDataException">On invalid client input vales.</exception>
 public void UpdateNode(SerializableNtwkNode node, int parentID = 0)
 {
     if (node.ID != 0)
     {
         NtwkNode entry = db.Nodes
                          .Include(n => n.Parent)
                          .SingleOrDefault(n => n.ID == node.ID);
         NtwkNode parent = null;
         if (entry == null)
         {
             throw new InvalidClientDataException(
                       "Can't update nonexisting node");
         }
         if (parentID != 0)
         {
             parent = db.Nodes.Find(parentID);
             if (parent == null)
             {
                 throw new InvalidClientDataException(
                           "Trying to set node's parent to nonexistent entry."
                           );
             }
         }
         try {
             entry.CopyFromSerializable(node);
         }
         catch (FormatException) {
             throw new InvalidClientDataException("Incorrect ip address format.");
         }
         if (parent != null)
         {
             entry.Parent = parent;
         }
     }
     db.SaveChanges();
 }
Ejemplo n.º 14
0
 public async Task <StatusMessage> UpdateNode(NtwkNode node)
 {
     return(await PerformOperationOrLogExceptions(async() =>
                                                  await _efDataSource.UpdateNode(node)
                                                  ));
 }
Ejemplo n.º 15
0
 public async Task <DataActionResult <NtwkNode> > CreateNodeWithParent(NtwkNode node, int parentId)
 {
     return(await PerformDataOperationOrLogExceptions(async() =>
                                                      await _efDataSource.CreateNodeWithParent(node, parentId)
                                                      ));
 }
Ejemplo n.º 16
0
 public async Task <DataActionResult <NtwkNode> > CreateNodeOnRoot(NtwkNode node)
 {
     return(await PerformDataOperationOrLogExceptions(async() =>
                                                      await _efDataSource.CreateNodeOnRoot(node)
                                                      ));
 }
        private static TestIDsSet AddTestDataSet(NtwkDBContext context)
        {
            var testProfile = new Profile
            {
                ID   = 0,
                Name = TestProfileName,
                StartMonitoringOnLaunch   = true,
                DepthMonitoring           = true,
                MonitoringStartHour       = 0,
                MonitoringSessionDuration = 24,
                MonitorInterval           = 10
            };

            context.Profiles.Add(testProfile);
            context.SaveChanges();

            // tags
            NodeTag[] testTags = Enumerable.Range(0, 3)
                                 .Select(i => new NodeTag
            {
                ID   = 0,
                Name = TagNames[i]
            }).ToArray();
            context.Tags.AddRange(testTags);
            context.SaveChanges();

            // nodes
            NtwkNode[] testNodes = new NtwkNode[3];
            {
                uint[] ips = new[]
                {
                    167837697u,
                    3232292602u,
                    167837697u
                };
                bool[] t = new[] { false, true, false };
                bool[] s = new[] { true, false, true };
                for (int i = 0; i < 3; i++)
                {
                    testNodes[i] = new NtwkNode
                    {
                        ID         = 0,
                        Parent     = null,
                        Name       = NodeNames[i],
                        ip         = ips[i],
                        OpenTelnet = t[i],
                        OpenSSH    = s[i],
                        OpenPing   = true
                    };
                }

                context.Nodes.Add(testNodes[0]);
                context.SaveChanges();
                testNodes[1].Parent = testNodes[0];
                context.Nodes.Add(testNodes[1]);
                context.Nodes.Add(testNodes[2]);
                context.SaveChanges();
            }


            CustomWebService[] testWebServices;
            {
                string[] wsStrings =
                {
                    "http://{node_ip}:8080",
                    "https://{node_ip}:{param1}"
                };
                string[] wsP1 = new[] { null, "Port" };
                testWebServices = Enumerable.Range(0, 2)
                                  .Select(i => new CustomWebService
                {
                    ID            = 0,
                    Name          = WebServicesNames[i],
                    ServiceStr    = wsStrings[i],
                    Parametr1Name = wsP1[i]
                }).ToArray();
                context.WebServices.AddRange(testWebServices);
                context.SaveChanges();
            }


            {
                //TagAttachments
                NodeTag[] t = new[]
                {
                    testTags[0], testTags[0], testTags[1], testTags[2]
                };
                NtwkNode[] n = new[]
                {
                    testNodes[0], testNodes[1], testNodes[1], testNodes[2]
                };
                context.TagAttachments.AddRange(Enumerable.Range(0, 4)
                                                .Select(i => new TagAttachment
                {
                    ID   = 0,
                    Tag  = t[i],
                    Node = n[i],
                })
                                                );
                context.SaveChanges();
            }


            {
                // WebServiceBindings
                CustomWebService[] s = new[]
                {
                    testWebServices[0], testWebServices[0],
                    testWebServices[1], testWebServices[1], testWebServices[1]
                };
                NtwkNode[] n = new[]
                {
                    testNodes[0], testNodes[1],
                    testNodes[0], testNodes[1], testNodes[2]
                };
                string[] p = new[]
                {
                    null, null,
                    "80", "55315", ""
                };
                context.WebServiceBindings.AddRange(Enumerable.Range(0, 5)
                                                    .Select(i => new CustomWsBinding
                {
                    ID      = 0,
                    Service = s[i],
                    Node    = n[i],
                    Param1  = p[i]
                })
                                                    );
                context.SaveChanges();
            }


            {
                // test monitoring session data
                MonitoringSession testSession = new MonitoringSession
                {
                    ID = 0,
                    CreatedByProfile      = testProfile,
                    ParticipatingNodesNum = 2,
                    CreationTime          = 1528359015,
                    LastPulseTime         = 1528360285,
                };
                MonitoringPulseResult[] pulses = new[]
                {
                    new MonitoringPulseResult
                    {
                        ID           = 0,
                        Responded    = 2,
                        Silent       = 0,
                        Skipped      = 0,
                        CreationTime = 1528359015
                    },
                    new MonitoringPulseResult
                    {
                        ID           = 0,
                        Responded    = 0,
                        Silent       = 1,
                        Skipped      = 1,
                        CreationTime = 1528360285
                    }
                };
                var monMessageForSecondPulse = new MonitoringMessage
                {
                    ID                    = 0,
                    MessageType           = MonitoringMessageType.DangerNoPingReturnedSkippedChildren,
                    MessageSourceNodeName = NodeNames[0],
                    NumSkippedChildren    = 0
                };
                context.MonitoringSessions.Add(testSession);
                context.MonitoringPulses.AddRange(pulses);
                context.SaveChanges();
                pulses[1] = context.MonitoringPulses
                            .Include(p => p.Messages)
                            .Single(p => p.ID == pulses[1].ID);
                testSession = context.MonitoringSessions
                              .Include(s => s.Pulses)
                              .Single(s => s.ID == testSession.ID);
                testSession.Pulses.Add(pulses[0]);
                testSession.Pulses.Add(pulses[1]);
                pulses[1].Messages.Add(monMessageForSecondPulse);
                context.SaveChanges();
            }

            TestIDsSet idsSet = new TestIDsSet
            {
                ProfileId      = testProfile.ID,
                WebServicesIDs = testWebServices.Select(s => s.ID).ToArray(),
                NodesIDs       = testNodes.Select(n => n.ID).ToArray(),
                TagsIDs        = testTags.Select(t => t.ID).ToArray(),
            };

            CreateClosuresForTestNodes(context, idsSet);
            return(idsSet);
        }
Ejemplo n.º 18
0
        // Should be checked by higher level
        // services for newParent not being part of node's subtree.
        public async Task MoveNodesSubtree(int nodeId, int newParentId)
        {
            int?newParentIdOrNull            = newParentId == 0 ? (int?)null : newParentId;
            IQueryable <int> subtreeNodesIDs = _context.NodesClosureTable
                                               .Where(c => c.AncestorID == nodeId)
                                               .Select(c => c.DescendantID)
                                               .Distinct();
            IQueryable <NodeClosure> oldSubtreeClosures = _context.NodesClosureTable
                                                          .Where(c => subtreeNodesIDs.Contains(c.DescendantID));
            IQueryable <NodeClosure> oldClosuresUnderSubtree = oldSubtreeClosures
                                                               .Where(c =>
                                                                      c.AncestorID == null ||
                                                                      !subtreeNodesIDs.Contains((int)c.AncestorID)
                                                                      );
            var subtreeNodesAboveSubtreeRoot =
                oldSubtreeClosures
                .Where(c =>
                       c.AncestorID == nodeId && c.DescendantID != nodeId &&
                       subtreeNodesIDs.Contains(c.DescendantID)
                       )
                .Select(c => new { c.DescendantID, c.Distance });
            List <NodeClosure> newClosuresUnderSubtreeForSubtreeRoot =
                await __CreateNewNodeClosures(
                    _context,
                    newParentIdOrNull,
                    nodeId);

            newClosuresUnderSubtreeForSubtreeRoot.Remove(
                newClosuresUnderSubtreeForSubtreeRoot
                .Single(c => c.AncestorID == c.DescendantID)
                );
            IEnumerable <NodeClosure> newClosuresUnderSubtreeForNodesAboveSubtreeRoot =
                await subtreeNodesAboveSubtreeRoot
                .Select(d => newClosuresUnderSubtreeForSubtreeRoot
                        .Select(c =>
                                new NodeClosure
            {
                ID           = 0,
                AncestorID   = c.AncestorID,
                DescendantID = d.DescendantID,
                Distance     = c.Distance + d.Distance
            }
                                )
                        ).SelectMany(cl => cl)
                .ToArrayAsync();

            NtwkNode subtreeRootNode = await _context.Nodes.FindAsync(nodeId);

            subtreeRootNode.ParentID = newParentIdOrNull;

            /* Debug output
             * void Output(string title, NodeClosure[] arr)
             * {
             *  Console.WriteLine(title);
             *  foreach (var t in arr)
             *  {
             *      System.Diagnostics.Debug.WriteLine($"A-D-d ({t.AncestorID}, {t.DescendantID}, {t.Distance})");
             *  }
             * }
             *
             * Output("Old closures under subtree", oldClosuresUnderSubtree.ToArray());
             * Output("New closures under subtree for root", newClosuresUnderSubtreeForSubtreeRoot.ToArray());
             * Output("New closures under subtree for other subtree nodes", newClosuresUnderSubtreeForNodesAboveSubtreeRoot.ToArray());
             */
            _context.NodesClosureTable.RemoveRange(oldClosuresUnderSubtree);
            _context.NodesClosureTable.AddRange(newClosuresUnderSubtreeForSubtreeRoot);
            _context.NodesClosureTable.AddRange(newClosuresUnderSubtreeForNodesAboveSubtreeRoot);
            //var oldSubtreeClosuresArray = oldSubtreeClosures.ToArray();
            await _context.SaveChangesAsync();

            //Output("All old subtree closures", oldSubtreeClosuresArray);
            //Output("All new subtree closures", oldSubtreeClosures.ToArray());
        }
 public async Task <ActionResult> CreateNodeOnRoot([FromBody] NtwkNode node)
 {
     return(ObserveDataOperationResult(
                await _data.CreateNodeOnRoot(node)
                ));
 }
 public async Task <ActionResult> CreateNodeWithParent(int parentId, [FromBody] NtwkNode node)
 {
     return(ObserveDataOperationResult(
                await _data.CreateNodeWithParent(node, parentId)
                ));
 }