mysql icon indicating copy to clipboard operation
mysql copied to clipboard

packets.go errors

Open dalerobbins opened this issue 11 years ago • 16 comments

I'm getting many errors from packets.go when running apache ab against a go web server that connects to a mysql database. These errors happen when load testing my go server.

Note: in the errors shown below, the routes.go errors are from my own code error handlers. My MySQL server is configured to handle more than the default concurrrent connections so that isn't the issue.

Errors:

2015/07/13 09:30:10.029531 routes.go:521: Bad Request: dial tcp 127.0.0.1:3306: connection refused [USER: xxxx, PASSWORD: xxxx], Remote IP: 192.168.1.100:51940 [MySQL] 2015/07/13 09:30:10 packets.go:32: unexpected EOF [MySQL] 2015/07/13 09:30:10 packets.go:32: read tcp 127.0.0.1:3306: connection reset by peer [MySQL] 2015/07/13 09:30:12 packets.go:118: write tcp 127.0.0.1:3306: broken pipe

The errors shown above happen multiple times during a load test, specifically the unexpected EOF error. During these errors, the CPU load is very high.

dalerobbins avatar Jul 13 '15 17:07 dalerobbins

Can you narrow down how to reproduce this? A load test is pretty broad.

When I had intermittent errors and was trying to find a way to reproduce, I found it helpful to set both SetMaxIdleConns() and SetMaxOpenConns() to 1 so errors surfaced immediately instead of getting lost in a pool until a connection got reused.

PuppyKhan avatar Jul 13 '15 19:07 PuppyKhan

I load test with apache ab:

ab -l -r -n 4000 -c 4000 -s 60 -H "Cookie: name=someusername;password=userpassword" http://192.168.1.100:3000/

My go http server simply checks for a user in mysql from the supplied cookies. My project requires supporting a high level on concurrent connections. Since these connections to my go server are stateless, the go server establishes a new mysql connection for each http request, does it's thing and closes that mysql connection for the current http request. That's it in a nutshell. I have also brought down the number of concurrent connections with the ab test and the same results occur.

dalerobbins avatar Jul 13 '15 20:07 dalerobbins

Could you provide a code example that triggers this error?

PuppyKhan avatar Jul 13 '15 20:07 PuppyKhan

func GetUserNamePassword(name, password string) (string, error) {
    var (
        err     error
        dbname  = settings.GetSetting("dbName")
        dbuser  = settings.GetSetting("dbUser")
        dbpass  = settings.GetSetting("dbPass")
        retName string
        retPass string
    )

    // Check for db settings
    if (dbname == "") || (dbuser == "") || (dbpass == "") {
        err = errors.New("Invalid database settings")
        return "", err
    }

    // Get db connection handle
    db, err := sql.Open("mysql", dbuser+":"+dbpass+"@/"+dbname)
    if err != nil {
        return "", err
    }
    defer db.Close()

    // Query for user name and password
    rows, err := db.Query("select name, password from users where name = '" + name + "' and password = '" + password + "'")
    if err != nil {
        return "", err
    }
    defer rows.Close()

    // Get returned row if any
    hasRow := rows.Next()
    if !hasRow {
        // no rows, none existing user
        return "", errors.New("db: no user found")
    }
    err = rows.Scan(&retName, &retPass)
    if err != nil {
        return "", err
    }

    return retName, nil
}

The code above is called with name and password supplied from cookies sent with a http request, this function is verifying an existing user.

dalerobbins avatar Jul 13 '15 20:07 dalerobbins

If you are only checking for one row, you should use QueryRow(). When using rows.Next(), you should loop through until it fails, then you also need to check for rows.Err() afterwards.

See if that gives you a more specific cause of the error.

PuppyKhan avatar Jul 13 '15 21:07 PuppyKhan

Ok, will try that and see what happens. Thanks.

dalerobbins avatar Jul 13 '15 21:07 dalerobbins

