src/http/modules/ngx_http_upstream_hash_module.c - nginx-1.7.10

Global variables defined

Data types defined

Functions defined

Source code


  1. /*
  2. * Copyright (C) Roman Arutyunyan
  3. * Copyright (C) Nginx, Inc.
  4. */


  5. #include <ngx_config.h>
  6. #include <ngx_core.h>
  7. #include <ngx_http.h>


  8. typedef struct {
  9.     uint32_t                            hash;
  10.     ngx_str_t                          *server;
  11. } ngx_http_upstream_chash_point_t;


  12. typedef struct {
  13.     ngx_uint_t                          number;
  14.     ngx_http_upstream_chash_point_t     point[1];
  15. } ngx_http_upstream_chash_points_t;


  16. typedef struct {
  17.     ngx_http_complex_value_t            key;
  18.     ngx_http_upstream_chash_points_t   *points;
  19. } ngx_http_upstream_hash_srv_conf_t;


  20. typedef struct {
  21.     /* the round robin data must be first */
  22.     ngx_http_upstream_rr_peer_data_t    rrp;
  23.     ngx_http_upstream_hash_srv_conf_t  *conf;
  24.     ngx_str_t                           key;
  25.     ngx_uint_t                          tries;
  26.     ngx_uint_t                          rehash;
  27.     uint32_t                            hash;
  28.     ngx_event_get_peer_pt               get_rr_peer;
  29. } ngx_http_upstream_hash_peer_data_t;


  30. static ngx_int_t ngx_http_upstream_init_hash(ngx_conf_t *cf,
  31.     ngx_http_upstream_srv_conf_t *us);
  32. static ngx_int_t ngx_http_upstream_init_hash_peer(ngx_http_request_t *r,
  33.     ngx_http_upstream_srv_conf_t *us);
  34. static ngx_int_t ngx_http_upstream_get_hash_peer(ngx_peer_connection_t *pc,
  35.     void *data);

  36. static ngx_int_t ngx_http_upstream_init_chash(ngx_conf_t *cf,
  37.     ngx_http_upstream_srv_conf_t *us);
  38. static void ngx_http_upstream_add_chash_point(
  39.     ngx_http_upstream_chash_points_t *points, uint32_t hash, ngx_str_t *server);
  40. static ngx_uint_t ngx_http_upstream_find_chash_point(
  41.     ngx_http_upstream_chash_points_t *points, uint32_t hash);
  42. static ngx_int_t ngx_http_upstream_init_chash_peer(ngx_http_request_t *r,
  43.     ngx_http_upstream_srv_conf_t *us);
  44. static ngx_int_t ngx_http_upstream_get_chash_peer(ngx_peer_connection_t *pc,
  45.     void *data);

  46. static void *ngx_http_upstream_hash_create_conf(ngx_conf_t *cf);
  47. static char *ngx_http_upstream_hash(ngx_conf_t *cf, ngx_command_t *cmd,
  48.     void *conf);


  49. static ngx_command_t  ngx_http_upstream_hash_commands[] = {

  50.     { ngx_string("hash"),
  51.       NGX_HTTP_UPS_CONF|NGX_CONF_TAKE12,
  52.       ngx_http_upstream_hash,
  53.       NGX_HTTP_SRV_CONF_OFFSET,
  54.       0,
  55.       NULL },

  56.       ngx_null_command
  57. };


  58. static ngx_http_module_t  ngx_http_upstream_hash_module_ctx = {
  59.     NULL,                                  /* preconfiguration */
  60.     NULL,                                  /* postconfiguration */

  61.     NULL,                                  /* create main configuration */
  62.     NULL,                                  /* init main configuration */

  63.     ngx_http_upstream_hash_create_conf,    /* create server configuration */
  64.     NULL,                                  /* merge server configuration */

  65.     NULL,                                  /* create location configuration */
  66.     NULL                                   /* merge location configuration */
  67. };


  68. ngx_module_t  ngx_http_upstream_hash_module = {
  69.     NGX_MODULE_V1,
  70.     &ngx_http_upstream_hash_module_ctx,    /* module context */
  71.     ngx_http_upstream_hash_commands,       /* module directives */
  72.     NGX_HTTP_MODULE,                       /* module type */
  73.     NULL,                                  /* init master */
  74.     NULL,                                  /* init module */
  75.     NULL,                                  /* init process */
  76.     NULL,                                  /* init thread */
  77.     NULL,                                  /* exit thread */
  78.     NULL,                                  /* exit process */
  79.     NULL,                                  /* exit master */
  80.     NGX_MODULE_V1_PADDING
  81. };


  82. static ngx_int_t
  83. ngx_http_upstream_init_hash(ngx_conf_t *cf, ngx_http_upstream_srv_conf_t *us)
  84. {
  85.     if (ngx_http_upstream_init_round_robin(cf, us) != NGX_OK) {
  86.         return NGX_ERROR;
  87.     }

  88.     us->peer.init = ngx_http_upstream_init_hash_peer;

  89.     return NGX_OK;
  90. }


  91. static ngx_int_t
  92. ngx_http_upstream_init_hash_peer(ngx_http_request_t *r,
  93.     ngx_http_upstream_srv_conf_t *us)
  94. {
  95.     ngx_http_upstream_hash_srv_conf_t   *hcf;
  96.     ngx_http_upstream_hash_peer_data_t  *hp;

  97.     hp = ngx_palloc(r->pool, sizeof(ngx_http_upstream_hash_peer_data_t));
  98.     if (hp == NULL) {
  99.         return NGX_ERROR;
  100.     }

  101.     r->upstream->peer.data = &hp->rrp;

  102.     if (ngx_http_upstream_init_round_robin_peer(r, us) != NGX_OK) {
  103.         return NGX_ERROR;
  104.     }

  105.     r->upstream->peer.get = ngx_http_upstream_get_hash_peer;

  106.     hcf = ngx_http_conf_upstream_srv_conf(us, ngx_http_upstream_hash_module);

  107.     if (ngx_http_complex_value(r, &hcf->key, &hp->key) != NGX_OK) {
  108.         return NGX_ERROR;
  109.     }

  110.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
  111.                    "upstream hash key:\"%V\"", &hp->key);

  112.     hp->conf = hcf;
  113.     hp->tries = 0;
  114.     hp->rehash = 0;
  115.     hp->hash = 0;
  116.     hp->get_rr_peer = ngx_http_upstream_get_round_robin_peer;

  117.     return NGX_OK;
  118. }


  119. static ngx_int_t
  120. ngx_http_upstream_get_hash_peer(ngx_peer_connection_t *pc, void *data)
  121. {
  122.     ngx_http_upstream_hash_peer_data_t  *hp = data;

  123.     time_t                        now;
  124.     u_char                        buf[NGX_INT_T_LEN];
  125.     size_t                        size;
  126.     uint32_t                      hash;
  127.     ngx_int_t                     w;
  128.     uintptr_t                     m;
  129.     ngx_uint_t                    i, n, p;
  130.     ngx_http_upstream_rr_peer_t  *peer;

  131.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, pc->log, 0,
  132.                    "get hash peer, try: %ui", pc->tries);

  133.     if (hp->tries > 20 || hp->rrp.peers->single) {
  134.         return hp->get_rr_peer(pc, &hp->rrp);
  135.     }

  136.     now = ngx_time();

  137.     pc->cached = 0;
  138.     pc->connection = NULL;

  139.     for ( ;; ) {

  140.         /*
  141.          * Hash expression is compatible with Cache::Memcached:
  142.          * ((crc32([REHASH] KEY) >> 16) & 0x7fff) + PREV_HASH
  143.          * with REHASH omitted at the first iteration.
  144.          */

  145.         ngx_crc32_init(hash);

  146.         if (hp->rehash > 0) {
  147.             size = ngx_sprintf(buf, "%ui", hp->rehash) - buf;
  148.             ngx_crc32_update(&hash, buf, size);
  149.         }

  150.         ngx_crc32_update(&hash, hp->key.data, hp->key.len);
  151.         ngx_crc32_final(hash);

  152.         hash = (hash >> 16) & 0x7fff;

  153.         hp->hash += hash;
  154.         hp->rehash++;

  155.         if (!hp->rrp.peers->weighted) {
  156.             p = hp->hash % hp->rrp.peers->number;

  157.         } else {
  158.             w = hp->hash % hp->rrp.peers->total_weight;

  159.             for (i = 0; i < hp->rrp.peers->number; i++) {
  160.                 w -= hp->rrp.peers->peer[i].weight;
  161.                 if (w < 0) {
  162.                     break;
  163.                 }
  164.             }

  165.             p = i;
  166.         }

  167.         n = p / (8 * sizeof(uintptr_t));
  168.         m = (uintptr_t) 1 << p % (8 * sizeof(uintptr_t));

  169.         if (hp->rrp.tried[n] & m) {
  170.             goto next;
  171.         }

  172.         ngx_log_debug2(NGX_LOG_DEBUG_HTTP, pc->log, 0,
  173.                        "get hash peer, value:%uD, peer:%ui", hp->hash, p);

  174.         peer = &hp->rrp.peers->peer[p];

  175.         if (peer->down) {
  176.             goto next;
  177.         }

  178.         if (peer->max_fails
  179.             && peer->fails >= peer->max_fails
  180.             && now - peer->checked <= peer->fail_timeout)
  181.         {
  182.             goto next;
  183.         }

  184.         break;

  185.     next:

  186.         if (++hp->tries > 20) {
  187.             return hp->get_rr_peer(pc, &hp->rrp);
  188.         }
  189.     }

  190.     hp->rrp.current = p;

  191.     pc->sockaddr = peer->sockaddr;
  192.     pc->socklen = peer->socklen;
  193.     pc->name = &peer->name;

  194.     if (now - peer->checked > peer->fail_timeout) {
  195.         peer->checked = now;
  196.     }

  197.     hp->rrp.tried[n] |= m;

  198.     return NGX_OK;
  199. }


  200. static ngx_int_t
  201. ngx_http_upstream_init_chash(ngx_conf_t *cf, ngx_http_upstream_srv_conf_t *us)
  202. {
  203.     u_char                             *host, *port, c;
  204.     size_t                              host_len, port_len, size;
  205.     uint32_t                            hash, base_hash, prev_hash;
  206.     ngx_str_t                          *server;
  207.     ngx_uint_t                          npoints, i, j;
  208.     ngx_http_upstream_rr_peer_t        *peer;
  209.     ngx_http_upstream_rr_peers_t       *peers;
  210.     ngx_http_upstream_chash_points_t   *points;
  211.     ngx_http_upstream_hash_srv_conf_t  *hcf;

  212.     if (ngx_http_upstream_init_round_robin(cf, us) != NGX_OK) {
  213.         return NGX_ERROR;
  214.     }

  215.     us->peer.init = ngx_http_upstream_init_chash_peer;

  216.     peers = us->peer.data;
  217.     npoints = peers->total_weight * 160;

  218.     size = sizeof(ngx_http_upstream_chash_points_t)
  219.            + sizeof(ngx_http_upstream_chash_point_t) * (npoints - 1);

  220.     points = ngx_palloc(cf->pool, size);
  221.     if (points == NULL) {
  222.         return NGX_ERROR;
  223.     }

  224.     points->number = 0;

  225.     for (i = 0; i < peers->number; i++) {
  226.         peer = &peers->peer[i];
  227.         server = &peer->server;

  228.         /*
  229.          * Hash expression is compatible with Cache::Memcached::Fast:
  230.          * crc32(HOST \0 PORT PREV_HASH).
  231.          */

  232.         if (server->len >= 5
  233.             && ngx_strncasecmp(server->data, (u_char *) "unix:", 5) == 0)
  234.         {
  235.             host = server->data + 5;
  236.             host_len = server->len - 5;
  237.             port = NULL;
  238.             port_len = 0;
  239.             goto done;
  240.         }

  241.         for (j = 0; j < server->len; j++) {
  242.             c = server->data[server->len - j - 1];

  243.             if (c == ':') {
  244.                 host = server->data;
  245.                 host_len = server->len - j - 1;
  246.                 port = server->data + server->len - j;
  247.                 port_len = j;
  248.                 goto done;
  249.             }

  250.             if (c < '0' || c > '9') {
  251.                 break;
  252.             }
  253.         }

  254.         host = server->data;
  255.         host_len = server->len;
  256.         port = NULL;
  257.         port_len = 0;

  258.     done:

  259.         ngx_crc32_init(base_hash);
  260.         ngx_crc32_update(&base_hash, host, host_len);
  261.         ngx_crc32_update(&base_hash, (u_char *) "", 1);
  262.         ngx_crc32_update(&base_hash, port, port_len);

  263.         prev_hash = 0;
  264.         npoints = peer->weight * 160;

  265.         for (j = 0; j < npoints; j++) {
  266.             hash = base_hash;

  267.             ngx_crc32_update(&hash, (u_char *) &prev_hash, sizeof(uint32_t));
  268.             ngx_crc32_final(hash);

  269.             ngx_http_upstream_add_chash_point(points, hash, &peer->server);

  270.             prev_hash = hash;
  271.         }
  272.     }

  273.     hcf = ngx_http_conf_upstream_srv_conf(us, ngx_http_upstream_hash_module);
  274.     hcf->points = points;

  275.     return NGX_OK;
  276. }


  277. static void
  278. ngx_http_upstream_add_chash_point(ngx_http_upstream_chash_points_t *points,
  279.     uint32_t hash, ngx_str_t *server)
  280. {
  281.     size_t                            size;
  282.     ngx_uint_t                        i;
  283.     ngx_http_upstream_chash_point_t  *point;

  284.     i = ngx_http_upstream_find_chash_point(points, hash);
  285.     point = &points->point[i];

  286.     if (point->hash == hash) {
  287.         return;
  288.     }

  289.     size = (points->number - i) * sizeof(ngx_http_upstream_chash_point_t);

  290.     ngx_memmove(point + 1, point, size);

  291.     points->number++;
  292.     point->hash = hash;
  293.     point->server = server;
  294. }


  295. static ngx_uint_t
  296. ngx_http_upstream_find_chash_point(ngx_http_upstream_chash_points_t *points,
  297.     uint32_t hash)
  298. {
  299.     ngx_uint_t                        i, j, k;
  300.     ngx_http_upstream_chash_point_t  *point;

  301.     /* find first point >= hash */

  302.     point = &points->point[0];

  303.     i = 0;
  304.     j = points->number;

  305.     while (i < j) {
  306.         k = (i + j) / 2;

  307.         if (hash > point[k].hash) {
  308.             i = k + 1;

  309.         } else if (hash < point[k].hash) {
  310.             j = k;

  311.         } else {
  312.             return k;
  313.         }
  314.     }

  315.     return i;
  316. }


  317. static ngx_int_t
  318. ngx_http_upstream_init_chash_peer(ngx_http_request_t *r,
  319.     ngx_http_upstream_srv_conf_t *us)
  320. {
  321.     uint32_t                             hash;
  322.     ngx_http_upstream_hash_srv_conf_t   *hcf;
  323.     ngx_http_upstream_hash_peer_data_t  *hp;

  324.     if (ngx_http_upstream_init_hash_peer(r, us) != NGX_OK) {
  325.         return NGX_ERROR;
  326.     }

  327.     r->upstream->peer.get = ngx_http_upstream_get_chash_peer;

  328.     hp = r->upstream->peer.data;
  329.     hcf = ngx_http_conf_upstream_srv_conf(us, ngx_http_upstream_hash_module);

  330.     hash = ngx_crc32_long(hp->key.data, hp->key.len);
  331.     hp->hash = ngx_http_upstream_find_chash_point(hcf->points, hash);

  332.     return NGX_OK;
  333. }


  334. static ngx_int_t
  335. ngx_http_upstream_get_chash_peer(ngx_peer_connection_t *pc, void *data)
  336. {
  337.     ngx_http_upstream_hash_peer_data_t  *hp = data;

  338.     time_t                              now;
  339.     intptr_t                            m;
  340.     ngx_str_t                          *server;
  341.     ngx_int_t                           total;
  342.     ngx_uint_t                          i, n;
  343.     ngx_http_upstream_rr_peer_t        *peer, *best;
  344.     ngx_http_upstream_chash_point_t    *point;
  345.     ngx_http_upstream_chash_points_t   *points;
  346.     ngx_http_upstream_hash_srv_conf_t  *hcf;

  347.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, pc->log, 0,
  348.                    "get consistent hash peer, try: %ui", pc->tries);

  349.     pc->cached = 0;
  350.     pc->connection = NULL;

  351.     now = ngx_time();
  352.     hcf = hp->conf;

  353.     points = hcf->points;
  354.     point = &points->point[0];

  355.     for ( ;; ) {
  356.         server = point[hp->hash % points->number].server;

  357.         ngx_log_debug2(NGX_LOG_DEBUG_HTTP, pc->log, 0,
  358.                        "consistent hash peer:%uD, server:\"%V\"",
  359.                        hp->hash, server);

  360.         best = NULL;
  361.         total = 0;

  362.         for (i = 0; i < hp->rrp.peers->number; i++) {

  363.             n = i / (8 * sizeof(uintptr_t));
  364.             m = (uintptr_t) 1 << i % (8 * sizeof(uintptr_t));

  365.             if (hp->rrp.tried[n] & m) {
  366.                 continue;
  367.             }

  368.             peer = &hp->rrp.peers->peer[i];

  369.             if (peer->down) {
  370.                 continue;
  371.             }

  372.             if (peer->server.len != server->len
  373.                 || ngx_strncmp(peer->server.data, server->data, server->len)
  374.                    != 0)
  375.             {
  376.                 continue;
  377.             }

  378.             if (peer->max_fails
  379.                 && peer->fails >= peer->max_fails
  380.                 && now - peer->checked <= peer->fail_timeout)
  381.             {
  382.                 continue;
  383.             }

  384.             peer->current_weight += peer->effective_weight;
  385.             total += peer->effective_weight;

  386.             if (peer->effective_weight < peer->weight) {
  387.                 peer->effective_weight++;
  388.             }

  389.             if (best == NULL || peer->current_weight > best->current_weight) {
  390.                 best = peer;
  391.             }
  392.         }

  393.         if (best) {
  394.             best->current_weight -= total;

  395.             i = best - &hp->rrp.peers->peer[0];

  396.             hp->rrp.current = i;

  397.             n = i / (8 * sizeof(uintptr_t));
  398.             m = (uintptr_t) 1 << i % (8 * sizeof(uintptr_t));

  399.             hp->rrp.tried[n] |= m;

  400.             if (now - best->checked > best->fail_timeout) {
  401.                 best->checked = now;
  402.             }

  403.             pc->sockaddr = best->sockaddr;
  404.             pc->socklen = best->socklen;
  405.             pc->name = &best->name;

  406.             return NGX_OK;
  407.         }

  408.         hp->hash++;
  409.         hp->tries++;

  410.         if (hp->tries >= points->number) {
  411.             return NGX_BUSY;
  412.         }
  413.     }
  414. }


  415. static void *
  416. ngx_http_upstream_hash_create_conf(ngx_conf_t *cf)
  417. {
  418.     ngx_http_upstream_hash_srv_conf_t  *conf;

  419.     conf = ngx_palloc(cf->pool, sizeof(ngx_http_upstream_hash_srv_conf_t));
  420.     if (conf == NULL) {
  421.         return NULL;
  422.     }

  423.     conf->points = NULL;

  424.     return conf;
  425. }


  426. static char *
  427. ngx_http_upstream_hash(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
  428. {
  429.     ngx_http_upstream_hash_srv_conf_t  *hcf = conf;

  430.     ngx_str_t                         *value;
  431.     ngx_http_upstream_srv_conf_t      *uscf;
  432.     ngx_http_compile_complex_value_t   ccv;

  433.     value = cf->args->elts;

  434.     ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t));

  435.     ccv.cf = cf;
  436.     ccv.value = &value[1];
  437.     ccv.complex_value = &hcf->key;

  438.     if (ngx_http_compile_complex_value(&ccv) != NGX_OK) {
  439.         return NGX_CONF_ERROR;
  440.     }

  441.     uscf = ngx_http_conf_get_module_srv_conf(cf, ngx_http_upstream_module);

  442.     if (uscf->peer.init_upstream) {
  443.         ngx_conf_log_error(NGX_LOG_WARN, cf, 0,
  444.                            "load balancing method redefined");
  445.     }

  446.     uscf->flags = NGX_HTTP_UPSTREAM_CREATE
  447.                   |NGX_HTTP_UPSTREAM_WEIGHT
  448.                   |NGX_HTTP_UPSTREAM_MAX_FAILS
  449.                   |NGX_HTTP_UPSTREAM_FAIL_TIMEOUT
  450.                   |NGX_HTTP_UPSTREAM_DOWN;

  451.     if (cf->args->nelts == 2) {
  452.         uscf->peer.init_upstream = ngx_http_upstream_init_hash;

  453.     } else if (ngx_strcmp(value[2].data, "consistent") == 0) {
  454.         uscf->peer.init_upstream = ngx_http_upstream_init_chash;

  455.     } else {
  456.         ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  457.                            "invalid parameter \"%V\"", &value[2]);
  458.         return NGX_CONF_ERROR;
  459.     }

  460.     return NGX_CONF_OK;
  461. }