Exemplo n.º 1
0
 public CloudflareModule(IOptions <CloudflareSettings> settings) : base(settings)
 {
     API = new CloudflareAPI(this);
     API.TryAddToGlobalPollers();
     AllDatacenters = settings.Value?.DataCenters
                      .ToDictionary(
         dc => dc.Name,
         dc => dc.Ranges.Concat(dc.MaskedRanges).Select(r => IPNet.Parse(r)).ToList()
         ) ?? new Dictionary <string, List <IPNet> >();
 }
Exemplo n.º 2
0
 private static Dictionary <string, List <IPNet> > GetDataCenters()
 {
     if (Current.Settings.CloudFlare != null)
     {
         return(Current.Settings.CloudFlare.DataCenters
                .ToDictionary(
                    dc => dc.Name,
                    dc => dc.Ranges.Select(r => IPNet.Parse(r)).ToList()
                    ));
     }
     return(new Dictionary <string, List <IPNet> >());
 }
Exemplo n.º 3
0
 public CloudflareModule(IConfiguration config, PollingService poller) : base(config, poller)
 {
     if (Settings.Enabled)
     {
         API = new CloudflareAPI(this);
         API.TryAddToGlobalPollers();
         AllDatacenters = Settings?.DataCenters
                          .ToDictionary(
             dc => dc.Name,
             dc => dc.Ranges.Concat(dc.MaskedRanges).Select(r => IPNet.Parse(r)).ToList()
             ) ?? new Dictionary <string, List <IPNet> >();
     }
 }
Exemplo n.º 4
0
        public static void Main(string[] args)
        {
            WriteLine("Press any key to begin");
            ReadKey();

            WriteLine("Running Loop ({0} iteations)...", loops);
            var sw = Stopwatch.StartNew();

            for (var i = 0; i < loops; i++)
            {
                IPNet.Parse("127.0.0.1/16");
            }
            sw.Stop();
            WriteLine("Done: " + sw.ElapsedMilliseconds + " ms");
            //WriteLine("Press any key to exit");
            //ReadKey();
        }
Exemplo n.º 5
0
 protected SecurityProvider()
 {
     InternalNetworks = new List <IPNet>();
     if (SecuritySettings.Current.InternalNetworks != null)
     {
         foreach (var n in SecuritySettings.Current.InternalNetworks.All)
         {
             if ((n.CIDR.HasValue() || (n.IP.HasValue() && n.Subnet.IsNullOrEmpty())) && IPNet.TryParse(n.CIDR.IsNullOrEmptyReturn(n.IP), out IPNet net))
             {
                 InternalNetworks.Add(net);
             }
             else if (n.IP.HasValue() && n.Subnet.HasValue() && IPNet.TryParse(n.IP, n.Subnet, out net))
             {
                 InternalNetworks.Add(net);
             }
         }
     }
 }