func GetUserNamePassword(name, password string) (string, error) {
    var (
        err     error
        dbname  = settings.GetSetting("dbName")
        dbuser  = settings.GetSetting("dbUser")
        dbpass  = settings.GetSetting("dbPass")
        retName string
        retPass string
    )

    // Check for db settings
    if (dbname == "") || (dbuser == "") || (dbpass == "") {
        err = errors.New("Invalid database settings")
        return "", err
    }

    // Get db connection handle
    db, err := sql.Open("mysql", dbuser+":"+dbpass+"@/"+dbname)
    if err != nil {
        return "", err
    }
    defer db.Close()

    err = db.QueryRow("select name, password from users where name = '" + name + "' and password = '" + password + "'").Scan(&retName, &retPass)
    switch {
    case err == sql.ErrNoRows:
        return "", errors.New("db: no user found")

    case err != nil:
        return "", err
    }

    return retName, nil
}

Using the new code above achieves the same results from previously, still get lot's of packets.go:32: unexpected EOF messages. The MySQL server is set at 25000 for max_connections and running the ab test with 10000 concurrent connections still produces the errors and 80-90 CPU load. Before I posted here about this error condition the test would sometimes run fine with the 10000-15000 concurrent connections from apache bench and much lower CPU load.

dalerobbins avatar Jul 13 '15 22:07 dalerobbins

Wait, Are you attempting to sql.Open() on every API call? That should be opened once as your app is initialized, and then the API calls use the db object which manages the connection pool. Otherwise you are trying to spin up 10000 concurrent db pools, not concurrent connections.

Also, db statements either get prepared explicitly by you, or implicitly when you call db.QueryRow() doubling each of the connections to query the db. And without prepared statements SQL injection attacks become much easier even with sanitizing your data.

PuppyKhan avatar Jul 13 '15 22:07 PuppyKhan

I see your point, didn't realize that. I'll redo some code and open a permanent connection in a go init() function of my package then use the db object for all http requests coming in. Will let you know what happens. Wonder how to handle any lost connection issues after doing this as there will be long idle times in the app.

dalerobbins avatar Jul 13 '15 22:07 dalerobbins

var (
    err error
    db  *sql.DB

    dbname string
    dbuser string
    dbpass string
)

// Gets called once before using the database for http requests
func OpenDB() error {
    dbname = settings.GetSetting("dbName")
    dbuser = settings.GetSetting("dbUser")
    dbpass = settings.GetSetting("dbPass")
    // Check for db settings
    if (dbname == "") || (dbuser == "") || (dbpass == "") {
        err = errors.New("Invalid database settings")
        return err
    }

    // Get db connection handle
    db, err = sql.Open("mysql", dbuser+":"+dbpass+"@/"+dbname)
    if err != nil {
        return err
    }

    return nil
}

// Gets called before server terminates
func CloseDB() {
    db.Close()
}

// Returns requested user record or error (name, error)
func GetUserNamePassword(name, password string) (string, error) {
    var (
        retName string
        retPass string
    )

    err = db.QueryRow("select name, password from users where name = '"+name+"' and password = '"+password+"'").Scan(&retName, &retPass)
    switch {
    case err == sql.ErrNoRows:
        return "", errors.New("db: no user found")

    case err != nil:
        return "", err
    }

    return retName, nil
}

Still get the same errors. I'm opening a MySQL connection one time that gets stored in a package variable. All calls to GetUserNamePassword(name, password string) happen for each http request. The MySQL connection is closed when my server terminates. Don't know what else to do. If nothing else I can just interface to the MySQL C library from go. Appreciate the help. I'm willing to give a few more things a try before I move my efforts to the C library. Let me know, would like to help get go-sql-driver working.

dalerobbins avatar Jul 13 '15 23:07 dalerobbins

screenshot from 2015-07-13 16 32 14

