// Return the value descriptors that are associated with the device specified by the device ID
// Associated value descripts are expected parameters of PUT commands and expected results of PUT/GET commands
// api/v1/valuedescriptor/deviceid/{id}
960621
func valueDescriptorByDeviceIdHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	vars := mux.Vars(r)

	deviceId, err := url.QueryUnescape(vars["id"])
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		LoggingClient.Error("Error unescaping the device ID: " + err.Error())
		return
	}

	ctx := r.Context()
	// Get the value descriptors
	vdList, err := getValueDescriptorsByDeviceId(deviceId, ctx)
	if err != nil {
		switch err := err.(type) {
		case *types.ErrServiceClient:
			http.Error(w, err.Error(), err.StatusCode)
		case *errors.ErrDbNotFound:
			http.Error(w, err.Error(), http.StatusNotFound)
			return
		default:
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	encode(vdList, w)
}
785769
func (c *Adb) ListDevices() ([]*DeviceInfo, error) {
	resp, err := roundTripSingleResponse(c.server, "host:devices-l")
	if err != nil {
		return nil, wrapClientError(err, c, "ListDevices")
	}

	devices, err := parseDeviceList(string(resp), parseDeviceLong)
	if err != nil {
		return nil, wrapClientError(err, c, "ListDevices")
	}
	return devices, nil
}
922264
func (devices *DeviceSet) List() []string {
	devices.Lock()
	defer devices.Unlock()

	ids := make([]string, len(devices.Devices))
	i := 0
	for k := range devices.Devices {
		ids[i] = k
		i++
	}
	return ids
}
776528
func readingByValueDescriptorAndDeviceHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	vars := mux.Vars(r)
	ctx := r.Context()

	// Get the variables from the URL
	name, err := url.QueryUnescape(vars["name"])
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		LoggingClient.Error("Error unescaping the value descriptor name: " + err.Error())
		return
	}

	device, err := url.QueryUnescape(vars["device"])
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		LoggingClient.Error("Error unescaping the device: " + err.Error())
		return
	}

	limit, err := strconv.Atoi(vars["limit"])
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		LoggingClient.Error("Error converting limit to an integer: " + err.Error())
		return
	}

	err = checkMaxLimit(limit)
	if err != nil {
		http.Error(w, maxExceededString, http.StatusRequestEntityTooLarge)
		return
	}

	// Check device
	if err := checkDevice(device, ctx); err != nil {
		LoggingClient.Error(fmt.Sprintf("error checking device %s %v", device, err))
		switch err := err.(type) {
		case *types.ErrServiceClient:
			http.Error(w, err.Error(), err.StatusCode)
			return
		default: //return an error on everything else.
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	// Check for value descriptor
	if Configuration.Writable.ValidateCheck {
		_, err = getValueDescriptorByName(name)
		if err != nil {
			switch err.(type) {
			case *errors.ErrDbNotFound:
				http.Error(w, "Value descriptor not found for reading", http.StatusConflict)
				return
			default:
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
	}

	readings, err := getReadingsByDeviceAndValueDescriptor(device, name, limit)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	encode(readings, w)
}
745544
func (_m *DBClient) UpdateValueDescriptor(v models.ValueDescriptor) error {
	ret := _m.Called(v)

	var r0 error
	if rf, ok := ret.Get(0).(func(models.ValueDescriptor) error); ok {
		r0 = rf(v)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
601615
func (handler *deviceHandler) FindDevicesForISCSILun(targetIqn string, lun int) ([]string, error) {
	devices := make([]string, 0)
	io := handler.getIo

	// Iterate over all the iSCSI hosts in sysfs
	sysPath := "/sys/class/iscsi_host"
	hostDirs, err := io.ReadDir(sysPath)
	if err != nil {
		return nil, err
	}
	for _, hostDir := range hostDirs {
		// iSCSI hosts are always of the format "host%d"
		// See drivers/scsi/hosts.c in Linux
		hostName := hostDir.Name()
		if !strings.HasPrefix(hostName, "host") {
			continue
		}
		hostNumber, err := strconv.Atoi(strings.TrimPrefix(hostName, "host"))
		if err != nil {
			klog.Errorf("Could not get number from iSCSI host: %s", hostName)
			continue
		}

		// Iterate over the children of the iscsi_host device
		// We are looking for the associated session
		devicePath := sysPath + "/" + hostName + "/device"
		deviceDirs, err := io.ReadDir(devicePath)
		if err != nil {
			return nil, err
		}
		for _, deviceDir := range deviceDirs {
			// Skip over files that aren't the session
			// Sessions are of the format "session%u"
			// See drivers/scsi/scsi_transport_iscsi.c in Linux
			sessionName := deviceDir.Name()
			if !strings.HasPrefix(sessionName, "session") {
				continue
			}

			// Read the target name for the iSCSI session
			targetNamePath := devicePath + "/" + sessionName + "/iscsi_session/" + sessionName + "/targetname"
			targetName, err := io.ReadFile(targetNamePath)
			if err != nil {
				return nil, err
			}

			// Only if the session matches the target we were looking for,
			// add it to the map
			if strings.TrimSpace(string(targetName)) != targetIqn {
				continue
			}

			// The list of block devices on the scsi bus will be in a
			// directory called "target%d:%d:%d".
			// See drivers/scsi/scsi_scan.c in Linux
			// We assume the channel/bus and device/controller are always zero for iSCSI
			targetPath := devicePath + "/" + sessionName + fmt.Sprintf("/target%d:0:0", hostNumber)

			// The block device for a given lun will be "%d:%d:%d:%d" --
			// host:channel:bus:LUN
			blockDevicePath := targetPath + fmt.Sprintf("/%d:0:0:%d", hostNumber, lun)

			// If the LUN doesn't exist on this bus, continue on
			_, err = io.Lstat(blockDevicePath)
			if err != nil {
				continue
			}

			// Read the block directory, there should only be one child --
			// the block device "sd*"
			path := blockDevicePath + "/block"
			dirs, err := io.ReadDir(path)
			if err != nil {
				return nil, err
			}
			if 0 < len(dirs) {
				devices = append(devices, dirs[0].Name())
			}
		}
	}

	return devices, nil
}
1270160
func (ispr iscsiDevicePathResolver) getDevicePaths(devices []string, shouldExist bool) ([]string, error) {
	var paths []string
	for _, device := range devices {
		exist, err := regexp.MatchString("-part1", device)
		if err != nil {
			return paths, bosherr.WrapError(err, "There is a problem with your regexp: '-part1'. That is used to find existing device")
		}
		if exist == shouldExist {
			matchedPath := path.Join("/dev/mapper", strings.Split(strings.Fields(device)[0], "-")[0])
			ispr.logger.Debug(ispr.logTag, "path in device list: '%+v'", matchedPath)
			paths = append(paths, matchedPath)
		}
	}

	return paths, nil
}
535527
func (_m *DBClient) GetAllDevices() ([]models.Device, error) {
	ret := _m.Called()

	var r0 []models.Device
	if rf, ok := ret.Get(0).(func() []models.Device); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]models.Device)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func() error); ok {
		r1 = rf()
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
1231007
func (_m *DBClient) ValueDescriptorsByName(names []string) ([]models.ValueDescriptor, error) {
	ret := _m.Called(names)

	var r0 []models.ValueDescriptor
	if rf, ok := ret.Get(0).(func([]string) []models.ValueDescriptor); ok {
		r0 = rf(names)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]models.ValueDescriptor)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func([]string) error); ok {
		r1 = rf(names)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
614008
func getDevices(pool, block, metadatadev string) (map[int]*DeviceBlockStats, error) {
	cmd := exec.Command("thin_dump", "-f", "xml", metadatadev, "-m", block)
	stdout, err := cmd.StdoutPipe()
	cmd.Stderr = os.Stderr
	if err != nil {
		return nil, err
	}
	if err := cmd.Start(); err != nil {
		return nil, err
	}
	devices, err := parseMetadata(stdout)
	if err != nil {
		return nil, err
	}
	if err := cmd.Wait(); err != nil {
		return nil, err
	}
	return devices, nil
}
574469
func valueDescriptorHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	switch r.Method {
	case http.MethodGet:
		vList, err := getAllValueDescriptors()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// Check the limit
		err = checkMaxLimit(len(vList))
		if err != nil {
			http.Error(w, maxExceededString, http.StatusRequestEntityTooLarge)
			return
		}

		encode(vList, w)
	case http.MethodPost:
		v, err := decodeValueDescriptor(r.Body)
		if err != nil {
			switch err.(type) {
			case *errors.ErrJsonDecoding:
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			case *errors.ErrValueDescriptorInvalid:
				http.Error(w, err.Error(), http.StatusConflict)
				return
			default:
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		id, err := addValueDescriptor(v)
		if err != nil {
			switch err.(type) {
			case *errors.ErrValueDescriptorInUse:
				http.Error(w, err.Error(), http.StatusConflict)
				return
			case *errors.ErrDuplicateValueDescriptorName:
				http.Error(w, err.Error(), http.StatusConflict)
				return
			default:
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		w.WriteHeader(http.StatusOK)
		w.Write([]byte(id))
	case http.MethodPut:
		vd, err := decodeValueDescriptor(r.Body)
		if err != nil {
			switch err.(type) {
			case *errors.ErrJsonDecoding:
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			case *errors.ErrValueDescriptorInvalid:
				http.Error(w, err.Error(), http.StatusConflict)
				return
			default:
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		err = updateValueDescriptor(vd)
		if err != nil {
			switch err.(type) {
			case *errors.ErrDbNotFound:
				http.Error(w, err.Error(), http.StatusNotFound)
				return
			case *errors.ErrValueDescriptorInvalid:
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			case *errors.ErrValueDescriptorInUse:
				http.Error(w, "Data integrity issue. Value Descriptor still in use by readings", http.StatusConflict)
				return
			default:
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("true"))
	}
}
487973
func NewDeviceAllocator(lastIndex int) DeviceAllocator {
	possibleDevices := []mountDevice{}
	for _, firstChar := range []rune{'b', 'c'} {
		for i := 'a'; i <= 'z'; i++ {
			dev := mountDevice([]rune{firstChar, i})
			possibleDevices = append(possibleDevices, dev)
		}
	}
	return &deviceAllocator{
		possibleDevices: possibleDevices,
		lastIndex:       lastIndex,
	}
}
97816
func getEphemeralDevices(
	ctx types.Context) (deviceNames []string, err error) {

	buf, err := BlockDevices(ctx)
	if err != nil {
		return nil, err
	}

	// Filter list of all block devices for ephemeral devices
	scanner := bufio.NewScanner(bytes.NewReader(buf))
	scanner.Split(bufio.ScanWords)

	for scanner.Scan() {
		word := scanner.Bytes()
		if !ephemDevRX.Match(word) {
			continue
		}

		name, err := BlockDeviceName(ctx, string(word))
		if err != nil {
			return nil, goof.WithError(
				"ec2 block device mapping lookup failed", err)
		}

		// compensate for kernel volume mapping i.e. change "/dev/sda" to
		// "/dev/xvda"
		deviceNameStr := strings.Replace(
			string(name),
			"sd",
			NextDeviceInfo.Prefix, 1)

		deviceNames = append(deviceNames, deviceNameStr)
	}
	return deviceNames, nil
}
866930
func (mc MongoClient) ValueDescriptorById(id string) (contract.ValueDescriptor, error) {
	query, err := idToBsonM(id)
	if err != nil {
		return contract.ValueDescriptor{}, err
	}

	mvd, err := mc.getValueDescriptor(query)
	if err != nil {
		return contract.ValueDescriptor{}, err
	}
	return mvd.ToContract(), nil
}
1243039
func mapDevices(devices []protocol.DeviceID) map[protocol.DeviceID]struct{} {
	m := make(map[protocol.DeviceID]struct{}, len(devices))
	for _, dev := range devices {
		m[dev] = struct{}{}
	}
	return m
}
330998
func (_m *DBClient) ReadingsByDeviceAndValueDescriptor(deviceId string, valueDescriptor string, limit int) ([]models.Reading, error) {
	ret := _m.Called(deviceId, valueDescriptor, limit)

	var r0 []models.Reading
	if rf, ok := ret.Get(0).(func(string, string, int) []models.Reading); ok {
		r0 = rf(deviceId, valueDescriptor, limit)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]models.Reading)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string, string, int) error); ok {
		r1 = rf(deviceId, valueDescriptor, limit)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
691359
func (c *Client) ValueDescriptorsByName(names []string) (values []contract.ValueDescriptor, err error) {
	conn := c.Pool.Get()
	defer conn.Close()

	for _, name := range names {
		value, err := valueByName(conn, name)
		if err != nil && err != redis.ErrNil {
			return nil, err
		}

		if err == nil {
			values = append(values, value)
		}
	}

	return values, nil
}