コード例 #1
0
        /// <summary>
        /// Gets the device handler of the given handler class name via reflection.
        /// </summary>
        /// <param name="handlerClassName">The class name of the device handler to get.</param>
        /// <param name="lowerLayer">The lower layer for talking to this device.</param>
        /// <param name="oidTable">The OID lookup table for the device.</param>
        /// <param name="osVersion">The SW version of the device.</param>
        /// <param name="model">The device's model name. Shall be the same name as used for the device name during OID database lookups.</param>
        /// <param name="options">The options to use.</param>
        /// <returns>The generated device handler.</returns>
        protected IDeviceHandler GetHandlerViaReflection(string handlerClassName, ISnmpLowerLayer lowerLayer, IDeviceSpecificOidLookup oidTable, SemanticVersion osVersion, string model, IQuerierOptions options)
        {
            var type = Type.GetType($"SnmpAbstraction.{handlerClassName}");

            if (type == null)
            {
                var ex = new HamnetSnmpException($"{lowerLayer.Address} ({model} v {osVersion}): Cannot find a DeviceHandler implementation of name '{handlerClassName}'", lowerLayer.Address?.ToString());
                this.CollectException("Missing handler class name", ex);
                throw ex;
            }

            object myObject = null;

            try
            {
                myObject = Activator.CreateInstance(type, lowerLayer, oidTable, osVersion, model, options);
            }
            catch (Exception ex)
            {
                this.CollectException($"Instantiate handler class '{type.FullName}'", ex);

                throw new HamnetSnmpException($"{lowerLayer.Address} ({model} v {osVersion}): Exception while instantiating DeviceHandler of name '{handlerClassName}': {ex.Message}", ex, lowerLayer.Address?.ToString());
            }

            IDeviceHandler castedHandler = myObject as IDeviceHandler;

            if (castedHandler == null)
            {
                var ex = new HamnetSnmpException($"{lowerLayer.Address} ({model} v {osVersion}): Instantiating DeviceHandler of name '{handlerClassName}' is NOT an IDeviceHandler", lowerLayer.Address?.ToString());
                this.CollectException($"Cast handler class '{type.FullName}' to IDeviceHandler", ex);
                throw ex;
            }

            return(castedHandler);
        }
コード例 #2
0
        /// <inheritdoc />
        public VbCollection Query(IEnumerable <Oid> oids)
        {
            if (this.disposedValue)
            {
                throw new ObjectDisposedException(nameof(SnmpLowerLayer), "The object is already disposed off. Cannot execute any more commands on it.");
            }

            if (oids == null)
            {
                throw new ArgumentNullException(nameof(oids), "The list of OIDs to query is null");
            }

            SnmpPacket response = this.SendRequest(oids);

            if (response == null)
            {
                throw new HamnetSnmpException($"Query for {oids.Count()} OIDs from {this.Address} produced 'null' response", this.Address?.ToString());
            }

            // ErrorStatus other then 0 is an error returned by the Agent - see SnmpConstants for error definitions
            if (response.Pdu.ErrorStatus != 0)
            {
                // agent reported an error with the request
                var ex = new HamnetSnmpException($"Error in SNMP reply from device '{this.Address}': Error status {response.Pdu.ErrorStatus} at index {response.Pdu.ErrorIndex}, requested OIDs were '{string.Join(", ", response.Pdu.VbList.Select(o => o.Oid.ToString()))}'", this.Address?.ToString());
                log.Info(ex.Message);
                throw ex;
            }

            return(response.Pdu.VbList);
        }
