root/trunk/whisperlib/net/http/failsafe_http_client.cc

Revision 7, 7.2 kB (checked in by whispercastorg, 2 years ago)

version 0.2.0

Line 
1 // Copyright (c) 2009, Whispersoft s.r.l.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Whispersoft s.r.l. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // Author: Catalin Popescu
31 //
32
33 #include <whisperlib/net/http/failsafe_http_client.h>
34
35 #define LOG_HTTP \
36   LOG_INFO_IF(client_params_->dlog_level_) << " - HTTP Failsafe: "
37
38 namespace http {
39
40 FailSafeClient::FailSafeClient(
41     net::Selector* selector,
42     const ClientParams* client_params,
43     const vector<net::HostPort>& servers,
44     ResultClosure<BaseClientConnection*>* connection_factory,
45     int num_retries,
46     int32 request_timeout_ms,
47     int32 reopen_connection_interval_ms,
48     bool force_host_header)
49     : selector_(selector),
50       client_params_(client_params),
51       servers_(servers),
52       connection_factory_(connection_factory),
53       num_retries_(num_retries),
54       request_timeout_ms_(request_timeout_ms),
55       reopen_connection_interval_ms_(reopen_connection_interval_ms),
56       force_host_header_(force_host_header),
57       pending_requests_(new PendingQueue),
58       closing_(false) {
59   CHECK(connection_factory_->is_permanent());
60   // CHECK(!servers.empty());
61   // copy(servers.begin(), servers.end(), servers_.begin());
62   CHECK(!servers_.empty());
63   for ( int i = 0; i < servers_.size(); ++i ) {
64     clients_.push_back(new ClientProtocol(
65                            client_params,
66                            connection_factory->Run(),
67                            servers_[i]));
68     death_time_.push_back(0);
69   }
70   requeue_pending_callback_ = NewPermanentCallback(
71       this, &FailSafeClient::RequeuePendingAlarm);
72   selector_->RegisterAlarm(requeue_pending_callback_, kRequeuePendingAlarmMs);
73 }
74
75 FailSafeClient::~FailSafeClient() {
76   closing_ = true;
77   for ( int i = 0; i < clients_.size(); ++i ) {
78     if ( clients_[i] != NULL ) {
79       clients_[i]->ResolveAllRequestsWithError();
80       delete clients_[i];
81     }
82   }
83   while ( !pending_requests_->empty() ) {
84     PendingStruct* const ps = pending_requests_->front();
85     ps->req_->set_error(CONN_CLIENT_CLOSE);
86     ps->completion_closure_->Run();
87     delete ps;
88     pending_requests_->pop_front();
89   }
90   delete pending_requests_;
91   selector_->UnregisterAlarm(requeue_pending_callback_);
92   delete requeue_pending_callback_;
93 }
94
95 void FailSafeClient::StartRequest(ClientRequest* request,
96                                   Closure* completion_callback) {
97   LOG_HTTP << " Starting request: " << request->name();
98   if ( InternalStartRequest(new PendingStruct(
99                                 selector_->now(), num_retries_,
100                                 request, completion_callback)) ) {
101     RequeuePending();
102   }
103 }
104
105 ////////////////////
106
107 void FailSafeClient::RequeuePendingAlarm() {
108   RequeuePending();
109   selector_->ReregisterAlarm(requeue_pending_callback_, kRequeuePendingAlarmMs);
110 }
111
112 void FailSafeClient::RequeuePending() {
113   if ( !pending_requests_->empty() ) {
114     PendingQueue* const old_queue = pending_requests_;
115     pending_requests_ = new PendingQueue();
116     while ( !old_queue->empty() ) {
117       LOG_HTTP << " Requeueing: " << old_queue->front()->req_;
118       if ( !InternalStartRequest(old_queue->front()) ) {
119         // This means that it ended in queueing .. just move around ..
120         old_queue->pop_front();
121         while ( !old_queue->empty() ) {
122           PendingStruct* const ps = old_queue->front();
123           if ( selector_->now() - ps->start_time_ > request_timeout_ms_ ) {
124             ps->req_->set_error(CONN_REQUEST_TIMEOUT);
125             ps->completion_closure_->Run();
126             delete ps;
127           } else {
128             pending_requests_->push_back(ps);
129           }
130         }
131       } else {
132         old_queue->pop_front();
133       }
134     }
135     delete old_queue;
136   }
137 }
138
139 bool FailSafeClient::InternalStartRequest(PendingStruct* ps) {
140   if ( selector_->now() - ps->start_time_ > request_timeout_ms_ ) {
141     ps->req_->set_error(CONN_REQUEST_TIMEOUT);
142     ps->completion_closure_->Run();
143     delete ps;
144     return true;
145   }
146   if ( ps->retries_left_ <= 0 ) {
147     ps->req_->set_error(CONN_TOO_MANY_RETRIES);
148     ps->completion_closure_->Run();
149     delete ps;
150     return true;
151   }
152   int min_id = -1;
153   int min_load = 0;
154   for ( int i = 0; i < clients_.size(); ++i ) {
155     if ( clients_[i] != NULL && clients_[i]->IsAlive() ) {
156       const int32 load = (clients_[i]->num_active_requests() +
157                           clients_[i]->num_waiting_requests());
158       if ( load < min_load || min_id < 0 ) {
159         min_load = load;
160         min_id = i;
161       }
162     } else if ( selector_->now() - death_time_[i] >
163                 reopen_connection_interval_ms_ ) {
164       LOG_INFO << " Reopening client for: " << servers_[i].ToString();
165       if ( clients_[i] != NULL ) {
166         clients_[i]->ResolveAllRequestsWithError();
167         delete clients_[i];
168       }
169       clients_[i] = new ClientProtocol(client_params_,
170                                        connection_factory_->Run(),
171                                        servers_[i]);
172       death_time_[i] = selector_->now();
173     }
174   }
175   if ( min_id < 0 ) {
176     pending_requests_->push_back(ps);
177     return false;
178   }
179   ps->retries_left_--;
180   LOG_HTTP << " Sending request: " << ps->req_
181            << " to " << servers_[min_id].ToString();
182
183   bool host_added = false;
184   if ( force_host_header_ ) {
185     host_added = true;
186     ps->req_->request()->client_header()->AddField(
187         "Host", servers_[min_id].ip_object().ToString().c_str(), true, true);
188   }
189   clients_[min_id]->SendRequest(
190       ps->req_,
191       NewCallback(this, &FailSafeClient::CompletionCallback, ps));
192   return true;
193 }
194
195 void FailSafeClient::CompletionCallback(PendingStruct* ps) {
196   CHECK(ps->req_->is_finalized());
197   if ( closing_ || ps->req_->error() == CONN_OK ) {
198     ps->completion_closure_->Run();
199     delete ps;
200   } else {
201     ps->req_->request()->server_data()->Clear();
202     ps->req_->request()->server_header()->Clear();
203     LOG_INFO << " Failsafe retrying request: " << ps->req_->name();
204     InternalStartRequest(ps);
205   }
206 }
207 }
Note: See TracBrowser for help on using the browser.