Exemplo n.º 6
0
        // ReSharper restore ClassNeverInstantiated.Local

        private async Task <List <OrionIPMap> > GetNodeIPMapAsync(DbConnection conn)
        {
            var result = await conn.QueryAsync <OrionIPMap>(@"
Select Cast(i.InterfaceID as varchar(50)) as InterfaceID, ipa.IPAddress, ipa.SubnetMask
  From NodeIPAddresses ipa
       Join Interfaces i
         On ipa.NodeID = i.NodeID
         And ipa.InterfaceIndex = i.InterfaceIndex",
                                                            commandTimeout : QueryTimeoutMs);

            foreach (var m in result)
            {
                if (IPNet.TryParse(m.IPAddress, m.SubnetMask, out var net))
                {
                    m.IPNet = net;
                }
            }
            return(result);
        }
        public async Task <List <Node> > GetAllNodesAsync()
        {
            using (MiniProfiler.Current.Step("Get Server Nodes"))
            {
                var nodes = new List <Node>();

                var apiResponse = await GetFromBosunAsync <Dictionary <string, BosunHost> >(GetUrl("api/host")).ConfigureAwait(false);

                if (!apiResponse.Success)
                {
                    return(nodes);
                }

                var hostsDict = apiResponse.Result;

                foreach (var h in hostsDict.Values)
                {
                    if (Current.Settings.Dashboard.ExcludePatternRegex?.IsMatch(h.Name) ?? false)
                    {
                        continue;
                    }

                    if (h.Name == "unspecified")
                    {
                        continue;
                    }

                    Version kernelVersion;
                    // Note: we can't follow this pattern, we'll need to refresh existing nodes
                    // not wholesale replace on poll
                    var n = new Node
                    {
                        Id           = h.Name,
                        Name         = h.Name,
                        Model        = h.Model,
                        Ip           = "scollector",
                        DataProvider = this,
                        Status       = GetNodeStatus(h),
                        // TODO: Add Last Ping time to all providers
                        LastSync         = h.CPU?.StatsLastUpdated,
                        CPULoad          = (short?)h.CPU?.PercentUsed,
                        MemoryUsed       = h.Memory?.UsedBytes,
                        TotalMemory      = h.Memory?.TotalBytes,
                        Manufacturer     = h.Manufacturer,
                        ServiceTag       = h.SerialNumber,
                        MachineType      = h.OS?.Caption,
                        MachineOSVersion = h.OS?.Version,
                        KernelVersion    = Version.TryParse(h.OS?.Version, out kernelVersion) ? kernelVersion : null,

                        Interfaces = h.Interfaces?.Select(hi => new Interface
                        {
                            Id              = hi.Key,
                            NodeId          = h.Name,
                            Name            = hi.Value.Name.IsNullOrEmptyReturn($"Unknown: {hi.Key}"),
                            FullName        = hi.Value.Name,
                            TypeDescription = hi.Value.Type,
                            Caption         = hi.Value.Description,
                            PhysicalAddress = hi.Value.MAC,
                            IPs             = hi.Value?.IPAddresses?.Select(ip =>
                            {
                                IPNet result;
                                return(IPNet.TryParse(ip, out result) ? result : null);
                            }).Where(ip => ip != null).ToList() ?? new List <IPNet>(),
                            LastSync    = hi.Value.StatsLastUpdated,
                            InBps       = hi.Value.Inbps,
                            OutBps      = hi.Value.Outbps,
                            Speed       = hi.Value.LinkSpeed * 1000000,
                            Status      = NodeStatus.Active, // TODO: Implement
                            TeamMembers =
                                h.Interfaces?.Where(i => i.Value.Master == hi.Value.Name).Select(i => i.Key).ToList()
                        }).ToList(),
                        Volumes = h.Disks?.Select(hd => new Volume
                        {
                            Id          = hd.Key,
                            Name        = hd.Key,
                            NodeId      = h.Name,
                            Caption     = hd.Key,
                            Description = $"{hd.Key}",
                            LastSync    = hd.Value.StatsLastUpdated,
                            Used        = hd.Value.UsedBytes,
                            Size        = hd.Value.TotalBytes,
                            Available   = hd.Value.TotalBytes - hd.Value.UsedBytes,
                            PercentUsed = 100 * (hd.Value.UsedBytes / hd.Value.TotalBytes),
                        }).ToList(),
                        //Apps = new List<Application>(),
                        //VMs = new List<Node>()
                    };

                    if (h.OpenIncidents?.Count > 0)
                    {
                        n.Issues = h.OpenIncidents.Select(i => new Issue <Node>(n, "Bosun", n.PrettyName)
                        {
                            Date          = i.LastAbnormalTime.ToDateTime(),
                            Description   = i.Subject,
                            MonitorStatus = !i.Active ? MonitorStatus.Good : GetStatusFromString(i.Status)
                        }).ToList();
                    }

                    var hs = new HardwareSummary();
                    if (h.CPU?.Processors != null)
                    {
                        foreach (var p in h.CPU.Processors)
                        {
                            hs.Processors.Add(new HardwareSummary.ProcessorInfo
                            {
                                Name        = p.Key,
                                Description = p.Value
                            });
                        }
                    }

                    var hw = h.Hardware;
                    if (hw != null)
                    {
                        if (hw.ChassisComponents != null)
                        {
                            foreach (var c in hw.ChassisComponents)
                            {
                                hs.Components.Add(new HardwareSummary.ComponentInfo
                                {
                                    Name   = c.Key.Replace("_", " "),
                                    Status = c.Value.Status
                                });
                            }
                        }
                        if (hw.Memory != null)
                        {
                            foreach (var m in hw.Memory)
                            {
                                hs.MemoryModules.Add(new HardwareSummary.MemoryModuleInfo
                                {
                                    Name   = m.Key,
                                    Status = m.Value.Status,
                                    Size   = m.Value.Size
                                });
                            }
                        }
                        if (hw.Storage != null)
                        {
                            var s = new HardwareSummary.StorageInfo();
                            if (hw.Storage.Controllers != null)
                            {
                                foreach (var c in hw.Storage.Controllers)
                                {
                                    s.Controllers.Add(new HardwareSummary.StorageInfo.ControllerInfo
                                    {
                                        Name            = c.Value.Name,
                                        Status          = c.Value.Status,
                                        State           = c.Value.State,
                                        SlotId          = c.Value.SlotId,
                                        FirmwareVersion = c.Value.FirmwareVersion,
                                        DriverVersion   = c.Value.DriverVersion
                                    });
                                }
                            }
                            if (hw.Storage.PhysicalDisks != null)
                            {
                                foreach (var d in hw.Storage.PhysicalDisks)
                                {
                                    s.PhysicalDisks.Add(new HardwareSummary.StorageInfo.PhysicalDiskInfo
                                    {
                                        Name            = d.Value.Name,
                                        CapableSpeed    = d.Value.CapableSpeed,
                                        Capacity        = d.Value.Capacity,
                                        Media           = d.Value.Media,
                                        NegotatiedSpeed = d.Value.NegotatiedSpeed,
                                        Part            = d.Value.Part,
                                        ProductId       = d.Value.ProductId,
                                        SectorSize      = d.Value.SectorSize,
                                        Serial          = d.Value.Serial,
                                        Status          = d.Value.Status,
                                        VendorId        = d.Value.VendorId
                                    });
                                }
                            }
                            if (hw.Storage.VirtualDisks != null)
                            {
                                foreach (var d in hw.Storage.VirtualDisks)
                                {
                                    s.VirtualDisks.Add(new HardwareSummary.StorageInfo.VirtualDiskInfo
                                    {
                                        Name   = d.Key,
                                        Status = d.Value.Status,
                                        // TODO: Add to Bosun
                                        // Size = d.Value.Size
                                    });
                                }
                            }
                            if (hw.Storage.Batteries != null)
                            {
                                foreach (var b in hw.Storage.Batteries)
                                {
                                    s.Batteries.Add(new HardwareSummary.ComponentInfo
                                    {
                                        Name   = b.Key,
                                        Status = b.Value.Status
                                    });
                                }
                            }
                            hs.Storage = s;
                        }
                        if (hw.PowerSupplies != null)
                        {
                            foreach (var ps in hw.PowerSupplies)
                            {
                                hs.PowerSupplies.Add(new HardwareSummary.PowerSupplyInfo
                                {
                                    Name   = ps.Key,
                                    Amps   = ps.Value.Amps,
                                    Status = ps.Value.Status,
                                    Volts  = ps.Value.Volts
                                });
                            }
                        }
                        if (hw.Temps != null)
                        {
                            foreach (var t in hw.Temps)
                            {
                                hs.Temps.Add(new HardwareSummary.TemperatureInfo
                                {
                                    Name    = t.Key.Replace("_", " "),
                                    Status  = t.Value.Status,
                                    Celsius = t.Value.Celsius
                                });
                            }
                        }
                        if (hw.BoardPowerReading != null)
                        {
                            hs.BoardPowerReading = new HardwareSummary.BoardPowerInfo
                            {
                                Watts = hw.BoardPowerReading.Watts
                            };
                        }
                        n.Hardware = hs;
                    }

                    if (h.VM != null)
                    {
                        n.VMHostID = h.VM.Host;
                    }

                    if (h.UptimeSeconds.HasValue) // TODO: Check if online - maybe against ICMP data last?
                    {
                        n.LastBoot = DateTime.UtcNow.AddSeconds(-h.UptimeSeconds.Value);
                    }
                    n.SetReferences();
                    nodes.Add(n);
                }

                // Hook up relationships after a full decode
                foreach (var n in nodes)
                {
                    n.VMs    = nodes.Where(on => on.VMHostID == n.Id).ToList();
                    n.VMHost = nodes.Find(on => n.VMHostID == on.Id);
                }

                return(nodes);
            }
        }
        public async Task <List <Node> > GetAllNodesAsync()
        {
            using (MiniProfiler.Current.Step("Get Server Nodes"))
            {
                var nodes = new List <Node>();

                var apiResponse = await GetFromBosunAsync <Dictionary <string, BosunHost> >(GetUrl("api/host"));

                if (!apiResponse.Success)
                {
                    return(nodes);
                }

                var hostsDict = apiResponse.Result;

                foreach (var h in hostsDict.Values)
                {
                    if (Module.Settings.ExcludePatternRegex?.IsMatch(h.Name) ?? false)
                    {
                        continue;
                    }

                    if (h.Name == "unspecified")
                    {
                        continue;
                    }

                    // Note: we can't follow this pattern, we'll need to refresh existing nodes
                    // not wholesale replace on poll
                    var n = new Node
                    {
                        Id           = h.Name,
                        Name         = h.Name,
                        Model        = h.Model,
                        Ip           = "scollector",
                        DataProvider = this,
                        Status       = GetNodeStatus(h),
                        // TODO: Add Last Ping time to all providers
                        LastSync         = h.CPU?.StatsLastUpdated,
                        CPULoad          = (short?)h.CPU?.PercentUsed,
                        MemoryUsed       = h.Memory?.UsedBytes,
                        TotalMemory      = h.Memory?.TotalBytes,
                        Manufacturer     = h.Manufacturer,
                        ServiceTag       = h.SerialNumber,
                        MachineType      = h.OS?.Caption,
                        MachineOSVersion = h.OS?.Version,
                        KernelVersion    = Version.TryParse(h.OS?.Version, out var kernelVersion) ? kernelVersion : null,

                        Interfaces = h.Interfaces?.Select(hi => new Interface
                        {
                            Id              = hi.Key,
                            NodeId          = h.Name,
                            Name            = hi.Value.Name.IsNullOrEmptyReturn($"Unknown: {hi.Key}"),
                            FullName        = hi.Value.Name,
                            TypeDescription = hi.Value.Type,
                            Caption         = hi.Value.Description,
                            PhysicalAddress = hi.Value.MAC,
                            IPs             = hi.Value?.IPAddresses?.Select(ip => IPNet.TryParse(ip, out var result) ? result : null).Where(ip => ip != null).ToList() ?? new List <IPNet>(),
                            LastSync        = hi.Value.StatsLastUpdated,
                            InBps           = hi.Value.Inbps,
                            OutBps          = hi.Value.Outbps,
                            Speed           = hi.Value.LinkSpeed * 1000000,
                            Status          = NodeStatus.Active, // TODO: Implement
                            TeamMembers     =
                                h.Interfaces?.Where(i => i.Value.Master == hi.Value.Name).Select(i => i.Key).ToList()
                        }).ToList(),
Exemplo n.º 9
0
        public void ConfigureServices(IServiceCollection services)
        {
            // Register Opserver.Core config and polling
            services.AddCoreOpserverServices(_configuration);

            services.AddResponseCaching();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.AccessDeniedPath = "/denied";
                options.LoginPath        = "/login";
                options.LogoutPath       = "/logout";
            });

            services.AddResponseCompression(
                options =>
            {
                options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "image/svg+xml" });
                options.Providers.Add <GzipCompressionProvider>();
                options.EnableForHttps = true;
            }
                );

            services
            .AddHttpContextAccessor()
            .AddMemoryCache()
            .AddExceptional(
                _configuration.GetSection("Exceptional"),
                settings =>
            {
                settings.UseExceptionalPageOnThrow = true;
                settings.DataIncludeRegex          = new Regex("^(Redis|Elastic|ErrorLog|Jil)", RegexOptions.Singleline | RegexOptions.Compiled);
                settings.GetCustomData             = (ex, data) =>
                {
                    // everything below needs a context
                    // Don't *init* a user here, since that'll stack overflow when it errors
                    var u = Current.Context?.UserIfExists;
                    if (u != null)
                    {
                        data.Add("User", u.AccountName);
                        data.Add("Roles", u.Roles.ToString());
                    }

                    while (ex != null)
                    {
                        foreach (DictionaryEntry de in ex.Data)
                        {
                            var key = de.Key as string;
                            if (key.HasValue() && key.StartsWith(ExtensionMethods.ExceptionLogPrefix))
                            {
                                data.Add(key.Replace(ExtensionMethods.ExceptionLogPrefix, ""), de.Value?.ToString() ?? "");
                            }
                        }
                        ex = ex.InnerException;
                    }
                };
            }
                );

            services.AddSingleton <IConfigureOptions <MiniProfilerOptions>, MiniProfilerCacheStorageDefaults>();
            services.AddMiniProfiler(options =>
            {
                //options.RouteBasePath = "/profiler/";
                options.PopupRenderPosition  = RenderPosition.Left;
                options.PopupMaxTracesToShow = 5;
                options.ShouldProfile        = _ =>
                {
                    return(true);
                    //switch (SiteSettings.ProfilingMode)
                    //{
                    //    case ProfilingModes.Enabled:
                    //        return true;
                    //    case SiteSettings.ProfilingModes.LocalOnly:
                    //        return Current.User?.Is(Models.Roles.LocalRequest) == true;
                    //    case SiteSettings.ProfilingModes.AdminOnly:
                    //        return Current.User?.IsGlobalAdmin == true;
                    //    default:
                    //        return false;
                    //}
                };
                options.EnableServerTimingHeader = true;
                options.IgnorePath("/graph")
                .IgnorePath("/login")
                .IgnorePath("/spark")
                .IgnorePath("/top-refresh");
            });
            services.Configure <SecuritySettings>(_configuration.GetSection("Security"));
            services.Configure <ActiveDirectorySecuritySettings>(_configuration.GetSection("Security"));
            services.Configure <OIDCSecuritySettings>(_configuration.GetSection("Security"));
            services.Configure <ForwardedHeadersOptions>(_configuration.GetSection("ForwardedHeaders"));
            services.PostConfigure <ForwardedHeadersOptions>(
                options =>
            {
                // what's all this mess I hear you cry? well ForwardedHeadersOptions
                // has a bunch of read-only list props that can't be bound from configuration
                // so we need to go populate them ourselves
                var forwardedHeaders = _configuration.GetSection("ForwardedHeaders");
                var allowedHosts     = forwardedHeaders.GetSection(nameof(ForwardedHeadersOptions.AllowedHosts)).Get <List <string> >();
                if (allowedHosts != null)
                {
                    options.AllowedHosts.Clear();
                    foreach (var allowedHost in allowedHosts)
                    {
                        options.AllowedHosts.Add(allowedHost);
                    }
                }

                var knownProxies  = forwardedHeaders.GetSection(nameof(ForwardedHeadersOptions.KnownProxies)).Get <List <string> >();
                var knownNetworks = forwardedHeaders.GetSection(nameof(ForwardedHeadersOptions.KnownNetworks)).Get <List <string> >();
                if (knownNetworks != null || knownProxies != null)
                {
                    options.KnownProxies.Clear();
                    options.KnownNetworks.Clear();
                }

                if (knownProxies != null)
                {
                    foreach (var knownProxy in knownProxies)
                    {
                        options.KnownProxies.Add(IPAddress.Parse(knownProxy));
                    }
                }


                if (knownNetworks != null)
                {
                    foreach (var knownNetwork in knownNetworks)
                    {
                        var ipNet = IPNet.Parse(knownNetwork);
                        options.KnownNetworks.Add(new IPNetwork(ipNet.IPAddress, ipNet.CIDR));
                    }
                }
            }
                );
            services.AddSingleton <SecurityManager>();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);
            services.AddMvc();
        }
