How to workaround the lack of cosocket API at init context?

164 views
Skip to first unread message

Yan Gabriel Minário

unread,
May 6, 2017, 1:30:44 PM5/6/17
to openresty-en
I’ve forked a Telegram Bot written in lua and decided to add webhook support using openresty: https://gitlab.com/Synko/GroupButler 

So far so good, but I’d like to do some initialization work before handling requests, like getting bot info from telegram API (/getMe), sending a message for the admin when the bot starts up (/sendMessage), load plugins (optional lua modules) etc. Most of these tasks require reaching the telegram servers from http, that means I can’t use resty.http (also getting ssl errors with this one but that’s another problem) to do these requisitions.

Currently I’m calling curl using os.execute, which is ugly to say the least.

David Birdsong

unread,
May 6, 2017, 1:56:51 PM5/6/17
to openresty-en
Use 'timer.at' to schedule the work to run in another coroutine.

If you search around, there should be examples. I think the resty consul lib might illustrate how.

--
You received this message because you are subscribed to the Google Groups "openresty-en" group.
To unsubscribe from this group and stop receiving emails from it, send an email to openresty-en+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Michal Cichra

unread,
Jun 1, 2017, 2:21:30 AM6/1/17
to openresty-en
I'm working on API Gateway which needs to download configuration before accepting any work and I settled on calling `os.execute` to a helper script in libexec spawning `resty` with some lua to perform a request. 

I tried timer.at and using semaphore and resty.lock for synchronization, but none of those worked. 

tokers

unread,
Jun 1, 2017, 3:33:53 AM6/1/17
to openresty-en
cosocket can not be used in the phase like init_by_lua or init_worker_by_lua.
BTW, maybe you can use the lua socket lib?

Yan Gabriel Minário

unread,
Jun 22, 2017, 2:47:32 PM6/22/17
to openresty-en
So I ended up dropping init in favor of init_woker and using shared dict to “lock” the startup process to a single worker. It looks like this:
init_worker.lua:

local function bot_init()
--call things that use cosocket
end

local bot = ngx.shared.bot
local started = bot:get(‘started')

if not started then -- Check if no other worker has already run the startup process
bot:set(‘started’, luatz.time()) -- “Lock” so no other worker run this again
local ok, err = ngx.timer.at(0, bot_init) -- Create a 0 delay timer with init function
if not ok then
ngx.log(ngx.ERR, "failed to create timer: ", err)
return
end
end

mci...@redhat.com

unread,
Jun 30, 2017, 7:14:04 AM6/30/17
to openresty-en
Looks like this is worked on https://github.com/openresty/lua-nginx-module/issues/1020
Maybe express the interest there to bump the priority.
Reply all
Reply to author
Forward
0 new messages