// EnsureDead sets the Life of the space to Dead, if it's Alive. If the space is
// already Dead, no error is returned. When the space is no longer Alive or
// already removed, errNotAlive is returned.
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)
}
1199269
func (a *Authenticator) ensureInitialized() error {
	// Already initialized (successfully or not)?
	if initialized, err := a.checkInitialized(); initialized {
		return err
	}

	// SelectBestMethod may do heavy calls like talking to GCE metadata server,
	// call it lazily here rather than in NewAuthenticator.
	if a.opts.Method == AutoSelectMethod {
		a.opts.Method = SelectBestMethod(a.ctx, *a.opts)
	}

	// In Actor mode, make the base token IAM-scoped, to be able to use SignBlob
	// API. In non-actor mode, the base token is also the main auth token, so
	// scope it to whatever options were requested.
	scopes := a.opts.Scopes
	if a.isActing() {
		scopes = []string{iam.OAuthScope}
	}
	a.baseToken = &tokenWithProvider{}
	a.baseToken.provider, a.err = makeBaseTokenProvider(a.ctx, a.opts, scopes)
	if a.err != nil {
		return a.err // note: this can be ErrInsufficientAccess
	}

	// In non-actor mode, the token we must check in 'CheckLoginRequired' is the
	// same as returned by 'GetAccessToken'. In actor mode, they are different.
	// See comments for 'baseToken' and 'authToken'.
	if a.isActing() {
		a.authToken = &tokenWithProvider{}
		a.authToken.provider, a.err = makeIAMTokenProvider(a.ctx, a.opts)
		if a.err != nil {
			return a.err
		}
	} else {
		a.authToken = a.baseToken
	}

	// Initialize the token cache. Use the disk cache only if SecretsDir is given
	// and any of the providers is not "lightweight" (so it makes sense to
	// actually hit the disk, rather then call the provider each time new token is
	// needed).
	//
	// Note also that tests set a.testingCache before ensureInitialized() is
	// called to mock the cache. Respect this.
	if a.testingCache != nil {
		a.baseToken.cache = a.testingCache
		a.authToken.cache = a.testingCache
	} else {
		cache := internal.ProcTokenCache
		if !a.baseToken.provider.Lightweight() || !a.authToken.provider.Lightweight() {
			if a.opts.SecretsDir != "" {
				cache = &internal.DiskTokenCache{
					Context:    a.ctx,
					SecretsDir: a.opts.SecretsDir,
				}
			} else {
				logging.Warningf(a.ctx, "Disabling auth disk token cache. Not configured.")
			}
		}
		// Use the disk cache only for non-lightweight providers to avoid
		// unnecessarily leaks of tokens to the disk.
		if a.baseToken.provider.Lightweight() {
			a.baseToken.cache = internal.ProcTokenCache
		} else {
			a.baseToken.cache = cache
		}
		if a.authToken.provider.Lightweight() {
			a.authToken.cache = internal.ProcTokenCache
		} else {
			a.authToken.cache = cache
		}
	}

	// Interactive providers need to know whether there's a cached token (to ask
	// to run interactive login if there's none). Non-interactive providers do not
	// care about state of the cache that much (they know how to update it
	// themselves). So examine the cache here only when using interactive
	// provider. Non interactive providers will do it lazily on a first
	// refreshToken(...) call.
	if a.baseToken.provider.RequiresInteraction() {
		// Broken token cache is not a fatal error. So just log it and forget, a new
		// token will be minted in Login.
		if err := a.baseToken.fetchFromCache(a.ctx); err != nil {
			logging.Warningf(a.ctx, "Failed to read auth token from cache: %s", err)
		}
	}

	// Note: a.authToken.provider is either equal to a.baseToken.provider (if not
	// using actor mode), or (when using actor mode) it doesn't require
	// interaction (because it is an IAM one). So don't bother with fetching
	// 'authToken' from cache. It will be fetched lazily on the first use.

	return nil
}
664073
func (b *Bundle) EnsureLoaded(c context.Context) error {
	// Always reload in debug mode. Load only once in non-debug mode.
	if dm := b.DebugMode; dm != nil && dm(c) {
		b.templates, b.err = b.Loader(c, b.FuncMap)
	} else {
		b.once.Do(func() {
			b.templates, b.err = b.Loader(c, b.FuncMap)
		})
	}
	return b.err
}
429558
func EnsureSpelling() error {
	goSpelling := func() error {
		return goSourceApply("misspell", "-error")
	}
	mg.SerialDeps(
		goSpelling,
		EnsureMarkdownSpelling)
	return nil
}
771131
func (c *Conn) CloseRead() error {
	return c.opError(opClose, c.fd.Shutdown(shutRd))
}
679949
func ensureCap(s []byte, n int) []byte {
	if n <= cap(s) {
		return s
	}
	// logic adapted from appendslice1 in runtime
	m := cap(s)
	if m == 0 {
		m = n
	} else {
		for {
			if m < 1024 {
				m += m
			} else {
				m += m / 4
			}
			if m >= n {
				break
			}
		}
	}
	t := make([]byte, len(s), m)
	copy(t, s)
	return t
}
287998
func (c *Cert) ensureDestination() error {
	dir := filepath.Dir(c.Destination())
	fi, err := os.Stat(dir)

	// Path exists but throws an error
	if err != nil && os.IsExist(err) {
		return fmt.Errorf("failed to read at location '%s': %v", dir, err)
	}

	// Path doesn't exist
	if err != nil && os.IsNotExist(err) {
		os.MkdirAll(dir, os.FileMode(0750))
		c.Log.Debugf("Destination directory doesn't exist. Directory created: %s", dir)
		return nil
	}

	// Exists but is not a directory
	if mode := fi.Mode(); !mode.IsDir() {
		return fmt.Errorf("destination '%s' is not a directory", dir)
	}

	if fi.Mode().Perm() != os.FileMode(0750) {
		c.Log.Debugf("Destination directory has incorrect permissons. Changing to 0770: %s", dir)
		c.WritePermissions(dir, os.FileMode(0750))
	}

	c.Log.Debugf("Destination directory exists")

	return nil
}
392997
func (d *Descriptor) HandleRead(h ReadHandler) {
	if d.value != nil {
		panic("descriptor has been configured with a static value")
	}
	d.props |= CharRead
	// d.secure |= CharRead
	d.rhandler = h
}
930395
func ensureDirectory(fs utilfs.Filesystem, path string) error {
	if _, err := fs.Stat(path); err != nil {
		// MkdirAll returns nil if directory already exists.
		return fs.MkdirAll(path, 0755)
	}
	return nil
}
456997
func (m *PoolMetadata) ensureDatabaseInitialized() error {
	return m.db.Update(func(tx *bolt.Tx) error {
		if _, err := tx.CreateBucketIfNotExists(devicesBucketName); err != nil {
			return err
		}

		if _, err := tx.CreateBucketIfNotExists(deviceIDBucketName); err != nil {
			return err
		}

		return nil
	})
}
1275104
func (opts *Options) ensure() error {
	if !opts.Enabled {
		return nil
	}

	if opts.Name == "" {
		opts.Name = config.GetString("name")
	}
	if opts.Name == "" {
		return ErrEmptyName
	}

	//if opts.Reporter.Address == "" {
	//	opts.Reporter.Address = "127.0.0.1"
	//}
	if opts.Reporter.FlushInterval <= 0 {
		opts.Reporter.FlushInterval = 10 * time.Second
	}
	if opts.Reporter.QueueSize <= 0 {
		opts.Reporter.QueueSize = 1000
	}
	return nil
}
959175
func (l *blocksLRU) prepareForAdd() {
	switch {
	case l.ll.Len() > l.capacity:
		panic("impossible")
	case l.ll.Len() == l.capacity:
		oldest := l.ll.Remove(l.ll.Back()).(block)
		delete(l.blocks, oldest.offset)
		l.evicted(oldest)
	}
}
364404
func ensureDir(loc string) error {
	s, err := os.Stat(loc)
	switch {
	case err != nil && os.IsNotExist(err):
		// the location does not exist, so make directories to there
		return os.MkdirAll(loc, DirPerms)
	case err == nil && !s.IsDir():
		return newErrFixtureDirectoryIsFile(loc)
	}

	return err
}
392913
func Ensure(fname string) (err error) {
  if ! checkfile(fname) {
    // does not exist generate file now
    err = Save(fname)
  }
  if err == nil {
    err = Load(fname)
  }
  return
}
1041019
func (s *Store) EnsureNode(idx uint64, node *structs.Node) error {
	tx := s.db.Txn(true)
	defer tx.Abort()

	// Call the node upsert
	if err := s.ensureNodeTxn(tx, idx, node); err != nil {
		return err
	}

	tx.Commit()
	return nil
}
1199109
func (c *ZooKeeperBackend) ensurePath(path string, value []byte) error {
	nodes := strings.Split(path, "/")
	fullPath := ""
	for index, node := range nodes {
		if strings.TrimSpace(node) != "" {
			fullPath += "/" + node
			isLastNode := index+1 == len(nodes)

			// set parent nodes to nil, leaf to value
			// this block reduces round trips by being smart on the leaf create/set
			if exists, _, _ := c.client.Exists(fullPath); !isLastNode && !exists {
				if _, err := c.client.Create(fullPath, nil, int32(0), c.acl); err != nil {
					return err
				}
			} else if isLastNode && !exists {
				if _, err := c.client.Create(fullPath, value, int32(0), c.acl); err != nil {
					return err
				}
			} else if isLastNode && exists {
				if _, err := c.client.Set(fullPath, value, int32(-1)); err != nil {
					return err
				}
			}
		}
	}
	return nil
}
1364787
func EnsureFile(ctx context.Context, fs FileSystem, path string, content io.Reader) error {
	return fs.EnsureFile(ctx, path, func(f *os.File) error {
		_, err := io.Copy(f, content)
		return err
	})
}