// Search /sys/bus for rbd device that matches given pool and image.
965080
func getRbdDevFromImageAndPool(pool string, image string) (string, bool) {
	// /sys/bus/rbd/devices/X/name and /sys/bus/rbd/devices/X/pool
	sys_path := "/sys/bus/rbd/devices"
	if dirs, err := ioutil.ReadDir(sys_path); err == nil {
		for _, f := range dirs {
			// Pool and name format:
			// see rbd_pool_show() and rbd_name_show() at
			// https://github.com/torvalds/linux/blob/master/drivers/block/rbd.c
			name := f.Name()
			// First match pool, then match name.
			poolFile := filepath.Join(sys_path, name, "pool")
			poolBytes, err := ioutil.ReadFile(poolFile)
			if err != nil {
				klog.V(4).Infof("error reading %s: %v", poolFile, err)
				continue
			}
			if strings.TrimSpace(string(poolBytes)) != pool {
				klog.V(4).Infof("device %s is not %q: %q", name, pool, string(poolBytes))
				continue
			}
			imgFile := filepath.Join(sys_path, name, "name")
			imgBytes, err := ioutil.ReadFile(imgFile)
			if err != nil {
				klog.V(4).Infof("error reading %s: %v", imgFile, err)
				continue
			}
			if strings.TrimSpace(string(imgBytes)) != image {
				klog.V(4).Infof("device %s is not %q: %q", name, image, string(imgBytes))
				continue
			}
			// Found a match, check if device exists.
			devicePath := "/dev/rbd" + name
			if _, err := os.Lstat(devicePath); err == nil {
				return devicePath, true
			}
		}
	}
	return "", false
}
288200
func (bs Binaries) Find(id int) *Binary {
	for i := range bs {
		if bs[i].ID == id {
			return &bs[i]
		}
	}
	return nil
}
501011
func (_class SRClass) GetPBDs(sessionID SessionRef, self SRRef) (_retval []PBDRef, _err error) {
	_method := "SR.get_PBDs"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertSRRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertPBDRefSetToGo(_method + " -> ", _result.Value)
	return
}
1146012
func (idx *MemoryIndex) FindCRC32(h plumbing.Hash) (uint32, error) {
	k := idx.FanoutMapping[h[0]]
	i, ok := idx.findHashIndex(h)
	if !ok {
		return 0, plumbing.ErrObjectNotFound
	}

	return idx.getCRC32(k, i), nil
}
444817
func (s *spiConfig) GetBusOrDefault(d int) int {
	if s.bus == NotInitialized {
		return d
	}
	return s.bus
}
1073090
func (c *Client) FindStoragePoolsForMigration(p *FindStoragePoolsForMigrationParameter) (*StoragePool, error) {
	obj, err := c.Request("findStoragePoolsForMigration", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*StoragePool), err
}
649206
func InitBus(busType string, config interface{}) error {
	switch busType {
	case "NATS":
		// Start NATS
		bus = new(NATS)
	case "OSLO":
		// Start an OSLO producer
		log.Fatal("OSLO message bus producer is not yet implemented.")
	case "RABBITMQ":
		// Start a RabbitMQ producer
		bus = new(RabbitMQ)
	default:
		log.Fatal("No bus type was specified for the producer that we recognize.")
	}
	bus.InitBus(config)
	return nil
}
1222860
func (c *Connect) FindStoragePoolSources(pooltype string, srcSpec string, flags uint32) (string, error) {
	cpooltype := C.CString(pooltype)
	defer C.free(unsafe.Pointer(cpooltype))
	var csrcSpec *C.char
	if srcSpec != "" {
		csrcSpec := C.CString(srcSpec)
		defer C.free(unsafe.Pointer(csrcSpec))
	}
	var err C.virError
	ret := C.virConnectFindStoragePoolSourcesWrapper(c.ptr, cpooltype, csrcSpec, C.uint(flags), &err)
	if ret == nil {
		return "", makeError(&err)
	}

	defer C.free(unsafe.Pointer(ret))

	return C.GoString(ret), nil
}
1164746
func DevLinkGetDeviceByName(Bus string, Device string) (*DevlinkDevice, error) {
	return pkgHandle.DevLinkGetDeviceByName(Bus, Device)
}
1009531
func (_class PoolClass) GetAll(sessionID SessionRef) (_retval []PoolRef, _err error) {
	_method := "pool.get_all"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg)
	if _err != nil {
		return
	}
	_retval, _err = convertPoolRefSetToGo(_method + " -> ", _result.Value)
	return
}
323905
func (u *RBDUtil) rbdStatus(image string, pOpts *rbdProvisionOptions) (bool, error) {
	var err error
	var output string
	var cmd []byte

	mon := u.kernelRBDMonitorsOpt(pOpts.monitors)
	// cmd "rbd status" list the rbd client watch with the following output:
	//
	// # there is a watcher (exit=0)
	// Watchers:
	//   watcher=10.16.153.105:0/710245699 client.14163 cookie=1
	//
	// # there is no watcher (exit=0)
	// Watchers: none
	//
	// Otherwise, exit is non-zero, for example:
	//
	// # image does not exist (exit=2)
	// rbd: error opening image kubernetes-dynamic-pvc-<UUID>: (2) No such file or directory
	//
	klog.V(4).Infof("rbd: status %s using mon %s, pool %s id %s key %s", image, mon, pOpts.pool, pOpts.adminID, pOpts.adminSecret)
	args := []string{"status", image, "--pool", pOpts.pool, "-m", mon, "--id", pOpts.adminID, "--key=" + pOpts.adminSecret}
	cmd, err = u.execCommand("rbd", args)
	output = string(cmd)

	// If command never succeed, returns its last error.
	if err != nil {
		return false, err
	}

	if strings.Contains(output, imageWatcherStr) {
		klog.V(4).Infof("rbd: watchers on %s: %s", image, output)
		return true, nil
	}
	klog.Warningf("rbd: no watchers on %s", image)
	return false, nil
}
660471
func RBDRemove(
	ctx types.Context,
	pool *string,
	image *string) error {

	cmd := exec.Command(rbdCmd, "rm", poolOpt, *pool, "--no-progress",
		*image,
	)
	_, _, err := RunCommand(ctx, cmd)
	if err != nil {
		return goof.WithError("unable to delete rbd", err)
	}
	return nil
}
42290
func (d *dockerAPI) findImage(name string) (*types.Image, error) {
	glog.V(4).Infof("docker query for image %q", name)
	options := types.ImageListOptions{
		MatchName: name,
	}
	ctx := context.Background()
	images, err := d.client.ImageList(ctx, options)
	if err != nil {
		return nil, fmt.Errorf("error listing images: %v", err)
	}
	for i := range images {
		for _, repoTag := range images[i].RepoTags {
			if repoTag == name {
				return &images[i], nil
			}
		}
	}
	return nil, nil
}
327740
func (prv *ProcessorProvider) Get(params imageserver.Params) (image.Image, error) {
	nim, err := prv.Provider.Get(params)
	if err != nil {
		return nil, err
	}
	nim, err = prv.Processor.Process(nim, params)
	if err != nil {
		return nil, err
	}
	return nim, nil
}
695989
func (_class PoolClass) GetMetadataVDIs(sessionID SessionRef, self PoolRef) (_retval []VDIRef, _err error) {
	_method := "pool.get_metadata_VDIs"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertPoolRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertVDIRefSetToGo(_method + " -> ", _result.Value)
	return
}
790756
func (util *RBDUtil) AttachDisk(b rbdMounter) (string, error) {
	var output []byte

	globalPDPath := util.MakeGlobalPDName(*b.rbd)
	if pathExists, pathErr := mount.PathExists(globalPDPath); pathErr != nil {
		return "", fmt.Errorf("Error checking if path exists: %v", pathErr)
	} else if !pathExists {
		if err := os.MkdirAll(globalPDPath, 0750); err != nil {
			return "", err
		}
	}

	// Evalute whether this device was mapped with rbd.
	devicePath, mapped := waitForPath(b.Pool, b.Image, 1 /*maxRetries*/, false /*useNbdDriver*/)

	// If rbd-nbd tools are found, we will fallback to it should the default krbd driver fail.
	nbdToolsFound := false

	if !mapped {
		nbdToolsFound = checkRbdNbdTools(b.exec)
		if nbdToolsFound {
			devicePath, mapped = waitForPath(b.Pool, b.Image, 1 /*maxRetries*/, true /*useNbdDriver*/)
		}
	}

	if !mapped {
		// Currently, we don't acquire advisory lock on image, but for backward
		// compatibility, we need to check if the image is being used by nodes running old kubelet.
		// osd_client_watch_timeout defaults to 30 seconds, if the watcher stays active longer than 30 seconds,
		// rbd image does not get mounted and failure message gets generated.
		backoff := wait.Backoff{
			Duration: rbdImageWatcherInitDelay,
			Factor:   rbdImageWatcherFactor,
			Steps:    rbdImageWatcherSteps,
		}
		needValidUsed := true
		if b.accessModes != nil {
			// If accessModes only contains ReadOnlyMany, we don't need check rbd status of being used.
			if len(b.accessModes) == 1 && b.accessModes[0] == v1.ReadOnlyMany {
				needValidUsed = false
			}
		}
		// If accessModes is nil, the volume is referenced by in-line volume.
		// We can assume the AccessModes to be {"RWO" and "ROX"}, which is what the volume plugin supports.
		// We do not need to consider ReadOnly here, because it is used for VolumeMounts.

		if needValidUsed {
			err := wait.ExponentialBackoff(backoff, func() (bool, error) {
				used, rbdOutput, err := util.rbdStatus(&b)
				if err != nil {
					return false, fmt.Errorf("fail to check rbd image status with: (%v), rbd output: (%s)", err, rbdOutput)
				}
				return !used, nil
			})
			// Return error if rbd image has not become available for the specified timeout.
			if err == wait.ErrWaitTimeout {
				return "", fmt.Errorf("rbd image %s/%s is still being used", b.Pool, b.Image)
			}
			// Return error if any other errors were encountered during waiting for the image to become available.
			if err != nil {
				return "", err
			}
		}

		mon := util.kernelRBDMonitorsOpt(b.Mon)
		klog.V(1).Infof("rbd: map mon %s", mon)

		_, err := b.exec.Run("modprobe", "rbd")
		if err != nil {
			klog.Warningf("rbd: failed to load rbd kernel module:%v", err)
		}
		output, err = execRbdMap(b, "rbd", mon)
		if err != nil {
			if !nbdToolsFound {
				klog.V(1).Infof("rbd: map error %v, rbd output: %s", err, string(output))
				return "", fmt.Errorf("rbd: map failed %v, rbd output: %s", err, string(output))
			}
			klog.V(3).Infof("rbd: map failed with %v, %s. Retrying with rbd-nbd", err, string(output))
			errList := []error{err}
			outputList := output
			output, err = execRbdMap(b, "rbd-nbd", mon)
			if err != nil {
				errList = append(errList, err)
				outputList = append(outputList, output...)
				return "", fmt.Errorf("rbd: map failed %v, rbd output: %s", errors.NewAggregate(errList), string(outputList))
			}
			devicePath, mapped = waitForPath(b.Pool, b.Image, 10 /*maxRetries*/, true /*useNbdDrive*/)
		} else {
			devicePath, mapped = waitForPath(b.Pool, b.Image, 10 /*maxRetries*/, false /*useNbdDriver*/)
		}
		if !mapped {
			return "", fmt.Errorf("Could not map image %s/%s, Timeout after 10s", b.Pool, b.Image)
		}
	}
	return devicePath, nil
}
684648
func (r ImageStreamSearcher) Search(precise bool, terms ...string) (ComponentMatches, []error) {
	componentMatches := ComponentMatches{}
	var errs []error
	for _, term := range terms {
		var (
			ref imageapi.DockerImageReference
			err error
		)
		switch term {
		case "__imagestream_fail":
			errs = append(errs, fmt.Errorf("unable to find the specified image: %s", term))
			continue
		case "*":
			ref = imageapi.DockerImageReference{Name: term}
		default:
			ref, err = imageapi.ParseDockerImageReference(term)
			if err != nil || len(ref.Registry) != 0 {
				klog.V(2).Infof("image streams must be of the form [<namespace>/]<name>[:<tag>|@<digest>], term %q did not qualify", term)
				continue
			}
		}

		namespaces := r.Namespaces
		if len(ref.Namespace) != 0 {
			namespaces = []string{ref.Namespace}
		}
		followTag := false
		searchTag := ref.Tag
		if len(searchTag) == 0 {
			searchTag = imageapi.DefaultImageTag
			followTag = true
		}
		for _, namespace := range namespaces {
			klog.V(4).Infof("checking ImageStreams %s/%s with ref %q", namespace, ref.Name, searchTag)
			exact := false
			streams, err := r.Client.ImageStreams(namespace).List(metav1.ListOptions{})
			if err != nil {
				if errors.IsNotFound(err) || errors.IsForbidden(err) {
					continue
				}
				errs = append(errs, err)
				continue
			}
			original := ref
			ref.Namespace = namespace
			for i := range streams.Items {
				stream := &streams.Items[i]
				score, scored := imageStreamScorer(*stream, ref.Name)
				if !scored {
					klog.V(2).Infof("unscored %s: %v", stream.Name, score)
					continue
				}

				// indicate the server knows how to directly import image stream tags
				var meta map[string]string
				if stream.Generation > 0 {
					meta = map[string]string{"direct-tag": "1"}
				}

				imageref := original
				imageref.Name = stream.Name
				imageref.Registry = ""
				matchName := fmt.Sprintf("%s/%s", stream.Namespace, stream.Name)

				addMatch := func(tag string, matchScore float32, image *dockerv10.DockerImage, notFound bool) {
					name := matchName
					var description, argument string
					if len(tag) > 0 {
						name = fmt.Sprintf("%s:%s", name, tag)
						argument = fmt.Sprintf("--image-stream=%q", name)
						description = fmt.Sprintf("Image stream %q (tag %q) in project %q", stream.Name, tag, stream.Namespace)
					} else {
						argument = fmt.Sprintf("--image-stream=%q --allow-missing-imagestream-tags", name)
						description = fmt.Sprintf("Image stream %q in project %q", stream.Name, stream.Namespace)
					}

					match := &ComponentMatch{
						Value:       term,
						Argument:    argument,
						Name:        name,
						Description: description,
						Score:       matchScore,
						ImageStream: stream,
						DockerImage: image,
						ImageTag:    tag,
						Meta:        meta,
						NoTagsFound: notFound,
					}
					klog.V(2).Infof("Adding %s as component match for %q with score %v", match.Description, term, matchScore)
					componentMatches = append(componentMatches, match)
				}

				// When the user has not provided a tag themselves (i.e. they asked for
				// mysql and we defaulted to mysql:latest), and "latest" references
				// another local tag, and neither tag is hidden, use the referenced tag
				// instead of "latest".  This ensures that applications can default to
				// using a "stable" branch by giving the control over version to the
				// image stream author.
				finalTag := searchTag
				var specTag *imagev1.TagReference
				if t, hasTag := imageutil.SpecHasTag(stream, searchTag); hasTag {
					specTag = &t
				}

				if specTag != nil && followTag && !imageutil.HasAnnotationTag(specTag, imageapi.TagReferenceAnnotationTagHidden) {
					if specTag.From != nil && specTag.From.Kind == "ImageStreamTag" && !strings.Contains(specTag.From.Name, ":") {
						if t, hasTag := imageutil.SpecHasTag(stream, specTag.From.Name); hasTag && !imageutil.HasAnnotationTag(&t, imageapi.TagReferenceAnnotationTagHidden) {
							if imageutil.LatestTaggedImage(stream, specTag.From.Name) != nil {
								finalTag = specTag.From.Name
							}
						}
					}
				}

				latest := imageutil.LatestTaggedImage(stream, finalTag)

				// Special case in addition to the other tag not found cases: if no tag
				// was specified, and "latest" is hidden, then behave as if "latest"
				// doesn't exist (in this case, to get to "latest", the user must hard
				// specify tag "latest").
				if (specTag != nil && followTag && imageutil.HasAnnotationTag(specTag, imageapi.TagReferenceAnnotationTagHidden)) ||
					latest == nil || len(latest.Image) == 0 {

					klog.V(2).Infof("no image recorded for %s/%s:%s", stream.Namespace, stream.Name, finalTag)
					if r.AllowMissingTags {
						addMatch(finalTag, score, nil, false)
						continue
					}
					// Find tags that do exist and return those as partial matches
					foundOtherTags := false
					for _, tag := range stream.Status.Tags {
						latest := imageutil.LatestTaggedImage(stream, tag.Tag)
						if latest == nil || len(latest.Image) == 0 {
							continue
						}
						foundOtherTags = true

						// We check the "hidden" tags annotation /after/ setting
						// foundOtherTags = true.  The ordering matters in the case that all
						// the tags on the imagestream are hidden.  In this case, in new-app
						// we should behave as the imagestream didn't exist at all.  This
						// means not calling addMatch("", ..., nil, true) below.
						t, hasTag := imageutil.SpecHasTag(stream, tag.Tag)
						if hasTag && imageutil.HasAnnotationTag(&t, imageapi.TagReferenceAnnotationTagHidden) {
							continue
						}

						// at best this is a partial match situation.  The user didn't
						// specify a tag, so we tried "latest" but could not find an image associated
						// with the latest tag (or one that is followed by the latest tag), or
						// they specified a tag that we could not find.
						tagScore := score + 0.5
						addMatch(tag.Tag, tagScore, nil, false)
					}
					if !foundOtherTags {
						addMatch("", 0.5+score, nil, true)
					}
					continue
				}

				imageStreamImage, err := r.Client.ImageStreamImages(namespace).Get(imageapi.JoinImageStreamImage(stream.Name, latest.Image), metav1.GetOptions{})
				if err != nil {
					if errors.IsNotFound(err) {
						// continue searching
						klog.V(2).Infof("tag %q is set, but image %q has been removed", finalTag, latest.Image)
						continue
					}
					errs = append(errs, err)
					continue
				}

				if err := imageutil.ImageWithMetadata(&imageStreamImage.Image); err != nil {
					errs = append(errs, err)
					continue
				}

				dockerImage, ok := imageStreamImage.Image.DockerImageMetadata.Object.(*dockerv10.DockerImage)
				if !ok {
					continue
				}

				addMatch(finalTag, score, dockerImage, false)
				if score == 0.0 {
					exact = true
				}
			}

			// If we found one or more exact matches in this namespace, do not continue looking at
			// other namespaces
			if exact && precise {
				break
			}
		}
	}
	return componentMatches, errs
}