Screenshot shows CPU load during test of simple sql query with 15000 concurrent connections running from apache bench.

dalerobbins avatar Jul 13 '15 23:07 dalerobbins

screenshot from 2015-07-13 20 29 48

~~Looks like the MySQL server needed to have back_log increased from it's default of 50. I set this to 1000 and the load test seems to be working fine and completes roughly in 6 seconds for 15000 concurrent connections. Just a little tweaking to the MySQL server needed to handle the burst.~~

After testing again and rebooting the laptop, the same problem is still there. I have tried increasing the back_log in my.cnf to a few more 1000 but no good.

dalerobbins avatar Jul 14 '15 03:07 dalerobbins

After adding a mutex to the GetUserNamePassword function, all is good. Test completes with no db errors within 4 sec's and 20000 concurrent connections. Forgot that each http request is being handled by a go routine hidden within http. In my case I'm using github.com/julienschmidt/httprouter.

Thanks for the tips to PuppyKhan. Problem solved.

dalerobbins avatar Jul 14 '15 07:07 dalerobbins

Calling QueryRow() should not require locking. I think this not so much solves the problem as avoids it

PuppyKhan avatar Jul 14 '15 16:07 PuppyKhan

package database

import (
    "database/sql"
    "errors"
    _ "github.com/go-sql-driver/mysql"
    "httpserver/modules/settings"
    "sync"
)

var (
    err     error
    db      *sql.DB
    dbMutex = new(sync.RWMutex)

    dbname string
    dbuser string
    dbpass string
)

// Called once for the running instance
func OpenDB() error {
    dbname = settings.GetSetting("dbName")
    dbuser = settings.GetSetting("dbUser")
    dbpass = settings.GetSetting("dbPass")
    // Check for db settings
    if (dbname == "") || (dbuser == "") || (dbpass == "") {
        err = errors.New("Invalid database settings")
        return err
    }

    // Get db connection handle
    db, err = sql.Open("mysql", dbuser+":"+dbpass+"@/"+dbname)
    if err != nil {
        return err
    }

    return nil
}

// Called before instance shutdown
func CloseDB() {
    db.Close()
}

// Returns requested user record or error (name, error)
func GetUserNamePassword(name, password string) (string, error) {
    var (
        retName string
        retPass string
    )

    dbMutex.Lock()
    defer dbMutex.Unlock()

    err = db.QueryRow("select name, password from users where name = '"+name+"' and password = '"+password+"'").Scan(&retName, &retPass)
    switch {
    case err == sql.ErrNoRows:
        return "", errors.New("db: no user found")

    case err != nil:
        return "", err
    }

    return retName, nil
}

I understand, here is the complete source to the current package I'm using so far for MySQL access from a http handler. I'd like to know why I get so many errors when I don't use the mutex. I've even run my bash script twice executing ab twice to get 40000 hits on my go server and the test completes fine in 8 sec's. This is repeatable even after rebooting. CPU load is also reasonable. Without the mutex, the test takes longer with errors from thousands of EOF errors and refused connection errors coming from packets.go and high CPU load. Having given the whole actual code to what I'm doing here minus the http router part, I'd like to know if anyone else can reproduce the problem.

dalerobbins avatar Jul 14 '15 17:07 dalerobbins

@dalerobbins You need to call SetMaxOpenConns and set a reasonable max. The default is unlimited (or rather, not limited). You need to configure this to a reasonable number. Your mutex is limiting the http requests to a single db connection. --- Beyond that - and you should be able to get pretty far by just doing that - you can scale horizontally by spinning up more instances w/ a load balancer in-front.

This project is far from abandoned. Last commit was 24 days ago w/ 11 issues open. This issue was opened ~24 hours ago. Emailing every author more than desperate. Rude even. If you need an immediate response the #go-nuts room on irc.freenode.net is a great resource. Stackoverflow is also great for fast responses.

lukescott avatar Jul 14 '15 20:07 lukescott