Skip to content

Instantly share code, notes, and snippets.

@erorus
Created December 11, 2017 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erorus/57f63ff486413746915127cdfa30dc9e to your computer and use it in GitHub Desktop.
Save erorus/57f63ff486413746915127cdfa30dc9e to your computer and use it in GitHub Desktop.
script to close stuck-open electrumx server connections
<?php
echo "Starting.. ", date('Y-m-d H:i:s'), "\n";
$conns = [];
$lsof = `lsof -n -a -c electrumx -itcp -sTCP:ESTABLISHED -Ffn`;
$tok = strtok($lsof, "\n");
$pid = 0;
$fd = 0;
while ($tok !== false) {
$op = substr($tok, 0, 1);
$data = substr($tok, 1);
switch ($op) {
case 'p':
$pid = $data;
break;
case 'f':
$fd = $data;
break;
case 'n':
$conns[$pid][$fd] = substr($data, strpos($data, '->') + 2);
break;
}
$tok = strtok("\n");
}
$cmd = '/usr/local/bin/electrumx_rpc.py sessions | grep -o \'[^[:space:]]*$\' | grep -v Peer;';
$cmd .= '/usr/local/bin/electrumx_rpc.py peers | awk \'{if($2 == "good") {print $NF;}}\';';
$sessions = array_flip(explode("\n", shell_exec($cmd)));
foreach ($conns as $pid => &$fds) {
foreach ($fds as $fd => $conn) {
if (isset($sessions[$conn])) {
unset($sessions[$conn]);
unset($fds[$fd]);
}
}
}
unset($fds);
foreach ($conns as $pid => $fds) {
$cmds = '';
asort($fds);
foreach ($fds as $fd => $conn) {
echo "Closing pid $pid fd $fd to $conn\n";
$cmds .= "call shutdown($fd, 2)\n";
}
if ($cmds != '') {
$f = tempnam('/tmp', 'stale-electrum');
if ($f === false) {
break;
}
file_put_contents($f, $cmds);
passthru(sprintf('gdb -p %d --batch -x %s', $pid, escapeshellarg($f)));
unlink($f);
}
}
echo "Finished.. ", date('Y-m-d H:i:s'), "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment