//private to this file
func _createSession() (*mgo.Session, error) {

	if _cfg == nil {
		_cfg = &mongoConfig{}
		framework.Config.ReadInto("mongo", &_cfg)
	}

	var timeout = 10 * time.Second

	if _cfg.ConnectionString != "" {

		return mgo.DialWithTimeout(_cfg.ConnectionString, timeout)
	} else {

		dialInfo := mgo.DialInfo{}
		dialInfo.Database = _cfg.Database
		dialInfo.Username = _cfg.User
		dialInfo.Password = _cfg.Password
		dialInfo.Addrs = []string{fmt.Sprintf("%s:%s", _cfg.Host, _cfg.Port)}
		dialInfo.Timeout = timeout

		fmt.Println("Logging to", dialInfo.Addrs[0])

		return mgo.DialWithInfo(&dialInfo)
	}
}
Example #2
0
func (a *agent) mongoWorker() (worker.Worker, error) {
	dialInfo := gitjujutesting.MgoDialInfo(coretesting.Certs, a.hostPort)
	session, err := mgo.DialWithInfo(dialInfo)
	if err != nil {
		return nil, err
	}
	mc := &mongoConn{
		localHostPort: a.hostPort,
		session:       session,
	}
	runner := worker.NewRunner(
		connectionIsFatal(mc),
		func(err0, err1 error) bool { return true },
	)
	singularRunner, err := singular.New(runner, mc)
	if err != nil {
		return nil, fmt.Errorf("cannot start singular runner: %v", err)
	}
	a.notify.workerConnected()
	singularRunner.StartWorker(fmt.Sprint("worker-", a.notify.id), func() (worker.Worker, error) {
		return worker.NewSimpleWorker(func(stop <-chan struct{}) error {
			return a.worker(session, stop)
		}), nil
	})
	return runner, nil
}
Example #3
0
func (s *adminSuite) TestSetAdminMongoPassword(c *gc.C) {
	dialInfo := s.setUpMongo(c)
	session, err := mgo.DialWithInfo(dialInfo)
	c.Assert(err, gc.IsNil)
	defer session.Close()
	admin := session.DB("admin")

	// Check that we can SetAdminMongoPassword to nothing when there's
	// no password currently set.
	err = mongo.SetAdminMongoPassword(session, "admin", "")
	c.Assert(err, gc.IsNil)

	err = mongo.SetAdminMongoPassword(session, "admin", "foo")
	c.Assert(err, gc.IsNil)
	err = admin.Login("admin", "")
	c.Assert(err, gc.ErrorMatches, "auth fails")
	err = admin.Login("admin", "foo")
	c.Assert(err, gc.IsNil)
	checkRoles(c, admin, "admin",
		[]interface{}{
			string(mgo.RoleReadWriteAny),
			string(mgo.RoleDBAdminAny),
			string(mgo.RoleUserAdminAny),
			string(mgo.RoleClusterAdmin)})
}
Example #4
0
func changeVotes(c *gc.C, insts []*gitjujutesting.MgoInstance, voteId int) {
	c.Logf("changing voting id to %v", voteId)

	addrs := make([]string, len(insts))
	for i, inst := range insts {
		addrs[i] = inst.Addr()
	}
	dialInfo := gitjujutesting.MgoDialInfo(coretesting.Certs, addrs...)

	session, err := mgo.DialWithInfo(dialInfo)
	c.Assert(err, gc.IsNil)
	defer session.Close()

	members, err := replicaset.CurrentMembers(session)
	c.Assert(err, gc.IsNil)
	c.Assert(members, gc.HasLen, len(insts))
	for i := range members {
		member := &members[i]
		if member.Id == voteId {
			member.Priority = nil
		} else {
			member.Priority = newFloat64(0.1)
		}
	}
	c.Logf("new member set: %#v", members)
	err = replicaset.Set(session, members)
	c.Assert(err, gc.IsNil)

	c.Logf("successfully changed replica set members")
}
Example #5
0
func (s *S) TestCustomDial(c *C) {
	dials := make(chan bool, 16)
	dial := func(addr net.Addr) (net.Conn, error) {
		tcpaddr, ok := addr.(*net.TCPAddr)
		if !ok {
			return nil, fmt.Errorf("unexpected address type: %T", addr)
		}
		dials <- true
		return net.DialTCP("tcp", nil, tcpaddr)
	}
	info := mgo.DialInfo{
		Addrs: []string{"localhost:40012"},
		Dial:  dial,
	}

	// Use hostname here rather than IP, to make things trickier.
	session, err := mgo.DialWithInfo(&info)
	c.Assert(err, IsNil)
	defer session.Close()

	const N = 3
	for i := 0; i < N; i++ {
		select {
		case <-dials:
		case <-time.After(5 * time.Second):
			c.Fatalf("expected %d dials, got %d", N, i)
		}
	}
	select {
	case <-dials:
		c.Fatalf("got more dials than expected")
	case <-time.After(100 * time.Millisecond):
	}
}
Example #6
0
// Open connects to the server described by the given
// info, waits for it to be initialized, and returns a new State
// representing the environment connected to.
//
// A policy may be provided, which will be used to validate and
// modify behaviour of certain operations in state. A nil policy
// may be provided.
//
// Open returns unauthorizedError if access is unauthorized.
func Open(info *Info, opts mongo.DialOpts, policy Policy) (*State, error) {
	logger.Infof("opening state, mongo addresses: %q; entity %q", info.Addrs, info.Tag)
	di, err := mongo.DialInfo(info.Info, opts)
	if err != nil {
		return nil, err
	}
	logger.Debugf("dialing mongo")
	session, err := mgo.DialWithInfo(di)
	if err != nil {
		return nil, err
	}
	logger.Debugf("connection established")

	_, err = replicaset.CurrentConfig(session)
	safe := &mgo.Safe{J: true}
	if err == nil {
		// set mongo to write-majority (writes only returned after replicated
		// to a majority of replica-set members)
		safe.WMode = "majority"
	}
	session.SetSafe(safe)

	st, err := newState(session, info, policy)
	if err != nil {
		session.Close()
		return nil, err
	}
	session.SetSocketTimeout(mongo.SocketTimeout)
	return st, nil
}
Example #7
0
File: mgo.go Project: jkary/core
// MustDial returns a new connection to the MongoDB server, and panics on
// errors.
func (inst *MgoInstance) MustDial() *mgo.Session {
	s, err := mgo.DialWithInfo(inst.DialInfo())
	if err != nil {
		panic(err)
	}
	return s
}
Example #8
0
// attemptInitiateMongoServer attempts to initiate the replica set.
func attemptInitiateMongoServer(dialInfo *mgo.DialInfo, memberHostPort string) error {
	session, err := mgo.DialWithInfo(dialInfo)
	if err != nil {
		return fmt.Errorf("can't dial mongo to initiate replicaset: %v", err)
	}
	defer session.Close()
	session.SetSocketTimeout(mongo.SocketTimeout)

	var cfg *replicaset.Config
	cfg, err = replicaset.CurrentConfig(session)
	if err == nil && len(cfg.Members) > 0 {
		logger.Infof("replica set configuration already found: %#v", cfg)
		return nil
	}
	if err != nil && err != mgo.ErrNotFound {
		return fmt.Errorf("cannot get replica set configuration: %v", err)
	}
	return replicaset.Initiate(
		session,
		memberHostPort,
		mongo.ReplicaSetName,
		map[string]string{
			jujuMachineTag: agent.BootstrapMachineId,
		},
	)
}
Example #9
0
func (s *S) TestCustomDialNew(c *C) {
	dials := make(chan bool, 16)
	dial := func(addr *mgo.ServerAddr) (net.Conn, error) {
		dials <- true
		if addr.TCPAddr().Port == 40012 {
			c.Check(addr.String(), Equals, "localhost:40012")
		}
		return net.DialTCP("tcp", nil, addr.TCPAddr())
	}
	info := mgo.DialInfo{
		Addrs:      []string{"localhost:40012"},
		DialServer: dial,
	}

	// Use hostname here rather than IP, to make things trickier.
	session, err := mgo.DialWithInfo(&info)
	c.Assert(err, IsNil)
	defer session.Close()

	const N = 3
	for i := 0; i < N; i++ {
		select {
		case <-dials:
		case <-time.After(5 * time.Second):
			c.Fatalf("expected %d dials, got %d", N, i)
		}
	}
	select {
	case <-dials:
		c.Fatalf("got more dials than expected")
	case <-time.After(100 * time.Millisecond):
	}
}
func display(w http.ResponseWriter, r *http.Request) {

	mongoDBDialInfo := &mgo.DialInfo{
		Addrs:    []string{MongoDBHosts},
		Database: AuthDatabase,
		Username: AuthUserName,
		Password: AuthPassword,
	}

	mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
	if err != nil {
		fmt.Println("error1")
	}

	mongoSession.SetMode(mgo.Monotonic, true)

	collection := mongoSession.DB(TestDatabase).C("AddressData")

	var result AddressData

	err = collection.Find(bson.M{"Name": r.FormValue("name")}).One(&result)

	if result.Email != "" {
		errn := displayTemplate.Execute(w, "The email id you wanted is: "+result.Email)
		if errn != nil {
			http.Error(w, errn.Error(), http.StatusInternalServerError)
		}
	} else {
		displayTemplate.Execute(w, "Sorry... The email id you wanted does not exist.")
	}
}
Example #11
0
func (g *MongoGateway) Initialize() error {
	var connectionErr error
	if g.DialInfo == nil {
		g.InitDialInfo()
	}
	g.BaseSession, connectionErr = mgo.DialWithInfo(g.DialInfo)
	return connectionErr
}
Example #12
0
// MaybeInitiateMongoServer checks for an existing mongo configuration.
// If no existing configuration is found one is created using Initiate.
func MaybeInitiateMongoServer(p InitiateMongoParams) error {
	logger.Debugf("Initiating mongo replicaset; dialInfo %#v; memberHostport %q; user %q; password %q", p.DialInfo, p.MemberHostPort, p.User, p.Password)
	defer logger.Infof("finished MaybeInitiateMongoServer")

	if len(p.DialInfo.Addrs) > 1 {
		logger.Infof("more than one member; replica set must be already initiated")
		return nil
	}
	p.DialInfo.Direct = true

	// TODO(rog) remove this code when we no longer need to upgrade
	// from pre-HA-capable environments.
	if p.User != "" {
		p.DialInfo.Username = p.User
		p.DialInfo.Password = p.Password
	}

	session, err := mgo.DialWithInfo(p.DialInfo)
	if err != nil {
		return fmt.Errorf("can't dial mongo to initiate replicaset: %v", err)
	}
	defer session.Close()

	// Initiate may fail while mongo is initialising, so we retry until
	// we succssfully populate the replicaset config.
	for attempt := initiateAttemptStrategy.Start(); attempt.Next(); {
		var cfg *replicaset.Config
		cfg, err = replicaset.CurrentConfig(session)
		if err == nil && len(cfg.Members) > 0 {
			logger.Infof("replica set configuration already found: %#v", cfg)
			return nil
		}
		if err != nil && err != mgo.ErrNotFound {
			return fmt.Errorf("cannot get replica set configuration: %v", err)
		}
		err = replicaset.Initiate(
			session,
			p.MemberHostPort,
			mongo.ReplicaSetName,
			map[string]string{
				jujuMachineTag: agent.BootstrapMachineId,
			},
		)
		if err == nil {
			logger.Infof("replica set initiated")
			return nil
		}
		if attempt.HasNext() {
			logger.Debugf("replica set initiation failed, will retry: %v", err)
		}
		// Release sockets, which may have been closed by mgo.
		session.Refresh()
	}
	return fmt.Errorf("cannot initiate replica set: %v", err)
}
Example #13
0
func main() {
	results = make(chan *common.FileStat)
	commonStatMutex = make(chan int, 1)
	commonStat = new(common.FileStat)
	commonStat.Filename = "all"
	// Listen on TCP port 2000 on all interfaces.
	mongoSession, err := mgo.DialWithInfo(&mgo.DialInfo{
		Addrs: []string{"localhost"}, Database: "gotest", Username: "******", Password: "******"})

	if err != nil {
		log.Fatalf("CreateSession: %s\n", err)
	}
	mongoSession.SetMode(mgo.Monotonic, true)
	log.Println("Start listen tcp on 8911")
	l, err := net.Listen("tcp", ":8911")
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()
	for {
		// Wait for a connection.
		conn, err := l.Accept()
		if err != nil {
			log.Fatal(err)
		}
		// Handle the connection in a new goroutine.
		// The loop then returns to accepting, so that
		// multiple connections may be served concurrently.
		go func(c net.Conn) {
			// Echo all incoming data.
			defer c.Close()
			info := new(common.FileStat)
			if err := info.Read(c); err != nil {
				log.Println(err)
				return
			}
			//			json_to_save := to_json(info)
			item_to_save := to_bson(info)
			commonStatMutex <- 1 // It will block next concurrent call
			conn.Write(commonStat.Bytes())
			<-commonStatMutex
			//			fmt.Println(json_to_save)
			//				client.Set('a', dat)
			// Shut down the connection.
			go func() {
				sessionCopy := mongoSession.Copy()
				defer sessionCopy.Close()
				// save received data to mongo sessionCopy
				collection := sessionCopy.DB("gotest").C("filestat")
				collection.Insert(item_to_save)
			}()

		}(conn)
	}
}
Example #14
0
// CreateSession creates a connection pool for use
func CreateSession(sessionId string, mode string, sessionName string, hosts []string, databaseName string, username string, password string) (err error) {
	defer helper.CatchPanic(nil, sessionId, "CreateSession")

	tracelog.STARTEDf(sessionId, "CreateSession", "Mode[%s] SessionName[%s] Hosts[%s] DatabaseName[%s] Username[%s]", mode, sessionName, hosts, databaseName, username)

	// Create the database object
	mongoSession := &mongoSession{
		mongoDBDialInfo: &mgo.DialInfo{
			Addrs:    hosts,
			Timeout:  60 * time.Second,
			Database: databaseName,
			Username: username,
			Password: password,
		},
	}

	// Establish the master session
	mongoSession.mongoSession, err = mgo.DialWithInfo(mongoSession.mongoDBDialInfo)
	if err != nil {
		tracelog.COMPLETED_ERROR(err, sessionId, "CreateSession")
		return err
	}

	switch mode {
	case "strong":
		// Reads and writes will always be made to the master server using a
		// unique connection so that reads and writes are fully consistent,
		// ordered, and observing the most up-to-date data.
		// http://godoc.org/labix.org/v2/mgo#Session.SetMode
		mongoSession.mongoSession.SetMode(mgo.Strong, true)
		break

	case "monotonic":
		// Reads may not be entirely up-to-date, but they will always see the
		// history of changes moving forward, the data read will be consistent
		// across sequential queries in the same session, and modifications made
		// within the session will be observed in following queries (read-your-writes).
		// http://godoc.org/labix.org/v2/mgo#Session.SetMode
		mongoSession.mongoSession.SetMode(mgo.Monotonic, true)
	}

	// Have the session check for errors
	// http://godoc.org/labix.org/v2/mgo#Session.SetSafe
	mongoSession.mongoSession.SetSafe(&mgo.Safe{})

	// Add the database to the map
	_This.sessions[sessionName] = mongoSession

	tracelog.COMPLETED(sessionId, "CreateSession")
	return err
}
Example #15
0
func (s *S) TestFailFast(c *C) {
	info := mgo.DialInfo{
		Addrs:    []string{"localhost:99999"},
		Timeout:  5 * time.Second,
		FailFast: true,
	}

	started := time.Now()

	_, err := mgo.DialWithInfo(&info)
	c.Assert(err, ErrorMatches, "no reachable servers")

	c.Assert(started.After(time.Now().Add(-time.Second)), Equals, true)
}
Example #16
0
func (s *adminSuite) TestSetMongoPassword(c *gc.C) {
	dialInfo := s.setUpMongo(c)
	session, err := mgo.DialWithInfo(dialInfo)
	c.Assert(err, gc.IsNil)
	defer session.Close()
	db := session.DB("juju")

	err = db.Login("foo", "bar")
	c.Assert(err, gc.ErrorMatches, "auth fails")

	err = mongo.SetMongoPassword("foo", "bar", db)
	c.Assert(err, gc.IsNil)
	err = db.Login("foo", "bar")
	c.Assert(err, gc.IsNil)
}
Example #17
0
func (m *Mongo) Conn() error {
	dialInfo := &mgo.DialInfo{
		Addrs:    []string{m.uri},
		Timeout:  m.timeout * time.Second,
		Database: m.database,
	}

	sess, err := mgo.DialWithInfo(dialInfo)

	if err != nil {
		return err
	}

	m.session = sess
	return nil
}
Example #18
0
// Open connects to the server described by the given
// info, waits for it to be initialized, and returns a new State
// representing the environment connected to.
// It returns unauthorizedError if access is unauthorized.
func Open(info *Info, opts DialOpts) (*State, error) {
	log.Infof("state: opening state; mongo addresses: %q; entity %q", info.Addrs, info.Tag)
	if len(info.Addrs) == 0 {
		return nil, stderrors.New("no mongo addresses")
	}
	if len(info.CACert) == 0 {
		return nil, stderrors.New("missing CA certificate")
	}
	xcert, err := cert.ParseCert(info.CACert)
	if err != nil {
		return nil, fmt.Errorf("cannot parse CA certificate: %v", err)
	}
	pool := x509.NewCertPool()
	pool.AddCert(xcert)
	tlsConfig := &tls.Config{
		RootCAs:    pool,
		ServerName: "anything",
	}
	dial := func(addr net.Addr) (net.Conn, error) {
		c, err := net.Dial("tcp", addr.String())
		if err != nil {
			log.Errorf("state: connection failed, will retry: %v", err)
			return nil, err
		}
		cc := tls.Client(c, tlsConfig)
		if err := cc.Handshake(); err != nil {
			log.Errorf("state: TLS handshake failed: %v", err)
			return nil, err
		}
		return cc, nil
	}
	session, err := mgo.DialWithInfo(&mgo.DialInfo{
		Addrs:   info.Addrs,
		Timeout: opts.Timeout,
		Dial:    dial,
	})
	if err != nil {
		return nil, err
	}
	log.Infof("state: connection established")
	st, err := newState(session, info)
	if err != nil {
		session.Close()
		return nil, err
	}
	return st, nil
}
Example #19
0
func (s *adminSuite) TestSetMongoPassword(c *gc.C) {
	dialInfo := s.setUpMongo(c)
	session, err := mgo.DialWithInfo(dialInfo)
	c.Assert(err, gc.IsNil)
	defer session.Close()
	db := session.DB("juju")

	err = db.Login("foo", "bar")
	c.Assert(err, gc.ErrorMatches, "auth fails")

	err = mongo.SetMongoPassword("foo", "bar", db)
	c.Assert(err, gc.IsNil)
	err = db.Login("foo", "bar")
	c.Assert(err, gc.IsNil)
	checkRoles(c, db, "foo",
		[]interface{}{string(mgo.RoleReadWriteAny), string(mgo.RoleUserAdmin), string(mgo.RoleClusterAdmin)})
}
Example #20
0
func (db *MongoDB) Connect() (err error) {

	if db.Session == nil {
		//set connection properties
		dialinfo := &mgo.DialInfo{
			Addrs:    []string{db.Url.Host},
			FailFast: true,
			Database: db.name,
			Source:   db.name,
		}

		//set username/password info from the db url
		if db.Url.User != nil {
			dialinfo.Username = db.Url.User.Username()
			password, has_password := db.Url.User.Password()

			if has_password {
				dialinfo.Password = password
			}
		}

		//connect to MongoDB
		//db.Session, err = mgo.DialWithInfo(dialinfo)
		db.Session, err = mgo.DialWithInfo(dialinfo)
		if err != nil {
			return
		}
	}

	//create an mgo.Database object
	db.Database = db.Session.DB(db.Url.Path[1:])

	//fetch the session information
	info, err := db.Session.BuildInfo()
	if err != nil {
		return
	}

	db.SessionInfo = &info

	//set the session in safe mode
	db.Session.SetSafe(&mgo.Safe{})

	return
}
Example #21
0
// MaybeInitiateMongoServer checks for an existing mongo configuration.
// If no existing configuration is found one is created using Initiate.
func MaybeInitiateMongoServer(p InitiateMongoParams) error {
	logger.Debugf("Initiating mongo replicaset; dialInfo %#v; memberHostport %q; user %q; password %q", p.DialInfo, p.MemberHostPort, p.User, p.Password)
	defer logger.Infof("finished MaybeInitiateMongoServer")

	if len(p.DialInfo.Addrs) > 1 {
		logger.Infof("more than one member; replica set must be already initiated")
		return nil
	}
	p.DialInfo.Direct = true

	// TODO(rog) remove this code when we no longer need to upgrade
	// from pre-HA-capable environments.
	if p.User != "" {
		p.DialInfo.Username = p.User
		p.DialInfo.Password = p.Password
	}

	session, err := mgo.DialWithInfo(p.DialInfo)
	if err != nil {
		return fmt.Errorf("can't dial mongo to initiate replicaset: %v", err)
	}
	defer session.Close()

	cfg, err := replicaset.CurrentConfig(session)
	if err == nil && len(cfg.Members) > 0 {
		logger.Infof("replica set configuration already found: %#v", cfg)
		return nil
	}
	if err != nil && err != mgo.ErrNotFound {
		return fmt.Errorf("cannot get replica set configuration: %v", err)
	}
	err = replicaset.Initiate(
		session,
		p.MemberHostPort,
		mongo.ReplicaSetName,
		map[string]string{
			jujuMachineTag: agent.BootstrapMachineId,
		},
	)
	if err != nil {
		return fmt.Errorf("cannot initiate replica set: %v", err)
	}
	return nil
}
Example #22
0
func (s *adminSuite) TestSetAdminMongoPassword(c *gc.C) {
	dialInfo := s.setUpMongo(c)
	session, err := mgo.DialWithInfo(dialInfo)
	c.Assert(err, gc.IsNil)
	defer session.Close()
	admin := session.DB("admin")

	// Check that we can SetAdminMongoPassword to nothing when there's
	// no password currently set.
	err = mongo.SetAdminMongoPassword(session, "admin", "")
	c.Assert(err, gc.IsNil)

	err = mongo.SetAdminMongoPassword(session, "admin", "foo")
	c.Assert(err, gc.IsNil)
	err = admin.Login("admin", "")
	c.Assert(err, gc.ErrorMatches, "auth fails")
	err = admin.Login("admin", "foo")
	c.Assert(err, gc.IsNil)
}
func (s *MongoTests) Test_CopyCanBeUsedConcurrently(c *check.C) {

	runtime.GOMAXPROCS(runtime.NumCPU())

	masterSession, mErr := mgo.DialWithInfo(&mgo.DialInfo{
		Database: "test",
		Username: "",
		Password: "",
		Addrs:    []string{fmt.Sprintf("%s:%s", _cfg.Host, _cfg.Port)},
		Timeout:  10000 * time.Second,
	})

	if mErr != nil {
		c.Error(mErr)
		return
	}

	defer masterSession.Close()

	num := 1000
	wg := &sync.WaitGroup{}
	wg.Add(num)

	for i := 0; i < num; i++ {
		go func() {

			defer wg.Done()

			s := masterSession.Copy()
			defer s.Close()

			err := s.Ping()
			if err != nil {
				c.Error(err)
			}

		}()
	}

	wg.Wait()
}
Example #24
0
File: open.go Project: jkary/core
// Open connects to the server described by the given
// info, waits for it to be initialized, and returns a new State
// representing the environment connected to.
//
// A policy may be provided, which will be used to validate and
// modify behaviour of certain operations in state. A nil policy
// may be provided.
//
// Open returns unauthorizedError if access is unauthorized.
func Open(info *Info, opts DialOpts, policy Policy) (*State, error) {
	logger.Infof("opening state, mongo addresses: %q; entity %q", info.Addrs, info.Tag)
	di, err := DialInfo(info, opts)
	if err != nil {
		return nil, err
	}
	logger.Debugf("dialing mongo")
	session, err := mgo.DialWithInfo(di)
	if err != nil {
		return nil, err
	}
	logger.Debugf("connection established")

	st, err := newState(session, info, policy)
	if err != nil {
		session.Close()
		return nil, err
	}
	session.SetSocketTimeout(mongoSocketTimeout)
	return st, nil
}
Example #25
0
// Open connects to the server described by the given
// info, waits for it to be initialized, and returns a new State
// representing the environment connected to.
// It returns ErrUnauthorized if access is unauthorized.
func Open(info *Info) (*State, error) {
	log.Printf("state: opening state; mongo addresses: %q; entity %q", info.Addrs, info.EntityName)
	if len(info.Addrs) == 0 {
		return nil, errors.New("no mongo addresses")
	}
	if len(info.CACert) == 0 {
		return nil, errors.New("missing CA certificate")
	}
	xcert, err := cert.ParseCert(info.CACert)
	if err != nil {
		return nil, fmt.Errorf("cannot parse CA certificate: %v", err)
	}
	pool := x509.NewCertPool()
	pool.AddCert(xcert)
	tlsConfig := &tls.Config{
		RootCAs:    pool,
		ServerName: "anything",
	}
	dial := func(addr net.Addr) (net.Conn, error) {
		log.Printf("state: connecting to %v", addr)
		c, err := tls.Dial("tcp", addr.String(), tlsConfig)
		if err != nil {
			log.Printf("state: connection failed: %v", err)
			return nil, err
		}
		log.Printf("state: connection established")
		return c, err
	}
	session, err := mgo.DialWithInfo(&mgo.DialInfo{
		Addrs:   info.Addrs,
		Timeout: 10 * time.Minute,
		Dial:    dial,
	})
	st, err := newState(session, info)
	if err != nil {
		session.Close()
		return nil, err
	}
	return st, nil
}
Example #26
0
func (mongo *AlinMongo) UpdateSession() (err error) {
	conf := mongo.Config
	if len(conf.ConnString) > 0 {
		if strings.Contains(conf.ConnString, "mongodb://") {
			mongo.Session, err = mgo.Dial(conf.ConnString)
		} else {
			mongo.Session, err = mgo.Dial(fmt.Sprintf("mongodb://%s", conf.ConnString))
		}

	} else {
		dial_info := &mgo.DialInfo{
			Addrs:    []string{conf.HostPort},
			Direct:   true,
			FailFast: true,
		}

		mongo.Session, err = mgo.DialWithInfo(dial_info)
	}

	if err != nil {
		return err
	}

	mongo.Session.SetSafe(&mgo.Safe{})
	if len(conf.ConnString) == 0 {
		mongo.Session.SetMode(mgo.Monotonic, true)
	}

	mongo.DB = mongo.Session.DB(conf.DB)

	// If prefix is defined then setting gridfs handler
	if len(conf.Prefix) > 0 {
		err = mongo.UpdateGridFS()
		if err != nil {
			return err
		}
	}
	mongo.Active = true
	return nil
}
Example #27
0
// MgoDial returns a new connection to the shared MongoDB server.
func MgoDial() *mgo.Session {
	pool := x509.NewCertPool()
	xcert, err := cert.ParseCert([]byte(CACert))
	if err != nil {
		panic(err)
	}
	pool.AddCert(xcert)
	tlsConfig := &tls.Config{
		RootCAs:    pool,
		ServerName: "anything",
	}
	session, err := mgo.DialWithInfo(&mgo.DialInfo{
		Addrs: []string{MgoAddr},
		Dial: func(addr net.Addr) (net.Conn, error) {
			return tls.Dial("tcp", addr.String(), tlsConfig)
		},
	})
	if err != nil {
		panic(err)
	}
	return session
}
// main is the entry point for the application.
func main() {
	// We need this object to establish a session to our MongoDB.
	mongoDBDialInfo := &mgo.DialInfo{
		Addrs:    []string{MongoDBHosts},
		Timeout:  60 * time.Second,
		Database: AuthDatabase,
		Username: AuthUserName,
		Password: AuthPassword,
	}

	// Create a session which maintains a pool of socket connections
	// to our MongoDB.
	mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
	if err != nil {
		log.Fatalf("CreateSession: %s\n", err)
	}

	// Reads may not be entirely up-to-date, but they will always see the
	// history of changes moving forward, the data read will be consistent
	// across sequential queries in the same session, and modifications made
	// within the session will be observed in following queries (read-your-writes).
	// http://godoc.org/labix.org/v2/mgo#Session.SetMode
	mongoSession.SetMode(mgo.Monotonic, true)

	// Create a wait group to manage the goroutines.
	var waitGroup sync.WaitGroup

	// Perform 10 concurrent queries against the database.
	waitGroup.Add(10)
	for query := 0; query < 10; query++ {
		go RunQuery(query, &waitGroup, mongoSession)
	}

	// Wait for all the queries to complete.
	waitGroup.Wait()
	log.Println("All Queries Completed")
}
Example #29
0
File: mgo.go Project: jkary/core
// DialDirect returns a new direct connection to the shared MongoDB server. This
// must be used if you're connecting to a replicaset that hasn't been initiated
// yet.
func (inst *MgoInstance) DialDirect() (*mgo.Session, error) {
	info := inst.DialInfo()
	info.Direct = true
	return mgo.DialWithInfo(info)
}
Example #30
0
File: mgo.go Project: jkary/core
// Dial returns a new connection to the MongoDB server.
func (inst *MgoInstance) Dial() (*mgo.Session, error) {
	return mgo.DialWithInfo(inst.DialInfo())
}