Number of mysql user Connections in a date range - mysql

Have a database. How can I get the total number of connections for a user?
e,g database name: north_wind
database user: smuwanga
How do I know that smuwanga made 200 connections to the database in the last 3 months?
Regards,
Simon.

MySQL does not keep a connection log by default. However, if you want to find out current connections and users, you can use SHOW FULL PROCESSLIST.
If you still insist on logging user connections, you may want to check out this blog post with steps on how you can accomplish that.

I managed to get my way around it.
I did a grep 'mysql_username' /path/to/mysql.log |grep Connect | wc -l
Its seems when installing mysql I left everything as default.

Related

Lost connection to MySQL server during query on random simple queries

FINAL UPDATE: We fixed this problem by finding a way to accomplish our goals without forking. But forking was the cause of the problem.
---Original Post---
I'm running a ruby on rails stack, our mysql server is separate, but housed at the same site as our app servers. (we've tried swapping it out for a different mysql server with double the specs, but no improvement was seen.
during business hours we get a handful of these from no particular query.
ActiveRecord::StatementInvalid: Mysql2::Error: Lost connection to MySQL server during query
most of the queries that fail are really simple, and there seems to be no pattern between one query and another. This all started when I upgraded from Rails 4.1 to 4.2.
I'm at a loss as to what to try. Our database server is less than 5% CPU throughout the day. I do get bug reports from users who have random interactions fail due to this, so it's not queries that have been running for hours or anything like that, of course when they retry the exact same thing it works.
Our servers are configured by cloud66.
So in short: our mysql server is going away for some reason, but it's not because of lack of resources, it's also a brand new server as we migrated from another server when this problem started.
this also happens to me on localhost while developing features sometimes, so I don't believe it's a load issue.
We're running the following:
ruby 2.2.5
rails 4.2.6
mysql2 0.4.8
UPDATE: per the first answer below I increased our max_connections variable to 500 last night, and confirmed the increase via
show global variables like 'max_connections';
I'm still getting dropped connection, the first one today was dropped only a few minutes ago....
ActiveRecord::StatementInvalid: Mysql2::Error: Lost connection to MySQL server during query
I ran select * from information_schema.processlist; and I got 36 rows back. Does this mean my app servers were running 36 connections at that moment? or can a process be multiple connections?
UPDATE: I just set net_read_timeout = 60 (it was 30 before) I'll see if that helps
UPDATE: It didn't help, I'm still looking for a solution...
Heres my Database.yml with credentials removed.
production:
adapter: mysql2
encoding: utf8
host: localhost
database:
username:
password:
port: 3306
reconnect: true
The connection to MySQL can be disrupted by a number of means, but I would recommend revisiting Mario Carrion's answer since it's a very wise answer.
It seems likely that connection is disrupted because it's being shared with the other processes, causing communication protocol errors...
...this could easily happen if the connection pool is process bound, which I believe it is, in ActiveRecord, meaning that the same connection could be "checked-out" a number of times simultaneously in different processes.
The solution is that database connections must be established only AFTER the fork statement in the application server.
I'm not sure which server you're using, but if you're using a warmup feature - don't.
If you're running any database calls before the first network request - don't.
Either of these actions could potentially initialize the connection pool before forking occurs, causing the MySQL connection pool to be shared between processes while the locking system isn't.
I'm not saying this is the only possible reason for the issue, as stated by #sloth-jr, there are other options... but most of them seem less likely according to your description.
Sidenote:
I ran select * from information_schema.processlist; and I got 36 rows back. Does this mean my app servers were running 36 connections at that moment? or can a process be multiple connections?
Each process could hold a number of connections. In your case, you might have up to 500X36 connections. (see edit)
In general, the number of connections in the pool can often be the same as the number of threads in each process (it shouldn't be less than the number of thread, or contention will slow you down). Sometimes it's good to add a few more depending on your application.
EDIT:
I apologize for ignoring the fact that the process count was referencing the MySQL data and not the application data.
The process count you showed is the MySQL server data, which seems to use a thread per connection IO scheme. The "Process" data actually counts active connections and not actual processes or threads (although it should translate to the number of threads as well).
This means that out of possible 500 connections per application processes (i.e., if you're using 8 processes for your application, that would be 8X500=4,000 allowed connections) your application only opened 36 connections so far.
This indicates a timeout error. It's usually a general resource or connection error.
I would check your MySQL config for max connections on MySQL console:
show global variables like 'max_connections';
And ensure the number of pooled connections used by Rails database.yml is less than that:
pool: 10
Note that database.yml reflects number of connections that will be pooled by a single Rails process. If you have multiple processes or other servers like Sidekiq, you'll need to add them together.
Increase max_connections if necessary in your MySQL server config (my.cnf), assuming your kit can handle it.
[mysqld]
max_connections = 100
Note other things might be blocking too, e.g. open files, but looking at connections is a good starting point.
You can also monitor active queries:
select * from information_schema.processlist;
as well as monitoring the MySQL slow log.
One issue may be a long-running update command. If you have a slow-running command that affects a lot of records (e.g. a whole table), it might be blocking even the simplest queries. This means you could see random queries timeout, but if you check MySQL status, the real cause is another long-running query.
Things you did not mention but you should take a look:
Are you using unicorn? If so, are your reconnecting and disconnecting in your after_fork and before_fork?
Is reconnect: true set in your database.yml configuration?
Well,at first glance this sounds like your webserver is keeping the mysql sessions open and sometimes a user runs into a timeout. Try disabling the keep mysql sessions alive.
It will be a hog but you only use 5% ...
other tipps:
Enable the mysql "Slow Query Log" and take a look.
write a short script which pulls and logs the mysql processlist every minute and cross check the log with timeouts
look at the pool size in your db connection or set one!
http://guides.rubyonrails.org/configuring.html#database-pooling
should be equal to the max-connections mysql likes to have!
Good luck!
Find out if your database is limited in terms of multiple connections. Because normally a SQL database is supposed to have more than one active connection.
(Contact your network provider)
Would you mind posting some of your queries? The MySQL documentation has this to say about it:
https://dev.mysql.com/doc/refman/5.7/en/error-lost-connection.html
TL;DR:
Network problems; are any of your boxes renewing leases
periodically, or experiencing other network connection errors
(netstat / ss), firewall timeouts, etc. Not sure how managed your
hosts are by cloud66....
Query timed out. This can happen if you've got commands backed up
behind blocking statements (eg, alters/locking backups on MyISAM
tables). How simple are your queries? No cartesian products in-play?
EXPLAIN query could help.
Exceeding MAX_PACKET_SIZE. Are you storing pictures, video content, etc.?
There are lots of possibilities here, and without more information, will be difficult to pinpoint this.
Would look first at mysql_error.log, then work your way from the DB server back to your application.
UPDATE: this didn't work.
Heres the solution, special thanks to #Myst for pointing out that forking can cause issues, I had no idea to look at this particular code. As the errors seemed random because we forked in this fashion in several places.
It turns out that when I was forking processes, rails was using the same database connection for all forked processes, This created a situation where when one of the processes (the parent process?) terminated the database connection, the remaining process would have its connection interrupted.
The solution was to change this code:
def recalculate_completion
Process.fork do
if self.course
self.course.user_groups.includes(user:[:events]).each do |ug|
ug.recalculate_completion
end
end
end
end
into this code:
def recalculate_completion
ActiveRecord::Base.remove_connection
Process.fork do
ActiveRecord::Base.establish_connection
if self.course
self.course.user_groups.includes(user:[:events]).each do |ug|
ug.recalculate_completion
end
end
ActiveRecord::Base.remove_connection
end
ActiveRecord::Base.establish_connection
end
Making this change stopped the errors from our servers and everything appears to be working well now. If anyone has any more info as to why this worked I would be happy to hear it, as I would like to have a deeper understanding of this.
Edit: it turns out this didn't work either.... we still got dropped connections but not as often.
If you have query cache enabled, please reset it and it should work.
RESET QUERY CACHE;

How to detect what is running on MySQL every hour?

Munin showing huge spike on MySQL queries every hour but I am unable to detect what is causing this. I am running version 5.6.30.
Tried to enable slow running queries but can't find it there.
Also logged all queries and tried to see what is running on that particular time. I cannot find it.
Checked cronjobs but there wasn't anything related
Disabled almost everything on LFD & CSF
The event scheduler status is set to OFF
Is there any other way to find what is running every hour?
Munin graph showing sql queries:
You can use a shell script and put the instruccion "processlist" and send the output to a log file.
Put the delay in seconds that you want for run again the instucction.
while [true];
mysql -h localhost -u root -ppasswd < process
delay xtime
done
And the file processlist you put the instrucction "show full processlist"
I hope this help you
Regards
Some crawlers were mining data from my website. I wasn't able to detect because requests sent from a million different IPs.
Added captcha to website as human control and spikes gone.

Do mysql connection ids always increment, even if lower connections have been terminated?

I'm setting up mysql and have noticed that whenever I connect, the connection id always increments. I thought that might mean the connection I thought had terminated didn't, but when I checked the number of connections using sudo mysqladmin processlist, it only listed the connection needed for that one command.
Normally I would just assume this was normal behavior and ignore it, but I had some problems uninstalling my old/messy installation from back when I didn't know what I was doing. Can anyone verify that this is normal? I tried checking the mysql manual here but it wasn't specific enough to answer my question.
To list all processes running on a MySQL instance state a query like this:
SHOW PROCESSLIST
Each Connection will have a representation here (inactive ones with Command column = Sleep).
As to your question: No, Connection-ids will get re-used and will not increment forever. But you can't rely on the exact way they do so.

Mysql unauthenticated users from specific machine

So one of our developers VMs is desperately trying to connect to our dev mysql server.
Looking at show full processlist shows a number of 'unauthenticated user` lines trying to connect from his specific IP.
Using ps aux | grep httpd I can see where a number of threads from httpd are running but I don't know enough to correlate what I'm seeing in the terminal with a reason his machine (not being touched) continually tries to connect.
I've looked in all crontabs and there's nothing that I can see that would do that.
Is there a way to see all processes trying to connect to a specific IP?
You can use the following to get the processes connecting to a specific ip
#netstat -ant -p | grep "ip:port"
This should give you the list, try cleaning up the processes , then do a differential analysis by disabling the crontab once and enabling them but disabling the httpd processes the next time, maybe this will help.

Locating zombie mySQL connections

I have a colleague who has been using PHP's mysql_pconnect() without my knowing it. We have had a number of instances where connections were denied due to a large number of zombie connections (per our sys admin who is currently not available).
What is the best way from the command line to locate/identify the zombie processes. I have looked at the time columns in ps aux and top but I am not sure I am getting a complete picture.
Thanks.
From MySQL console SHOW FULL PROCESSLIST; and look for these with Sleep in Command column and high values in Time. Then KILL