Exemplo n.º 10
0
 //[Benchmark, BenchmarkCategory("Orig")] public void IPNetParsev6() => IPNetOriginal.Parse("::1");
 [Benchmark, BenchmarkCategory("Span")] public void IPNetSpanParsev6() => IPNet.Parse("::1");
Exemplo n.º 11
0
 public void IPNetCidrv6() => IPNet.Parse("::1/96");
Exemplo n.º 12
0
 public void IPNetParsev6() => IPNet.Parse("::1");
Exemplo n.º 13
0
 public void IPNetCidrv4() => IPNet.Parse("127.0.0.1/16");
Exemplo n.º 14
0
 public void IPNetParsev4() => IPNet.Parse("127.0.0.1");
Exemplo n.º 15
0
 //[Benchmark, BenchmarkCategory("Orig")] public void IPNetCidrv6() => IPNetOriginal.Parse("::1/96");
 [Benchmark, BenchmarkCategory("Span")] public void IPNetSpanCidrv6() => IPNet.Parse("::1/96");
Exemplo n.º 16
0
            private async Task GetAllInterfacesAsync()
            {
                const string query = @"
SELECT Name,
       PNPDeviceID,
       DeviceID,       
       NetConnectionID,
       Description,
       MACAddress,
       Speed,
       InterfaceIndex
  FROM Win32_NetworkAdapter
 WHERE NetConnectionStatus = 2"; //connected adapters.
                //'AND PhysicalAdapter = True' causes exceptions with old windows versions.

                var indexMap = new Dictionary <uint, Interface>();

                using (var q = Wmi.Query(Endpoint, query))
                {
                    foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false))
                    {
                        string id = $"{data.DeviceID}";
                        var    i  = Interfaces.Find(x => x.Id == id) ?? new Interface();
                        indexMap[data.InterfaceIndex] = i;

                        i.Id       = id;
                        i.Alias    = "!alias";
                        i.Caption  = data.NetConnectionID;
                        i.FullName = data.Description;
                        i.NodeId   = Id;
                        i.LastSync = DateTime.UtcNow;
                        i.Name     = await GetRealAdapterName(data.PNPDeviceID).ConfigureAwait(false);

                        i.PhysicalAddress = data.MACAddress;
                        i.Speed           = data.Speed;
                        i.Status          = NodeStatus.Active;
                        i.TypeDescription = "";
                        i.IPs             = new List <IPNet>();
                        i.TeamMembers     = new List <string>();

                        if (i.Node == null)
                        {
                            i.Node = this;
                            Interfaces.Add(i);
                        }
                    }
                }

                if (_canQueryTeamingInformation)
                {
                    const string teamsQuery            = "SELECT InstanceID, Name FROM MSFT_NetLbfoTeam";
                    var          teamNamesToInterfaces = new Dictionary <string, Interface>();

                    using (var q = Wmi.Query(Endpoint, teamsQuery, @"root\standardcimv2"))
                    {
                        foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false))
                        {
                            var teamInterface = Interfaces.Find(x => x.Caption == data.Name);

                            if (teamInterface == null)
                            {
                                continue;
                            }

                            teamNamesToInterfaces.Add(data.Name, teamInterface);
                        }
                    }

                    const string teamMembersQuery = "SELECT InstanceID, Name, Team FROM MSFT_NetLbfoTeamMember";
                    using (var q = Wmi.Query(Endpoint, teamMembersQuery, @"root\standardcimv2"))
                    {
                        foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false))
                        {
                            var teamName = data.Team;

                            if (teamNamesToInterfaces.TryGetValue(teamName, out Interface teamInterface))
                            {
                                var adapterName     = data.Name;
                                var memberInterface = Interfaces.Find(x => x.Name == adapterName);

                                if (memberInterface == null)
                                {
                                    continue;
                                }

                                teamInterface.TeamMembers.Add(memberInterface.Id);
                            }
                        }
                    }
                }

                const string ipQuery = @"
