scb
scb

Reputation: 13

Initialize an nginx module's shared memory depending on a server configuration directive

I'm writing a small nginx module that reads some url pairs from a data file, and then stores its contents on an rb-tree in nginx's shared memory. In the handler's code, the tree contents are matched with the request uri, and a redirection is performed based on certain conditions.
This works fine at the moment. The module kicks in during the postconfiguration phase at the function ngx_http_mymodule_init, where it adds the shared memory and assigns the init function that will be called by nginx later.

ngx_http_mymodule_init(ngx_conf_t *cf) {
    [...]
  ngx_http_mymodule_shm_zone = ngx_shared_memory_add(...);
    [...]
  ngx_http_mymodule_shm_zone->init = ngx_http_mymodule_init_shm_zone;           
  return NGX_OK; 
}

And that init_shm_zone function is the one that creates the tree, reads the data file, and initializes the tree contents.
But there should be one data file for each virtual server, so I need to read the path for the input data file from an nginx configuration directive, like this:

static ngx_command_t ngx_http_mymodule_commands[] = {
  [...]
  { ngx_string("mymodule_input_filepath"),
    NGX_HTTP_SRV_CONF|NGX_CONF_TAKE1,
    ngx_conf_set_str_slot, // should be ngx_conf_set_path_slot i guess...
    NGX_HTTP_SRV_CONF_OFFSET,
    offsetof(ngx_http_mymodule_srv_conf_t, input_filepath),
    NULL },
  ngx_null_command
};

...and then use that filepath to open the file and store its contents on shared memory. However, at the ngx_http_mymodule_init function, I can't access the config object, so I can't read the file name.
So, my question is, in which handler or phase should I hook my initialization code, so that I can read the filename from the server config and use it to initialize my shared memory?
It has to be somewhere after the config file has been parsed, and after the shared memory has been created, but before any actual request processing. I have tried to hook into the init_master and init_process handlers, but I can't seem to find the config object from the cycle object that those handlers receive as parameter...

Upvotes: 1

Views: 2777

Answers (1)

VBart
VBart

Reputation: 15110

mmcf = (ngx_my_module_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_my_module);

See here for example: http://trac.nginx.org/nginx/browser/nginx/trunk/src/core/ngx_regex.c#L316

Upvotes: 2

Related Questions