container_discovery/internal/discoverer/zone.go

91 lines
1.7 KiB
Go
Raw Normal View History

2018-04-19 11:36:56 +00:00
package discoverer
import (
"net"
"regexp"
"strings"
2018-05-11 02:44:47 +00:00
occu "git.loafle.net/overflow/commons-go/core/util"
2018-04-26 09:00:24 +00:00
ocmd "git.loafle.net/overflow/commons-go/model/discovery"
2018-04-19 11:36:56 +00:00
)
2018-04-27 16:20:01 +00:00
func scanZone(dz *ocmd.DiscoverZone, resultChan chan interface{}, errChan chan error, doneChan chan<- struct{}, stopChan chan struct{}) {
2018-04-19 11:36:56 +00:00
defer func() {
doneChan <- struct{}{}
}()
var err error
var ifaces []net.Interface
var addrs []net.Addr
var ipnet *net.IPNet
var zones []*net.IPNet
// var gwIP net.IP
// var gwIFace string
// if gwIP, gwIFace, err = gateway.DiscoverGateway(); nil != err {
// logChan <- err
// return
// }
if ifaces, err = net.Interfaces(); nil != err {
errChan <- err
return
}
zones = make([]*net.IPNet, 0)
for _, i := range ifaces {
if addrs, err = i.Addrs(); nil != err {
errChan <- err
continue
}
for _, addr := range addrs {
if _, ipnet, err = net.ParseCIDR(addr.String()); nil != err {
errChan <- err
continue
}
if ipnet.IP.IsLoopback() || checkSameZone(zones, ipnet) || checkExclude(dz.ExcludePatterns, i.Name) {
continue
}
zones = append(zones, ipnet)
2018-04-26 09:00:24 +00:00
z := &ocmd.Zone{
2018-05-11 02:44:47 +00:00
Network: ipnet.String(),
Iface: i.Name,
Mac: i.HardwareAddr.String(),
IPV4: strings.Split(addr.String(), "/")[0],
DiscoveredDate: occu.NowPtr(),
2018-04-19 11:36:56 +00:00
}
resultChan <- z
}
}
}
func checkExclude(ep []string, iface string) bool {
var r *regexp.Regexp
var err error
for _, p := range ep {
if r, err = regexp.Compile(p); nil != err {
return false
}
if r.MatchString(iface) {
return true
}
}
return false
}
func checkSameZone(zones []*net.IPNet, ipnet *net.IPNet) bool {
for _, i := range zones {
if i.Contains(ipnet.IP) {
return true
}
}
return false
}