SELECT InterfaceIndex, IPAddress, IPSubnet, DHCPEnabled
  FROM WIn32_NetworkAdapterConfiguration 
 WHERE IPEnabled = 'True'";

                using (var q = Wmi.Query(Endpoint, ipQuery))
                {
                    foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false))
                    {
                        if (indexMap.TryGetValue(data.InterfaceIndex, out Interface i))
                        {
                            i.DHCPEnabled = data.DHCPEnabled;
                            var ips     = data.IPAddress as string[];
                            var subnets = data.IPSubnet as string[];

                            if (ips == null ||
                                subnets == null)
                            {
                                continue;
                            }

                            for (var j = 0; j < (ips?.Length).GetValueOrDefault(0); j++)
                            {
                                if (int.TryParse(subnets[j], out int cidr) && IPNet.TryParse(ips[j], cidr, out IPNet net))
                                {
                                    i.IPs.Add(net);
                                }
                                else if (IPNet.TryParse(ips[j], subnets[j], out net))
                                {
                                    i.IPs.Add(net);
                                }
                            }
                        }
                    }
                }
            }
Exemplo n.º 17
0
            private async Task GetAllInterfacesAsync()
            {
                const string query = @"
SELECT Name,
       DeviceID,
       NetConnectionID,
       Description,
       MACAddress,
       Speed,
       InterfaceIndex
  FROM Win32_NetworkAdapter
 WHERE NetConnectionStatus = 2"; //connected adapters.
                //'AND PhysicalAdapter = True' causes exceptions with old windows versions.
                var indexMap = new Dictionary <uint, Interface>();

                using (var q = Wmi.Query(Endpoint, query))
                {
                    foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false))
                    {
                        string id = $"{data.DeviceID}";
                        var    i  = Interfaces.FirstOrDefault(x => x.Id == id);
                        if (i == null)
                        {
                            i = new Interface();
                            Interfaces.Add(i);
                        }
                        indexMap[data.InterfaceIndex] = i;

                        i.Id              = $"{data.DeviceID}";
                        i.Alias           = "!alias";
                        i.Caption         = data.NetConnectionID == "Ethernet" ? data.Name : data.NetConnectionID;
                        i.FullName        = data.Description;
                        i.NodeId          = Id;
                        i.LastSync        = DateTime.UtcNow;
                        i.Name            = data.Name;
                        i.PhysicalAddress = data.MACAddress;
                        i.Speed           = data.Speed;
                        i.Status          = NodeStatus.Active;
                        i.TypeDescription = "";
                        i.IPs             = new List <IPNet>();
                    }
                }

                const string ipQuery = @"
