I'm hosting an Aurora MySql instance on AWS and trying to read a table from it on a Lambda function.
This is my connection string:
Server=xxx.xxx.xxx4.xxx; port=3306; database=thedatabase; uid=theuser; pwd=thepassword; Connect Timeout=300
This is the code (.Net Core 2.1):
private static void GetFromDb()
{
LambdaLogger.Log($"Function name GetFromDb() has been called.\n");
int counter = 0;
try
{
LambdaLogger.Log($"Using {str}\n");
using (MySqlConnection conn = new MySqlConnection(str))
{
LambdaLogger.Log($"Connection is about to be opened\n");
conn.Open();
LambdaLogger.Log($"Connection was opened\n");
var text = "SELECT * FROM MarketPlace.Customers";
using (MySqlCommand cmd = new MySqlCommand(text, conn))
{
cmd.CommandTimeout = 360;
var reader = cmd.ExecuteReader();
LambdaLogger.Log($"Command was issued\n");
if (reader.HasRows)
{
LambdaLogger.Log($"reader has rows\n");
products = new List<Product>();
while (reader.Read())
{
counter++;
LambdaLogger.Log($"Reading # {counter}\n");
Product p = new Product();
p.Id = reader.GetInt32(0);
p.Name = reader.GetString(1);
products.Add(p);
}
}
reader.Close();
LambdaLogger.Log($"{counter} items readed");
}
}
}
catch (Exception ex)
{
throw new Exception($"[GetFromDb] Error {ex.ToString()}", ex);
}
}
When try to open the connection, code stops executing, no exception is caught or raised.
Log from CloudWatch:
START RequestId: 52225968-d360-4d27-8872-305e4b92e346 Version: $LATEST
...
...
Function name GetFromDb() has been called.
Using Server=xxx.xxx.xxx4.xxx; port=3306; database=thedatabase; uid=theuser; pwd=thepassword; Connect Timeout=300
Connection is about to be opened
END RequestId: 52225968-d360-4d27-8872-305e4b92e346
REPORT RequestId: 52225968-d360-4d27-8872-305e4b92e346 Duration: 30030.17 ms Billed Duration: 30000 ms Memory Size: 256 MB Max Memory Used: 107 MB Init Duration: 207.87 ms
2019-12-12T18:23:58.089Z 52225968-d360-4d27-8872-305e4b92e346 Task timed out after 30.03 seconds
I'm really stuck here. I don't have any idea of what is happening. Roles, policies, etc. are ok.
The strange thing is despite connection timeout is set to 300 seconds, it takes less the this to stop running.
Any help would be appreciated. Thanks in advance.
A timeout is usually an indication of network connectivity issues.
Assumption:
The AWS Lambda function is configured to use the same VPC as the Aurora instance
Your Security Group configurations should be:
A Security Group on the Lambda function (Lambda-SG) — Allow all Outbound
A Security Group on the Aurora database (Aurora-SG) — Allow inbound connections on the appropriate port (3306?) from Lambda-SG
That is, Aurora-SG specifically allows inbound traffic from Lambda-SG.
Related
The state of the connection stays active in pool, when there is an exception while executing a query or stored procedure through c#.
The Npgsql version that I am using is 4.1.7.
Here is the code that I am trying to execute.
NpgsqlCommand cmd = null;
NpgsqlDataAdapter sda = null;
NpgsqlConnection conn = null;
try {
string sql = "a_test";
conn = new NpgsqlConnection("Server=localhost;Port=5432;Username=admin;Password=test;Database=majordb;SearchPath=dbs;CommandTimeout=300;MaxPoolSize=500;Connection Idle Lifetime=180;Connection Pruning Interval=5;");
cmd = new NpgsqlCommand(sql);
cmd.CommandType = CommandType.StoredProcedure;
sda = new NpgsqlDataAdapter(cmd);
cmd.Connection = conn;
sda.Fill(dataTable);
}
catch (Exception e) {
//log
}
finally {
if(null != sda)
{
try
{
sda.Dispose();
}
catch (Exception)
{
}
}
try
{
cmd.Connection.Close();
cmd.Connection.Dispose();
}
catch (Exception)
{
}
try
{
cmd.Dispose();
}
catch (Exception)
{
}
}
If the above code executes properly without any exception, the connection state in pool goes to idle, which is correct. But if an exception occurs while executing, like below:
"Npgsql.NpgsqlException (0x80004005): Exception while reading from stream --->
System.IO.IOException: Unable to read data from the transport connection: A connection attempt
failed because the connected party did not properly respond after a period of time, or established
connection failed because connected host has failed to respond."
The connection state in pool shows as active for about 5 mins or so, even though the close/dispose methods are called in finally block. This means the close/dispose did not properly executed by Npgsql. If the program keeps the connection state in pool active for every connection ran within 5 mins, then there can be an issue with MaxPoolSize error.
I wanted to see the connection state to idle, even when there is an exception. How do I do this.
Please note: I am not looking for a solution to the exception that I listed above. I am looking for a solution where the connection state is changed to idle from active when there is an exception while executing the above code.
To know if the connection state is active or not I used the following query:
SELECT
pid,
usename,
application_name,
datname,
client_addr,
rank() over (partition by client_addr order by backend_start ASC) as rank,
state,
state_change,
current_timestamp,
query,
query_start,
backend_start,
FROM
pg_stat_activity
WHERE
pid <> pg_backend_pid( )
AND
application_name !~ '(?:psql)|(?:pgAdmin.+)'
AND
datname = current_database()
AND
usename = current_user
Any help is really appreciated.
I have been experiencing db transaction timemouts in an ASP.NET 2.0 & SQL Server 2008 application for several days now.
The issue is something using SQL Server profiler tracing to "a function calling web service".
We have transaction include several stored procedure (sp). But stored procedure #3 has some bytes to save in DB, it consumes time. When the time goes over 25 seconds, it throws a timeout exception message:
Message : System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
My code:
using (System.Data.Common.DbConnection connection = o_DB.CreateConnection())
{
connection.Open();
System.Data.Common.DbTransaction o_Transaction = connection.BeginTransaction();
try
{
- exec sp1
- exec sp2
foreach{
- exec sp3
}
}
We tried some solutions in the web but it did not work. I hope someone can give a hand to me. Many Thanks.
We do not have timeout in the connection string in web.config, it does not suffer on exception after 15s (default)
We set the transaction timeout in web.config:
<system.transactions>
<machineSettings maxTimeout="00:00:30" />
</system.transactions>
Something like that
using (var ts = CreateTransactionScope(TimeSpan.FromSeconds(mySecondsVar)))
{
using (System.Data.Common.DbConnection connection = o_DB.CreateConnection())
{
using (IDbTransaction tran = connection.BeginTransaction()) {
try
{
// your code
}
catch {
tran.Rollback();
}
}
}
ts.Complete();
}
If is "ok", the dispose do the commit automatically.
This you can directly handle by code also.
Please see the below code
public DataSet getData(string command)
{
DataSet ds = new DataSet();
string connectionString = ConfigurationManager.ConnectionStrings["TESTDB"].ConnectionString;
using (var conn = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(command, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
conn.Open();
adapt.Fill(ds);
conn.Close();
}
}
return ds;
}
The blow line will change the execution time to infinity or until query execution complete.
cmd.CommandTimeout = 0;
I have a C# project that is working with TCP socket in an asynchronous way.
Every request comes from client and ask question from SQL Server stored procedure, opens and closes a SQL connection after ending of question.
I've used this code:
using (var con = new SqlConnection(setting.ConnectionString))
{
try
{
//some codes (edited)
SqlCommand command = new SqlCommand(con);
command.CommandText = "procedurename1";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#name", sb.ToString()));
SqlDataAdapter adapter = new SqlDataAdapter(command);
try
{
adapter.Fill(dataSet);
}
catch (Exception ex)
{
con.Close();
con.Dispose();
throw ex;
}
finally {
con.Close();
con.Dispose();
}
}
catch(Exception ex)
{}
finally
{
con.close();
con.dispose();
}
}
I've used
netstat -a -n | find /c "1433"
to count SQL connections open and close.
Problem is SQL connections count increases and it rarely decreases and count down.
Main problem, is when my program works under lots of requests about 30 minutes, I get
SqlCommand timeout error (default 30 seconds passed)
and after restarting my C# program, the SqlCommand timeout will be gone.
Is this a problem of my program or SQL Server side?
Remember it always calls a stored procedure in SQL Server, not executing query
directly.
main method:
public void main()
{
Task.Factory.StartNew(() =>
{
allDone.Reset();
mySocket.AcceptAsync(e);
allDone.WaitOne();
});
}
public void e_Completed(object sender, SocketAsyncEventArgs e)
{
var socket = (Socket)sender;
ThreadPool.QueueUserWorkItem(HandleTcpRequest, e.AcceptSocket);
e.AcceptSocket = null;
socket.AcceptAsync(e);
}
public void HandleTcpRequest(object state)
{
//do some code and connection to SQL server
DLL.Request httprequest = new DLL.Request(dataSet.Tables[0], fileDt);
DLL.IHttpContext _context = new DLL.HttpContext(httprequest);
_context.GetResults();
}
Main problem, is when my program works under lots of requests about 30 minutes,
To isolate the root problem of the time-out, I suggest testing the sql query of the stored procedure independent of TCP socket calls for 30 minutes
and log the time-out exception details for inspection
Run the following query within 30 minutes to simulate your working environment:
public void RunQuery()
{
using (var con = new SqlConnection(setting.ConnectionString))
{
try
{
//some codes
}
catch(SqlException ex)
{
//test for timeout
if (ex.Number == -2) {
Console.WriteLine ("Timeout occurred");
// log ex details for more inspection
}
}
}
}
Read How to handle the CommandTimeout properly?
As you use async calls, I suggest you to try to use Asynchronous Database Calls With Task-based Asynchronous Programming Model (TAP)
I'm going to take a long-shot based on the way the limited Sql-related code we can see is written since we can't see "//some codes".
I'm going to guess that some of the disposable things like SqlCommand, DataReader, SqlDataAdapter, TransactionScope, etc are not in 'using' blocks, so are holding resources open on the database.
It may also be worth raising the possibility that this kind of problem could be in the code shown in the question or any other program accessing that database, including your own applications and SSMS (e.g. if a developer has an uncommitted transaction running in a window).
P.S. I would suggest deleting everything in the using block except the "//some codes" part.
UPDATE after more code was added
Here is your code after correction. this will ensure that the resources are disposed, which will prevent the leaking resources that are probably causing your problem.
using (var con = new SqlConnection(setting.ConnectionString))
{
//some codes (edited)
using (SqlCommand command = new SqlCommand(con))
{
command.CommandText = "procedurename1";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#name", sb.ToString()));
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dataSet);
}
}
}
P.S. don't ever write "throw ex;" from inside a catch ever again. It causes the stack trace to be lost - just use "throw;".
[Disclaimer] : I think I have read every stackoverflow post about this already
I have been breaking my head over this for quite some time now. I am getting the following exception in my asp.net web.api.
Exception thrown: 'System.InvalidOperationException' in mscorlib.dll
Additional information: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
Most people suggested that I should look for leaked connections in my application. Here is my code. Now I am sure that I am not leaking any connections
public async Task<IEnumerable<string>> Get()
{
var ds = new DataSet();
var constring = "Data Source=xxx;Initial Catalog=xxx;User Id=xxx;Password=xxx;Max Pool Size=100";
var asyncConnectionString = new SqlConnectionStringBuilder(constring)
{
AsynchronousProcessing = true
}.ToString();
using (var con = new SqlConnection(asyncConnectionString))
using (var cmd = new SqlCommand("[dbo].[xxx]", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#x1", 1);
cmd.Parameters.AddWithValue("#x2", "something");
await con.OpenAsync();
using (var rdr =await cmd.ExecuteReaderAsync())
{
if (rdr.HasRows)
{
ds.Load(rdr, LoadOption.OverwriteChanges, "MyTable");
}
rdr.Close();
con.Close();
ds.Dispose();
}
}
//I know this looks wrong, just an empty api method to show the code
return new string[] { "value1", "value2" };
}
The exception does not occur when I am using my local Sql Server. Only happens when I connect to our 'test server'. Are there anything else I can look at when trying resolve this issue. Like Sql server settings / network settings etc.
The stored procedure I call does not lock up the db I have checked for that as well. If that was the case it should have failed on my local Sql instance as well.
I am using jmeter to generate load, 1500 - threads(users). Surely I should be able to handle way more than that.
Thanks in advance
You have not specified any Connection Time out property, so it's 15 seconds default. using Max Pool Size=100 is not a good idea until you don't have proper hardware resources.
You started 1500 threads, so it seems that the some the threads keep waiting for 15 seconds to get their chance for connection opening. And as time goes out, you get the connection time out error.
So I think increasing the 'Connection Timeout' property in connection string may resolve your issue.
I am getting this error when I try to get all the username password from production copied local database, I guess it is because of not closing the connection properly, but I am not sure how . I am using the Microsoft Enterprise Library, ant thought or comment about it?
Timeout expired. The timeout period elapsed prior to
obtaining a connection from the pool. This may have occurred
because all pooled connections were in use and max pool size was reached.
this is the mothod that is getting the username and password and producing the error.
private Model.UsernameandPass GetUsernamePass(string AccountNumber)
{
Model.UsernameandPass model = null;
string myConnection = System.Configuration.ConfigurationManager.ConnectionStrings[connectionName].ToString();
SqlDatabase db = new SqlDatabase(myConnection);
using (DbCommand command = db.GetStoredProcCommand("Get_TheUsernamePassWordFromProduction"))
{
db.AddInParameter(command, "AccountNumber", DbType.String, AccountNumber);
var result = db.ExecuteReader(command);
try
{
while (result.Read())
{
model = new Model.UsernameandPass();
model.Username = result.GetString(1);
model.Password = result.GetString(2);
}
}
catch (Exception ex)
{
}
}
db = null;
return model;
}
I am getting the error in this line after program runs for a while.
var result = db.ExecuteReader(command);
You're getting that error because a connection cannot be established, not only because they aren't being closed properly. Check permissions for the user you're trying to authenticate against the database with. Also be sure to call .open()/.close() when/if you are programatically opening/closing connections.
Check this link. You may want to increase your pool size, or check for long-running queries.