コード例 #1
0
        /// <summary>
        /// Fetches the system data from lower querier and saves it to the database.
        /// </summary>
        private void LowerQuerierFetchSystemData()
        {
            lock (this.SyncRoot)
            {
                if (this.volatileFetchingSystemData != null)
                {
                    return;
                }

                if (this.cacheEntry.SystemData == null)
                {
                    this.InitializeLowerQuerier();

                    this.cacheEntry.SystemData       = new SerializableSystemData(this.lowerQuerier.SystemData);
                    this.cacheEntry.LastModification = DateTime.UtcNow;

                    this.cacheDatabaseContext.CacheData.Update(this.cacheEntry);
                    this.cacheDatabaseContext.SaveChanges();
                }

                if (this.cacheEntry.ApiUsed.HasFlag(QueryApis.VendorSpecific))
                {
                    log.Info($"Forcing non-cached operation for FetchSystemData of device {this.Address} due to vendor specific API usage");
                    this.InitializeLowerQuerier();
                    this.volatileFetchingSystemData = this.lowerQuerier.SystemData;
                }
                else
                {
                    this.volatileFetchingSystemData = new VolatileFetchingSystemData(this.cacheEntry.SystemData, this.lowerLayer);
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// Construct from device address.
        /// </summary>
        public SystemDataStoreOnlyContainer(IDeviceSystemData inputSystemData)
        {
            if (inputSystemData is null)
            {
                throw new ArgumentNullException(nameof(inputSystemData), "The IDeviceSystemData to 'store only' is null");
            }

            // as we'll anyway need all values, we trigger immediate aquisition hoping for better performance
            inputSystemData.ForceEvaluateAll();

            this.Description        = inputSystemData.Description;
            this.EnterpriseObjectId = inputSystemData.EnterpriseObjectId;
            this.Contact            = inputSystemData.Contact;
            this.Location           = inputSystemData.Location;
            this.Name              = inputSystemData.Name;
            this.Uptime            = inputSystemData.Uptime;
            this.Model             = inputSystemData.Model;
            this.Version           = inputSystemData.Version;
            this.DeviceAddress     = inputSystemData.DeviceAddress;
            this.DeviceModel       = inputSystemData.DeviceModel;
            this.SupportedFeatures = inputSystemData.SupportedFeatures;
            this.Oids              = inputSystemData.Oids;

            // we intentionally do not copy the query duration as after deserializting it will have no more meaning
            // because there was in fact no query. So Zero seems much more correct in this context.
        }
コード例 #3
0
        /// <summary>
        /// Construct from system data.
        /// </summary>
        /// <param name="address">The IP address that this host info reply is for.</param>
        /// <param name="systemData">The system data.</param>
        /// <param name="defaultApi">The API that is, by default, used for talking to this device.</param>
        /// <param name="lastDataUpdate">The date and time when the data has last been updated.</param>
        public HostInfoReply(IpAddress address, IDeviceSystemData systemData, QueryApis defaultApi, DateTime?lastDataUpdate)
        {
            this.address    = address ?? throw new ArgumentNullException(nameof(address), "The IP address to construct a HostInfoReply for is null");
            this.systemData = systemData ?? throw new ArgumentNullException(nameof(systemData), "The system data to construct a HostInfoReply from is null");

            this.systemData.ForceEvaluateAll();

            this.DefaultApi     = defaultApi.ToString();
            this.LastDataUpdate = lastDataUpdate;
            this.UnixTimeStamp  = (ulong?)((this.LastDataUpdate - DateTime.UnixEpoch)?.TotalSeconds);

            this.SupportedFeatures = this.systemData.SupportedFeatures
                                     .ToString()
                                     .Split(',', StringSplitOptions.RemoveEmptyEntries)
                                     .Select(f => f.Trim());
        }
コード例 #4
0
        /// <summary>
        /// Formats as block-formatted string of an <see cref="IDeviceSystemData" />.
        /// </summary>
        /// <param name="deviceSystemData">The data to format.</param>
        /// <returns>The formatted string.</returns>
        public string Format(IDeviceSystemData deviceSystemData)
        {
            if (deviceSystemData == null)
            {
                return("<null>");
            }

            StringBuilder returnBuilder = new StringBuilder(256);

            returnBuilder.Append("  - System Model      : ").AppendLine(string.IsNullOrWhiteSpace(deviceSystemData.Model) ? NotAvailableString : deviceSystemData.Model);
            returnBuilder.Append("  - System SW Version : ").AppendLine((deviceSystemData.Version == null) ? NotAvailableString : deviceSystemData.Version.ToString());
            returnBuilder.Append("  - System Name       : ").AppendLine(string.IsNullOrWhiteSpace(deviceSystemData.Name) ? NotAvailableString : deviceSystemData.Name);
            returnBuilder.Append("  - System location   : ").AppendLine(string.IsNullOrWhiteSpace(deviceSystemData.Location) ? NotAvailableString : deviceSystemData.Location);
            returnBuilder.Append("  - System description: ").AppendLine(string.IsNullOrWhiteSpace(deviceSystemData.Description) ? NotAvailableString : deviceSystemData.Description);
            returnBuilder.Append("  - System admin      : ").AppendLine(string.IsNullOrWhiteSpace(deviceSystemData.Contact) ? NotAvailableString : deviceSystemData.Contact);
            returnBuilder.Append("  - System uptime     : ").AppendLine(deviceSystemData.Uptime.HasValue ? deviceSystemData.Uptime?.ToString() : NotAvailableString);
            returnBuilder.Append("  - System root OID   : ").AppendLine(deviceSystemData.EnterpriseObjectId == null ? NotAvailableString : deviceSystemData.EnterpriseObjectId?.ToString());
            returnBuilder.Append("  - Max. SNMP version : ").AppendLine(deviceSystemData.MaximumSnmpVersion.ToString());

            return(returnBuilder.ToString());
        }
コード例 #5
0
        public void QuerySystemDataTest()
        {
            // test a (hopefully) successful query.
            // THIS CAN FAIL IF THE DEVICE HOLDING THE address specified by "testAddress"
            // is not available or has no SNMP service running.
            using (var snmpll = new SnmpLowerLayer(TestConstants.TestAddressMikrotik1))
            {
                IDeviceSystemData systemData = snmpll.SystemData;
                Assert.NotNull(systemData, "The system data is null");

                Assert.IsNotEmpty(systemData.Name, "system name is empty");
                Assert.IsNotEmpty(systemData.Contact, "system contact is empty");
                Assert.IsNotEmpty(systemData.Location, "system location is empty");
                Assert.IsNotEmpty(systemData.Description, "system description is empty");
                Assert.IsNotNull(systemData.Uptime, "system uptime is null");
                Assert.IsNotNull(systemData.EnterpriseObjectId, "system enterprise OID is null");

                Console.WriteLine($"{Environment.NewLine}{systemData}");
            }

            // test a (hopefully) successful query.
            // THIS CAN FAIL IF THE DEVICE HOLDING THE address specified by "testAddress"
            // is not available or has no SNMP service running.
            using (var snmpll = new SnmpLowerLayer(TestConstants.TestAddressUbntAirOs4side1, QuerierOptions.Default.WithProtocolVersion(SnmpVersion.Ver1)))
            {
                IDeviceSystemData systemData = snmpll.SystemData;
                Assert.NotNull(systemData, "The system data is null");

                Assert.IsNotEmpty(systemData.Name, "system name is empty");
                Assert.IsNotEmpty(systemData.Contact, "system contact is empty");
                Assert.IsNotEmpty(systemData.Location, "system location is empty");
                Assert.IsNotEmpty(systemData.Description, "system description is empty");
                Assert.IsNotNull(systemData.Uptime, "system uptime is null");
                Assert.IsNotNull(systemData.EnterpriseObjectId, "system enterprise OID is null");

                Console.WriteLine($"{Environment.NewLine}{systemData}");
            }
        }
コード例 #6
0
        /// <summary>
        /// Formats a generic object if it's of one of the supported types.
        /// </summary>
        /// <param name="someObject">The object to format.</param>
        /// <returns>The formatted text.</returns>
        public string Format(object someObject)
        {
            if (someObject == null)
            {
                return("<null>");
            }

            IDeviceSystemData asDevSysData = someObject as IDeviceSystemData;

            if (asDevSysData != null)
            {
                return(this.Format(asDevSysData));
            }

            IInterfaceDetails asIfDetails = someObject as IInterfaceDetails;

            if (asIfDetails != null)
            {
                return(this.Format(asIfDetails));
            }

            IInterfaceDetail asIfDetail = someObject as IInterfaceDetail;

            if (asIfDetail != null)
            {
                return(this.Format(asIfDetail));
            }

            IWirelessPeerInfos asWiPeerInfos = someObject as IWirelessPeerInfos;

            if (asWiPeerInfos != null)
            {
                return(this.Format(asWiPeerInfos));
            }

            IWirelessPeerInfo asWiPeerInfo = someObject as IWirelessPeerInfo;

            if (asWiPeerInfo != null)
            {
                return(this.Format(asWiPeerInfo));
            }

            ILinkDetails asLinkDetails = someObject as ILinkDetails;

            if (asLinkDetails != null)
            {
                return(this.Format(asLinkDetails));
            }

            IBgpPeers asBgpPeers = someObject as IBgpPeers;

            if (asBgpPeers != null)
            {
                return(this.Format(asBgpPeers));
            }

            IBgpPeer asBgpPeer = someObject as IBgpPeer;

            if (asBgpPeer != null)
            {
                return(this.Format(asBgpPeer));
            }

            ITracerouteResult asTracerouteResult = someObject as ITracerouteResult;

            if (asTracerouteResult != null)
            {
                return(this.Format(asTracerouteResult));
            }

            ITracerouteHop asTracerouteHop = someObject as ITracerouteHop;

            if (asTracerouteHop != null)
            {
                return(this.Format(asTracerouteHop));
            }

            // fallback: call the object's ToString
            return(someObject.ToString());
        }
コード例 #7
0
        /// <summary>
        /// Fetches the system data info.
        /// </summary>
        private void FetchSystemData()
        {
            if (this.systemDataBacking != null)
            {
                return;
            }

            var versionMatch = OsVersionExtractionRegex.Match(sysResource.Version);

            if (versionMatch.Success)
            {
                this.osVersionBacking = versionMatch.Value.ToSemanticVersion();
            }
            else
            {
                throw new InvalidOperationException($"Cannot convert version string '{sysResource.Version}' to a valid SemanticVersion: It's not matching the version Regex '{OsVersionExtractionRegex.ToString()}'");
            }

            this.modelBacking = this.sysRouterboard.Model.Replace("RouterBOARD", "RB").Replace(" ", string.Empty);

            var users  = this.TikConnection.LoadList <User>();
            var groups = this.TikConnection.LoadList <UserGroup>();

            var detectedFeatures = DeviceSupportedFeatures.None;
            var myUser           = users.SingleOrDefault(u => u.Name == this.Options.LoginUser);

            if (myUser != null)
            {
                var myGroup = groups.SingleOrDefault(g => g.Name == myUser.Group);
                if (myGroup != null)
                {
                    string[] policies = myGroup.Policy.Split(',');
                    if (policies.Contains("api"))
                    {
                        // only with API allowed we need to check further (well - since we connected to it, this should always be true)
                        if (policies.Contains("read"))
                        {
                            detectedFeatures |= DeviceSupportedFeatures.BgpPeers | DeviceSupportedFeatures.Rssi;
                        }

                        if (policies.Contains("test"))
                        {
                            detectedFeatures |= DeviceSupportedFeatures.Traceroute;
                        }
                    }
                }
            }

            this.systemDataBacking = new SerializableSystemData
            {
                Contact            = string.Empty,
                Description        = $"RouterOS {this.modelBacking}",
                DeviceAddress      = this.Address,
                DeviceModel        = $"{this.modelBacking} v {this.osVersionBacking}",
                EnterpriseObjectId = new Oid(),
                Location           = string.Empty,
                MaximumSnmpVersion = SnmpVersion.Ver2, // we know that MTik supports SNMPv2c
                Model             = this.modelBacking,
                Name              = this.sysIdent.Name,
                Uptime            = this.sysResource.Uptime,
                Version           = this.osVersionBacking,
                QueryDuration     = TimeSpan.Zero,
                SupportedFeatures = detectedFeatures
            };
        }
コード例 #8
0
 public VolatileFetchingSystemData(IDeviceSystemData underlyingSystemData, ISnmpLowerLayer lowerLayer)
 {
     this.underlyingSystemData = underlyingSystemData ?? throw new System.ArgumentNullException(nameof(underlyingSystemData));
     this.lowerLayer           = lowerLayer ?? throw new System.ArgumentNullException(nameof(lowerLayer));
 }