Example #1
0
func (mu *MysqlUser) GrantExists(db mysql.Conn) (bool, error) {
	rows, _, err := db.Query(
		"SHOW GRANTS FOR '%v'@'%v'",
		mu.Username,
		mu.Hostname,
	)
	if err != nil {
		return false, err
	}

	if len(rows) == 0 {
		return false, nil
	}

	for _, row := range rows {
		grant := row.Str(0)
		// This regex hasn't been extensively tested but works in my local tests
		regex := fmt.Sprintf("GRANT ALL (.+) ON .%v.(.+) TO .%v.@.%v.", mu.Database, mu.Username, mu.Hostname)
		matched, err := regexp.MatchString(regex, grant)
		if err != nil {
			return false, err
		}
		if matched {
			return true, nil
		}
	}
	return false, nil
}
func (m MySQLPlugin) fetchShowStatus(db mysql.Conn, stat map[string]float64) error {
	rows, _, err := db.Query("show /*!50002 global */ status")
	if err != nil {
		log.Fatalln("FetchMetrics (Status): ", err)
		return err
	}

	for _, row := range rows {
		if len(row) > 1 {
			variableName := string(row[0].([]byte))
			if err != nil {
				log.Fatalln("FetchMetrics (Status Fetch): ", err)
				return err
			}
			stat[variableName], _ = atof(string(row[1].([]byte)))
		} else {
			log.Fatalln("FetchMetrics (Status): row length is too small: ", len(row))
		}
	}
	if m.EnableExtended {
		err = fetchShowStatusBackwardCompatibile(stat)
		if err != nil {
			log.Fatalln("FetchExtendedMetrics (Status Fetch): ", err)
		}
	}
	return nil
}
func (m MySQLPlugin) fetchProcesslist(db mysql.Conn, stat map[string]float64) error {
	rows, _, err := db.Query("SHOW PROCESSLIST")
	if err != nil {
		log.Fatalln("FetchMetrics (Processlist): ", err)
		return err
	}

	for k := range processState {
		stat[k] = 0
	}

	for _, row := range rows {
		if len(row) > 1 {
			var state string
			if row[6] == nil {
				state = "NULL"
			} else {
				state = string(row[6].([]byte))
			}
			parseProcesslist(state, &stat)
		} else {
			log.Fatalln("FetchMetrics (Processlist): row length is too small: ", len(row))
		}
	}

	return nil
}
Example #4
0
func udpateMySqlCdrImportStatus(db mysql.Conn, uniqueid string, status int) (err error) {
	var query = fmt.Sprintf("UPDATE cdr SET import = %d WHERE uniqueid = '%s'", status, uniqueid)
	log.Tracef("update cdr status [%s].\n", query)
	_, _, err = db.Query(query)
	//
	return err
}
Example #5
0
func mysqlVersion(conn mysqlc.Conn) (uint, uint, uint, error) {
	rows, _, err := conn.Query("SELECT VERSION()")
	if err != nil {
		return 0, 0, 0, err
	}
	if len(rows) == 0 {
		return 0, 0, 0, fmt.Errorf("SELECT VERSION() returned an empty set")
	}

	versionString := rows[0].Str(0)
	version := strings.Split(versionString, ".")
	invalidVersionErr := fmt.Errorf("Invalid major.minor.patch in %q", versionString)
	if len(version) != 3 {
		return 0, 0, 0, invalidVersionErr
	}

	major, err := strconv.ParseUint(version[0], 10, 32)
	if err != nil {
		return 0, 0, 0, invalidVersionErr
	}

	minor, err := strconv.ParseUint(version[1], 10, 32)
	if err != nil {
		return 0, 0, 0, invalidVersionErr
	}

	patch, err := strconv.ParseUint(version[2], 10, 32)
	if err != nil {
		return 0, 0, 0, invalidVersionErr
	}

	return uint(major), uint(minor), uint(patch), nil
}
// Dump the script to create the table
func dumpCreateTable(w io.Writer, db mysql.Conn, table string) {
	fmt.Fprintf(w, "\n--\n")
	fmt.Fprintf(w, "-- Table structure for table `%s`\n", table)
	fmt.Fprintf(w, "--\n\n")
	fmt.Fprintf(w, "DROP TABLE IF EXISTS `%s`;\n", table)
	row, _, err := db.QueryFirst("SHOW CREATE TABLE `%s`", table)
	checkError(err)
	fmt.Fprintf(w, "%s;\n", row.Str(1))
}
Example #7
0
func innodbStatus(m *MysqlIns, db mysql.Conn) ([]*MetaData, error) {
	status, _, err := db.QueryFirst("SHOW /*!50000 ENGINE */ INNODB STATUS")
	if err != nil {
		return nil, err
	}
	ctn := status.Str(2)
	rows := strings.Split(ctn, "\n")
	return parseInnodbStatus(m, rows)
}
Example #8
0
func (mydb *MysqlDatabase) CreateDatabase(db mysql.Conn) error {
	// IF NOT EXISTS isn't strictly necessary since we are checking
	// to make sure it doesn't exist first but it doesn't hurt.
	_, _, err := db.Query("CREATE DATABASE IF NOT EXISTS %v", mydb.Name)
	if err != nil {
		return err
	}
	mydb.Result.Changed = true
	return nil
}
Example #9
0
func del(db mysql.Conn, bag_id int, stuff_id int) {
	_, _, err := db.Query("delete from player_bag where bag_id=%d", bag_id)
	if err != nil {
		panic(err)
	}
	_, _, err = db.Query("delete from paladin where paladin_id=%d", stuff_id)
	if err != nil {
		panic(err)
	}
	fmt.Printf("delete %d, %d\n", bag_id, stuff_id)
}
Example #10
0
func serverVersion(conn mysqlc.Conn) (*version.Version, error) {
	rows, _, err := conn.Query("SELECT VERSION()")
	if err != nil {
		return nil, err
	}
	if len(rows) == 0 {
		return nil, fmt.Errorf("SELECT VERSION() returned an empty set")
	}

	return version.NewVersion(rows[0].Str(0))
}
// Get list of existing tables in database
func getTables(db mysql.Conn) (tables []string) {
	tables = make([]string, 0)
	rows, _, err := db.Query("SHOW TABLES")
	checkError(err)
	for _, row := range rows {
		for k, _ := range row {
			tables = append(tables, row.Str(k))
		}
	}
	return
}
Example #12
0
func QueryCheck(db mysql.Conn, sql string, params ...interface{}) ([]mysql.Row, mysql.Result) {
	rows, res, err := db.Query(sql)
	if err != nil {
		errlog.Error("QueryCheck =%s", sql)
		errlog.Error("QueryCheck err=%s", err.Error())
		fmt.Println(sql)
		fmt.Println(err)
		os.Exit(1)
	}

	return rows, res
}
Example #13
0
func ProcessNum(db mysql.Conn, cfg *base.Cfg) (*model.MetaData, error) {
	sql := "SHOW PROCESSLIST"
	rows, _, err := db.Query(sql)
	if err != nil {
		return nil, err
	}
	monitorName := "process_nums"
	threadNum := len(rows) - 1
	data := model.NewMetric(monitorName, cfg)
	data.SetValue(threadNum)
	return data, nil
}
Example #14
0
func queryByPath(w http.ResponseWriter, db mysql.Conn, pt string) {
	rows, res := checkedResult(db.Query("select full_result from risks_check_history where apk='%s' ORDER BY id DESC Limit 1", pt))
	full_result := res.Map("full_result")
	for _, row := range rows {
		//fmt.Ffmt.Printlnf(w,
		fmt.Fprintf(w,
			"------[ %s 包含以下风险]---------\n%s\n",
			pt,
			row.Str(full_result),
		)
		RightLine()
	}
}
func (m MySQLPlugin) fetchShowInnodbStatus(db mysql.Conn, stat map[string]float64) error {
	row, _, err := db.QueryFirst("SHOW /*!50000 ENGINE*/ INNODB STATUS")
	if err != nil {
		log.Fatalln("FetchMetrics (InnoDB Status): ", err)
		return err
	}

	if len(row) > 0 {
		parseInnodbStatus(string(row[len(row)-1].([]byte)), &stat)
	} else {
		log.Fatalln("FetchMetrics (InnoDB Status): row length is too small: ", len(row))
	}
	return nil
}
Example #16
0
func (m MySQLPlugin) fetchShowSlaveStatus(db mysql.Conn, stat map[string]float64) error {
	rows, res, err := db.Query("show slave status")
	if err != nil {
		log.Fatalln("FetchMetrics (Slave Status): ", err)
		return err
	}

	for _, row := range rows {
		idx := res.Map("Seconds_Behind_Master")
		Value := row.Int(idx)
		stat["Seconds_Behind_Master"] = float64(Value)
	}
	return nil
}
// Get the column list for the SELECT, applying the select map
// from config file.
func getColumnListForSelect(db mysql.Conn, table string) string {
	columns := make([]string, 0)
	rows, res, err := db.Query("SHOW COLUMNS FROM `%s`", table)
	checkError(err)
	for _, row := range rows {
		column := row.Str(res.Map("Field"))
		replacement, ok := selectMap[table][column]
		if ok {
			column = fmt.Sprintf("%s AS `%s`", replacement, column)
		}
		columns = append(columns, column)
	}
	return strings.Join(columns, ", ")
}
Example #18
0
func deleteMySqlCelRecord(db mysql.Conn, uniqueid string) (err error) {

	if config.PurgeCelEvents == false {
		return nil
	}

	var query = fmt.Sprintf("DELETE FROM cel WHERE uniqueid = '%s' OR linkedid = '%s'", uniqueid, uniqueid)
	_, _, err = db.Query(query)

	log.Debugf("getMySqlCallDetails execute : [%s] .\n", query)

	if err != nil {
		log.Errorf("deleteMySqlCelRecord Failed delete record into cel table for uniqueid [%s].\n", uniqueid)
	}
	return err
}
Example #19
0
//Execute customize requests provisted by configuration file
func executeCustomRequests(db mysql.Conn) (err error) {
	for i := range config.CleanupRequests {
		var query = config.CleanupRequests[i]

		if strings.Contains(strings.ToLower(query), "delete") == true {
			return errors.New("Using delete keyword is forbiden. Please check your configuration file(config.json)")
		}
		_, _, err = db.Query(query)

		if err != nil {
			return err
		}

	}
	return nil
}
Example #20
0
func (mydb *MysqlDatabase) DatabaseExists(db mysql.Conn) (bool, error) {
	rows, _, err := db.Query(
		"SELECT count(*) AS dbs FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '%v'",
		mydb.Name,
	)
	if err != nil {
		return false, err
	}

	if len(rows) != 1 {
		return false, errors.New("Unexpected number of rows in DatabaseExists()")
	}

	if rows[0].Int(0) > 0 {
		return true, nil
	}
	return false, nil
}
Example #21
0
// Allocates a new transaction
func NewTransaction(connection mysql.Conn, query TransactionQuery) (*Transaction, error) {
	if len(query.Columns) < 1 {
		return nil, transactionError{"Too few columns"}
	}

	sss := fmt.Sprintf("INSERT IGNORE INTO `%s`.`%s` (`%s`) VALUES (?%s)", query.Database, query.Table, strings.Join(query.Columns, "`, `"), strings.Repeat(", ?", len(query.Columns)-1))
	ins, err := connection.Prepare(sss)
	if err != nil {
		return nil, err
	}

	trans, err := connection.Begin()
	if err != nil {
		return nil, err
	}

	return &Transaction{trans.Do(ins), trans, len(query.Columns)}, nil
}
func (m MySQLPlugin) fetchShowVariables(db mysql.Conn, stat map[string]float64) error {
	rows, _, err := db.Query("SHOW VARIABLES")
	if err != nil {
		log.Fatalln("FetchMetrics (Variables): ", err)
	}

	for _, row := range rows {
		if len(row) > 1 {
			variableName := string(row[0].([]byte))
			if err != nil {
				log.Println("FetchMetrics (Fetch Variables): ", err)
			}
			stat[variableName], _ = atof(string(row[1].([]byte)))
		} else {
			log.Fatalln("FetchMetrics (Variables): row length is too small: ", len(row))
		}
	}
	return nil
}
Example #23
0
func (mu *MysqlUser) UserExists(db mysql.Conn) (bool, error) {
	rows, _, err := db.Query(
		"SELECT COUNT(*) FROM mysql.user WHERE User = '******' and Host = '%v' and Password = password('%v')",
		mu.Username,
		mu.Hostname,
		mu.Password,
	)
	if err != nil {
		return false, err
	}

	if len(rows) != 1 {
		return false, errors.New("Unexpected number of rows in UserExists()")
	}

	if rows[0].Int(0) > 0 {
		return true, nil
	}

	return false, nil
}
Example #24
0
func SlaveStatus(db mysql.Conn, cfg *base.Cfg) ([]*model.MetaData, error) {
	isSlave := model.NewMetric("Is_slave", cfg)
	row, res, err := db.QueryFirst("SHOW SLAVE STATUS")
	if err != nil {
		return nil, err
	}

	// be master
	if row == nil {
		isSlave.SetValue(0)
		isSlave.Tags = fmt.Sprintf("%s,role=%s", isSlave.Tags, "master")
		return []*model.MetaData{isSlave}, nil
	}

	// be slave
	isSlave.SetValue(1)
	isSlave.Tags = fmt.Sprintf("%s,role=%s", isSlave.Tags, "slaver")

	data := make([]*model.MetaData, len(SlaveStatusToSend))
	for i, s := range SlaveStatusToSend {
		data[i] = model.NewMetric(s, cfg)
		switch s {
		case "Slave_SQL_Running", "Slave_IO_Running":
			data[i].SetValue(0)
			v := row.Str(res.Map(s))
			if v == "Yes" {
				data[i].SetValue(1)
			}
		default:
			v, err := row.Int64Err(res.Map(s))
			if err != nil {
				data[i].SetValue(-1)
			} else {
				data[i].SetValue(v)
			}
		}
	}
	return append(data, isSlave), nil
}
Example #25
0
/**
 * Process selection CEL events for given unique id
 */
