// EnsureDirExist ...
193975
func EnsureDirExist(dir string) error {
	exist, err := IsDirExists(dir)
	if !exist || err != nil {
		return os.MkdirAll(dir, 0777)
	}
	return nil
}
209224
func (e *Env) ensure(c context.Context, blocking bool) (err error) {
	// Fastest path: If this environment is already complete, then there is no
	// additional setup necessary.
	if err := e.AssertCompleteAndLoad(); err == nil {
		logging.Debugf(c, "Environment is already initialized: %s", e.Environment)
		return nil
	}

	// Repeatedly try and create our Env. We do this so that if we
	// encounter a lock, we will let the other process finish and try and leverage
	// its success.
	for {
		// We will be creating the Env. Acquire an exclusive lock so that any other
		// processes will wait for our setup to complete.
		switch lock, err := e.acquireExclusiveLock(); err {
		case nil:
			// We MUST successfully release our exclusive lock on completion.
			return mustReleaseLock(c, lock, func() error {
				// Fast path: if our complete flag is present, assume that the
				// environment is setup and complete. No additional work is necessary.
				err := e.AssertCompleteAndLoad()
				if err == nil {
					// This will generally happen if another process created the environment
					// in between when we checked for the completion stamp initially and
					// when we actually obtained the lock.
					logging.Debugf(c, "Completion flag found! Environment is set-up: %s", e.completeFlagPath)
					return nil
				}
				logging.WithError(err).Debugf(c, "VirtualEnv is not complete.")

				// No complete flag. Create a new VirtualEnv here.
				if err := e.createLocked(c); err != nil {
					return errors.Annotate(err, "failed to create new VirtualEnv").Err()
				}

				// Mark that this environment is complete. This MUST succeed so other
				// instances know that this environment is complete.
				if err := e.touchCompleteFlagLocked(); err != nil {
					return errors.Annotate(err, "failed to create complete flag").Err()
				}

				logging.Debugf(c, "Successfully created new virtual environment [%s]!", e.Name)
				return nil
			})

		case fslock.ErrLockHeld:
			// We couldn't get an exclusive lock. Try again to load the environment
			// stamp, asserting the existence of the completion flag in the process.
			// If another process has created the environment, we may be able to use
			// it without ever having to obtain its lock!
			if err := e.AssertCompleteAndLoad(); err == nil {
				logging.Infof(c, "Environment was completed while waiting for lock: %s", e.EnvironmentStampPath)
				return nil
			}

			logging.Fields{
				logging.ErrorKey: err,
				"path":           e.EnvironmentStampPath,
			}.Debugf(c, "Lock is held, and environment is not complete.")
			if !blocking {
				return errors.Annotate(err, "VirtualEnv lock is currently held (non-blocking)").Err()
			}

			// Some other process holds the lock. Sleep a little and retry.
			if err := blocker(c)(); err != nil {
				return err
			}

		default:
			return errors.Annotate(err, "failed to ensure VirtualEnv").Err()
		}
	}
}
1345071
func (rs *Resource) EnsureInstance(key addrs.InstanceKey) *ResourceInstance {
	ret := rs.Instance(key)
	if ret == nil {
		ret = NewResourceInstance()
		rs.Instances[key] = ret
	}
	return ret
}
629585
func (d *Downloader) ensureDir(dir string) error {
	dir = normalizePathSeparator(dir)
	// Fast path: if the cache has the directory, we're done.
	d.muCache.RLock()
	cached := d.dirCache.Has(dir)
	d.muCache.RUnlock()
	if cached {
		return nil
	}

	// Slow path: collect the directory and its parents, then create
	// them and add them to the cache.
	d.muCache.Lock()
	defer d.muCache.Unlock()
	parents := make([]string, 0, 1)
	for i := dir; i != "" && !d.dirCache.Has(i); i = filepath.Dir(i) {
		if i == d.outputDir {
			break
		}
		parents = append(parents, i)
	}
	for i := len(parents) - 1; i >= 0; i-- {
		if err := os.Mkdir(parents[i], os.ModePerm); err != nil && !os.IsExist(err) {
			return err
		}
		d.dirCache.Add(parents[i])
	}
	return nil
}
763302
func (s *Space) EnsureDead() (err error) {
	defer errors.DeferredAnnotatef(&err, "cannot set space %q to dead", s)

	if s.doc.Life == Dead {
		return nil
	}

	ops := []txn.Op{{
		C:      spacesC,
		Id:     s.doc.Name,
		Update: bson.D{{"$set", bson.D{{"life", Dead}}}},
		Assert: isAliveDoc,
	}}

	txnErr := s.st.db().RunTransaction(ops)
	if txnErr == nil {
		s.doc.Life = Dead
		return nil
	}
	return onAbort(txnErr, spaceNotAliveErr)
}
1306047
func ensureSuperuser(cf func(cmd *cobra.Command, args []string)) func(cmd *cobra.Command, args []string) {
	return func(cmd *cobra.Command, args []string) {
		if os.Geteuid() != 0 {
			stderr.Print("cannot run as unprivileged user")
			cmdExitCode = 254
			return
		}

		cf(cmd, args)
	}
}
683499
func ensureMtabExists(rootfs string) error {
	stat, err := os.Stat(filepath.Join(rootfs, "etc"))
	if os.IsNotExist(err) {
		// If your image has no /etc you don't get /etc/mtab either
		return nil
	}
	if err != nil {
		return errwrap.Wrap(errors.New("error determining if /etc existed in the image"), err)
	}
	if !stat.IsDir() {
		return nil
	}
	mtabPath := filepath.Join(rootfs, "etc", "mtab")
	if _, err = os.Lstat(mtabPath); err == nil {
		// If the image already has an mtab, don't replace it
		return nil
	}
	if !os.IsNotExist(err) {
		return errwrap.Wrap(errors.New("error determining if /etc/mtab exists in the image"), err)
	}

	target := "../proc/self/mounts"
	err = os.Symlink(target, mtabPath)
	if err != nil {
		return errwrap.Wrap(errors.New("error creating mtab symlink"), err)
	}
	return nil
}
565791
func EnsureErr(w Errer) error {
	err := w.Err()
	if err == nil {
		return errors.Errorf("expected an error from %v, got nil", w)
	} else if err == tomb.ErrStillAlive {
		return errors.Annotatef(err, "expected %v to be stopped", w)
	}
	return errors.Trace(err)
}
1263549
func (st *State) EnsureDead(tags []names.Tag) ([]params.ErrorResult, error) {
	var results params.ErrorResults
	args := params.Entities{
		Entities: make([]params.Entity, len(tags)),
	}
	for i, tag := range tags {
		args.Entities[i].Tag = tag.String()
	}
	if err := st.facade.FacadeCall("EnsureDead", args, &results); err != nil {
		return nil, err
	}
	if len(results.Results) != len(tags) {
		return nil, errors.Errorf("expected %d result(s), got %d", len(tags), len(results.Results))
	}
	return results.Results, nil
}
641078
func (c *V1) EnsureInit() error {
	c.initOnce.Do(c.init)
	return c.aclCheckerInitErr
}
434900
func ensureDirectories(home helmpath.Home, out io.Writer) error {
	configDirectories := []string{
		home.String(),
		home.Repository(),
		home.Cache(),
		home.LocalRepository(),
		home.Plugins(),
		home.Starters(),
		home.Archive(),
	}
	for _, p := range configDirectories {
		if fi, err := os.Stat(p); err != nil {
			fmt.Fprintf(out, "Creating %s \n", p)
			if err := os.MkdirAll(p, 0755); err != nil {
				return fmt.Errorf("Could not create %s: %s", p, err)
			}
		} else if !fi.IsDir() {
			return fmt.Errorf("%s must be a directory", p)
		}
	}

	return nil
}
869561
func ensureInt(x interface{}) int {
	res, ok := x.(int)
	if !ok {
		res = int(x.(float64))
	}
	return res
}
534189
func (sam *SAM) EnsureKeyfile(fname string) (keys I2PKeys, err error) {
	if fname == "" {
		// transient
		keys, err = sam.NewKeys()
		if err == nil {
			sam.keys = &keys
		}
	} else {
		// persistant
		_, err = os.Stat(fname)
		if os.IsNotExist(err) {
			// make the keys
			keys, err = sam.NewKeys()
			if err == nil {
				sam.keys = &keys
				// save keys
				var f io.WriteCloser
				f, err = os.OpenFile(fname, os.O_WRONLY|os.O_CREATE, 0600)
				if err == nil {
					err = StoreKeysIncompat(keys, f)
					f.Close()
				}
			}
		} else if err == nil {
			// we haz key file
			var f *os.File
			f, err = os.Open(fname)
			if err == nil {
				keys, err = LoadKeysIncompat(f)
				if err == nil {
					sam.keys = &keys
				}
			}
		}
	}
	return
}
528313
func (p *MemPostings) EnsureOrder() {
	p.mtx.Lock()
	defer p.mtx.Unlock()

	if p.ordered {
		return
	}

	n := runtime.GOMAXPROCS(0)
	workc := make(chan []uint64)

	var wg sync.WaitGroup
	wg.Add(n)

	for i := 0; i < n; i++ {
		go func() {
			for l := range workc {
				sort.Slice(l, func(i, j int) bool { return l[i] < l[j] })
			}
			wg.Done()
		}()
	}

	for _, e := range p.m {
		for _, l := range e {
			workc <- l
		}
	}
	close(workc)
	wg.Wait()

	p.ordered = true
}
1230543
func EnsureConstraints(im IndexManager, indexes map[string]string) error {
	for label, propertyName := range indexes {
		err := ensureConstraint(im, label, propertyName)
		if err != nil { // stop as soon as something goes wrong
			return err
		}
	}
	return nil
}
770445
func EnsureDockerInContainer(dockerAPIVersion *utilversion.Version, oomScoreAdj int, manager *fs.Manager) error {
	type process struct{ name, file string }
	dockerProcs := []process{{dockerProcessName, dockerPidFile}}
	if dockerAPIVersion.AtLeast(containerdAPIVersion) {
		dockerProcs = append(dockerProcs, process{containerdProcessName, containerdPidFile})
	}
	var errs []error
	for _, proc := range dockerProcs {
		pids, err := getPidsForProcess(proc.name, proc.file)
		if err != nil {
			errs = append(errs, fmt.Errorf("failed to get pids for %q: %v", proc.name, err))
			continue
		}

		// Move if the pid is not already in the desired container.
		for _, pid := range pids {
			if err := ensureProcessInContainerWithOOMScore(pid, oomScoreAdj, manager); err != nil {
				errs = append(errs, fmt.Errorf("errors moving %q pid: %v", proc.name, err))
			}
		}
	}
	return utilerrors.NewAggregate(errs)
}
317741
func (k *Kubernetes) EnsureDryRun() (bool, error) {
	d := &DryRun{
		new(multierror.Error),
	}

	if len(k.initTokens) == 0 {
		k.initTokens = k.NewInitTokens()
	}

	if d.changeNeeded(k.ensureDryRunMaxLeaseTTL()) {
		return true, d.ErrorOrNil()
	}

	for _, b := range k.backends() {
		if d.changeNeeded(b.EnsureDryRun()) {
			return true, d.ErrorOrNil()
		}
	}

	if d.changeNeeded(k.ensureDryRunPKIRolesEtcd(k.etcdKubernetesBackend)) {
		return true, d.ErrorOrNil()
	}

	if d.changeNeeded(k.ensureDryRunPKIRolesEtcd(k.etcdOverlayBackend)) {
		return true, d.ErrorOrNil()
	}

	if d.changeNeeded(k.ensureDryRunPKIRolesK8S(k.kubernetesBackend)) {
		return true, d.ErrorOrNil()
	}

	if d.changeNeeded(k.ensureDryRunPKIRolesK8SAPIProxy(k.kubernetesAPIProxyBackend)) {
		return true, d.ErrorOrNil()
	}

	if d.changeNeeded(k.ensureDryRunPolicies()) {
		return true, d.ErrorOrNil()
	}

	if d.changeNeeded(k.ensureDryRunInitTokens()) {
		return true, d.ErrorOrNil()
	}

	return false, d.ErrorOrNil()
}