Memory leak in perl server - multithreading

I'm trying to write a multithreaded server with perl (Windows x64). When trying to connect to it from another computer, I found the memory and handle usage kept going up, even if I maintained only one connection at a time. And after thousands of trials it used up nearly all system memory. I can't figure out the reason.
Here is the server side:
use IO::Socket::INET;
use threads;
sub session_thread
{
my $client_socket=$_[0];
my $client_address = $client_socket->peerhost();
my $client_port = $client_socket->peerport();
print "connection from $client_address:$client_port\n";
my $data = "";
$client_socket->recv($data, 1024);
print "$client_address:$client_port says: $data";
$data = "ok";
$client_socket->send($data);
shutdown($client_socket, 1);
$client_socket->close();
threads->exit();
}
$| = 1;
my $socket = new IO::Socket::INET (
LocalHost => '0.0.0.0',
LocalPort => '7777',
Proto => 'tcp',
Listen => 5,
ReuseAddr => 1
);
die "cannot create socket $!\n" unless $socket;
print "server waiting for client connection on port 7777\n";
while(1)
{
my $client_socket = $socket->accept();
threads->create('session_thread',$client_socket);
}
$socket->close();
Thanks.

You either have to wait for the thread to finish by joining it or tell Perl that you don't care about the thread's return value and that Perl itself should clean up the data once the thread exits. The latter seems to match your use case and is done by detaching.
Also note that using exit is not necessary in your example. You can simply return from the thread's subroutine normally. exit is used for ending a thread from a deeper nesting level within the program.

Related

Perl Socket accept failing in thread on Windows

