当前位置: 首页>>代码示例>>Golang>>正文


Golang mysql.NewConnection函数代码示例

本文整理汇总了Golang中github.com/percona/percona-agent/mysql.NewConnection函数的典型用法代码示例。如果您正苦于以下问题:Golang NewConnection函数的具体用法?Golang NewConnection怎么用?Golang NewConnection使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewConnection函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Make

func (f *Factory) Make(service string, instanceId uint, data []byte) (sysconfig.Monitor, error) {
	var monitor sysconfig.Monitor
	switch service {
	case "mysql":
		// Load the MySQL instance info (DSN, name, etc.).
		mysqlIt := &proto.MySQLInstance{}
		if err := f.ir.Get(service, instanceId, mysqlIt); err != nil {
			return nil, err
		}

		// Parse the MySQL sysconfig config.
		config := &mysql.Config{}
		if err := json.Unmarshal(data, config); err != nil {
			return nil, err
		}

		// The user-friendly name of the service, e.g. sysconfig-mysql-db101:
		alias := "sysconfig-mysql-" + mysqlIt.Hostname

		// Make a MySQL sysconfig monitor.
		monitor = mysql.NewMonitor(
			alias,
			config,
			pct.NewLogger(f.logChan, alias),
			mysqlConn.NewConnection(mysqlIt.DSN),
		)
	default:
		return nil, errors.New("Unknown sysconfig monitor type: " + service)
	}
	return monitor, nil
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:31,代码来源:factory.go

示例2: TestStartWithInvalidDSN

// Even having a wrong user/pass, the monitor should be able to start
// It won't be able to connect to the DB, but it should start without
// blocking.
// This test if for cases where the agent starts but MySQL is down
func (s *TestSuite) TestStartWithInvalidDSN(t *C) {
	config := &mysql.Config{
		Config: mm.Config{
			ServiceInstance: proto.ServiceInstance{
				Service:    "mysql",
				InstanceId: 1,
			},
			Collect: 1,
			Report:  60,
		},
		Status: map[string]string{
			"threads_connected": "gauge",
			"threads_running":   "gauge",
		},
	}

	failDsn := "user:[email protected](127.0.0.2:3309)/"
	m := mysql.NewMonitor(s.name, config, s.logger, mysqlConn.NewConnection(failDsn), s.mrm)
	if m == nil {
		t.Fatal("Make new mysql.Monitor")
	}

	err := m.Start(s.tickChan, s.collectionChan)
	t.Assert(err, IsNil)
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:29,代码来源:mysql_test.go

示例3: TestConnection

func (s *MysqlTestSuite) TestConnection(t *C) {
	conn := mysql.NewConnection(s.dsn)
	err := conn.Connect(1)
	t.Assert(err, IsNil)
	conn1 := conn.DB()

	err = conn.Connect(1)
	t.Assert(err, IsNil)
	conn2 := conn.DB()
	t.Check(conn1, Equals, conn2)

	conn.Close()
	t.Assert(conn.DB(), NotNil)

	/**
	 * we still have open connection,
	 * because we used Connect twice,
	 * so let's close it
	 */
	conn.Close()
	t.Assert(conn.DB(), IsNil)

	// lets test accidental extra closing
	conn.Close()
	t.Assert(conn.DB(), IsNil)
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:26,代码来源:mysql_test.go

示例4: NewSlowMySQL

func NewSlowMySQL(dsn string) *SlowMySQL {
	n := &SlowMySQL{
		realConnection: mysql.NewConnection(dsn),
		globalDelay:    0,
	}
	return n
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:7,代码来源:slow_mysql.go

示例5: TestMissingSocketError

func (s *MysqlTestSuite) TestMissingSocketError(t *C) {
	// https://jira.percona.com/browse/PCT-791
	conn := mysql.NewConnection("percona:[email protected](/foo/bar/my.sock)/")
	err := conn.Connect(1)
	t.Assert(
		fmt.Sprintf("%s", err),
		Equals,
		"Cannot connect to MySQL percona:<password-hidden>@unix(/foo/bar/my.sock)/: no such file or directory: /foo/bar/my.sock",
	)
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:10,代码来源:mysql_test.go

示例6: createNewMySQLUser

func (i *Installer) createNewMySQLUser() (dsn mysql.DSN, err error) {
	// Auto-detect the root MySQL user connection options.
	superUserDSN := i.defaultDSN
	if i.flags.Bool["auto-detect-mysql"] {
		if err := i.autodetectDSN(&superUserDSN); err != nil {
			if i.flags.Bool["debug"] {
				log.Println(err)
			}
		}
	}
	fmt.Printf("MySQL root DSN: %s\n", superUserDSN)

	// Try to connect as root automatically.  If this fails and interactive is true,
	// start prompting user to enter valid root MySQL connection info.
	if err = i.verifyMySQLConnection(superUserDSN); err != nil {
		fmt.Printf("Error connecting to MySQL %s: %s\n", superUserDSN, err)
		if i.flags.Bool["interactive"] {
			if again, err := i.term.PromptBool("Try again?", "Y"); err != nil {
				return superUserDSN, err
			} else if !again {
				return superUserDSN, fmt.Errorf("Failed to connect to MySQL")
			}
			fmt.Println("Specify a root/super MySQL user to create a user for the agent")
			if err := i.getDSNFromUser(&superUserDSN); err != nil {
				return dsn, err
			}
		} else {
			// Can't auto-detect MySQL root user and not interactive, fail.
			return dsn, err
		}
	}

	// Check MySQL Version
	dsnString, err := superUserDSN.DSN()
	if err != nil {
		return dsn, err
	}
	tmpConn := mysql.NewConnection(dsnString)
	isVersionSupported, err := i.IsVersionSupported(tmpConn)
	if err != nil {
		return dsn, err
	}

	if !isVersionSupported {
		return dsn, fmt.Errorf("MySQL version not supported. It should be > %s", agent.MIN_SUPPORTED_MYSQL_VERSION)
	}

	dsn, err = i.createMySQLUser(superUserDSN)
	if err != nil {
		return dsn, err
	}

	return dsn, nil
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:54,代码来源:mysql.go

示例7: SetUpSuite

func (s *TestSuite) SetUpSuite(t *C) {
	s.dsn = os.Getenv("PCT_TEST_MYSQL_DSN")
	if s.dsn == "" {
		t.Fatal("PCT_TEST_MYSQL_DSN is not set")
	}

	s.conn = mysql.NewConnection(s.dsn)
	if err := s.conn.Connect(1); err != nil {
		t.Fatal(err)
	}
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:11,代码来源:mysql_test.go

示例8: SetUpSuite

func (s *ManagerTestSuite) SetUpSuite(t *C) {
	s.dsn = os.Getenv("PCT_TEST_MYSQL_DSN")
	if s.dsn == "" {
		t.Fatal("PCT_TEST_MYSQL_DSN is not set")
	}
	s.realmysql = mysql.NewConnection(s.dsn)
	if err := s.realmysql.Connect(1); err != nil {
		t.Fatal(err)
	}
	s.reset = []mysql.Query{
		mysql.Query{Set: "SET GLOBAL slow_query_log=OFF"},
		mysql.Query{Set: "SET GLOBAL long_query_time=10"},
	}

	s.nullmysql = mock.NewNullMySQL()

	s.logChan = make(chan *proto.LogEntry, 1000)
	s.logger = pct.NewLogger(s.logChan, "qan-test")

	s.intervalChan = make(chan *qan.Interval, 1)
	s.iter = mock.NewMockIntervalIter(s.intervalChan)
	s.iterFactory = &mock.IntervalIterFactory{
		Iters:     []qan.IntervalIter{s.iter},
		TickChans: make(map[qan.IntervalIter]chan time.Time),
	}

	s.dataChan = make(chan interface{}, 2)
	s.spool = mock.NewSpooler(s.dataChan)
	s.workerFactory = &qan.SlowLogWorkerFactory{}

	var err error
	s.tmpDir, err = ioutil.TempDir("/tmp", "agent-test")
	t.Assert(err, IsNil)

	if err := pct.Basedir.Init(s.tmpDir); err != nil {
		t.Fatal(err)
	}
	s.configDir = pct.Basedir.Dir("config")

	s.im = instance.NewRepo(pct.NewLogger(s.logChan, "im-test"), s.configDir, s.api)
	data, err := json.Marshal(&proto.MySQLInstance{
		Hostname: "db1",
		DSN:      s.dsn,
	})
	t.Assert(err, IsNil)
	s.im.Add("mysql", 1, data, false)
	s.mysqlInstance = proto.ServiceInstance{Service: "mysql", InstanceId: 1}

	links := map[string]string{
		"agent":     "http://localhost/agent",
		"instances": "http://localhost/instances",
	}
	s.api = mock.NewAPI("http://localhost", "http://localhost", "123", "abc-123-def", links)
}
开发者ID:huangzhiyong,项目名称:percona-agent,代码行数:54,代码来源:qan_test.go

示例9: useExistingMySQLUser

func (i *Installer) useExistingMySQLUser() (mysql.DSN, error) {
	userDSN := i.defaultDSN
	userDSN.Username = "percona-agent"
	userDSN.Password = ""
	if i.flags.Bool["auto-detect-mysql"] {
		if err := i.autodetectDSN(&userDSN); err != nil {
			if i.flags.Bool["debug"] {
				log.Println(err)
			}
		}
	}
	for {
		// Let user specify the MySQL account to use for the agent.
		fmt.Println("Specify the existing MySQL user to use for the agent")
		if err := i.getDSNFromUser(&userDSN); err != nil {
			return userDSN, nil
		}

		// Verify DSN provided by user
		if err := i.verifyMySQLConnection(userDSN); err != nil {
			fmt.Printf("Error connecting to MySQL %s: %s\n", userDSN, err)
			if i.flags.Bool["interactive"] {
				if again, err := i.term.PromptBool("Try again?", "Y"); err != nil {
					return userDSN, err
				} else if !again {
					return userDSN, fmt.Errorf("Failed to connect to MySQL")
				}
				continue // again
			} else {
				// Can't auto-detect MySQL root user and not interactive, fail.
				return userDSN, err
			}
		}
		break
	}

	// Check MySQL Version
	dsnString, err := userDSN.DSN()
	if err != nil {
		return userDSN, err
	}
	tmpConn := mysql.NewConnection(dsnString)
	isVersionSupported, err := i.IsVersionSupported(tmpConn)
	if err != nil {
		return userDSN, err
	}
	if !isVersionSupported {
		return userDSN, fmt.Errorf("MySQL version not supported. It should be > %s", agent.MIN_SUPPORTED_MYSQL_VERSION)
	}
	return userDSN, nil // success
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:51,代码来源:mysql.go

示例10: TestMySQLConnection

func TestMySQLConnection(dsn mysql.DSN) error {
	dsnString, err := dsn.DSN()
	if err != nil {
		return err
	}

	fmt.Printf("Testing MySQL connection %s...\n", dsn)
	conn := mysql.NewConnection(dsnString)
	if err := conn.Connect(1); err != nil {
		return err
	}
	defer conn.Close()
	return nil
}
开发者ID:huangzhiyong,项目名称:percona-agent,代码行数:14,代码来源:mysql.go

示例11: verifyMySQLConnection

func (i *Installer) verifyMySQLConnection(dsn mysql.DSN) (err error) {
	dsnString, err := dsn.DSN()
	if err != nil {
		return err
	}
	if i.flags.Bool["debug"] {
		log.Printf("verifyMySQLConnection: %#v %s\n", dsn, dsnString)
	}
	conn := mysql.NewConnection(dsnString)
	if err := conn.Connect(1); err != nil {
		return err
	}
	conn.Close()
	return nil
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:15,代码来源:mysql.go

示例12: Make

func (f *Factory) Make(service string, instanceId uint, data []byte) (mm.Monitor, error) {
	var monitor mm.Monitor
	switch service {
	case "mysql":
		// Load the MySQL instance info (DSN, name, etc.).
		mysqlIt := &proto.MySQLInstance{}
		if err := f.ir.Get(service, instanceId, mysqlIt); err != nil {
			return nil, err
		}

		// Parse the MySQL sysconfig config.
		config := &mysql.Config{}
		if err := json.Unmarshal(data, config); err != nil {
			return nil, err
		}

		// The user-friendly name of the service, e.g. sysconfig-mysql-db101:
		alias := "mm-mysql-" + mysqlIt.Hostname

		// Make a MySQL metrics monitor.
		monitor = mysql.NewMonitor(
			alias,
			config,
			pct.NewLogger(f.logChan, alias),
			mysqlConn.NewConnection(mysqlIt.DSN),
			f.mrm,
		)
	case "server":
		// Parse the system mm config.
		config := &system.Config{}
		if err := json.Unmarshal(data, config); err != nil {
			return nil, err
		}

		// Only one system for now, so no SystemInstance and no  "-instanceName" suffix.
		alias := "mm-system"

		// Make a MySQL metrics monitor.
		monitor = system.NewMonitor(
			alias,
			config,
			pct.NewLogger(f.logChan, alias),
		)
	default:
		return nil, errors.New("Unknown metrics monitor type: " + service)
	}
	return monitor, nil
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:48,代码来源:factory.go

示例13: createMySQLUser

func (i *Installer) createMySQLUser(dsn mysql.DSN) (mysql.DSN, error) {
	// Same host:port or socket, but different user and pass.
	userDSN := dsn
	userDSN.Username = "percona-agent"
	userDSN.Password = fmt.Sprintf("%p%d", &dsn, rand.Uint32())
	userDSN.OldPasswords = i.flags.Bool["old-passwords"]

	dsnString, _ := dsn.DSN()
	conn := mysql.NewConnection(dsnString)
	if err := conn.Connect(1); err != nil {
		return userDSN, err
	}
	defer conn.Close()
	grants := MakeGrant(dsn, userDSN.Username, userDSN.Password, i.flags.Int64["mysql-max-user-connections"])
	for _, grant := range grants {
		if i.flags.Bool["debug"] {
			log.Println(grant)
		}
		_, err := conn.DB().Exec(grant)
		if err != nil {
			return userDSN, fmt.Errorf("Error executing %s: %s", grant, err)
		}
	}

	// Go MySQL driver resolves localhost to 127.0.0.1 but localhost is a special
	// value for MySQL, so 127.0.0.1 may not work with a grant @localhost, so we
	// add a 2nd grant @127.0.0.1 to be sure.
	if dsn.Hostname == "localhost" {
		dsn2 := dsn
		dsn2.Hostname = "127.0.0.1"
		grants := MakeGrant(dsn2, userDSN.Username, userDSN.Password, i.flags.Int64["mysql-max-user-connections"])
		for _, grant := range grants {
			if i.flags.Bool["debug"] {
				log.Println(grant)
			}
			_, err := conn.DB().Exec(grant)
			if err != nil {
				return userDSN, fmt.Errorf("Error executing %s: %s", grant, err)
			}
		}
	}

	return userDSN, nil
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:44,代码来源:mysql.go

示例14: GetMySQLInfo

func GetMySQLInfo(it *proto.MySQLInstance) error {
	conn := mysql.NewConnection(it.DSN)
	if err := conn.Connect(1); err != nil {
		return err
	}
	defer conn.Close()
	sql := "SELECT /* percona-agent */" +
		" CONCAT_WS('.', @@hostname, IF(@@port='3306',NULL,@@port)) AS Hostname," +
		" @@version_comment AS Distro," +
		" @@version AS Version"
	err := conn.DB().QueryRow(sql).Scan(
		&it.Hostname,
		&it.Distro,
		&it.Version,
	)
	if err != nil {
		return err
	}
	return nil
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:20,代码来源:manager.go

示例15: TestWorkerWithAnotherTZ

func (s *WorkerTestSuite) TestWorkerWithAnotherTZ(t *C) {
	if s.dsn == "" {
		t.Fatal("PCT_TEST_MYSQL_DSN is not set")
	}
	mysqlConn := mysql.NewConnection(s.dsn)
	err := mysqlConn.Connect(1)
	t.Assert(err, IsNil)
	defer mysqlConn.Close()
	mysqlConn.DB().Exec(`SET @@global.time_zone="-1:00"`)
	mysqlConn.DB().Exec(`SET time_zone="-1:00"`)
	// Reset the timezone or other tests could fail
	mysqlConn.DB().Exec(`SET @@global.time_zone="+00:00"`)
	defer mysqlConn.DB().Exec(`SET time_zone="+00:00"`)

	i := &qan.Interval{
		Number:      1,
		StartTime:   s.now,
		StopTime:    s.now.Add(1 * time.Minute),
		Filename:    inputDir + "slow001.log",
		StartOffset: 0,
		EndOffset:   524,
	}
	got, err := s.RunWorker(s.config, mysqlConn, i)
	t.Check(err, IsNil)
	expect := &qan.Result{}
	test.LoadMmReport(outputDir+"slow001.json", expect)

	// I'm going to use the same results for TestWorkerSlow001
	// But simulating tz = UTC -1

	expect.Class[0].Example.Ts = "2007-10-15 22:45:10"
	expect.Class[1].Example.Ts = "2007-10-15 22:43:52"

	sort.Sort(ByQueryId(got.Class))
	sort.Sort(ByQueryId(expect.Class))
	if ok, diff := IsDeeply(got, expect); !ok {
		Dump(got)
		t.Error(diff)
	}
}
开发者ID:hg3rdrock,项目名称:percona-agent,代码行数:40,代码来源:slowlog_test.go


注:本文中的github.com/percona/percona-agent/mysql.NewConnection函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。