// NewDatastore creates a new badger datastore.
//
// DO NOT set the Dir and/or ValuePath fields of opt, they will be set for you.
512600
func NewDatastore(path string, options *Options) (*Datastore, error) {
	// Copy the options because we modify them.
	var opt badger.Options
	var gcDiscardRatio float64
	if options == nil {
		opt = badger.DefaultOptions
		gcDiscardRatio = DefaultOptions.gcDiscardRatio
	} else {
		opt = options.Options
		gcDiscardRatio = options.gcDiscardRatio
	}

	opt.Dir = path
	opt.ValueDir = path
	opt.Logger = log

	kv, err := badger.Open(opt)
	if err != nil {
		if strings.HasPrefix(err.Error(), "manifest has unsupported version:") {
			err = fmt.Errorf("unsupported badger version, use github.com/ipfs/badgerds-upgrade to upgrade: %s", err.Error())
		}
		return nil, err
	}

	return &Datastore{
		DB:             kv,
		closing:        make(chan struct{}),
		gcDiscardRatio: gcDiscardRatio,
	}, nil
}
957973
func NewLocalStore(filename string) *LocalStore {
	store := &LocalStore{filename: filename, SaveDataChan: make(chan *StoredData)}
	store.listenSaveAction()
	return store
}
885880
func NewDator(name string) Dator {
	return &DefaultDator{
		Buffer: bytes.NewBuffer(nil),
		name:   name,
	}
}
663905
func (s *sessionV8) NewDataReader() io.Reader {
	// DataFP is always intitialized, either via new or load functions.
	s.DataFP.Seek(0, os.SEEK_SET)
	return io.Reader(s.DataFP)
}
875554
func NewFileStore(baseDir, fileExt string) (*FilesystemStore, error) {
	baseDir = filepath.Clean(baseDir)
	if err := createDirectory(baseDir, notary.PrivExecPerms); err != nil {
		return nil, err
	}
	if !strings.HasPrefix(fileExt, ".") {
		fileExt = "." + fileExt
	}

	return &FilesystemStore{
		baseDir: baseDir,
		ext:     fileExt,
	}, nil
}
387534
func NewStore(filepath string) (*Store, error) {
	kv := &Store{filename: filepath, db: make(map[string]interface{})}
	return kv, kv.loadAndMergeIfNeeded()
}
187930
func (dc *Datacenter) GetDatastoreByName(ctx context.Context, name string) (*Datastore, error) {
	finder := getFinder(dc)
	ds, err := finder.Datastore(ctx, name)
	if err != nil {
		klog.Errorf("Failed while searching for datastore: %s. err: %+v", name, err)
		return nil, err
	}
	datastore := Datastore{ds, dc}
	return &datastore, nil
}
765484
func New(db *bolt.DB, rootBucket string, opts ...Option) (*Store, error) {
	if db.IsReadOnly() {
		return nil, ErrDBReadOnly
	}
	bucket := []byte(rootBucket)

	err := db.Update(func(tx *bolt.Tx) error {
		// create root
		root, err := tx.CreateBucketIfNotExists(bucket)
		if err != nil {
			return err
		}
		// create the buckets inside the root
		for _, b := range [][]byte{
			tasksPath, orgsPath, taskMetaPath,
			orgByTaskID, nameByTaskID, runIDs,
		} {
			_, err := root.CreateBucketIfNotExists(b)
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	st := &Store{db: db, bucket: bucket, idGen: snowflake.NewDefaultIDGenerator(), minLatestCompleted: math.MinInt64}
	for _, opt := range opts {
		opt(st)
	}
	return st, nil
}
798590
func NewDatastoreManagementService(opts ...ManagementOption) DatastoreManagementService {
	s := &datastoreManagementService{
		QueueName:             "exec-rm-old-datastore-backups",
		ExpireAfter:           30 * 24 * time.Hour,
		APIDeleteBackupsURL:   "/api/datastore-management/delete-old-backups",
		DeleteOldBackupURL:    "/tq/datastore-management/delete-old-backups",
		DeleteUnitOfBackupURL: "/tq/datastore-management/delete-backup",
	}

	for _, opt := range opts {
		opt.implements(s)
	}

	return s
}
589402
func NewEventStore() *EventStore {
	s := &EventStore{
		db: map[string]map[uuid.UUID]aggregateRecord{},
	}
	return s
}
811996
func New(dir string) *Store {
	if d, err := filepath.EvalSymlinks(dir); err == nil {
		dir = d
	}
	return &Store{
		path: dir,
	}
}
805082
func NewPostgresDataStore(routeType string, pgx *pgx.ConnPool) *pgDataStore {
	tableName := ""
	switch routeType {
	case routeTypeHTTP:
		tableName = tableNameHTTP
	case routeTypeTCP:
		tableName = tableNameTCP
	default:
		panic(fmt.Sprintf("unknown routeType: %q", routeType))
	}
	return &pgDataStore{
		pgx:       pgx,
		routeType: routeType,
		tableName: tableName,
	}
}
278935
func recommendDatastore(
	ctx context.Context,
	vmObj *vclib.VirtualMachine,
	storagePod *object.StoragePod,
	spec *types.VirtualMachineConfigSpec) (*object.Datastore, error) {
	sp := storagePod.Reference()

	// Build pod selection spec from config spec
	podSelectionSpec := types.StorageDrsPodSelectionSpec{
		StoragePod: &sp,
	}

	for _, deviceConfigSpec := range spec.DeviceChange {
		s := deviceConfigSpec.GetVirtualDeviceConfigSpec()
		if s.Operation != types.VirtualDeviceConfigSpecOperationAdd {
			continue
		}

		if s.FileOperation != types.VirtualDeviceConfigSpecFileOperationCreate {
			continue
		}

		d, ok := s.Device.(*types.VirtualDisk)
		if !ok {
			continue
		}

		podConfigForPlacement := types.VmPodConfigForPlacement{
			StoragePod: sp,
			Disk: []types.PodDiskLocator{
				{
					DiskId:          d.Key,
					DiskBackingInfo: d.Backing,
				},
			},
		}

		podSelectionSpec.InitialVmConfig = append(podSelectionSpec.InitialVmConfig, podConfigForPlacement)
	}

	resourcePool, err := vmObj.ResourcePool(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to get vm resource pool due to: %v", err)
	}

	if resourcePool == nil {
		return nil, fmt.Errorf("failed to get vm resource pool")
	}

	resourcePoolRef := resourcePool.Reference()

	sps := types.StoragePlacementSpec{
		Type:             string(types.StoragePlacementSpecPlacementTypeCreate),
		PodSelectionSpec: podSelectionSpec,
		ConfigSpec:       spec,
		ResourcePool:     &resourcePoolRef,
	}

	srm := object.NewStorageResourceManager(vmObj.Client())
	result, err := srm.RecommendDatastores(ctx, sps)
	if err != nil {
		logrus.Errorf("failed to get datastore recommendations due to: %v", err)
		return nil, err
	}

	// Use result to pin disks to recommended datastores
	recs := result.Recommendations
	if len(recs) == 0 {
		return nil, fmt.Errorf("no datastores recommendations")
	}

	ds := recs[0].Action[0].(*types.StoragePlacementAction).Destination

	var mds mo.Datastore
	err = property.DefaultCollector(vmObj.Client()).RetrieveOne(ctx, ds, []string{"name"}, &mds)
	if err != nil {
		return nil, err
	}

	datastore := object.NewDatastore(vmObj.Client(), ds)
	datastore.InventoryPath = mds.Name

	return datastore, nil
}
1059331
func NewMemStore(params *StoreParams, _ *LDBStore) (m *MemStore) {
	if params.CacheCapacity == 0 {
		return &MemStore{
			disabled: true,
		}
	}

	c, err := lru.New(int(params.CacheCapacity))
	if err != nil {
		panic(err)
	}

	return &MemStore{
		cache: c,
	}
}
447818
func NewKVStore(path string) *KVStore {
	return &KVStore{
		path:   path,
		logger: zap.NewNop(),
	}
}
1210490
func dataStores() (blobserver.Storage, sorted.KeyValue, error) {
	dataDir := os.Getenv("CAMLI_GCE_DATA")
	if dataDir == "" {
		var err error
		dataDir, err = ioutil.TempDir("", "camli-gcedeployer-data")
		if err != nil {
			return nil, nil, err
		}
		log.Printf("data dir not provided as env var CAMLI_GCE_DATA, so defaulting to %v", dataDir)
	}
	blobsDir := filepath.Join(dataDir, "instance-conf")
	if err := os.MkdirAll(blobsDir, 0700); err != nil {
		return nil, nil, err
	}
	instConf, err := localdisk.New(blobsDir)
	if err != nil {
		return nil, nil, err
	}
	instState, err := leveldb.NewStorage(filepath.Join(dataDir, "instance-state"))
	if err != nil {
		return nil, nil, err
	}
	return instConf, instState, nil
}
1320548
func NewDatabase(path string) (Database, error) {
	storage, err := util.NewFileStorage(path)
	if err != nil {
		return nil, err
	}

	return NewDatabaseWithStorage(storage), nil
}