// Mounted determines if a specified mountpoint has been mounted.
// On Linux it looks at /proc/self/mountinfo.
480891
func Mounted(mountpoint string) (bool, error) {
	entries, err := GetMounts(SingleEntryFilter(mountpoint))
	if err != nil {
		return false, err
	}

	return len(entries) > 0, nil
}
1214856
func isShared(mount string, mountInfoPath string) (bool, error) {
	info, err := findMountInfo(mount, mountInfoPath)
	if err != nil {
		return false, err
	}

	// parse optional parameters
	for _, opt := range info.optionalFields {
		if strings.HasPrefix(opt, "shared:") {
			return true, nil
		}
	}
	return false, nil
}
755720
func Mount(driver Driver, remotePath, localPath string) error {
	// check if the driver is installed
	if err := driver.Installed(); err != nil {
		return err
	}

	// validate that the remote path
	if ok := func(remotePath string) bool {
		parts := strings.Split(remotePath, ":")
		if len(parts) != 2 {
			return false
		}

		ip := net.ParseIP(parts[0])
		if ip == nil {
			return false
		}

		dest := filepath.Clean(parts[1])
		return dest != "/" && filepath.IsAbs(dest)
	}(remotePath); !ok {
		return ErrMalformedNFSMountpoint
	}

	var mountInfo proc.NFSMountInfo
	mountError := driver.Info(localPath, &mountInfo)

	needsReMount := false

	if mountError == nil {
		// we need to check for a stale NFS mount
		if staleNFSCheck(localPath) {
			glog.Infof("Detected stale NFS mount, re-mounting %s", localPath)
			//unmount and re-mount
			needsReMount = true
			if err := driver.Unmount(localPath); err != nil {
				glog.Errorf("Error while unmounting %s: %s", localPath, err)
				return err
			}

		}
	}

	if mountError == proc.ErrMountPointNotFound || needsReMount {
		// the mountpoint is not found so try to mount
		glog.Infof("Creating new mount for %s -> %s", remotePath, localPath)
		if err := os.MkdirAll(localPath, 0775); err != nil {
			return err
		}
		if err := driver.Mount(remotePath, localPath, time.Second*30); err != nil {
			glog.Errorf("Error while creating mount point for %s -> %s: %s", remotePath, localPath, err)
			return err
		}

		// get the mount point
		mountError = driver.Info(localPath, &mountInfo)
	}

	if mountError != nil {
		// we should have a mount point by now or bust
		glog.Errorf("Could not get volume info for %s (mounting from %s): %s", localPath, remotePath, mountError)
		return mountError
	}

	// validate mount info
	glog.Infof("Mount Info: %+v", mountInfo)
	verr := validation.NewValidationError()
	verr.Add(validation.StringsEqual(remotePath, mountInfo.RemotePath, ""))
	verr.Add(validation.StringsEqual("nfs4", mountInfo.FSType, fmt.Sprintf("%s not mounted nfs4, %s instead", mountInfo.LocalPath, mountInfo.FSType)))

	if verr.HasError() {
		// the mountpoint is stale or wrong, so unmount
		glog.Warningf("Stale mount point at %s (mounting %s)", localPath, remotePath)
		if err := driver.Unmount(localPath); err != nil {
			glog.Errorf("Could not unmount %s: %s", localPath, err)
		}
		return verr
	}

	return nil
}
981289
func (m *DefaultMounter) Mount(
	source string,
	target string,
	fstype string,
	flags uintptr,
	data string,
	timeout int,
) error {
	return syscall.Mount(source, target, fstype, flags, data)
}
752565
func (m *Mounter) Mount(
	minor int,
	devPath, path, fs string,
	flags uintptr,
	data string,
	timeout int,
	opts map[string]string,
) error {
	// device gets overwritten if opts specifies fuse mount with
	// options.OptionsDeviceFuseMount.
	device := devPath
	if value, ok := opts[options.OptionsDeviceFuseMount]; ok {
		// fuse mounts show-up with this key as device.
		device = value
	}

	path = normalizeMountPath(path)
	if len(m.allowedDirs) > 0 {
		foundPrefix := false
		for _, allowedDir := range m.allowedDirs {
			if strings.Contains(path, allowedDir) {
				foundPrefix = true
				break
			}
		}
		if !foundPrefix {
			return ErrMountpathNotAllowed
		}
	}
	dev, ok := m.HasTarget(path)
	if ok && dev != device {
		logrus.Warnf("cannot mount %q,  device %q is mounted at %q", device, dev, path)
		return ErrExist
	}
	m.Lock()
	info, ok := m.mounts[device]
	if !ok {
		info = &Info{
			Device:     device,
			Mountpoint: make([]*PathInfo, 0),
			Minor:      minor,
			Fs:         fs,
		}
	}
	m.mounts[device] = info
	m.Unlock()
	info.Lock()
	defer info.Unlock()

	// Validate input params
	// FS check is not needed if it is a bind mount
	if !strings.HasPrefix(info.Fs, fs) && (flags&syscall.MS_BIND) != syscall.MS_BIND {
		logrus.Warnf("%s Existing mountpoint has fs %q cannot change to %q",
			device, info.Fs, fs)
		return ErrEinval
	}

	// Try to find the mountpoint. If it already exists, do nothing
	for _, p := range info.Mountpoint {
		if p.Path == path {
			logrus.Warnf("%q mountpoint for device %q already exists",
				device, path)
			return nil
		}
	}

	h := m.kl.Acquire(path)
	defer m.kl.Release(&h)

	// Record previous state of the path
	pathWasReadOnly := m.isPathSetImmutable(path)
	var (
		isBindMounted bool = false
		bindMountPath string
	)

	if err := m.makeMountpathReadOnly(path); err != nil {
		if strings.Contains(err.Error(), "Inappropriate ioctl for device") {
			logrus.Warnf("failed to make %s readonly. Err: %v", path, err)
			// If we cannot chattr the original mount path, we bind mount it to
			// a path in osd mount path and then chattr it
			if bindMountPath, err = m.bindMountOriginalPath(path); err != nil {
				return err
			}
			isBindMounted = true
		} else {
			return fmt.Errorf("failed to make %s readonly. Err: %v", path, err)
		}
	}

	// The device is not mounted at path, mount it and add to its mountpoints.
	if err := m.mountImpl.Mount(devPath, path, fs, flags, data, timeout); err != nil {
		// Rollback only if was writeable
		if !pathWasReadOnly {
			if e := m.makeMountpathWriteable(path); e != nil {
				return fmt.Errorf("failed to make %v writeable during rollback. Err: %v Mount err: %v",
					path, e, err)
			}
			if isBindMounted {
				if cleanupErr := m.cleanupBindMount(path, bindMountPath, err); cleanupErr != nil {
					return cleanupErr
				}
			}
		}

		return err
	}

	info.Mountpoint = append(info.Mountpoint, &PathInfo{Path: path})

	return nil
}
1369741
func (m *execMounter) Mount(source string, target string, fstype string, options []string) error {
	bind, bindOpts, bindRemountOpts := mount.IsBind(options)

	if bind {
		err := m.doExecMount(source, target, fstype, bindOpts)
		if err != nil {
			return err
		}
		return m.doExecMount(source, target, fstype, bindRemountOpts)
	}

	return m.doExecMount(source, target, fstype, options)
}
30592
func IsMounted(dir string, log Log) (bool, error) {
	return false, fmt.Errorf("IsMounted unsupported on this platform")
}
145488
func mount(pendingMounts ...Mounter) {
	for _, mounter := range pendingMounts {
		if mounter == nil {
			continue
		}
		if c, ok := mounter.(Component); ok {
			if c.Context().mounted {
				continue
			}
			c.Context().mounted = true
			c.Context().unmounted = false
		}
		mounter.Mount()
	}
}
1022237
func (c *Core) persistMounts(ctx context.Context, table *MountTable, local *bool) error {
	if table.Type != mountTableType {
		c.logger.Error("given table to persist has wrong type", "actual_type", table.Type, "expected_type", mountTableType)
		return fmt.Errorf("invalid table type given, not persisting")
	}

	for _, entry := range table.Entries {
		if entry.Table != table.Type {
			c.logger.Error("given entry to persist in mount table has wrong table value", "path", entry.Path, "entry_table_type", entry.Table, "actual_type", table.Type)
			return fmt.Errorf("invalid mount entry found, not persisting")
		}
	}

	nonLocalMounts := &MountTable{
		Type: mountTableType,
	}

	localMounts := &MountTable{
		Type: mountTableType,
	}

	for _, entry := range table.Entries {
		if entry.Local {
			localMounts.Entries = append(localMounts.Entries, entry)
		} else {
			nonLocalMounts.Entries = append(nonLocalMounts.Entries, entry)
		}
	}

	writeTable := func(mt *MountTable, path string) error {
		// Encode the mount table into JSON and compress it (lzw).
		compressedBytes, err := jsonutil.EncodeJSONAndCompress(mt, nil)
		if err != nil {
			c.logger.Error("failed to encode or compress mount table", "error", err)
			return err
		}

		// Create an entry
		entry := &logical.StorageEntry{
			Key:   path,
			Value: compressedBytes,
		}

		// Write to the physical backend
		if err := c.barrier.Put(ctx, entry); err != nil {
			c.logger.Error("failed to persist mount table", "error", err)
			return err
		}
		return nil
	}

	var err error
	switch {
	case local == nil:
		// Write non-local mounts
		err := writeTable(nonLocalMounts, coreMountConfigPath)
		if err != nil {
			return err
		}

		// Write local mounts
		err = writeTable(localMounts, coreLocalMountConfigPath)
		if err != nil {
			return err
		}
	case *local:
		// Write local mounts
		err = writeTable(localMounts, coreLocalMountConfigPath)
	default:
		// Write non-local mounts
		err = writeTable(nonLocalMounts, coreMountConfigPath)
	}

	return err
}
248172
func Mounted(mountpoint string) (bool, error) {
	var mntpointSt unix.Stat_t
	if err := unix.Stat(mountpoint, &mntpointSt); err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, err
	}
	var parentSt unix.Stat_t
	if err := unix.Stat(filepath.Join(mountpoint, ".."), &parentSt); err != nil {
		return false, err
	}
	return mntpointSt.Dev != parentSt.Dev, nil
}
56150
func (s *VolumeServer) Mount(
	ctx context.Context,
	req *api.SdkVolumeMountRequest,
) (*api.SdkVolumeMountResponse, error) {

	if s.cluster() == nil || s.driver(ctx) == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}

	if len(req.GetVolumeId()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Must supply volume id")
	}
	if len(req.GetMountPath()) == 0 {
		return nil, status.Error(codes.InvalidArgument, "Invalid Mount Path")
	}

	// Get access rights
	err := s.checkAccessForVolumeId(ctx, req.GetVolumeId(), api.Ownership_Write)
	if err != nil {
		return nil, err
	}

	err = s.driver(ctx).Mount(req.GetVolumeId(), req.GetMountPath(), req.GetDriverOptions())
	if err != nil {
		return nil, status.Errorf(
			codes.Internal,
			"Failed to mount volume %s: %v",
			req.GetVolumeId(),
			err.Error())
	}
	return &api.SdkVolumeMountResponse{}, err
}
681034
func doMount(source string, target string, fstype string, options []string) error {
	glog.V(5).Infof("Mounting %s %s %s %v", source, target, fstype, options)
	mountArgs := makeMountArgs(source, target, fstype, options)
	command := exec.Command("mount", mountArgs...)
	output, err := command.CombinedOutput()
	if err != nil {
		return fmt.Errorf("Mount failed: %v\nMounting arguments: %s %s %s %v\nOutput: %s\n",
			err, source, target, fstype, options, string(output))
	}
	return err
}
377301
func IsMounted(dir string, log Log) (bool, error) {
	mountInfo, err := getMountInfo(dir)
	if err != nil {
		return false, err
	}

	log.Debug("Mount info: %s", mountInfo)
	if strings.Contains(mountInfo, "@kbfuse") {
		return true, nil
	}

	return false, nil
}
789912
func (d *driver) Unmount(
	ctx types.Context,
	mountPoint string,
	opts types.Store) error {

	if !gotil.FileExists(mountPoint) {
		return os.ErrNotExist
	}
	return os.RemoveAll(mountPoint)
}
1085943
func (d *driver) Mount(volumeID string, mountpath string, options map[string]string) error {
	v, err := d.GetVol(volumeID)
	if err != nil {
		logrus.Println(err)
		return err
	}
	if len(v.AttachPath) > 0 && len(v.AttachPath) > 0 {
		return fmt.Errorf("Volume %q already mounted at %q", volumeID, v.AttachPath[0])
	}
	syscall.Unmount(mountpath, 0)
	if err := syscall.Mount(
		filepath.Join(volume.VolumeBase, string(volumeID)),
		mountpath,
		string(v.Spec.Format),
		syscall.MS_BIND, "",
	); err != nil {
		logrus.Printf("Cannot mount %s at %s because %+v",
			filepath.Join(volume.VolumeBase, string(volumeID)),
			mountpath,
			err,
		)
		return err
	}
	if v.AttachPath == nil {
		v.AttachPath = make([]string, 1)
	}
	v.AttachPath[0] = mountpath
	return d.UpdateVol(v)
}
567261
func (mounter *Mounter) IsLikelyNotMountPoint(file string) (bool, error) {
	stat, err := os.Lstat(file)
	if err != nil {
		return true, err
	}
	// If current file is a symlink, then it is a mountpoint.
	if stat.Mode()&os.ModeSymlink != 0 {
		target, err := os.Readlink(file)
		if err != nil {
			return true, fmt.Errorf("readlink error: %v", err)
		}
		exists, err := mounter.ExistsPath(target)
		if err != nil {
			return true, err
		}
		return !exists, nil
	}

	return true, nil
}
393279
func (m *LinuxMount) ListAll() (mounts []MountInfo, err error) {
	fh, err := os.Open(m.ProcMount)
	if err != nil {
		return nil, err
	}
	defer fh.Close()
	reader := bufio.NewReader(fh)
	for {
		line, err := reader.ReadString('\n')
		if line = strings.TrimSpace(line); line != "" {
			var fields []string
			if fields = strings.Fields(line); len(fields) != 6 {
				return nil, ErrParseMount
			}
			mount := MountInfo{}
			mount.Device = fields[0]
			mount.MountPoint = fields[1]
			mount.FSType = fields[2]
			mount.Options = strings.Split(fields[3], ",")
			if mount.Dump, err = strconv.Atoi(fields[4]); err != nil {
				return nil, ErrParseMount
			}
			if mount.Fsck, err = strconv.Atoi(fields[5]); err != nil {
				return nil, ErrParseMount
			}
			mounts = append(mounts, mount)
		}
		if err == io.EOF {
			return mounts, nil
		} else if err != nil {
			return nil, err
		}
	}
}