|
| 1 | +// Copyright (c) 2015 |
| 2 | +// Author: Chrono Law |
| 3 | +#ifndef _NDG_LOAD_BALANCE_HANDLER_HPP |
| 4 | +#define _NDG_LOAD_BALANCE_HANDLER_HPP |
| 5 | + |
| 6 | +#include <boost/random.hpp> |
| 7 | + |
| 8 | +#include "NdgLoadBalanceConf.hpp" |
| 9 | + |
| 10 | +class NdgLoadBalanceCallback final |
| 11 | +{ |
| 12 | +public: |
| 13 | + typedef NgxLogDebug log; |
| 14 | + typedef NdgLoadBalanceCallback this_type; |
| 15 | + typedef boost::rand48 random_type; |
| 16 | +public: |
| 17 | + // the round robin data must be first |
| 18 | + ngx_http_upstream_rr_peer_data_t rrp; |
| 19 | + |
| 20 | + u_char tries = 0; |
| 21 | + ngx_event_get_peer_pt get_rr_peer = ngx_http_upstream_get_round_robin_peer; |
| 22 | +public: |
| 23 | + static ngx_int_t get(ngx_peer_connection_t *pc, void *data) |
| 24 | + { |
| 25 | + auto& peer_data = *reinterpret_cast<this_type*>(data); |
| 26 | + auto& peers = *peer_data.rrp.peers; |
| 27 | + |
| 28 | + if(peer_data.tries++ > 5 || peers.single) |
| 29 | + { |
| 30 | + return peer_data.get_rr_peer(pc, &peer_data.rrp); |
| 31 | + } |
| 32 | + |
| 33 | + static random_type rand(time(0)); |
| 34 | + |
| 35 | + auto& peer = peers.peer[rand() % peers.number]; |
| 36 | + |
| 37 | + pc->sockaddr = peer.sockaddr; |
| 38 | + pc->socklen = peer.socklen; |
| 39 | + pc->name = &peer.name; |
| 40 | + |
| 41 | + log(pc->log).print("peer=%V", &peer.name); |
| 42 | + |
| 43 | + pc->cached = false; |
| 44 | + pc->connection = nullptr; |
| 45 | + |
| 46 | + return NGX_OK; |
| 47 | + } |
| 48 | + |
| 49 | +public: |
| 50 | + static void free(ngx_peer_connection_t *pc, void *data, ngx_uint_t state) |
| 51 | + { |
| 52 | + //auto peer_data = reinterpret_cast<this_type*>(data); |
| 53 | + } |
| 54 | +}; |
| 55 | + |
| 56 | +class NdgLoadBalanceHandler final |
| 57 | +{ |
| 58 | +public: |
| 59 | + typedef NdgLoadBalanceHandler this_type; |
| 60 | + typedef NdgLoadBalanceCallback callback_type; |
| 61 | + typedef NdgLoadBalanceCallback peer_data_type; |
| 62 | + |
| 63 | + //typedef NdgLoadBalanceModule this_module; |
| 64 | + typedef NgxLoadBalance<peer_data_type, |
| 65 | + &callback_type::get> |
| 66 | + //&callback_type::free> |
| 67 | + this_load_balance; |
| 68 | +public: |
| 69 | + static ngx_int_t init(ngx_conf_t *cf, ngx_http_upstream_srv_conf_t *us) |
| 70 | + try |
| 71 | + { |
| 72 | + this_load_balance::init(cf, us, &this_type::init_peer); |
| 73 | + return NGX_OK; |
| 74 | + } |
| 75 | + catch(const NgxException& e) |
| 76 | + { |
| 77 | + return e.code(); |
| 78 | + } |
| 79 | +public: |
| 80 | + static ngx_int_t init_peer(ngx_http_request_t *r, ngx_http_upstream_srv_conf_t *us) |
| 81 | + { |
| 82 | + this_load_balance::init(r, us); |
| 83 | + |
| 84 | + return NGX_OK; |
| 85 | + } |
| 86 | +}; |
| 87 | + |
| 88 | +#endif //_NDG_LOAD_BALANCE_HANDLER_HPP |
0 commit comments