Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Tuesday, 4 April 2017

"Let your Daemons rest", aka PHP Daemons not sleeping as expected

I was enhancing some inherited PHP code which used the so-called "Daemon Loop" design pattern to read jobs off a queue and hand them off for processing by a configurable number of child worker processes. Specifically, I was trying to get the daemon to wake up once every minute (instead of every 5s) to see it there were any jobs on the queue, so in the loop (in practice the value was read from a config file into a class-level variable), I had:
    sleep(60)

We were also capturing SIGCHLD for notification of when the child closed (in this instance after just a few seconds).

The problem was that the daemon was not waiting 60s to poll unless there was nothing to do. Turns out that SIGCHLD cancels the running sleep(60).

My inelegant solution? sleep(1) 60 times and then only 1s of sleep is lost!
while ($sec>0) {
    sleep(1);
    $sec--;


Thanks to Stuporglue, on whose PHP daemon example code I built a testbed to find a solution.

Thursday, 15 September 2016

PHP SOAP Fault: Error fetching http headers - tweak default_socket_timeout

Started getting the above error on some servers that communicate via soap. I control both ends, so I was pretty sure it wasn't a code issue. After searching round and experimenting I discovered that the query that produced the results that the soap server was being asked to supply could, under heavy load conditions, take longer than 60s, and the connection was dropping at the 60s mark.

Turns out this is the default for the PHP ini variable default_socket_timeout.

I reset it to zero - bad move. 0 = timeout after zero seconds.
    ini_set("default_socket_timeout",0);
I reset it to 3600 = an hour and all seems OK.
    ini_set("default_socket_timeout",3600);

Note that the SOAP method is being called by a crontab-scheduled batch script, so waiting a l-o-n-g time for results is perfectly OK in this case. Might not be if there was a person on the other end! ;)