// discover implements the actual discovery process, with its result cached
// by the public-facing Discover method.
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
}
498149
func (m *MockApiExtensionsClientInterface) Discovery() discovery.DiscoveryInterface {
	ret := m.ctrl.Call(m, "Discovery")
	ret0, _ := ret[0].(discovery.DiscoveryInterface)
	return ret0
}
819204
func Discover(machineInfo *cadvisorapi.MachineInfo) (*CPUTopology, error) {
	if machineInfo.NumCores == 0 {
		return nil, fmt.Errorf("could not detect number of cpus")
	}

	CPUDetails := CPUDetails{}
	numPhysicalCores := 0

	for _, socket := range machineInfo.Topology {
		numPhysicalCores += len(socket.Cores)
		for _, core := range socket.Cores {
			if coreID, err := getUniqueCoreID(core.Threads); err == nil {
				for _, cpu := range core.Threads {
					CPUDetails[cpu] = CPUInfo{
						CoreID:   coreID,
						SocketID: socket.Id,
					}
				}
			} else {
				klog.Errorf("could not get unique coreID for socket: %d core %d threads: %v",
					socket.Id, core.Id, core.Threads)
				return nil, err
			}
		}
	}

	return &CPUTopology{
		NumCPUs:    machineInfo.NumCores,
		NumSockets: len(machineInfo.Topology),
		NumCores:   numPhysicalCores,
		CPUDetails: CPUDetails,
	}, nil
}
83752
func (p *Profile) Find(target interface{}) interface{} {
	switch target.(type) {
	case *Service:
	case *Characteristic:
	case *Descriptor:
	default:
		return nil
	}
	for _, s := range p.Services {
		ts, ok := target.(*Service)
		if ok && s.UUID.Equal(ts.UUID) {
			target = s
			return s
		}
		for _, c := range s.Characteristics {
			tc, ok := target.(*Characteristic)
			if ok && c.UUID.Equal(tc.UUID) {
				return c
			}
			for _, d := range c.Descriptors {
				td, ok := target.(*Descriptor)
				if ok && d.UUID.Equal(td.UUID) {
					return d
				}
			}
		}
	}
	return nil
}
927683
func (builder *Builder) Find(q grimoire.Query) (string, []interface{}) {
	qs, args := builder.query(q)
	return builder.fields(q.AsDistinct, q.Fields...) + qs, args
}
954093
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
	if c == nil {
		return nil
	}
	return c.DiscoveryClient
}
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}
}
333610
func (c *Cluster) discover() {
	// Keep retrying with exponential backoff.
	b := backoff.NewExponentialBackOff()
	// Never finish retrying (max interval is still 60s)
	b.MaxElapsedTime = 0

	// Keep trying to discover new nodes
	for {
		backoff.RetryNotify(func() error {
			// If no hosts try seeding nodes
			if len(c.GetNodes()) == 0 {
				c.connectNodes(c.getSeeds())
			}

			return c.listenForNodeChanges()
		}, b, func(err error, wait time.Duration) {
			Log.Debugf("Error discovering hosts %s, waiting: %s", err, wait)
		})
	}
}
1291693
func GetDiscovery(ctx ttnlog.Interface) (*grpc.ClientConn, discovery.DiscoveryClient) {
	path := path.Join(GetDataDir(), "/ca.cert")
	cert, err := ioutil.ReadFile(path)
	if err == nil && !pool.RootCAs.AppendCertsFromPEM(cert) {
		ctx.Warnf("Could not add root certificates from %s", path)
	}

	conn, err := api.Dial(viper.GetString("discovery-address"))
	if err != nil {
		ctx.WithError(err).Fatal("Could not connect to Discovery server")
	}
	return conn, discovery.NewDiscoveryClient(conn)
}
833623
func (c *Connection) Find(model interface{}, id interface{}) error {
	return Q(c).Find(model, id)
}
371492
func (b *Remote) discover(serviceID string) (*url.URL, *disco.Constraints, error) {
	hostname, err := svchost.ForComparison(b.hostname)
	if err != nil {
		return nil, nil, err
	}

	host, err := b.services.Discover(hostname)
	if err != nil {
		return nil, nil, err
	}

	service, err := host.ServiceURL(serviceID)
	// Return the error, unless its a disco.ErrVersionNotSupported error.
	if _, ok := err.(*disco.ErrVersionNotSupported); !ok && err != nil {
		return nil, nil, err
	}

	// We purposefully ignore the error and return the previous error, as
	// checking for version constraints is considered optional.
	constraints, _ := host.VersionConstraints(serviceID, "terraform")

	return service, constraints, err
}
396453
func (e *MirrorSecrets) Find(c *fi.Context) (*MirrorSecrets, error) {
	if vfsSecretStore, ok := c.SecretStore.(*secrets.VFSSecretStore); ok {
		if vfsSecretStore.VFSPath().Path() == e.MirrorPath.Path() {
			return e, nil
		}
	}

	// TODO: implement Find so that we aren't always mirroring
	glog.V(2).Infof("MirrorSecrets::Find not implemented; always copying (inefficient)")
	return nil, nil
}
962414
func (c *APICache) Find(verb, uri string) (bool, interface{}) {
	root, ok := c.methodRoots[verb]
	if !ok {
		return false, nil
	}
	return search(root, uri)
}
776832
func (f *Finder) Find(
	ctx context.Context, ipath ...string) ([]FindResult, error) {

	if len(ipath) == 0 {
		ipath = []string{""}
	}
	var result []FindResult
	for _, p := range ipath {
		results, err := f.find(ctx, p)
		if err != nil {
			return nil, err
		}
		result = append(result, results...)
	}
	return result, nil
}
679018
func (orc *orcClient) Discover(tablet *topodatapb.Tablet) error {
	host, port, err := mysqlHostPort(tablet)
	if err != nil {
		return err
	}
	_, err = orc.apiGet("discover", host, port)
	return err
}
1298466
func ExploreObject(t reflect.Value, path []string) *Result {
	if ret := checkConsts(t); ret != nil {
		return ret
	}
	ret := &Result{}
	switch t.Kind() {
	case reflect.Bool:
		ret.Desc = fmt.Sprintf("%t", t.Bool())
		return ret
	case reflect.String:
		ret.Desc = t.String()
		return ret
	}
	c := map[reflect.Kind](func(reflect.Value, []string) *Result){
		reflect.Array:     exploreArray,
		reflect.Func:      exploreFunc,
		reflect.Slice:     exploreSlice,
		reflect.Map:       exploreMap,
		reflect.Struct:    exploreStruct,
		reflect.Chan:      exploreChan,
		reflect.Ptr:       explorePtr,
		reflect.Interface: exploreInterface,
	}
	callback, exists := c[t.Kind()]
	if exists {
		return callback(t, path)
	}
	ret.Desc = "<Unsupported>"
	return ret
}
1373439
func (e *Archive) Find(c *fi.Context) (*Archive, error) {
	// We write a marker file to prevent re-execution
	localStateFile := path.Join(localArchiveStateDir, e.Name)
	stateBytes, err := ioutil.ReadFile(localStateFile)
	if err != nil {
		if os.IsNotExist(err) {
			stateBytes = nil
		} else {
			glog.Warningf("error reading archive state %s: %v", localStateFile, err)
			// We can just reinstall
			return nil, nil
		}
	}

	if stateBytes == nil {
		// No marker file found, assume archive not installed
		return nil, nil
	}

	state := &Archive{}
	if err := json.Unmarshal(stateBytes, state); err != nil {
		glog.Warningf("error unmarshaling archive state %s: %v", localStateFile, err)
		// We can just reinstall
		return nil, nil
	}

	if state.Hash == e.Hash && state.TargetDir == e.TargetDir {
		return state, nil
	}

	// Existing version is different, force a reinstall
	return nil, nil
}