r1355@opsdev009 (orig r71477): mcslee | 2007-11-27 00:42:19 -0800
[amiethrift.git] / lib / cpp / src / transport / TSocketPool.cpp
blobb6440fc826e02d0a677ed9374f0ee8280a7f1d76
1 // Copyright (c) 2007- Facebook
2 // Distributed under the Thrift Software License
3 //
4 // See accompanying file LICENSE or visit the Thrift site at:
5 // http://developers.facebook.com/thrift/
7 #include <algorithm>
8 #include <iostream>
10 #include "TSocketPool.h"
12 namespace facebook { namespace thrift { namespace transport {
14 using namespace std;
16 /**
17 * TSocketPool implementation.
19 * @author Jason Sobel <jsobel@facebook.com>
22 TSocketPool::TSocketPool(const vector<string> &hosts,
23 const vector<int> &ports) : TSocket(),
24 numRetries_(1),
25 retryInterval_(60),
26 maxConsecutiveFailures_(1),
27 randomize_(true),
28 alwaysTryLast_(true)
30 if (hosts.size() != ports.size()) {
31 GlobalOutput("TSocketPool::TSocketPool: hosts.size != ports.size");
32 throw TTransportException(TTransportException::BAD_ARGS);
35 for (unsigned int i = 0; i < hosts.size(); ++i) {
36 addServer(hosts[i], ports[i]);
40 TSocketPool::TSocketPool(const vector<pair<string, int> > servers) : TSocket(),
41 servers_(servers),
42 numRetries_(1),
43 retryInterval_(60),
44 maxConsecutiveFailures_(1),
45 randomize_(true),
46 alwaysTryLast_(true)
50 TSocketPool::TSocketPool(const string& host, int port) : TSocket(),
51 numRetries_(1),
52 retryInterval_(60),
53 maxConsecutiveFailures_(1),
54 randomize_(true),
55 alwaysTryLast_(true)
57 addServer(host, port);
60 TSocketPool::~TSocketPool() {
61 close();
64 void TSocketPool::addServer(const string& host, int port) {
65 servers_.push_back(pair<string, int>(host, port));
68 void TSocketPool::setNumRetries(int numRetries) {
69 numRetries_ = numRetries;
72 void TSocketPool::setRetryInterval(int retryInterval) {
73 retryInterval_ = retryInterval;
77 void TSocketPool::setMaxConsecutiveFailures(int maxConsecutiveFailures) {
78 maxConsecutiveFailures_ = maxConsecutiveFailures;
81 void TSocketPool::setRandomize(bool randomize) {
82 randomize_ = randomize;
85 void TSocketPool::setAlwaysTryLast(bool alwaysTryLast) {
86 alwaysTryLast_ = alwaysTryLast;
89 /* TODO: without apc we ignore a lot of functionality from the php version */
90 void TSocketPool::open() {
91 if (randomize_) {
92 std::random_shuffle(servers_.begin(), servers_.end());
95 for (unsigned int i = 0; i < servers_.size(); ++i) {
96 host_ = servers_[i].first;
97 port_ = servers_[i].second;
99 for (int j = 0; j < numRetries_; ++j) {
100 try {
101 TSocket::open();
103 // success
104 return;
105 } catch (TException e) {
106 // connection failed
111 GlobalOutput("TSocketPool::open: all connections failed");
112 throw TTransportException(TTransportException::NOT_OPEN);
115 }}} // facebook::thrift::transport