From fb94656f49b6907dd4e0bc0e5024a43b7188c4b4 Mon Sep 17 00:00:00 2001 From: Stef Dunlap Date: Wed, 24 Aug 2022 12:27:37 -0400 Subject: [PATCH] Timeout commands if they run for longer than three seconds --- .envrc | 3 +++ our.example.service | 2 +- our.rb | 19 ++++++++++++------- 3 files changed, 16 insertions(+), 8 deletions(-) create mode 100644 .envrc diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..a900826 --- /dev/null +++ b/.envrc @@ -0,0 +1,3 @@ +export OUR_NICK=your +export OUR_CHANNELS='#bots' +export OUR_CMDS_DIR=/town/our diff --git a/our.example.service b/our.example.service index 0442070..94d0418 100644 --- a/our.example.service +++ b/our.example.service @@ -8,7 +8,7 @@ WorkingDirectory=/home/kindrobot/spacework/our ExecStart=/home/kindrobot/spacework/our/our.rb Environment="OUR_NICK=your" Environment="OUR_CHANNELS=#bots" -Environment="OUR_CMDS_DIR=/home/kindrobot/spacework/our/cmds/" +Environment="OUR_CMDS_DIR=/town/our" Restart=always RestartSec=5 StartLimitInterval=60s diff --git a/our.rb b/our.rb index 0522345..e00fd65 100755 --- a/our.rb +++ b/our.rb @@ -1,6 +1,7 @@ #!/usr/bin/env ruby -require 'socket' require 'open3' +require 'socket' +require 'timeout' # configurable environment variables nick = ENV['OUR_NICK'] || 'our' @@ -94,13 +95,17 @@ i.hook do |msg| end begin - # child = IO.popen [cmd, args, msg.prefix, target] - # out = child.gets - # child.close - Open3.popen2e(cmd, args, msg.prefix, target) {|_, stdout, _| - out = stdout.gets + Open3.popen2e(cmd, args, msg.prefix, target) do |_, stdout, wait_thread| + out = nil + Timeout::timeout(3) do + out = stdout.gets # only interested in the first line of output + stdout.gets until stdout.eof? # make sure process finishes in time allotted + end i.privmsg target, out if out - } + rescue Timeout::Error + Process.kill("KILL", wait_thread.pid) + i.privmsg target, "[our.rb] command timed out" + end rescue Exception => e i.privmsg target, "[our.rb] #{e.to_s}" end