<p>I am trying to implement a request to an unreliable server.  The request is a nice to have, but not 100% required for my perl script to successfully complete.  The problem is that the server will occasionally deadlock (we're trying to figure out why) and the request will never succeed.  Since the server thinks it is live, it keeps the socket connection open thus LWP::UserAgent's timeout value does us no good what-so-ever.  What is the best way to enforce an absolute timeout on a request?  </p>

<p>FYI, this is not an DNS problem.  The deadlock has something to do with a massive number of updates hitting our Postgres database at the same time.  For testing purposes, we've essentially put a while(1) {} line in the servers response handler.  </p>

<p>Currently, the code looks like so:</p>

<pre><code>my $ua = LWP::UserAgent-&gt;new;
ua-&gt;timeout(5); $ua-&gt;cookie_jar({});

my $req = HTTP::Request-&gt;new(POST =&gt; "http://$host:$port/auth/login");
$req-&gt;content_type('application/x-www-form-urlencoded');
$req-&gt;content("login[user]=$username&amp;login[password]=$password");

# This line never returns 
$res = $ua-&gt;request($req);
</code></pre>

<p>I've tried using signals to trigger a timeout, but that does not seem to work.  </p>

<pre><code>eval {
    local $SIG{ALRM} = sub { die "alarm\n" };
    alarm(1);
    $res = $ua-&gt;request($req);
    alarm(0);
};
# This never runs
print "here\n";
</code></pre>

<p>The final answer I'm going to use was proposed by someone offline, but I'll mention it here.  For some reason, SigAction works while $SIG(ALRM) does not.  Still not sure why, but this has been tested to work. Here are two working versions:</p>

<pre><code># Takes a LWP::UserAgent, and a HTTP::Request, returns a HTTP::Request
sub ua_request_with_timeout {
    my $ua = $_[0];
    my $req = $_[1];
    # Get whatever timeout is set for LWP and use that to 
    #  enforce a maximum timeout per request in case of server
    #  deadlock. (This has happened.)
    use Sys::SigAction qw( timeout_call );
    our $res = undef;
    if( timeout_call( 5, sub {$res = $ua-&gt;request($req);}) ) {
        return HTTP::Response-&gt;new( 408 ); #408 is the HTTP timeout
    } else {
        return $res;
    }
}
sub ua_request_with_timeout2 {
    print "ua_request_with_timeout\n";
    my $ua = $_[0];
    my $req = $_[1];
    # Get whatever timeout is set for LWP and use that to 
    #  enforce a maximum timeout per request in case of server
    #  deadlock. (This has happened.)
    my $timeout_for_client = $ua-&gt;timeout() - 2;
    our $socket_has_timedout = 0;

    use POSIX;
    sigaction SIGALRM, new POSIX::SigAction(
                                            sub {
                                                $socket_has_timedout = 1;
                                                die "alarm timeout";
                                            }
                                            ) or die "Error setting SIGALRM handler: $!\n";
    my $res = undef;
    eval {
        alarm ($timeout_for_client);
        $res = $ua-&gt;request($req);
        alarm(0);
    };
    if ( $socket_has_timedout ) {
        return HTTP::Response-&gt;new( 408 ); #408 is the HTTP timeout
    } else {
        return $res;
    }
}
</code></pre>

[{'answer_id': 73351, 'author': 'Alex Fort', 'author_id': 12624, 'author_profile': 'https://Stackoverflow.com/users/12624', 'pm_score': 0, 'selected': False, 'text': "<p>From what I understand, the timeout property doesn't take into account DNS timeouts. It's possible that you could make a DNS lookup separately, then make the request to the server if that works, with the correct timeout value set for the useragent.</p>\n\n<p>Is this a DNS problem with the server, or something else?</p>\n\n<p>EDIT: It could also be a problem with IO::Socket. Try updating your IO::Socket module, and see if that helps. I'm pretty sure there was a bug in there that was preventing LWP::UserAgent timeouts from working.</p>\n\n<p>Alex</p>\n"}, {'answer_id': 73374, 'author': 'Stephen Deken', 'author_id': 7154, 'author_profile': 'https://Stackoverflow.com/users/7154', 'pm_score': 5, 'selected': True, 'text': '<p>You might try <a href="http://search.cpan.org/%7Ebradfitz/LWPx-ParanoidAgent-1.02/lib/LWPx/ParanoidAgent.pm" rel="noreferrer">LWPx::ParanoidAgent</a>, a subclass of LWP::UserAgent which is more cautious about how it interacts with remote webservers.</p>\n<p>Among other things, it allows you to specify a global timeout.  It was developed by Brad Fitzpatrick as part of the LiveJournal project.</p>\n'}, {'answer_id': 76379, 'author': 'jkramer', 'author_id': 12523, 'author_profile': 'https://Stackoverflow.com/users/12523', 'pm_score': 1, 'selected': False, 'text': '<p>You can make your own timeout like this:</p>\n\n<pre><code>use LWP::UserAgent;\nuse IO::Pipe;\n\nmy $agent = new LWP::UserAgent;\n\nmy $finished = 0;\nmy $timeout = 5;\n\n$SIG{CHLD} = sub { wait, $finished = 1 };\n\nmy $pipe = new IO::Pipe;\nmy $pid = fork;\n\nif($pid == 0) {\n    $pipe-&gt;writer;\n    my $response = $agent-&gt;get("http://stackoverflow.com/");\n    $pipe-&gt;print($response-&gt;content);\n    exit;\n}\n\n$pipe-&gt;reader;\n\nsleep($timeout);\n\nif($finished) {\n    print "Finished!\\n";\n    my $content = join(\'\', $pipe-&gt;getlines);\n}   \nelse {\n    kill(9, $pid);\n    print "Timed out.\\n";\n}   \n</code></pre>\n'}, {'answer_id': 18542076, 'author': 'Andrei Georgescu', 'author_id': 2734397, 'author_profile': 'https://Stackoverflow.com/users/2734397', 'pm_score': 0, 'selected': False, 'text': '<p>The following generalization of one of the original answers also restores the alarm signal handler to the previous handler and adds a second call to alarm(0) in case the call in the eval clock throws a non alarm exception and we want to cancel the alarm. Further $@ inspection and handling can be added:</p>\n\n<pre><code>sub ua_request_with_timeout {\n    my $ua = $_[0];\n    my $request = $_[1];\n\n    # Get whatever timeout is set for LWP and use that to \n    #  enforce a maximum timeout per request in case of server\n    #  deadlock. (This has happened.)`enter code here`\n    my $timeout_for_client_sec = $ua-&gt;timeout();\n    our $res_has_timedout = 0; \n\n    use POSIX \':signal_h\';\n\n    my $newaction = POSIX::SigAction-&gt;new(\n        sub { $res_has_timedout = 1; die "web request timeout"; },# the handler code ref\n        POSIX::SigSet-&gt;new(SIGALRM),\n        # not using (perl 5.8.2 and later) \'safe\' switch or sa_flags\n    );  \n\n    my $oldaction = POSIX::SigAction-&gt;new();\n    if(!sigaction(SIGALRM, $newaction, $oldaction)) {\n        log(\'warn\',"Error setting SIGALRM handler: $!");\n        return $ua-&gt;request($request);\n    }   \n\n    my $response = undef;\n    eval {\n        alarm ($timeout_for_client_sec);\n        $response = $ua-&gt;request($request);\n        alarm(0);\n    }; \n\n    alarm(0);# cancel alarm (if eval failed because of non alarm cause)\n    if(!sigaction(SIGALRM, $oldaction )) {\n        log(\'warn\', "Error resetting SIGALRM handler: $!");\n    }; \n\n    if ( $res_has_timedout ) {\n        log(\'warn\', "Timeout($timeout_for_client_sec sec) while waiting for a response from cred central");\n        return HTTP::Response-&gt;new(408); #408 is the HTTP timeout\n    } else {\n        return $response;\n     }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/73308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12628/']