예제 #1
0
파일: ifstat.go 프로젝트: mgenov/snmpgo
func getIfInfo(snmp *snmpgo.SNMP) (*ifInfo, error) {
	pdu, err := snmp.GetBulkWalk(snmpgo.Oids{sysDescr, ifAdminStatus, ifName}, 1, maxRepetitions)
	if err != nil {
		return nil, err
	}

	if pdu.ErrorStatus() != snmpgo.NoError {
		return nil, fmt.Errorf(
			"failed to get system information - %s(%d)", pdu.ErrorStatus(), pdu.ErrorIndex())
	}

	info := newIfInfo()
	if descrs := pdu.VarBinds().MatchBaseOids(sysDescr); len(descrs) > 0 {
		info.descr = descrs[0].Variable.String()
	}

	ifNameDepth := len(ifName.Value)
	for _, varBind := range pdu.VarBinds().MatchBaseOids(ifName) {
		// get interface number and name
		if len(varBind.Oid.Value) != ifNameDepth+1 {
			continue
		}
		ifNum := varBind.Oid.Value[ifNameDepth]
		ifName := varBind.Variable.String()

		if ifRegexp != nil && !ifRegexp.MatchString(ifName) {
			continue
		}

		// get admin status
		oid, err := ifAdminStatus.AppendSubIds([]int{ifNum})
		if err != nil {
			return nil, err
		}

		// check admin status("1" is up)
		if adms := pdu.VarBinds().MatchOid(oid); adms == nil || adms.Variable.String() != "1" {
			continue
		}

		info.IfList = append(info.IfList, ifNum)
		info.IfName[ifNum] = ifName
		info.IfIn[ifNum] = nil
		info.IfOut[ifNum] = nil
		info.LastIfIn[ifNum] = nil
		info.LastIfOut[ifNum] = nil
	}

	if len(info.IfList) == 0 {
		return nil, fmt.Errorf("no interface")
	}

	return info, nil
}
예제 #2
0
파일: ifstat.go 프로젝트: mgenov/snmpgo
func getIfTraffic(snmp *snmpgo.SNMP, info *ifInfo) error {
	pdu, err := snmp.GetBulkWalk(snmpgo.Oids{ifHCInOctets, ifHCOutOctets}, 0, maxRepetitions)
	if err != nil {
		return err
	}

	if pdu.ErrorStatus() != snmpgo.NoError {
		return fmt.Errorf(
			"failed to get network traffic - %s(%d)", pdu.ErrorStatus(), pdu.ErrorIndex())
	}

	for _, ifNum := range info.IfList {
		oid, err := ifHCInOctets.AppendSubIds([]int{ifNum})
		if err != nil {
			return err
		}
		if in := pdu.VarBinds().MatchOid(oid); in != nil {
			count, err := in.Variable.BigInt()
			if err != nil {
				return err
			}
			info.LastIfIn[ifNum], info.IfIn[ifNum] = info.IfIn[ifNum], count
		} else {
			info.LastIfIn[ifNum], info.IfIn[ifNum] = info.IfIn[ifNum], nil
		}

		oid, err = ifHCOutOctets.AppendSubIds([]int{ifNum})
		if err != nil {
			return err
		}
		if out := pdu.VarBinds().MatchOid(oid); out != nil {
			count, err := out.Variable.BigInt()
			if err != nil {
				return err
			}
			info.LastIfOut[ifNum], info.IfOut[ifNum] = info.IfOut[ifNum], count
		} else {
			info.LastIfOut[ifNum], info.IfOut[ifNum] = info.IfOut[ifNum], nil
		}
	}

	info.LastTime, info.Time = info.Time, time.Now()
	return nil
}