// DiscoverNAT looks for a NAT device in the network and
// returns an object that can manage port mappings.
500340
func DiscoverNAT(ctx context.Context) (*NAT, error) {
	var (
		natInstance nat.NAT
		err         error
	)

	done := make(chan struct{})
	go func() {
		defer close(done)
		// This will abort in 10 seconds anyways.
		natInstance, err = nat.DiscoverGateway()
	}()

	select {
	case <-done:
	case <-ctx.Done():
		return nil, ctx.Err()
	}

	if err != nil {
		return nil, err
	}

	// Log the device addr.
	addr, err := natInstance.GetDeviceAddress()
	if err != nil {
		log.Debug("DiscoverGateway address error:", err)
	} else {
		log.Debug("DiscoverGateway address:", addr)
	}

	return newNAT(natInstance), nil
}
421732
func (c *Client) consulDiscovery() {
	for {
		select {
		case <-c.triggerDiscoveryCh:
			if err := c.consulDiscoveryImpl(); err != nil {
				c.logger.Error("error discovering nomad servers", "error", err)
			}
		case <-c.shutdownCh:
			return
		}
	}
}
1102432
func (v *VPCRouter) NetworkMaskLenAt(index int) int {
	if !v.HasInterfaces() {
		return -1
	}
	if len(v.Interfaces) <= index {
		return -1
	}

	if index == 0 {
		return v.Interfaces[0].Switch.Subnet.NetworkMaskLen
	}

	return v.Settings.Router.Interfaces[index].NetworkMaskLen
}
1039411
func NATManager(nm config.NATManagerC) Option {
	return func(cfg *Config) error {
		if cfg.NATManager != nil {
			return fmt.Errorf("cannot specify multiple NATManagers")
		}
		cfg.NATManager = nm
		return nil
	}
}
803120
func (s *ServiceCache) Find(ip net.IP, port int, host string, local bool) interface{} {
	s.RLock()
	defer s.RUnlock()

	if host != "" {
		if data := s.findHost(host, port, local); data != nil {
			return data
		}
	}

	return s.findIP(ip, port, local)
}
455044
func FindAvailableNetwork(list []*net.IPNet) (*net.IPNet, error) {
	// We don't check for an error here, because we don't really care if we
	// can't read /etc/resolv.conf. So instead we skip the append if resolvConf
	// is nil. It either doesn't exist, or we can't read it for some reason.
	var nameservers []string
	if rc, err := resolvconf.Get(); err == nil {
		nameservers = resolvconf.GetNameserversAsCIDR(rc.Content)
	}
	for _, nw := range list {
		if err := CheckNameserverOverlaps(nameservers, nw); err == nil {
			if err := CheckRouteOverlaps(nw); err == nil {
				return nw, nil
			}
		}
	}
	return nil, fmt.Errorf("no available network")
}
243502
func (p *V2) Discover() error {
	if err := p.init(); err != nil {
		return err
	}
	if p.lastDiscovery.After(time.Time{}) {
		var extinct []device.GenericDevice
		p.RLock()
		for _, dev := range p.devices {
			// If the device has not been seen in twice the time since the last
			// discovery, mark it as extinct
			if dev.Seen().Before(time.Now().Add(time.Since(p.lastDiscovery) * -2)) {
				extinct = append(extinct, dev)
			}
		}
		p.RUnlock()
		// Remove extinct devices
		for _, dev := range extinct {
			p.removeDevice(dev.ID())

			locationID := dev.CachedLocation()
			location, err := p.getLocation(locationID)
			if err == nil {
				if err = location.RemoveDevice(dev); err != nil {
					common.Log.Warnf("Failed removing extinct device '%d' from location (%s): %v", dev.ID(), locationID, err)
				}
				if len(location.Devices()) == 0 {
					p.removeLocation(location.ID())
					p.Notify(common.EventExpiredLocation{Location: location})
				}
			}

			groupID := dev.CachedGroup()
			group, err := p.getGroup(groupID)
			if err == nil {
				if err = group.RemoveDevice(dev); err != nil {
					common.Log.Warnf("Failed removing extinct device '%d' from group (%s): %v", dev.ID(), groupID, err)
				}
				if len(group.Devices()) == 0 {
					p.removeGroup(group.ID())
					p.Notify(common.EventExpiredGroup{Group: group})
				}
			}

			p.Notify(common.EventExpiredDevice{Device: dev})
		}
	}
	if err := p.broadcast.Discover(); err != nil {
		return err
	}
	p.Lock()
	p.lastDiscovery = time.Now()
	p.Unlock()

	return nil
}
614322
func (m *MobileGateway) NetworkMaskLenAt(index int) int {
	if len(m.Interfaces) <= index {
		return -1
	}
	if index == 0 {
		return m.Interfaces[0].Switch.UserSubnet.NetworkMaskLen
	}

	return m.Settings.MobileGateway.Interfaces[0].NetworkMaskLen
}
1093357
func (s *NATService) DisableStaticNat(p *DisableStaticNatParams) (*DisableStaticNatResponse, error) {
	resp, err := s.cs.newRequest("disableStaticNat", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DisableStaticNatResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
393094
func (np *Netplan) FindDeviceByNameOrMAC(name, mac string) (string, DeviceType, error) {
	if name != "" {
		bond, err := np.FindBondByName(name)
		if err == nil {
			return bond, TypeBond, nil
		}
		if !errors.IsNotFound(err) {
			return "", "", errors.Trace(err)
		}
		vlan, err := np.FindVLANByName(name)
		if err == nil {
			return vlan, TypeVLAN, nil
		}
		ethernet, err := np.FindEthernetByName(name)
		if err == nil {
			return ethernet, TypeEthernet, nil
		}

	}
	// by MAC is less reliable because things like vlans often have the same MAC address
	if mac != "" {
		bond, err := np.FindBondByMAC(mac)
		if err == nil {
			return bond, TypeBond, nil
		}
		if !errors.IsNotFound(err) {
			return "", "", errors.Trace(err)
		}
		vlan, err := np.FindVLANByMAC(mac)
		if err == nil {
			return vlan, TypeVLAN, nil
		}
		ethernet, err := np.FindEthernetByMAC(mac)
		if err == nil {
			return ethernet, TypeEthernet, nil
		}
	}
	return "", "", errors.NotFoundf("device - name %q MAC %q", name, mac)
}
856238
func (n *LegacyNovaNetworking) ResolveNetwork(name string, external bool) (string, error) {
	// Ignore external, it's a Neutron concept.
	if utils.IsValidUUIDString(name) {
		return name, nil
	}
	var networkIds []string
	networks, err := n.env.nova().ListNetworks()
	if err != nil {
		return "", err
	}
	for _, network := range networks {
		// Assuming a positive match on "" makes this behave the same as the
		// server-side filtering in Neutron networking.
		if name == "" || network.Label == name {
			networkIds = append(networkIds, network.Id)
		}
	}
	return processResolveNetworkIds(name, networkIds)
}
180848
func (b *AdapterBase) DiscoveryClient() (discovery.DiscoveryInterface, error) {
	if b.discoveryClient == nil {
		clientConfig, err := b.ClientConfig()
		if err != nil {
			return nil, err
		}
		discoveryClient, err := discovery.NewDiscoveryClientForConfig(clientConfig)
		if err != nil {
			return nil, fmt.Errorf("unable to construct discovery client for dynamic client: %v", err)
		}
		b.discoveryClient = discoveryClient
	}
	return b.discoveryClient, nil
}
850740
func (nDB *NetworkDB) findCommonNetworks(nodeName string) []string {
	nDB.RLock()
	defer nDB.RUnlock()

	var networks []string
	for nid := range nDB.networks[nDB.config.NodeID] {
		if n, ok := nDB.networks[nodeName][nid]; ok {
			if !n.leaving {
				networks = append(networks, nid)
			}
		}
	}

	return networks
}
957283
func Discover(renewal, timeout time.Duration) []nat.Device {
	var results []nat.Device

	interfaces, err := net.Interfaces()
	if err != nil {
		l.Infoln("Listing network interfaces:", err)
		return results
	}

	resultChan := make(chan nat.Device)

	wg := &sync.WaitGroup{}

	for _, intf := range interfaces {
		// Interface flags seem to always be 0 on Windows
		if runtime.GOOS != "windows" && (intf.Flags&net.FlagUp == 0 || intf.Flags&net.FlagMulticast == 0) {
			continue
		}

		for _, deviceType := range []string{"urn:schemas-upnp-org:device:InternetGatewayDevice:1", "urn:schemas-upnp-org:device:InternetGatewayDevice:2"} {
			wg.Add(1)
			go func(intf net.Interface, deviceType string) {
				discover(&intf, deviceType, timeout, resultChan)
				wg.Done()
			}(intf, deviceType)
		}
	}

	go func() {
		wg.Wait()
		close(resultChan)
	}()

	seenResults := make(map[string]bool)
nextResult:
	for result := range resultChan {
		if seenResults[result.ID()] {
			l.Debugf("Skipping duplicate result %s", result.ID())
			continue nextResult
		}

		results = append(results, result)
		seenResults[result.ID()] = true

		l.Debugf("UPnP discovery result %s", result.ID())
	}

	return results
}
820989
func (a *Allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
	if dType != discoverapi.DatastoreConfig {
		return nil
	}

	dsc, ok := data.(discoverapi.DatastoreConfigData)
	if !ok {
		return types.InternalErrorf("incorrect data in datastore update notification: %v", data)
	}

	ds, err := datastore.NewDataStoreFromConfig(dsc)
	if err != nil {
		return err
	}

	return a.initializeAddressSpace(globalAddressSpace, ds)
}
1293970
func (h *Handler) Discovery(base string) *camtypes.SignDiscovery {
	sd := &camtypes.SignDiscovery{
		PublicKeyID:   h.entity.PrimaryKey.KeyIdString(),
		SignHandler:   base + "camli/sig/sign",
		VerifyHandler: base + "camli/sig/verify",
	}
	if h.pubKeyBlobRef.Valid() {
		sd.PublicKeyBlobRef = h.pubKeyBlobRef
		sd.PublicKey = base + h.pubKeyBlobRefServeSuffix
	}
	return sd
}
1026736
func FindNetwork(key string) *Network {
	collections.networkMutex.Lock()
	defer collections.networkMutex.Unlock()

	obj := collections.networks[key]
	if obj == nil {
		return nil
	}

	return obj
}