We've got a Perl system which opens listener sockets, and then spawns threads to actually accept and act on connections. We're running on Windows Server 2008, and running Perl 5.8.8 (it's quite an old system).
(As an aside, this works fine on Linux, where we're using forking - but the implementation of fork on Windows is less than optimal).
We're creating the socket using this code:
use Socket;
...;
unless (
($rSock) = IO::Socket::INET->new(
LocalPort => $aChannelConfig{$sChannel}->{nPort},
Proto => 'tcp',
Type => SOCK_STREAM,
Reuse => 1,
Listen => $aChannelConfig{$sChannel}->{nListen},
)
and $rSock
)
{
$sErrNote = "Cannot create tcp listener socket: sChannel=$sChannel sService=>$aChannelConfig{$sChannel}->{nPort} Err=$!";
}
When the spawned processes come to accept the socket, only the first one works properly.
The problem is that subsequent processes just get undef from IO::Socket::accept - in the core IO::Socket::accept code below, the call to _accept_ returns undef (we're not using timeouts).
sub accept {
#_ == 1 || #_ == 2 or croak 'usage $sock->accept([PKG])';
my $sock = shift;
my $pkg = shift || $sock;
my $timeout = ${*$sock}{'io_socket_timeout'};
my $new = $pkg->new( Timeout => $timeout );
my $peer = undef;
print("!!! in IO::Socket::accept sock=$socket pkg=$pkg timeout=$timeout new=$new\n");
if ( defined $timeout ) {
require IO::Select;
my $sel = new IO::Select $sock;
unless ( $sel->can_read($timeout) ) {
$# = 'accept: timeout';
$! = ( exists &Errno::ETIMEDOUT ? &Errno::ETIMEDOUT : 1 );
return;
}
}
$peer = accept( $new, $sock )
or return;
return wantarray
? ( $new, $peer )
: $new;
}
Presumably we need to do something with the socket options to allow different threads to accept on it.
Can someone give me some pointers please?
Edit
Our call to create a thread is:
my $thr = server::start_thread(\&_start_server_process,$sServerType,$sIcPipe,$rIcSock,'thread');
sub start_thread {
my $thr = threads->create(#_) or return;
return $thr;
}
Edit 2
Log output from successful and unsuccessful calls are as below:
Successful accept:
2014-09-22 08:55:32,575 p:2532.5 e:2532.5 s:OA.2 DEBUG : CADETserver::channel_accept - !!! - TCP socket accept. Channel=oa rH=IO::Socket::INET=GLOB(0x743c4ac)
2014-09-22 08:55:32,635 p:2532.5 e:2532.5 s:OA.2 DEBUG : CADETserver::channel_accept - !!! - TCP socket accept result. Channel=oa $#= $rClient=IO::Socket::INET=GLOB(0x9fb2d3c)
Unsuccessful accept:
2014-09-22 08:55:32,575 p:2532.6 e:2532.6 s:OA.3 DEBUG : CADETserver::channel_accept - !!! - TCP socket accept. Channel=oa rH=IO::Socket::INET=GLOB(0x7aef7d4)
2014-09-22 08:55:32,606 p:2532.6 e:2532.6 s:OA.3 DEBUG : CADETserver::channel_accept - !!! - TCP socket accept result. Channel=oa $#= $rClient=
Note that we're just getting an undef client socket and no error recorded in $#
The code which produced the above log output is below - as you can see, we're just calling accept with no parameters.
my $rH = $rHndlHandles{$sCurrServerType}{$rSock};
$l4p->debug("!!! - TCP socket accept. Channel=$sChannel rH=$rH");
my $rClient;
eval {
local $SIG{__DIE__} = 'IGNORE';
$rClient = $rH->accept();
};
$l4p->debug('!!! - TCP socket accept result. Channel=' . $sChannel . ' $#=' .$# . ' $rClient=' . $rClient );
Interestingly I was looking at whether the problem is how we're setting the socket to non-blocking. Our current code is as follows:
ioctl ($rSock, 0x8004667E, \$temp); # set non-blocking
When I change it to:
use constant FIONREAD => 0x4004667f;
my $numbytes = "\x00" x 4; # pack('L',0) works too
ioctl($rSock, FIONREAD, unpack('I',pack('P',$numbytes)));
my $nbytes = unpack('I',$numbytes);
(with thanks to bitshiftleft on PerlMonks - http://www.perlmonks.org/?node_id=780083)
this allows the sockets to accept OK, but the sockets don't communicate reliably.
So... is it to do with how we're setting the sockets to non-blocking?

Unable to share sockets among threads perl

I am building a multithreaded perl TCP server that uses different threads to handle different clients. For this purpose, I am maintaining a thread pool which keeps track of whether the thread is idle or working.
In the main thread, I open a listening socket and bind to a specific port using:
$socket = new IO::Socket::INET(Localhost => '127.0.0.1',
LocalPort => '5000',
Proto => 'tcp',
Listen => $MAX_THREADS, Reuse => 1) or die "Error in Socket Creation: $!\n";
The main thread also listens to any incoming connections using socket->accept() and if successful passes this return socket to the child thread which handles it and sends an acknowledgement to the client corresponding to the socket. However, I was unable to pass this socket.
I googled a bit and having no luck, later I decided to maintain a global hashmap of incoming sockets which can be later accessed by the child threads(the hashmap is shared) and then work on it.
However perl is giving me an error as to Invalid value for shared scalar. Here is the code bit:
$sochandler->{$tid} = $socket->accept();
#$sochandler is the shared global hashmap with keys as thread IDs
PS: I am newbie to perl and I have tried to explain as much as I can regarding my problem
Here is the subroutine code which is run by every child thread:
sub worker
{
my ($work_q) = #_;
my $tid = threads->tid();
do {
printf("Idle -> %2d\n", $tid);
$IDLE_QUEUE->enqueue($tid);
my $work_tid = $work_q->dequeue();
my $work = $sochandler->{$work_tid};
last if ($work_tid < 0);
printf(" %2d <- Working\n", $tid);
while (($work_tid > 0) && ! $TERM) {
print "Accepted New Client Connection From: $work->peerhost(), $work->peerport()\n";
my $data = "ACK from server";
$work->send($data);
$work->recv($data,1024);
print "Received from Client : $data\n";
}
} while (! $TERM);
printf("Finished -> %2d\n", $tid);
}
The error you are getting is because the $tid is not declared as a shared variable. You need to share 'deep' so that not only is the hash shared, but also its keys.

Killing child thread in Perl cause death of the parent thread

Recently I'm doing a project on Network connections. I'm making the server side program on Perl which handle the request from client, processing, request data from other server. For the multiuser handling purpose I've to use Multitasking. And for not leaking the resource, each thread/connection from client have a limited time out (5 seconds)
Here are my codes:
while(1)
{
# waiting for new client connection.
$client_socket = $socket->accept();
threads->new(\&gotRequest, $client_socket);
#gotRequest($client_socket);
}
This is for Catching the connection from the client
sub gotRequest
{
$client_socket=$_[0];
# $peer_address = $client_socket->peeraddr();
$th1=threads->new(\&Responce, $client_socket);
sleep(5);
if (!($th1->is_running())) {print "Connection terminated\n";}
else
{
print "Operation time out, killing process and terminating connection\n";
print $client_socket "QUIT\n";
close $client_socket;
print "Closing...\n";
#$thr->set_thread_exit_only();
$th1->detach();
$th1->exit(); #This thing causing thread's death
print "Hello I'm still here!";
}
}
This is the thread that manage the processing thread to quit on time otherwise server cant get new connection
sub Responce
{
$client_socket=$_[0];
$peer_address = $client_socket->peeraddr();
$peer_port = $client_socket->peerport();
sleep (10);
print "I'm still alive";
print "Accepted New Client Connection From : $peeraddress, $peerport\n";#Dont know why but this printed null with 2 null string :(
$client_socket->recv($data,1024000);
$data_decode = decode("utf-16", $data);
print "Received from Client : $data_decode\n";
#Custom code added here
$data = encode("utf-16","DATA from Server");
print $client_socket "$data\n";
#close($sock);
}
I got the error:
Thread 1 terminated abnormally: Usage: threads->exit(status) at server-cotton.pl line 61 thread 1
When the
$th1->exit();
executing.
And one more thing, I can't not disconnect to connection from client.
As the message says, it's a static method call
threads->exit(1); # ok
Not an instance method call
$th1->exit(1); # not ok unless $th1 contains the string "threads"

Perl TCP Server handling multiple Client connections

I'll preface this by saying I have minimal experience with both Perl and Socket programming, so I appreciate any help I can get. I have a TCP Server which needs to handle multiple Client connections simultaneously and be able to receive data from any one of the Clients at any time and also be able to send data back to the Clients based on information it's received. For example, Client1 and Client2 connect to my Server. Client2 sends "Ready", the server interprets that and sends "Go" to Client1. The following is what I have written so far:
my $sock = new IO::Socket::INET
{
LocalHost => $host, // defined earlier in code
LocalPort => $port, // defined earlier in code
Proto => 'tcp',
Listen => SOMAXCONN,
Reuse => 1,
};
die "Could not create socket $!\n" unless $sock;
while ( my ($new_sock,$c_addr) = $sock->accept() ) {
my ($client_port, $c_ip) = sockaddr_in($c_addr);
my $client_ipnum = inet_ntoa($c_ip);
my $client_host = "";
my #threads;
print "got a connection from $client_host", "[$client_ipnum]\n";
my $command;
my $data;
while ($data = <$new_sock>) {
push #threads, async \&Execute, $data;
}
}
sub Execute {
my ($command) = #_;
// if($command) = "test"
// send "go" to socket1
print "Executing command: $command\n";
system($command);
}
I know both of my while loops will be blocking and I need a way to implement my accept command as a thread, but I'm not sure the proper way of writing it.
Either fork, thread or do I/O multiplexing with select. Take a look at Net::Server and AnyEvent::Socket, too. For an example of I/O multiplexing, take a look at How can I accept multiple TCP connections in Perl?.

Socket message hangs until thread completes in Perl

I am trying to write Perl code that does two-way communication over a Unix socket. It needs to do the following things:
Client code sends a request over the socket
Server code reads the request
Server performs any actions that should happen immediately
Server creates a new thread to do additional actions that may take a long time
Server sends response over the socket
Client receives response
The new thread continues to work after the response has been sent
I have gotten most of this to work now, but with one problem. Steps 1 - 5 work fine, but at step 6, the client is unable to read the response until AFTER the thread has exited. (even though the response was sent more-or-less immediately) Any idea what I'm doing wrong?
I'm using Perl 5.10.1 on Ubuntu Lucid.
Here's an example:
Client code:
#!/usr/bin/perl
use strict;
use Socket;
my $socket_name = 'catsock';
my $client_message = "Hello server, this is the client.";
my $SOCK;
socket($SOCK, PF_UNIX, SOCK_STREAM, 0) or die "socket: $!";
connect($SOCK, sockaddr_un($socket_name)) or die "connect: $!";
$| = 1, select $_ for select $SOCK; # turn on autoflush
print $SOCK $client_message; # send the message
shutdown($SOCK,1); # finished writing
print "sent: $client_message\n";
my $server_message = do { local $/; <$SOCK> }; # get the response
print "recieved: $server_message\n\n";
Server code
#!/usr/bin/perl
use strict;
use Socket;
use threads;
use threads::shared;
sub threadfunc
{
print " waiting 5 seconds in new thread...\n";
sleep(5);
print " exiting thread...\n\n";
}
my $server_message = "Hello client, this is the server.";
my $socket_name = 'catsock';
my $SERVER;
my $CLIENT;
socket($SERVER, PF_UNIX, SOCK_STREAM, 0) or die "socket: $!";
unlink($socket_name);
bind($SERVER, sockaddr_un($socket_name)) or die "bind: $!";
chmod(0660, $socket_name);
listen($SERVER, SOMAXCONN) or die "listen: $!";
print "server started on $socket_name\n\n";
while(1) {
accept($CLIENT, $SERVER);
my $client_message = do { local $/; <$CLIENT> }; # grab entire message
print "recieved: $client_message\n";
print "creating new thread...\n";
my $thr = threads->create(\&threadfunc);
$thr->detach();
print $CLIENT $server_message; # send the response
print "sent: $server_message\n\n";
close $CLIENT;
}
When I run this, the following things happen:
Client sends "Hello server, this is the client."
Server receives client's message
Server creates a new thread
Server sends "Hello client, this is the server."
Client should receive the message now, but it does not.
New thread on server sleeps for 5 seconds
Thread exits
Now the client receives the server's message, even though it was sent 5 seconds ago. Why?
my $server_message = do { local $/; <$SOCK> }
in the client script smells funny to me. By setting $/ to undef, you are asking the <$SOCK> statement to read all input from the handle $SOCK until end of file. In this context, end of file means that the other end of the socket has closed the connection.
The server is delivering the message, as you can see if you change the line above to something like
print "Received message: ";
print while $_ = getc($SOCK);
(this will also hang for 5 seconds when the input stream is exhausted, but it will at least display each character in the input in the meantime).
It is a "feature" that one end of a TCP socket connection can never really know whether the other end of the connection is still alive. Network programmers resort to other conventions -- encoding the message length at the beginning of each message, ending each message with a special token, implementing heartbeats -- to determine how much input can safely be read from a socket (you might also want to look into the 4-argument version of select)
For this problem, one possibility is to apply the convention that all messages from the server should end in a newline. Change the server script to say
print $CLIENT $server_message, "\n";
and change the client script to say
my $server_message = do { local $/="\n"; <$SOCK> }; # if you're paranoid about $/ setting
my $server_message = <$SOCK>; # if you're not
and you will get results closer to what you expect.

Resources