// discover services
495952
func (ble *BLE) DiscoverServices(deviceUuid xpc.UUID, uuids []xpc.UUID) {
	sUuid := deviceUuid.String()
	msg := 44
	if ble.utsname.Release >= "18." {
		msg = 72
	}
	if p, ok := ble.peripherals[sUuid]; ok {
		sUuids := make([]string, len(uuids))
		for i, uuid := range uuids {
			sUuids[i] = uuid.String() // uuids may be a list of []byte (2 bytes)
		}
		ble.sendCBMsg(msg, xpc.Dict{"kCBMsgArgDeviceUUID": p.Uuid, "kCBMsgArgUUIDs": sUuids})
	} else {
		log.Println("no peripheral", deviceUuid)
	}
}
17168
func Explore(serviceName string,
	serviceDescription string,
	lambdaAWSInfos []*LambdaAWSInfo,
	api *API,
	site *S3Site,
	s3BucketName string,
	buildTags string,
	linkerFlags string,
	logger *logrus.Logger) error {
	return errors.New("Explore not supported for this binary")
}
813257
func Enable(server *prpc.Server) {
	serviceNames := append(server.ServiceNames(), "discovery.Discovery")
	service, err := New(serviceNames...)
	if err != nil {
		panic(err)
	}
	RegisterDiscoveryServer(server, service)
}
697412
func (c *Client) DiscoverOffer() (*dhcp4.Packet, error) {
	ctx, cancel := context.WithCancel(context.Background())
	wg, out, errCh := c.SimpleSendAndRead(ctx, DefaultServers, c.DiscoverPacket())
	defer func() {
		// Explicitly cancel first, then wait.
		cancel()
		wg.Wait()
	}()

	for packet := range out {
		msgType := dhcp4opts.GetDHCPMessageType(packet.Packet.Options)
		if msgType == dhcp4opts.DHCPOffer {
			// Deferred cancel will cancel the goroutine.
			return packet.Packet, nil
		}
	}

	if err, ok := <-errCh; ok && err != nil {
		return nil, err
	}
	return nil, fmt.Errorf("didn't get a packet")
}
954093
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
	if c == nil {
		return nil
	}
	return c.DiscoveryClient
}
777448
func (d *Disco) discover(hostname svchost.Hostname) (*Host, error) {
	discoURL := &url.URL{
		Scheme: "https",
		Host:   hostname.String(),
		Path:   discoPath,
	}

	client := &http.Client{
		Transport: d.Transport,
		Timeout:   discoTimeout,

		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			log.Printf("[DEBUG] Service discovery redirected to %s", req.URL)
			if len(via) > maxRedirects {
				return errors.New("too many redirects") // this error will never actually be seen
			}
			return nil
		},
	}

	req := &http.Request{
		Header: make(http.Header),
		Method: "GET",
		URL:    discoURL,
	}
	req.Header.Set("Accept", "application/json")
	req.Header.Set("User-Agent", httpclient.UserAgentString())

	creds, err := d.CredentialsForHost(hostname)
	if err != nil {
		log.Printf("[WARN] Failed to get credentials for %s: %s (ignoring)", hostname, err)
	}
	if creds != nil {
		// Update the request to include credentials.
		creds.PrepareRequest(req)
	}

	log.Printf("[DEBUG] Service discovery for %s at %s", hostname, discoURL)

	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("Failed to request discovery document: %v", err)
	}
	defer resp.Body.Close()

	host := &Host{
		// Use the discovery URL from resp.Request in
		// case the client followed any redirects.
		discoURL:  resp.Request.URL,
		hostname:  hostname.ForDisplay(),
		transport: d.Transport,
	}

	// Return the host without any services.
	if resp.StatusCode == 404 {
		return host, nil
	}

	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("Failed to request discovery document: %s", resp.Status)
	}

	contentType := resp.Header.Get("Content-Type")
	mediaType, _, err := mime.ParseMediaType(contentType)
	if err != nil {
		return nil, fmt.Errorf("Discovery URL has a malformed Content-Type %q", contentType)
	}
	if mediaType != "application/json" {
		return nil, fmt.Errorf("Discovery URL returned an unsupported Content-Type %q", mediaType)
	}

	// This doesn't catch chunked encoding, because ContentLength is -1 in that case.
	if resp.ContentLength > maxDiscoDocBytes {
		// Size limit here is not a contractual requirement and so we may
		// adjust it over time if we find a different limit is warranted.
		return nil, fmt.Errorf(
			"Discovery doc response is too large (got %d bytes; limit %d)",
			resp.ContentLength, maxDiscoDocBytes,
		)
	}

	// If the response is using chunked encoding then we can't predict its
	// size, but we'll at least prevent reading the entire thing into memory.
	lr := io.LimitReader(resp.Body, maxDiscoDocBytes)

	servicesBytes, err := ioutil.ReadAll(lr)
	if err != nil {
		return nil, fmt.Errorf("Error reading discovery document body: %v", err)
	}

	var services map[string]interface{}
	err = json.Unmarshal(servicesBytes, &services)
	if err != nil {
		return nil, fmt.Errorf("Failed to decode discovery document as a JSON object: %v", err)
	}
	host.services = services

	return host, nil
}
247422
func (cln *Client) DiscoverServices(ss []ble.UUID) ([]*ble.Service, error) {
	rsp := cln.conn.sendReq(45, xpc.Dict{
		"kCBMsgArgDeviceUUID": cln.id,
		"kCBMsgArgUUIDs":      uuidSlice(ss),
	})
	if rsp.err() != nil {
		return nil, rsp.err()
	}
	svcs := []*ble.Service{}
	for _, xss := range rsp.services() {
		xs := msg(xss.(xpc.Dict))
		svcs = append(svcs, &ble.Service{
			UUID:      ble.MustParse(xs.uuid()),
			Handle:    uint16(xs.serviceStartHandle()),
			EndHandle: uint16(xs.serviceEndHandle()),
		})
	}
	if cln.profile == nil {
		cln.profile = &ble.Profile{Services: svcs}
	}
	return svcs, nil
}
895510
func DiscoverUPnP(ctx context.Context) (*UPnP, error) {
	// Scan the local network for a UPnP-enabled device.
	device, err := upnp.DiscoverCtx(ctx)
	if err != nil {
		return nil, err
	}

	u := &UPnP{
		device:         device,
		forwardedPorts: make(map[uint16]struct{}),
	}

	// We'll then attempt to retrieve the external IP address of this
	// device to ensure it is not behind multiple NATs.
	if _, err := u.ExternalIP(); err != nil {
		return nil, err
	}

	return u, nil
}
481402
func (dp *LocalProvider) CreateLocalDiscoveryService(mspID string) (fab.DiscoveryService, error) {
	peers := []fab.Peer{}
	netPeers := dp.config.NetworkPeers()

	logger.Debugf("Found %d peers", len(netPeers))

	for _, p := range netPeers {
		newPeer, err := dp.fabPvdr.CreatePeerFromConfig(&fab.NetworkPeer{PeerConfig: p.PeerConfig, MSPID: p.MSPID})
		if err != nil {
			return nil, errors.WithMessage(err, "NewPeerFromConfig failed")
		}
		if newPeer.MSPID() == mspID {
			logger.Debugf("Adding local peer [%s] for MSP [%s]", newPeer.URL(), mspID)
			peers = append(peers, newPeer)
		}
	}

	return &localDiscoveryService{config: dp.config, peers: peers}, nil
}
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)
}
922441
func (s *MockDiscoveryServer) Discover(ctx context.Context, request *discovery.SignedRequest) (*discovery.Response, error) {
	if request == nil {
		return nil, errors.New("nil request")
	}

	req := &discovery.Request{}
	err := proto.Unmarshal(request.Payload, req)
	if err != nil {
		return nil, errors.Wrap(err, "failed parsing request")
	}
	if req.Authentication == nil {
		return nil, errors.New("access denied, no authentication info in request")
	}
	if len(req.Authentication.ClientIdentity) == 0 {
		return nil, errors.New("access denied, client identity wasn't supplied")
	}

	var results []*discovery.QueryResult
	for _, q := range req.Queries {
		result := s.processQuery(q)
		if result != nil {
			results = append(results, result)
		}
	}
	return &discovery.Response{
		Results: results,
	}, nil
}
784974
func (d *Disco) DiscoverServiceURL(hostname svchost.Hostname, serviceID string) (*url.URL, error) {
	host, err := d.Discover(hostname)
	if err != nil {
		return nil, err
	}
	return host.ServiceURL(serviceID)
}
79620
func (c *Client) Discover() (NATType, *Host, error) {
	if c.serverAddr == "" {
		c.SetServerAddr(DefaultServerAddr)
	}
	serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr)
	if err != nil {
		return NATError, nil, err
	}
	// Use the connection passed to the client if it is not nil, otherwise
	// create a connection and close it at the end.
	conn := c.conn
	if conn == nil {
		conn, err = net.ListenUDP("udp", nil)
		if err != nil {
			return NATError, nil, err
		}
		defer conn.Close()
	}
	return c.discover(conn, serverUDPAddr)
}
1368788
func (d *MultiDiscovery) HealthCheck(svc *service.Service) (string, string) {
	for _, disco := range d.Discoverers {
		if healthCheck, healthCheckArgs := disco.HealthCheck(svc); healthCheck != "" {
			return healthCheck, healthCheckArgs
		}

	}
	return "", ""
}
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
}
922207
func (cfg *discoveryProcessConfig) NewDiscoveryProcess() *discoveryProcess {
	port := int(atomic.LoadInt32(&discoveryBasePort))
	atomic.AddInt32(&discoveryBasePort, 2)

	copied := *cfg
	copied.webPort = port
	copied.discoveryHost = fmt.Sprintf("http://localhost:%d", copied.webPort)

	return &discoveryProcess{cfg: &copied}
}
910666
func (c *Host) DiscoverdDeregisterJob(id string) error {
	return c.c.Put(fmt.Sprintf("/host/jobs/%s/discoverd-deregister", id), nil, nil)
}