From 7acf9d40534113c3f224e03f4459bf0918d7fe4f Mon Sep 17 00:00:00 2001
From: Christian Pointner <equinox@helsinki.at>
Date: Fri, 22 May 2015 20:30:41 +0200
Subject: make nopfetchd more resistent against mysql connection loss


diff --git a/src/qlistener.lua b/src/qlistener.lua
index 0cc2d6b..3f0430c 100644
--- a/src/qlistener.lua
+++ b/src/qlistener.lua
@@ -47,7 +47,7 @@ function handle_now(timestamp, nowcart, nowlen)
    local results, err = rddb:getCartInfo(nowcart);
    if results == nil then
       io.stderr:write("ERROR: can't fetch cart info: " .. err .. "\n")
---    TODO: this error shouldn't be ignored!!!!
+      return nil
    else
 --      print(timestamp .. " Info: '" .. results.TITLE .. "' von '" .. results.ARTIST .. "' aus '" .. results.ALBUM .. "'")
       local ret, err = playlog:insertNowMusic(timestamp, nowcart, nowlen, results.TITLE, results.ARTIST, results.ALBUM)
@@ -57,9 +57,11 @@ function handle_now(timestamp, nowcart, nowlen)
          pipe.signal(timestamp)
       end
    end
+
+   return true
 end
 
-function handle_message(msg)
+function handle_message(msg, q)
    local timestamp, nowcart, nowlen, nextcart, nextlen = string.match(msg, "^(%d+) (%d+) (%d+) (%d+) (%d+)$");
    if not timestamp or not nowcart or not nowlen or not nextcart or not nextlen then
       io.stderr:write("WARN: ignoring malformed message\n")
@@ -68,17 +70,26 @@ function handle_message(msg)
       nowlen = tonumber(nowlen)
       if last_cart ~= nowcart and nowcart >= cnf.music_carts_lo and nowcart <= cnf.music_carts_hi and nowlen > 0 then
          last_cart = nowcart
-         handle_now(timestamp, nowcart, nowlen)
+         local ret = handle_now(timestamp, nowcart, nowlen)
+         if ret == nil then
+            io.stderr:write("INFO: trying to push last message back onto the queue - before exiting\n")
+            local result, err = mq.send(q, timestamp .. " " .. nowcart .. " " .. nowlen .. " " .. nextcart .. " " .. nextlen, 0)
+            if result == nil then
+               io.stderr:write("ERROR: sending message failed: " .. err .. "\n")
+            end
+            return nil
+         end
       end
-      -- TODO handle next info
    end
+
+   return true
 end
 
 function main_loop()
    init(rhnopescdir .. "/nopfetchd.conf")
 
    posix.umask("rwxrwxr-x")
-   local q, err = mq.create(cnf.queue_name, "ro", "rw-rw----")
+   local q, err = mq.create(cnf.queue_name, "rw", "rw-rw----")
    if q == nil then
       q, err = mq.open(cnf.queue_name, "wo")
       if q == nil then
@@ -111,6 +122,9 @@ function main_loop()
          playlog:close()
          os.exit(2)
       end
-      handle_message(msg)
+      local ret = handle_message(msg, q)
+      if ret == nil then
+         os.exit(1)
+      end
    end
 end
-- 
cgit v0.10.2