Select InterfaceIndex, IPAddress, IPSubnet, DHCPEnabled
  From WIn32_NetworkAdapterConfiguration 
 Where IPEnabled = 'True'";

                using (var q = Wmi.Query(Endpoint, ipQuery))
                {
                    foreach (var data in await q.GetDynamicResultAsync().ConfigureAwait(false))
                    {
                        Interface i;
                        if (indexMap.TryGetValue(data.InterfaceIndex, out i))
                        {
                            i.DHCPEnabled = data.DHCPEnabled;
                            string[] ips = data.IPAddress as string[],
                            subnets = data.IPSubnet as string[];
                            for (var j = 0; j < (ips?.Length).GetValueOrDefault(0); j++)
                            {
                                IPNet net;
                                int   cidr;
                                if (int.TryParse(subnets[j], out cidr) && IPNet.TryParse(ips[j], cidr, out net))
                                {
                                    i.IPs.Add(net);
                                }
                                else if (IPNet.TryParse(ips[j], subnets[j], out net))
                                {
                                    i.IPs.Add(net);
                                }
                            }
                        }
                    }
                }
            }
Exemplo n.º 18
0
        public async Task <List <Node> > GetAllNodes()
        {
            using (MiniProfiler.Current.Step("Get Server Nodes"))
            {
                var nodes = new List <Node>();

                var apiResponse = await GetFromBosun <Dictionary <string, BosunHost> >(GetUrl("api/host"));

                if (!apiResponse.Success)
                {
                    return(nodes);
                }

                var hostsDict = apiResponse.Result;

                foreach (var h in hostsDict.Values)
                {
                    Version kernelVersion;
                    // Note: we can't follow this pattern, we'll need to refresh existing nodes
                    // not wholesale replace on poll
                    var n = new Node
                    {
                        Id           = h.Name,
                        Name         = h.Name,
                        Model        = h.Model,
                        Ip           = "scollector",
                        DataProvider = this,
                        Status       = GetNodeStatus(h),
                        // TODO: Add Last Ping time to all providers
                        LastSync      = h.CPU?.StatsLastUpdated,
                        CPULoad       = (short?)h.CPU?.PercentUsed,
                        MemoryUsed    = h.Memory?.UsedBytes,
                        TotalMemory   = h.Memory?.TotalBytes,
                        Manufacturer  = h.Manufacturer,
                        ServiceTag    = h.SerialNumber,
                        MachineType   = h.OS?.Caption,
                        KernelVersion = Version.TryParse(h.OS?.Version, out kernelVersion) ? kernelVersion : null,

                        Interfaces = h.Interfaces?.Select(hi => new Interface
                        {
                            Id              = hi.Key,
                            NodeId          = h.Name,
                            Name            = hi.Value.Name.IsNullOrEmptyReturn($"Unknown: {hi.Key}"),
                            FullName        = hi.Value.Name,
                            TypeDescription = hi.Value.Type,
                            Caption         = hi.Value.Description,
                            PhysicalAddress = hi.Value.MAC,
                            IPs             = hi.Value?.IPAddresses?.Select(ip =>
                            {
                                IPNet result;
                                return(IPNet.TryParse(ip, out result) ? result.IPAddress : null);
                            }).Where(ip => ip != null).ToList(),
                            LastSync    = hi.Value.StatsLastUpdated,
                            InBps       = hi.Value.Inbps * 8,
                            OutBps      = hi.Value.Outbps * 8,
                            Speed       = hi.Value.LinkSpeed * 1000000,
                            TeamMembers = h.Interfaces?.Where(i => i.Value.Master == hi.Value.Name).Select(i => i.Key).ToList()
                        }).ToList(),
                        Volumes = h.Disks?.Select(hd => new Volume
                        {
                            Id          = hd.Key,
                            Name        = hd.Key,
                            NodeId      = h.Name,
                            Caption     = hd.Key,
                            Description = $"{hd.Key}",
                            LastSync    = hd.Value.StatsLastUpdated,
                            Used        = hd.Value.UsedBytes,
                            Size        = hd.Value.TotalBytes,
                            Available   = hd.Value.TotalBytes - hd.Value.UsedBytes,
                            PercentUsed = 100 * (hd.Value.UsedBytes / hd.Value.TotalBytes),
                        }).ToList(),
                        //Apps = new List<Application>(),
                        //VMs = new List<Node>()
                    };

                    n.Interfaces.ForEach(i => i.IsTeam = i.TeamMembers.Any());

                    if (h.UptimeSeconds.HasValue) // TODO: Check if online - maybe against ICMP data last?
                    {
                        n.LastBoot = DateTime.UtcNow.AddSeconds(-h.UptimeSeconds.Value);
                    }
                    n.SetReferences();
                    nodes.Add(n);
                }

                return(nodes);

                // Nodes
                //    LastSync,
                //    Cast(Status as int) Status,
                //    LastBoot,
                //    IP_Address as Ip,
                //    PollInterval as PollIntervalSeconds,
                //    Cast(vmh.NodeID as varchar(50)) as VMHostID,
                //    Cast(IsNull(vh.HostID, 0) as Bit) IsVMHost,
                //    IsNull(UnManaged, 0) as IsUnwatched, // Silence

                // Interfaces
                //       InterfaceIndex [Index],
                //       LastSync,
                //       Comments,
                //       InterfaceAlias Alias,
                //       IfName,
                //       InterfaceTypeDescription TypeDescription,
                //       IsNull(UnManaged, 0) as IsUnwatched,
                //       UnManageFrom as UnwatchedFrom,
                //       UnManageUntil as UnwatchedUntil,
                //       Cast(Status as int) Status,
                //       InPps,
                //       OutPps,
                //       InterfaceMTU as MTU,
                //       InterfaceSpeed as Speed

                // Volumes
                //       LastSync,
                //       VolumeIndex as [Index],
                //       VolumeDescription as [Description],
                //       VolumeType as Type,

                // Applications
                //Select Cast(com.ApplicationID as varchar(50)) as Id,
                //       Cast(NodeID as varchar(50)) as NodeId,
                //       app.Name as AppName,
                //       IsNull(app.Unmanaged, 0) as IsUnwatched,
                //       app.UnManageFrom as UnwatchedFrom,
                //       app.UnManageUntil as UnwatchedUntil,
                //       com.Name as ComponentName,
                //       ccs.TimeStamp as LastUpdated,
                //       pe.PID as ProcessID,
                //       ccs.ProcessName,
                //       ccs.LastTimeUp,
                //       ccs.PercentCPU as CurrentPercentCPU,
                //       ccs.PercentMemory as CurrentPercentMemory,
                //       ccs.MemoryUsed as CurrentMemoryUsed,
                //       ccs.VirtualMemoryUsed as CurrentVirtualMemoryUsed,
                //       pe.AvgPercentCPU as PercentCPU,
                //       pe.AvgPercentMemory as PercentMemory,
                //       pe.AvgMemoryUsed as MemoryUsed,
                //       pe.AvgVirtualMemoryUsed as VirtualMemoryUsed,
                //       pe.ErrorMessage
            }
        }
Exemplo n.º 19
0
 //[Benchmark, BenchmarkCategory("Orig")] public void IPNetCidrv4() => IPNetOriginal.Parse("127.0.0.1/16");
 [Benchmark, BenchmarkCategory("Span")] public void IPNetSpanCidrv4() => IPNet.Parse("127.0.0.1/24");