func getMySqlCel(db mysql.Conn, uniqueid string) (cel Cel, err error) {
	myCelQuery := "select UNIX_TIMESTAMP(eventtime) as eventtime from cel where eventtype LIKE 'ANSWER' AND linkedid!=uniqueid AND linkedid='" + uniqueid + "'"
	//
	rows, res, err := db.Query(myCelQuery)
	if err != nil {
		return cel, err
	}

	log.Tracef("getMySqlCel request executed and get [%d] rows\r\n", len(rows))

	if len(rows) > 0 {
		log.Tracef("getMySqlCel get rows for uniqueid [%s]", uniqueid)
		row := rows[0]
		eventtime := res.Map("eventtime")
		cel.EventTime = row.Int64(eventtime)
	} else {
		log.Tracef("getMySqlCel faied to get rows for uniqueid [%s].", uniqueid)
		cel.EventTime = 0
	}

	return cel, nil
}
Example #26
0
func mysqlState(m *MysqlIns, db mysql.Conn, sql string) ([]*MetaData, error) {
	rows, _, err := db.Query(sql)
	if err != nil {
		return nil, err
	}

	data := make([]*MetaData, len(rows))
	i := 0
	for _, row := range rows {
		key_ := row.Str(0)
		v, err := row.Int64Err(1)
		// Ignore non digital value
		if err != nil {
			continue
		}

		data[i] = NewMetric(key_)
		data[i].SetValue(v)
		i++
	}
	return data[:i], nil
}
Example #27
0
func (m MySQLPlugin) FetchShowStatus(db mysql.Conn, stat map[string]float64) error {
	rows, _, err := db.Query("show /*!50002 global */ status")
	if err != nil {
		log.Fatalln("FetchMetrics (Status): ", err)
		return err
	}

	for _, row := range rows {
		if len(row) > 1 {
			Variable_name := string(row[0].([]byte))
			if err != nil {
				log.Fatalln("FetchMetrics (Status Fetch): ", err)
				return err
			}
			//fmt.Println(Variable_name, Value)
			stat[Variable_name], _ = _atof(string(row[1].([]byte)))
		} else {
			log.Fatalln("FetchMetrics (Status): row length is too small: ", len(row))
		}
	}
	return nil
}
Example #28
0
func slaveStatus(m *MysqlIns, db mysql.Conn) ([]*MetaData, error) {

	isSlave := NewMetric("Is_slave")

	row, res, err := db.QueryFirst("SHOW SLAVE STATUS")
	if err != nil {
		return nil, err
	}

	// be master
	if row == nil {
		isSlave.SetValue(0)
		return []*MetaData{isSlave}, nil
	}

	// be slave
	isSlave.SetValue(1)

	data := make([]*MetaData, len(SlaveStatusToSend))
	for i, s := range SlaveStatusToSend {
		data[i] = NewMetric(s)
		switch s {
		case "Slave_SQL_Running", "Slave_IO_Running":
			data[i].SetValue(0)
			v := row.Str(res.Map(s))
			if v == "Yes" {
				data[i].SetValue(1)
			}
		default:
			v, err := row.Int64Err(res.Map(s))
			if err != nil {
				data[i].SetValue(-1)
			} else {
				data[i].SetValue(v)
			}
		}
	}
	return append(data, isSlave), nil
}
Example #29
0
func (this *DataModule) AccountloginToo(param *acc.LoginPlayer_MA, itbid int32, conn mysql.Conn) *AccParams {
	str := fmt.Sprintf(`set @iisfcm = %d`, 1)
	res, err := conn.Start(str)
	if err != nil {
		fmt.Println("存储过程调用失败", err.Error())
	}

	str = fmt.Sprintf(`set @iserverid = %d`, 0)
	res, err = conn.Start(str)
	if err != nil {
		fmt.Println("存储过程调用失败", err.Error())
	}

	str = fmt.Sprintf(`call mfxy_accountlogin(%d,'%s','%s','%s','%s',@iserverid,%d,%d,%d,@iisfcm,@ifcmtime,@iaccid,@igmlevel,@igamepoints,@szprotectques,@szprotectansw,@iretval)`,
		itbid, *param.SzAccount, *param.SzPassword, *param.SzIp, "haha", *param.ProductId, *param.PlatformId, *param.LoginType)
	fmt.Println(str)
	res, err = conn.Start(str)
	if err != nil {
		fmt.Println("存储过程调用失败", err.Error())
	}

	str = fmt.Sprintf(`select @iserverid,@iisfcm,@ifcmtime,@iaccid,@igmlevel,@igamepoints,@szprotectques,@szprotectansw,@iretval`)
	fmt.Println(str)
	res, err = conn.Start(str)
	if err != nil {
		fmt.Println("存储过程调用失败", err.Error())
	}

	row, _ := res.GetRow()

	repParams := new(AccParams)
	repParams.Serverid = uint64(row.Int(0))
	repParams.Isfcm = uint32(row.Int(1))
	repParams.Ifcmtime = uint64(row.Int64(2))
	repParams.Accid = uint64(row.Int64(3))
	repParams.Gmlevel = uint32(row.Int(4))
	repParams.Points = uint64(row.Int(5))
	repParams.Productid = uint64(row.Int64(6))
	repParams.Protectansw = row.Str(7)
	repParams.Iretval = int32(row.Int(8))
	fmt.Println("datamodul end")
	return repParams
}
// Get the table data
func dumpTableData(w io.Writer, db mysql.Conn, table string) {
	fmt.Fprintf(w, "\n--\n-- Dumping data for table `%s`\n--\n\n", table)

	rowCnt, _, err := db.QueryFirst(getSelectCountQueryFor(db, table))
	checkError(err)
	if rowCnt.Int(0) == 0 {
		fmt.Fprintf(w, "--\n-- Empty table\n--\n\n")
		return
	} else {
		fmt.Fprintf(w, "--\n-- %d rows\n--\n\n", rowCnt.Int(0))
	}

	fmt.Fprintf(w, "LOCK TABLES `%s` WRITE;\n", table)
	query := fmt.Sprintf("INSERT INTO `%s` VALUES", table)
	rows := make([]string, 0)

	res, err := db.Start(getSelectQueryFor(db, table))
	checkError(err)
	row := res.MakeRow()

	for {
		err = res.ScanRow(row)
		if err == io.EOF {
			break
		}
		checkError(err)

		vals := make([]string, 0)
		for k, col := range row {
			val := "NULL"
			if col != nil {
				val = fmt.Sprintf("'%s'", db.EscapeString(row.Str(k)))
			}
			vals = append(vals, val)
		}

		rows = append(rows, fmt.Sprintf("( %s )", strings.Join(vals, ", ")))
		if len(rows) >= 100 {
			fmt.Fprintf(w, "%s\n%s;\n", query, strings.Join(rows, ",\n"))
			rows = make([]string, 0)
		}
	}

	if len(rows) > 0 {
		fmt.Fprintf(w, "%s\n%s;\n", query, strings.Join(rows, ",\n"))
	}

	fmt.Fprintf(w, "\nUNLOCK TABLES;\n")
}