コード例 #3
0
        /// <summary>
        /// Gets the OID lookup table for the specified device name and version.
        /// </summary>
        /// <param name="deviceName">The device name to look up.</param>
        /// <param name="version">The current version of the device.</param>
        /// <param name="deviceVersion">Returns the device version container matching this device.</param>
        /// <param name="deviceAddress">The IP address of the device (only used to include it with possible exceptions).</param>
        /// <returns>The OID lookup table for the specified device name and version.</returns>
        protected IDeviceSpecificOidLookup ObtainOidTable(string deviceName, SemanticVersion version, out DeviceVersion deviceVersion, IpAddress deviceAddress)
        {
            using (var database = DeviceDatabaseProvider.Instance.DeviceDatabase)
            {
                int foundDeviceId = -1;
                if (!database.TryFindDeviceId(deviceName, out foundDeviceId))
                {
                    var exception = new HamnetSnmpException($"Device name '{deviceName}' cannot be found in device database", deviceAddress?.ToString());
                    log.Error(exception.Message);
                    this.CollectException("No OID lookup for device name", exception);
                    throw exception;
                }

                deviceVersion = null;
                if (!database.TryFindDeviceVersionId(foundDeviceId, version, out deviceVersion))
                {
                    var exception = new HamnetSnmpException($"Version '{version}' of device named '{deviceName}' (ID {foundDeviceId}) cannot be matched to any version range of device database", deviceAddress?.ToString());
                    log.Error(exception.Message);
                    this.CollectException("No OID lookup for device version", exception);
                    throw exception;
                }

                string foundOidMappingIds = string.Empty;
                if (!database.TryFindOidLookupId(deviceVersion.Id, out foundOidMappingIds))
                {
                    var exception = new HamnetSnmpException($"Version '{version}' of device named '{deviceName}' (ID {foundDeviceId}, version ID {deviceVersion.Id}) cannot be matched to any OID mapping ID of device database", deviceAddress?.ToString());
                    log.Error(exception.Message);
                    this.CollectException("No OID mapping for device version", exception);
                    throw exception;
                }

                // need to convert the string containing a comma-separated list of OID lookup tables IDs into single, integer table IDs
                // Example: There are two lookups given in order "3,1" in the foundOidMappingIds string.
                //          If a RetrievableValuesEnum has a value in lookup of ID 3 that value shall be used. Otherwise the value of lookup #1.
                string[] splitOidMappingIds = foundOidMappingIds.Split(new char[] { ',', ';', ':', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                List <IDeviceSpecificOidLookup> orderedOidLookupsList = new List <IDeviceSpecificOidLookup>(splitOidMappingIds.Length);
                foreach (var sid in splitOidMappingIds)
                {
                    int intId;
                    if (!int.TryParse(sid, out intId))
                    {
                        log.Warn($"OID mapping table ID '{sid}' as found for device '{deviceName}' v '{version}' (version ID {deviceVersion.Id}, mapping IDs '{foundOidMappingIds}') is not an integer value and will be ignored");
                        continue;
                    }

                    IDeviceSpecificOidLookup foundLookup = null;
                    if (!database.TryFindDeviceSpecificOidLookup(intId, deviceVersion.MaximumSupportedSnmpVersion.ToSnmpVersion(), out foundLookup))
                    {
                        var exception = new HamnetSnmpException($"Version '{version}' of device named '{deviceName}': Cannot find OID mapping ID table of ID {intId} in device database", deviceAddress?.ToString());
                        log.Error(exception.Message);
                        this.CollectException("No OID mapping for mapping ID", exception);
                        throw exception;
                    }

                    orderedOidLookupsList.Add(foundLookup);
                }

                return(new DeviceSpecificMultiLayerOidLookupProxy(orderedOidLookupsList));
            }
        }
コード例 #4
0
        /// <inheritdoc />
        public override IDeviceHandler CreateHandler(ISnmpLowerLayer lowerLayer, IQuerierOptions options)
        {
            if (!this.detectionId.HasValue)
            {
                var ex = new InvalidOperationException("Cannot perform CreateHandler() without previous and successful call to IsApplicable");
                this.CollectException("UbntSnmp: CreateHandler(ISnmpLowerLayer, IQuerierOptions)", ex);
                throw ex;
            }

            try
            {
                List <Oid> queryList = new List <Oid>();

                Oid osVersionOid = null;
                if (string.IsNullOrWhiteSpace(this.osDetectedVersion))
                {
                    osVersionOid = OsVersionRootOid + new Oid(new uint[] { this.detectionId.Value });
                    queryList.Add(osVersionOid);
                }

                Oid modelOid = null;
                if (string.IsNullOrWhiteSpace(this.detectedModel))
                {
                    modelOid = ModelRootOid + new Oid(new uint[] { this.detectionId.Value });
                    queryList.Add(modelOid);
                }

                VbCollection osVersionCollection = null;
                if (queryList.Count > 0)
                {
                    osVersionCollection = lowerLayer.Query(queryList);
                }

                string osVersionString = (osVersionOid != null)
                    ? osVersionCollection[osVersionOid].Value.ToString()
                    : this.osDetectedVersion;

                Match           match     = OsVersionExtractionRegex.Match(osVersionString);
                SemanticVersion osVersion = match.Success ? match.Groups[1].Value.ToSemanticVersion() : null;

                string model = (modelOid != null)
                    ? osVersionCollection[modelOid].Value.ToString()
                    : this.detectedModel;

                if (string.IsNullOrWhiteSpace(model))
                {
                    var info = $"Model (retrieved using OID '{modelOid}') is null, empty or white-space-only";
                    log.Warn(info);
                    var ex = new HamnetSnmpException(info, lowerLayer?.Address?.ToString());
                    this.CollectException("UbntSnmp: No model", ex);
                    throw ex;
                }

                log.Info($"Detected device '{lowerLayer.Address}' as Ubiquiti '{model}' v '{osVersion}'");

                DeviceVersion            deviceVersion;
                IDeviceSpecificOidLookup oidTable = this.ObtainOidTable(model.Trim(), osVersion, out deviceVersion, lowerLayer?.Address);
                if (string.IsNullOrWhiteSpace(deviceVersion.HandlerClassName))
                {
                    return((model == AirFiberFakeModelString)
                        ? new UbiquitiAirFiberDeviceHandler(lowerLayer, oidTable, osVersion, model, options) as IDeviceHandler
                        : new UbiquitiAirOsAbove56DeviceHandler(lowerLayer, oidTable, osVersion, model, options) as IDeviceHandler);
                }
                else
                {
                    return(this.GetHandlerViaReflection(deviceVersion.HandlerClassName, lowerLayer, oidTable, osVersion, model, options));
                }
            }
            catch (Exception ex)
            {
                this.CollectException("UbntSnmp: Model detection and OID lookup", ex);

                // we want to catch and nest the exception here as the APIs involved are not able to append the infomration for which
                // device (i.e. IP address) the exception is for
                throw new HamnetSnmpException($"Failed to create handler for Ubiquiti device '{lowerLayer.Address}': {ex.Message}", ex, lowerLayer?.Address?.ToString());
            }
        }