container_discovery/internal/discoverer/zone.go

99 lines
2.0 KiB
Go
Raw Normal View History

2018-04-19 11:36:56 +00:00
package discoverer
import (
"net"
"regexp"
2018-06-13 10:20:14 +00:00
cun "git.loafle.net/commons/util-go/net"
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-06-13 10:20:14 +00:00
ocmm "git.loafle.net/overflow/commons-go/model/meta"
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
2018-06-13 10:20:14 +00:00
var ipnet *cun.IPNet
var zones []*cun.IPNet
2018-04-19 11:36:56 +00:00
// 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
}
2018-06-13 10:20:14 +00:00
zones = make([]*cun.IPNet, 0)
2018-04-19 11:36:56 +00:00
for _, i := range ifaces {
if addrs, err = i.Addrs(); nil != err {
errChan <- err
continue
}
for _, addr := range addrs {
2018-06-13 10:20:14 +00:00
if _, ipnet, err = cun.ParseCIDR(addr.String()); nil != err {
2018-04-19 11:36:56 +00:00
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(),
2018-06-13 10:20:14 +00:00
Address: addr.String(),
2018-05-11 02:44:47 +00:00
DiscoveredDate: occu.NowPtr(),
2018-04-19 11:36:56 +00:00
}
2018-06-13 10:20:14 +00:00
switch ipnet.Version() {
case 6:
z.MetaIPType = ocmm.ToMetaIPType(ocmm.MetaIPTypeEnumV6)
default:
z.MetaIPType = ocmm.ToMetaIPType(ocmm.MetaIPTypeEnumV4)
}
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
}
2018-06-13 10:20:14 +00:00
func checkSameZone(zones []*cun.IPNet, ipnet *cun.IPNet) bool {
2018-04-19 11:36:56 +00:00
for _, i := range zones {
if i.Contains(ipnet.IP) {
return true
}
}
return false
}