// OpenMongoDB open MongoDB connections in the context's default
16943
func OpenMongoDB(ctx context.Context) context.Context {
	uri, dbName := getHerokuMongoURI()
	databaseName = dbName

	sesh, err := mgo.Dial(uri)
	if err != nil {
		panic(err)
	}
	ctx = context.WithValue(ctx, mongodb(mongoDBName), sesh)
	return ctx
}
742561
func openDB(driver, config string) *sql.DB {
	db, err := sql.Open(driver, config)
	if err != nil {
		log.Fatalln("database connection failed:", err)
	}
	if driver == "mysql" {
		// per issue https://github.com/go-sql-driver/mysql/issues/257
		db.SetMaxIdleConns(0)
	}
	if err := pingDatabase(db); err != nil {
		log.Fatalln("database ping attempts failed:", err)
	}
	return db
}
194520
func Open(args OpenParams) (*State, error) {
	if err := args.Validate(); err != nil {
		return nil, errors.Annotate(err, "validating args")
	}
	session := args.MongoSession.Copy()
	st, err := open(
		args.ControllerModelTag,
		session,
		args.InitDatabaseFunc,
		nil,
		args.NewPolicy,
		args.Clock,
		args.RunTransactionObserver,
	)
	if err != nil {
		session.Close()
		return nil, errors.Trace(err)
	}
	if _, err := st.Model(); err != nil {
		if err := st.Close(); err != nil {
			logger.Errorf("closing State for %s: %v", args.ControllerModelTag, err)
		}
		return nil, mongo.MaybeUnauthorizedf(err, "cannot read model %s", args.ControllerModelTag.Id())
	}

	// State should only be Opened on behalf of a controller environ; all
	// other *States must be obtained via StatePool.
	if err := st.start(args.ControllerTag, nil); err != nil {
		return nil, errors.Trace(err)
	}
	return st, nil
}
1180538
func (m *SchemaDb) Open(schemaObjectName string) (schema.Conn, error) {

	tbl, err := m.Table(schemaObjectName)
	if err == nil && tbl != nil {

		switch schemaObjectName {
		case "session_variables", "global_variables":
			return &SchemaSource{db: m, tbl: tbl, session: true}, nil
		case "engines", "procedures", "functions", "indexes":
			return &SchemaSource{db: m, tbl: tbl, rows: nil}, nil
		default:
			return &SchemaSource{db: m, tbl: tbl, rows: tbl.AsRows()}, nil
		}

	}
	return nil, schema.ErrNotFound
}
382386
func (c *Client) OpenIndex(name string) *IndicesOpenService {
	return NewIndicesOpenService(c).Index(name)
}
400882
func openGeoDB() (*geoDB, error) {
	// Initiate a geoip database to cross reference locations
	db, err := freegeoip.OpenURL(freegeoip.MaxMindDB, 24*time.Hour, time.Hour)
	if err != nil {
		return nil, err
	}
	// Wait until the database is updated to the latest data
	select {
	case <-db.NotifyOpen():
	case err := <-db.NotifyError():
		return nil, err
	}
	// Assemble and return our custom wrapper
	return &geoDB{geodb: db}, nil
}
362902
func Open(path string, mode os.FileMode, options *Options) (*DB, error) {
	var db = &DB{opened: true}

	// Set default options if no options are provided.
	if options == nil {
		options = DefaultOptions
	}
	db.NoGrowSync = options.NoGrowSync
	db.MmapFlags = options.MmapFlags

	// Set default values for later DB operations.
	db.MaxBatchSize = DefaultMaxBatchSize
	db.MaxBatchDelay = DefaultMaxBatchDelay
	db.AllocSize = DefaultAllocSize

	flag := os.O_RDWR
	if options.ReadOnly {
		flag = os.O_RDONLY
		db.readOnly = true
	}

	// Open data file and separate sync handler for metadata writes.
	db.path = path
	var err error
	if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil {
		_ = db.close()
		return nil, err
	}

	// Lock file so that other processes using Bolt in read-write mode cannot
	// use the database  at the same time. This would cause corruption since
	// the two processes would write meta pages and free pages separately.
	// The database file is locked exclusively (only one process can grab the lock)
	// if !options.ReadOnly.
	// The database file is locked using the shared lock (more than one process may
	// hold a lock at the same time) otherwise (options.ReadOnly is set).
	if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil {
		_ = db.close()
		return nil, err
	}

	// Default values for test hooks
	db.ops.writeAt = db.file.WriteAt

	// Initialize the database if it doesn't exist.
	if info, err := db.file.Stat(); err != nil {
		return nil, err
	} else if info.Size() == 0 {
		// Initialize new files with meta pages.
		if err := db.init(); err != nil {
			return nil, err
		}
	} else {
		// Read the first meta page to determine the page size.
		var buf [0x1000]byte
		if _, err := db.file.ReadAt(buf[:], 0); err == nil {
			m := db.pageInBuffer(buf[:], 0).meta()
			if err := m.validate(); err != nil {
				// If we can't read the page size, we can assume it's the same
				// as the OS -- since that's how the page size was chosen in the
				// first place.
				//
				// If the first page is invalid and this OS uses a different
				// page size than what the database was created with then we
				// are out of luck and cannot access the database.
				db.pageSize = os.Getpagesize()
			} else {
				db.pageSize = int(m.pageSize)
			}
		}
	}

	// Initialize page pool.
	db.pagePool = sync.Pool{
		New: func() interface{} {
			return make([]byte, db.pageSize)
		},
	}

	// Memory map the data file.
	if err := db.mmap(options.InitialMmapSize); err != nil {
		_ = db.close()
		return nil, err
	}

	// Read in the freelist.
	db.freelist = newFreelist()
	db.freelist.read(db.page(db.meta().freelist))

	// Mark the database as opened and return.
	return db, nil
}
308422
func (c *configInternal) MongoInfo() (info *mongo.MongoInfo, ok bool) {
	ssi, ok := c.StateServingInfo()
	if !ok {
		return nil, false
	}
	// We return localhost first and then all addresses of known API
	// endpoints - this lets us connect to other Mongo instances and start
	// state even if our own Mongo has not started yet (see lp:1749383 #1).
	// TODO(macgreagoir) IPv6. Ubuntu still always provides IPv4 loopback,
	// and when/if this changes localhost should resolve to IPv6 loopback
	// in any case (lp:1644009). Review.
	local := net.JoinHostPort("localhost", strconv.Itoa(ssi.StatePort))
	addrs := []string{local}

	for _, addr := range c.apiDetails.addresses {
		host, _, err := net.SplitHostPort(addr)
		if err != nil {
			return nil, false
		}
		if host := net.JoinHostPort(host, strconv.Itoa(ssi.StatePort)); host != local {
			addrs = append(addrs, host)
		}
	}
	return &mongo.MongoInfo{
		Info: mongo.Info{
			Addrs:  addrs,
			CACert: c.caCert,
		},
		Password: c.statePassword,
		Tag:      c.tag,
	}, true
}
1035589
func (c *mongoDBConnectionProducer) Init(ctx context.Context, conf map[string]interface{}, verifyConnection bool) (map[string]interface{}, error) {
	c.Lock()
	defer c.Unlock()

	c.RawConfig = conf

	err := mapstructure.WeakDecode(conf, c)
	if err != nil {
		return nil, err
	}

	if len(c.ConnectionURL) == 0 {
		return nil, fmt.Errorf("connection_url cannot be empty")
	}

	c.ConnectionURL = dbutil.QueryHelper(c.ConnectionURL, map[string]string{
		"username": c.Username,
		"password": c.Password,
	})

	if c.WriteConcern != "" {
		input := c.WriteConcern

		// Try to base64 decode the input. If successful, consider the decoded
		// value as input.
		inputBytes, err := base64.StdEncoding.DecodeString(input)
		if err == nil {
			input = string(inputBytes)
		}

		concern := &mgo.Safe{}
		err = json.Unmarshal([]byte(input), concern)
		if err != nil {
			return nil, errwrap.Wrapf("error mashalling write_concern: {{err}}", err)
		}

		// Guard against empty, non-nil mgo.Safe object; we don't want to pass that
		// into mgo.SetSafe in Connection().
		if (mgo.Safe{} == *concern) {
			return nil, fmt.Errorf("provided write_concern values did not map to any mgo.Safe fields")
		}
		c.safe = concern
	}

	// Set initialized to true at this point since all fields are set,
	// and the connection can be established at a later time.
	c.Initialized = true

	if verifyConnection {
		if _, err := c.Connection(ctx); err != nil {
			return nil, errwrap.Wrapf("error verifying connection: {{err}}", err)
		}

		if err := c.session.Ping(); err != nil {
			return nil, errwrap.Wrapf("error verifying connection: {{err}}", err)
		}
	}

	return conf, nil
}
284316
func openDB(dbPath string, network wire.BitcoinNet, create bool) (database.DB, error) {
	// Error if the database doesn't exist and the create flag is not set.
	metadataDbPath := filepath.Join(dbPath, metadataDbName)
	dbExists := fileExists(metadataDbPath)
	if !create && !dbExists {
		str := fmt.Sprintf("database %q does not exist", metadataDbPath)
		return nil, makeDbErr(database.ErrDbDoesNotExist, str, nil)
	}

	// Ensure the full path to the database exists.
	if !dbExists {
		// The error can be ignored here since the call to
		// leveldb.OpenFile will fail if the directory couldn't be
		// created.
		_ = os.MkdirAll(dbPath, 0700)
	}

	// Open the metadata database (will create it if needed).
	opts := opt.Options{
		ErrorIfExist: create,
		Strict:       opt.DefaultStrict,
		Compression:  opt.NoCompression,
		Filter:       filter.NewBloomFilter(10),
	}
	ldb, err := leveldb.OpenFile(metadataDbPath, &opts)
	if err != nil {
		return nil, convertErr(err.Error(), err)
	}

	// Create the block store which includes scanning the existing flat
	// block files to find what the current write cursor position is
	// according to the data that is actually on disk.  Also create the
	// database cache which wraps the underlying leveldb database to provide
	// write caching.
	store := newBlockStore(dbPath, network)
	cache := newDbCache(ldb, store, defaultCacheSize, defaultFlushSecs)
	pdb := &db{store: store, cache: cache}

	// Perform any reconciliation needed between the block and metadata as
	// well as database initialization, if needed.
	return reconcileDB(pdb, create)
}
555946
func (p *Ports) OpenPorts(portRange PortRange) (err error) {
	defer errors.DeferredAnnotatef(&err, "cannot open ports %s", portRange)

	if err = portRange.Validate(); err != nil {
		return errors.Trace(err)
	}
	ports := Ports{st: p.st, doc: p.doc, areNew: p.areNew}

	buildTxn := func(attempt int) ([]txn.Op, error) {
		if attempt > 0 {
			if err := checkModelActive(p.st); err != nil {
				return nil, errors.Trace(err)
			}
			if err := p.verifySubnetAliveWhenSet(); err != nil {
				return nil, errors.Trace(err)
			}
			if err = ports.Refresh(); errors.IsNotFound(err) {
				// No longer exists, we'll create it.
				if !ports.areNew {
					ports.areNew = true
				}
			} else if err != nil {
				return nil, errors.Trace(err)
			} else if ports.areNew {
				// Already created, we'll update it.
				ports.areNew = false
			}
		}

		// Check for conflicts with existing ports.
		for _, existingPorts := range p.doc.Ports {
			if err := existingPorts.CheckConflicts(portRange); err != nil {
				return nil, errors.Trace(err)
			} else if existingPorts == portRange {
				// Trying to open the same range for the same unit is
				// ignored, as we don't need to change the document
				// and hence its txn-revno and trigger unnecessary
				// watcher notifications.
				return nil, statetxn.ErrNoOperations
			}
		}

		ops := []txn.Op{
			assertModelActiveOp(p.st.ModelUUID()),
		}
		if ports.areNew {
			// Create a new document.
			assert := txn.DocMissing
			ops = append(ops, addPortsDocOps(p.st, &ports.doc, assert, portRange)...)
		} else {
			// Update an existing document.
			assert := bson.D{{"txn-revno", ports.doc.TxnRevno}}
			ops = append(ops, updatePortsDocOps(p.st, ports.doc, assert, portRange)...)
		}
		return ops, nil
	}
	// Run the transaction using the state transaction runner.
	if err = p.st.db().Run(buildTxn); err != nil {
		return errors.Trace(err)
	}
	// Mark object as created.
	p.areNew = false
	p.doc.Ports = append(p.doc.Ports, portRange)
	return nil
}
326227
func (s *ModifyEndpointInput) SetMongoDbSettings(v *MongoDbSettings) *ModifyEndpointInput {
	s.MongoDbSettings = v
	return s
}
1367332
func (s *Endpoint) SetMongoDbSettings(v *MongoDbSettings) *Endpoint {
	s.MongoDbSettings = v
	return s
}
828549
func OpenDb(opts *Options, name string) (*DB, error) {
	var (
		cErr  *C.char
		cName = C.CString(name)
	)
	defer C.free(unsafe.Pointer(cName))
	db := C.rocksdb_open(opts.c, cName, &cErr)
	if cErr != nil {
		defer C.free(unsafe.Pointer(cErr))
		return nil, errors.New(C.GoString(cErr))
	}
	return &DB{
		name: name,
		c:    db,
		opts: opts,
	}, nil
}
587599
func OpenBase(L *LState) int {
	global := L.Get(GlobalsIndex).(*LTable)
	L.SetGlobal("_G", global)
	L.SetGlobal("_VERSION", LString(LuaVersion))
	L.SetGlobal("_GOPHER_LUA_VERSION", LString(PackageName+" "+PackageVersion))
	basemod := L.RegisterModule("_G", baseFuncs)
	global.RawSetString("ipairs", L.NewClosure(baseIpairs, L.NewFunction(ipairsaux)))
	global.RawSetString("pairs", L.NewClosure(basePairs, L.NewFunction(pairsaux)))
	L.Push(basemod)
	return 1
}
879929
func NewMongoDB(urlStr string) (*MongoDB, error) {
	s, err := mgo.Dial(urlStr)
	if err != nil {
		return nil, err
	}
	return &MongoDB{sess: s}, nil
}
376430
func Open(path string) (*DB, error) {
	db := &DB{}
	// initialize trees and indexes
	db.keys = btree.New(btreeDegrees, nil)
	db.exps = btree.New(btreeDegrees, &exctx{db})
	db.idxs = make(map[string]*index)
	// initialize default configuration
	db.config = Config{
		SyncPolicy:           EverySecond,
		AutoShrinkPercentage: 100,
		AutoShrinkMinSize:    32 * 1024 * 1024,
	}
	// turn off persistence for pure in-memory
	db.persist = path != ":memory:"
	if db.persist {
		var err error
		// hardcoding 0666 as the default mode.
		db.file, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0666)
		if err != nil {
			return nil, err
		}
		// load the database from disk
		if err := db.load(); err != nil {
			// close on error, ignore close error
			_ = db.file.Close()
			return nil, err
		}
	}
	// start the background manager.
	go db.backgroundManager()
	return db, nil
}