├── LICENSE
├── README.md
└── hbase
├── BaseHbaseConnection.h
├── ConnectionPool.h
├── ConnectionPoolTest.cpp
├── Counters.h
├── HbcExtensions.h
├── Makefile.am
├── NativeHbaseClient-inl.cpp
├── NativeHbaseClient.cpp
├── NativeHbaseClient.h
├── configure.ac
├── hbase.thrift
├── hbc.cpp
├── m4
├── ac_cxx_compile_stdcxx_0x.m4
└── ax_prefix_config.m4
├── nhc-config.h
└── testing
└── NativeTesting.cpp
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Overview
2 | This is a work in progress!
3 |
4 | Dependencies:
5 | - HBase 0.94.0 or later
6 | - thrift 0.8.0
7 | - google logging
8 | - google flags
9 | - gcc 4.6 or later, or some similarly C++11 compliant compiler
10 | - facebook's folly library (get the latest from github at
11 | https://github.com/facebook/folly/)
12 |
13 | For now, see hbc.cpp and LiveClusterTesting.cpp for examples of use of
14 | the API.
15 |
16 | # Compiling
17 |
18 | First, setup and install folly as per the instructions for that
19 | project, as well as thrift and the other dependencies, either from
20 | source or from your operating system's package manager. Once that is
21 | complete, run
22 |
23 | cd hbase
24 | autoreconf --install
25 | D=/path/to/double-conversion-library
26 | LDFLAGS="-L$D/double-conversion" CFLAGS="-I$D/double-conversion/src" CXXFLAGS="-I$D/double-conversion/src" ./configure
27 | make
28 | make check
29 | make install
30 |
31 | Voila! You're done.
32 |
33 | # Setting up your HBase environment
34 |
35 | NHC currently requires HBase 0.94.0 or newer. In addition, you should
36 | configure your environment to enable the Region Server's embedded
37 | thrift server. Specifically, put the following in your hbase-site.xml file:
38 |
39 |
40 | hbase.regionserver.export.thrift
41 | true
42 |
43 |
44 | hbase.regionserver.thrift.server.type
45 | threadedselector
46 |
47 |
48 | hbase.regionserver.thrift.port
49 | 9091
50 |
51 |
52 | In a nutshell, this enables the in-region server thrift support,
53 | changes to the 'threadedselector' server type (the most efficient and
54 | high performance option), and asks it to listen to port 9091 (it will
55 | otherwise listen to port 9090 which conflicts with the default thrift
56 | port).
57 |
58 | Restart your cluster, and you should now be able to test! For example:
59 |
60 | ./hbc --zookeeper localhost:2181 tables
61 |
62 | To test the API with the hbc utility (included in this distribution).
63 | In fact...
64 |
65 | # hbc: a command line tool for working with hbase!
66 | hbc is a simple command line tool for use with an HBase cluster. The
67 | tool is capable of getting and setting data, creating and dropping
68 | tables, and a variety of other commonly useful tasks.
69 |
70 | ## Why not use hbase shell?
71 |
72 | There is nothing wrong with the hbase shell; it's quite useful and
73 | functional. But it is more complicated to use, requiring xml
74 | configuration files, and presents a somewhat non-Unix interface. hbc,
75 | on the other hand, requires one piece of configuration (the ZooKeeper
76 | cell the HBase cluster uses), and is well suited for more Unix-like
77 | interaction. It also is useful for testing the Native C++ Client and
78 | more suited for scripting.
79 |
80 |
81 | Usage: hbc [params] command [command params]
82 |
83 | Note: all commands rely on either the --zookeeper option or the
84 | HBC_ZOOKEEPER environment variable, which contains the ZooKeeper
85 | instance where the HBase cluster stores its state.
86 |
87 | No ZooKeeper instance set via command line or environment
88 |
89 | Subcommands:
90 | Table/Cell inspection:
91 | hbc tables
92 | hbc schema
93 | hbc regions
94 |
95 | Data manipulation:
96 | hbc scan [ --start_row R ] [ --end_row R ] [ --column C ] [--num_scan_rows N]
97 | hbc get
98 | hbc set column=valuue column=value ...
99 | hbc delete [column column ...]
100 |
101 | TAO operations:
102 | hbc taoput
103 | hbc taodelete [true|false]
104 | hbc taoget
105 |
106 | Schema Manipulation:
107 | hbc create /path/to/schema
108 | hbc create (schema read from stdin)
109 | hbc drop
110 | hbc enable
111 | hbc disable
112 | hbc status
113 |
114 | ## Some Sample Usage
115 | [doctor@gallifrey hbase] hbc --zookeeper zk1:2181,zk2:2181 tables
116 | Table: abc_test_table
117 | Table: chip_mysql_import
118 | ...
119 |
120 |
121 | [doctor@gallifrey hbase] hbc --zookeeper zk1:2181,zk2:2181 scan --num_scan_rows 2 --start_row 400 chip_mysql_import
122 | Row 400
123 | fields:id - 15
124 | fields:value - "row 400"
125 | Row 4001
126 | fields:id - 324
127 | fields:value - "row 4001"
128 | Row 401
129 | fields:id - 17
130 | fields:value - "row 401"
131 |
132 |
133 | [doctor@gallifrey hbase] hbc --zookeeper zk1:2181,zk2:2181 schema chip_mysql_import | tee /tmp/table.schema
134 | # Table schema for chip_mysql_import
135 | # Dumped on Wed Jul 13 11:38:11 2011
136 |
137 | <
138 | name: fields:
139 | maxVersions: 3
140 | compression: LZO
141 | inMemory: 0
142 | bloomFilterType: NONE
143 | bloomFilterVectorSize: 0
144 | bloomFilterNbHashes: 0
145 | blockCacheEnabled: 1
146 | timeToLive: -1
147 | >
148 | [doctor@gallifrey hbase] hbc --zookeeper zk1:2181,zk2:2181 create chip_mysql_import_new < /tmp/table.schema
149 | Create successful!
150 |
151 | [doctor@gallifrey hbase] hbc --zookeeper zk1:2181,zk2:2181 schema chip_mysql_import_new
152 | # Table schema for chip_mysql_import_new
153 | # Dumped on Wed Jul 13 11:38:39 2011
154 |
155 | <
156 | name: rowdata:
157 | maxVersions: 3
158 | compression: LZO
159 | inMemory: 0
160 | bloomFilterType: NONE
161 | bloomFilterVectorSize: 0
162 | bloomFilterNbHashes: 0
163 | blockCacheEnabled: 1
164 | timeToLive: -1
165 | >
166 |
167 | [doctor@gallifrey hbase] ~/bin/hbc --zookeeper zk1:2181,zk2:2181 drop chip_mysql_import_new
168 | Unable to drop table: org.apache.hadoop.hbase.TableNotDisabledException: chip_mysql_import_new
169 | at org.apache.hadoop.hbase.master.HMaster.checkTableModifiable(HMaster.java:917)
170 | at org.apache.hadoop.hbase.master.handler.TableEventHandler.(TableEventHandler.java:54)
171 | at org.apache.hadoop.hbase.master.handler.DeleteTableHandler.(DeleteTableHandler.java:42)
172 | at org.apache.hadoop.hbase.master.HMaster.deleteTable(HMaster.java:834)
173 | at sun.reflect.GeneratedMethodAccessor16.invoke(Unknown Source)
174 | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
175 | at java.lang.reflect.Method.invoke(Method.java:597)
176 | at org.apache.hadoop.hbase.ipc.HBaseRPC$Server.call(HBaseRPC.java:569)
177 | at org.apache.hadoop.hbase.ipc.HBaseServer$Handler.run(HBaseServer.java:1173)
178 |
179 | [doctor@gallifrey hbase] ~/bin/hbc --zookeeper zk1:2181,zk2:2181 disable chip_mysql_import_new
180 | Table disabled.
181 | [doctor@gallifrey hbase] ~/bin/hbc --zookeeper zk1:2181,zk2:2181 drop chip_mysql_import_new
182 | Table deleted.
183 |
--------------------------------------------------------------------------------
/hbase/BaseHbaseConnection.h:
--------------------------------------------------------------------------------
1 | /* Copyright 2012 Facebook, Inc.
2 | *
3 | * Licensed under the Apache License, Version 2.0 (the "License");
4 | * you may not use this file except in compliance with the License.
5 | * You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS,
11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | * See the License for the specific language governing permissions and
13 | * limitations under the License.
14 | */
15 |
16 | // This class represents a connection to an HBase server. It is
17 | // templated to be usable with different actual RPC classes (such as
18 | // the default thrift RPCs or the extended logstream APIs).
19 |
20 | #ifndef HBASE_SRC_BASEHBASECONNECTION_H
21 | #define HBASE_SRC_BASEHBASECONNECTION_H
22 |
23 | #include "hbase/nhc-config.h"
24 |
25 | #include
26 | #include
27 |
28 | #include "folly/Logging.h"
29 |
30 | #if !NHC_OPEN_SOURCE
31 | #include "protocol/THeaderProtocol.h"
32 | #include "transport/THeaderTransport.h"
33 | #endif
34 |
35 | #include "protocol/TBinaryProtocol.h"
36 | #include "protocol/TCompactProtocol.h"
37 | #include "transport/TBufferTransports.h"
38 | #include "transport/TSocket.h"
39 |
40 | namespace facebook { namespace hbase {
41 |
42 | #if !NHC_OPEN_SOURCE
43 | using apache::thrift::protocol::THeaderProtocol;
44 | using apache::thrift::transport::THeaderTransport;
45 | #endif
46 |
47 | using apache::thrift::protocol::TBinaryProtocol;
48 | using apache::thrift::protocol::TCompactProtocol;
49 | using apache::thrift::protocol::TProtocol;
50 | using apache::thrift::transport::TFramedTransport;
51 | using apache::thrift::transport::TBufferedTransport;
52 | using apache::thrift::transport::TSocket;
53 | using apache::thrift::transport::TTransport;
54 | using apache::thrift::TException;
55 | using std::string;
56 |
57 | /// Transport to use when connecting.
58 | enum HbaseClientTransport {
59 | DEFAULT_TRANSPORT,
60 | BUFFERED_TRANSPORT,
61 | FRAMED_TRANSPORT,
62 | COMPACT_FRAMED_TRANSPORT,
63 | HEADER_TRANSPORT,
64 | HEADER_TRANSPORT_WITH_ZLIB
65 | };
66 |
67 | // Class representing a connection to a thrift server. Holds the
68 | // various Thrift classes such as the socket, transport, etc.
69 | template
70 | class BaseHbaseConnection : private boost::noncopyable {
71 | public:
72 | BaseHbaseConnection(const string& host, const int port);
73 | ~BaseHbaseConnection();
74 | bool connect(HbaseClientTransport transport,
75 | int timeout_ms);
76 | T* thrift_client() { return client_.get(); }
77 | const string& host() const { return host_; }
78 | const int port() const { return port_; }
79 | void markUnhealthy() { ++errors_; }
80 | const bool isHealthy() const { return errors_ == 0; }
81 |
82 | private:
83 | const string host_;
84 | const int port_;
85 | std::unique_ptr client_;
86 | int errors_;
87 | };
88 |
89 | template
90 | BaseHbaseConnection::BaseHbaseConnection(
91 | const string& host, const int port)
92 | : host_(host), port_(port), errors_(0) {
93 | }
94 |
95 | template
96 | bool BaseHbaseConnection::connect(
97 | HbaseClientTransport transport_type,
98 | int timeout_ms) {
99 | if (host_.empty()) {
100 | FB_LOG_EVERY_MS(ERROR, 1000) << "Request to connect to invalid host; "
101 | << "empty host specified?!";
102 | return false;
103 | }
104 | if (port_ <= 0) {
105 | FB_LOG_EVERY_MS(ERROR, 1000) << "Invalid port for host " << host_;
106 | return false;
107 | }
108 | VLOG(1) << "Connecting to " << host_ << ":" << port_ << "...";
109 |
110 | try {
111 | boost::shared_ptr socket(new TSocket(host_, port_));
112 | if (timeout_ms > 0) {
113 | socket->setConnTimeout(timeout_ms);
114 | socket->setRecvTimeout(timeout_ms);
115 | socket->setSendTimeout(timeout_ms);
116 | }
117 |
118 | assert(transport_type != DEFAULT_TRANSPORT);
119 |
120 | boost::shared_ptr protocol;
121 | boost::shared_ptr transport;
122 | if (transport_type == BUFFERED_TRANSPORT) {
123 | transport.reset(new TBufferedTransport(socket));
124 | protocol.reset(new TBinaryProtocol(transport));
125 | } else if (transport_type == FRAMED_TRANSPORT) {
126 | transport.reset(new TFramedTransport(socket));
127 | protocol.reset(new TBinaryProtocol(transport));
128 | } else if (transport_type == COMPACT_FRAMED_TRANSPORT) {
129 | transport.reset(new TFramedTransport(socket));
130 | protocol.reset(new TCompactProtocol(transport));
131 | }
132 | #if !NHC_OPEN_SOURCE
133 | else if (transport_type == HEADER_TRANSPORT) {
134 | transport.reset(new THeaderTransport(socket));
135 | protocol.reset(new THeaderProtocol(transport));
136 | } else if (transport_type == HEADER_TRANSPORT_WITH_ZLIB) {
137 | auto transport_tmp = new THeaderTransport(socket);
138 | transport_tmp->setTransform(THeaderTransport::ZLIB_TRANSFORM);
139 | transport.reset(transport_tmp);
140 | protocol.reset(new THeaderProtocol(transport));
141 | }
142 | #endif
143 |
144 | client_.reset(new T(protocol));
145 | transport->open();
146 | VLOG(1) << "done";
147 | }
148 | catch (const TException& e) {
149 | LOG(ERROR) << "Unable to connect to " << host_ << ":" << port_ << ": "
150 | << e.what();
151 | return false;
152 | }
153 | return true;
154 | }
155 |
156 | template
157 | BaseHbaseConnection::~BaseHbaseConnection() {
158 | }
159 |
160 | } } // namespace
161 |
162 | #endif // HBASE_SRC_BASEHBASECONNECTION_H
163 |
--------------------------------------------------------------------------------
/hbase/ConnectionPool.h:
--------------------------------------------------------------------------------
1 | /* Copyright 2012 Facebook, Inc.
2 | *
3 | * Licensed under the Apache License, Version 2.0 (the "License");
4 | * you may not use this file except in compliance with the License.
5 | * You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS,
11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | * See the License for the specific language governing permissions and
13 | * limitations under the License.
14 | */
15 |
16 | // A fairly simple, highly templetized connection pool, intended for
17 | // use with the HBase Client.
18 | //
19 | // A connection pool is similar to a hash, and is templetized on two
20 | // types -- the key to the hash, and the entries. However, in
21 | // addition to this, the pool knows how to create new entries for the
22 | // pool (via callbacks). This allows the pool to expand as needed.
23 | // See the test case for basic usage.
24 |
25 | #ifndef HBASE_SRC_CONNECTIONPOOL_H
26 | #define HBASE_SRC_CONNECTIONPOOL_H
27 |
28 | #include
29 | #include
30 | #include
31 | #include
32 |
33 | #include "folly/Logging.h"
34 |
35 | #include "hbase/Counters.h"
36 |
37 | // This needs to be declared before the template below for clang (ADL
38 | // rules, see http://clang.llvm.org/compatibility.html, somewhat
39 | // complicated by 'const std::pair' being the
40 | // typedef target of HostMapKey).
41 | std::ostream& operator<<(std::ostream& out,
42 | const std::pair& key);
43 |
44 | namespace facebook { namespace hbase {
45 | using std::unordered_multimap;
46 |
47 | template
48 | class ConnectionPool : private boost::noncopyable {
49 | public:
50 | // Types for our callbacks and map.
51 | typedef unordered_multimap connection_multimap;
52 | typedef std::function ConnectionFactory;
53 | typedef std::function ConnectionKeyMaker;
54 |
55 | // The conneciton pool is templetized on the Key and Conn types. In
56 | // addition, the pool contains a maximum number of retained
57 | // connections per key (if more than this limit are requested, they
58 | // will be created on the fly, and deleted when they are finished
59 | // being used).
60 | ConnectionPool(int max_retained_connections_per_key,
61 | int max_total_connections_per_key,
62 | ConnectionFactory factory,
63 | ConnectionKeyMaker key_maker,
64 | CounterBase* counters = NULL)
65 | : max_retained_connections_per_key_(max_retained_connections_per_key),
66 | max_total_connections_per_key_(max_total_connections_per_key),
67 | connection_factory_(factory),
68 | connection_key_maker_(key_maker),
69 | stats_counters_(counters) {
70 | if (max_total_connections_per_key_ > 0) {
71 | CHECK_GE(max_total_connections_per_key_,
72 | max_retained_connections_per_key_);
73 | }
74 | }
75 |
76 | // We should never be destroyed if there are any in-use connections.
77 | ~ConnectionPool() {
78 | std::lock_guard g(connections_mutex_);
79 | VLOG(1) << "Clearing out " << available_connections_.size()
80 | << " entries in the connection pool.";
81 | CHECK_EQ(in_use_connections_.size(), 0)
82 | << "Cannot destroy a connection pool while there are in-use "
83 | << "connections!";
84 | };
85 |
86 | // Given a key, find a connection in our unused connections, or
87 | // create a new connection. Note there is a race here; if multiple
88 | // threads decide to invoke connection_factory_ for this key, then
89 | // multiple entries will be simultaneously created. That's okay,
90 | // the worst result is we missed a chance to re-use an entry
91 | // returned to the pool.
92 | Conn* lookup(const Key& key) {
93 | std::unique_ptr ret;
94 | {
95 | std::lock_guard g(connections_mutex_);
96 | auto p = available_connections_.find(key);
97 | if (p != available_connections_.end()) {
98 | if (stats_counters_) {
99 | stats_counters_->incrementCounter("reused_connections");
100 | }
101 | ret = std::move(p->second);
102 | available_connections_.erase(p);
103 | VLOG(1) << "Using already created connection for " << key;
104 | }
105 | if (!ret.get()) {
106 | int total_key_connections = available_connections_.count(key) +
107 | in_use_connections_.count(key);
108 | VLOG(1) << "Total outstanding connections for " << key << ": "
109 | << total_key_connections;
110 | if (max_total_connections_per_key_ > 0 &&
111 | total_key_connections >= max_total_connections_per_key_) {
112 | FB_LOG_EVERY_MS(ERROR, 500) << "Hit max total allowed connections "
113 | << "for " << key;
114 | return NULL;
115 | }
116 | }
117 | }
118 | if (!ret.get()) {
119 | ret.reset(connection_factory_(key));
120 | if (stats_counters_) {
121 | stats_counters_->incrementCounter("created_connections");
122 | }
123 | if (!ret.get()) {
124 | LOG(ERROR) << "ConnectionPool factory failed to create connection"
125 | << " for key:" << key;
126 | return NULL;
127 | }
128 | VLOG(1) << "Creating connection for " << key;
129 | }
130 | std::lock_guard g(connections_mutex_);
131 | Conn* ret_ptr = ret.get();
132 | in_use_connections_.insert(make_pair(key, std::move(ret)));
133 | return ret_ptr;
134 | }
135 |
136 | // Release a key. If this would put us under the limit we have per
137 | // key, retain the connection, otherwise go ahead and free it.
138 | void release(Conn* conn) {
139 | CHECK(conn != NULL);
140 | if (stats_counters_) {
141 | stats_counters_->incrementCounter("released_connections");
142 | }
143 |
144 | std::unique_ptr conn_holder;
145 | const Key key(connection_key_maker_(conn));
146 | std::lock_guard g(connections_mutex_);
147 | auto p = in_use_connections_.equal_range(key);
148 | for (auto it = p.first; it != p.second; ++it) {
149 | if ((*it).second.get() == conn) {
150 | conn_holder = std::move((*it).second);
151 | in_use_connections_.erase(it);
152 | break;
153 | }
154 | }
155 |
156 | if (available_connections_.count(key) + in_use_connections_.count(key) <
157 | max_retained_connections_per_key_) {
158 | if (conn->isHealthy()) {
159 | VLOG(1) << "Returning healthy connection " << conn << " for " << key
160 | << " to pool";
161 | // Let's double check the exact same connection we're
162 | // releasing isn't already in available_connections_. Just in
163 | // case.
164 | auto p = available_connections_.equal_range(key);
165 | for (auto it = p.first; it != p.second; ++it) {
166 | if ((*it).second.get() == conn) {
167 | LOG(ERROR) << "Attempt to double release a connection?! "
168 | << "Shocking you didn't already crash.";
169 | return;
170 | }
171 | }
172 |
173 | available_connections_.insert(make_pair(key, std::move(conn_holder)));
174 | } else {
175 | if (stats_counters_) {
176 | stats_counters_->incrementCounter("discarded_connections");
177 | }
178 | LOG(ERROR) << "Discarding unhealthy connection " << conn << " for "
179 | << key;
180 | }
181 | } else {
182 | VLOG(1) << "Too many connections for " << key << ", deleting "
183 | << conn;
184 | }
185 | }
186 |
187 | private:
188 | const int max_retained_connections_per_key_;
189 | const int max_total_connections_per_key_;
190 | const ConnectionFactory connection_factory_;
191 | const ConnectionKeyMaker connection_key_maker_;
192 |
193 | std::mutex connections_mutex_;
194 | unordered_multimap> available_connections_;
195 | unordered_multimap> in_use_connections_;
196 |
197 | CounterBase* stats_counters_; // unowned
198 | };
199 |
200 | } } // facebook::hbase
201 |
202 | #endif // HBASE_SRC_CONNECTIONPOOL_H
203 |
--------------------------------------------------------------------------------
/hbase/ConnectionPoolTest.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 Facebook, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | // Test case for the ConnectionPool class.
18 |
19 | #include
20 | #include
21 |
22 | #include "hbase/ConnectionPool.h"
23 |
24 | #include
25 |
26 | namespace h = facebook::hbase;
27 | using std::string;
28 | using std::unordered_set;
29 |
30 | class TestPoolEntry {
31 | public:
32 | explicit TestPoolEntry(const string& s) : entry_name(s), healthy(true) {
33 | all_entries.insert(this);
34 | }
35 | ~TestPoolEntry() {
36 | all_entries.erase(this);
37 | }
38 | bool isHealthy() const { return healthy; }
39 |
40 | const string entry_name;
41 | static unordered_set all_entries;
42 | bool healthy;
43 | };
44 |
45 | unordered_set TestPoolEntry::all_entries;
46 |
47 | TestPoolEntry* factory(const string& s) {
48 | return new TestPoolEntry(s);
49 | }
50 |
51 | TestPoolEntry* null_factory(const string& s) {
52 | return NULL;
53 | }
54 |
55 | const string key_maker(const TestPoolEntry* entry) {
56 | return entry->entry_name;
57 | }
58 |
59 | TEST(ConnectionPool, ConnectionNullPoolTest) {
60 | h::ConnectionPool test_pool(
61 | 100, 0, null_factory, key_maker);
62 | EXPECT_EQ(0, TestPoolEntry::all_entries.size());
63 | TestPoolEntry* e1 = test_pool.lookup("test");
64 | EXPECT_TRUE(e1 == NULL);
65 | EXPECT_EQ(0, TestPoolEntry::all_entries.size());
66 | }
67 |
68 | TEST(ConnectionPool, ConnectionErrorTest) {
69 | h::ConnectionPool test_pool(
70 | 100, 0, factory, key_maker);
71 | EXPECT_EQ(0, TestPoolEntry::all_entries.size());
72 | TestPoolEntry* e1 = test_pool.lookup("test");
73 | EXPECT_TRUE(e1 != NULL);
74 | EXPECT_EQ(1, TestPoolEntry::all_entries.size());
75 | test_pool.release(e1);
76 | EXPECT_EQ(1, TestPoolEntry::all_entries.size());
77 | e1 = test_pool.lookup("test");
78 | e1->healthy = false;
79 | test_pool.release(e1);
80 | EXPECT_EQ(0, TestPoolEntry::all_entries.size());
81 | }
82 |
83 | TEST(ConnectionPool, ConnectionPoolTest) {
84 | {
85 | // Some basic tests with a "large" pool.
86 | h::ConnectionPool test_pool(100, 0, factory,
87 | key_maker);
88 | // starts empty...
89 | EXPECT_EQ(0, TestPoolEntry::all_entries.size());
90 | // should instantiate a new one by calling our factory method,
91 | // which we then let go, but confirm it still exists in the pool.
92 | TestPoolEntry* e1 = test_pool.lookup("test");
93 | EXPECT_EQ(1, TestPoolEntry::all_entries.size());
94 | test_pool.release(e1);
95 | EXPECT_EQ(1, TestPoolEntry::all_entries.size());
96 | // if we ask for one again, we get our old friend e1 back!
97 | EXPECT_EQ(e1, test_pool.lookup("test"));
98 | test_pool.release(e1);
99 | // confirm adding a second one doesn't give us the same entry
100 | TestPoolEntry* e2 = test_pool.lookup("test");
101 | EXPECT_EQ(1, TestPoolEntry::all_entries.size());
102 | TestPoolEntry* e3 = test_pool.lookup("test");
103 | EXPECT_NE(e2, e3);
104 | test_pool.release(e2);
105 | test_pool.release(e3);
106 | }
107 | // confirm ConnectionPool destructor empties out all our pool entries
108 | EXPECT_EQ(0, TestPoolEntry::all_entries.size());
109 | }
110 |
111 | TEST(ConnectionPool, ConnectionPoolLimitTest) {
112 | // Test a pool with a limit of two retained connections. First
113 | // check the basic stuff.
114 | h::ConnectionPool test_pool(2, 100, factory,
115 | key_maker);
116 | EXPECT_EQ(0, TestPoolEntry::all_entries.size());
117 | TestPoolEntry* e1 = test_pool.lookup("test");
118 | EXPECT_EQ(1, TestPoolEntry::all_entries.size());
119 |
120 | // Instantiate a "lot" of pool entries. All but 2 will be freed as
121 | // soon as they are released, as per the construction to test_pool.
122 | std::vector entries;
123 | for (int i = 0; i < 500; ++i) {
124 | TestPoolEntry* e = test_pool.lookup("test");
125 | // e1 plus the first 99 of this loop should get us to the 100 hard
126 | // limit; so subsequent calls will return NULL. Verify that here.
127 | if (i >= 99) {
128 | EXPECT_TRUE(e == NULL);
129 | } else {
130 | EXPECT_TRUE(e != NULL);
131 | entries.push_back(e);
132 | }
133 | }
134 |
135 | // All of 'entries' plus e1. Since we tried to create 500 entries
136 | // with a max retain count of 100, 400 were null so all_entries
137 | // should be limited in size.
138 | EXPECT_EQ(entries.size() + 1, TestPoolEntry::all_entries.size());
139 |
140 | // Release them all; should go back down to 2 entries in the pool
141 | // (e1 and a now unreferenced entry that was in the 'entries'
142 | // vector).
143 | for (TestPoolEntry* entry : entries) {
144 | test_pool.release(entry);
145 | }
146 | EXPECT_EQ(2, TestPoolEntry::all_entries.size());
147 |
148 | test_pool.release(e1);
149 | }
150 |
151 | int main(int argc, char *argv[]) {
152 | testing::InitGoogleTest(&argc, argv);
153 | google::ParseCommandLineFlags(&argc, &argv, true);
154 | return RUN_ALL_TESTS();
155 | }
156 |
--------------------------------------------------------------------------------
/hbase/Counters.h:
--------------------------------------------------------------------------------
1 | /* Copyright 2012 Facebook, Inc.
2 | *
3 | * Licensed under the Apache License, Version 2.0 (the "License");
4 | * you may not use this file except in compliance with the License.
5 | * You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS,
11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | * See the License for the specific language governing permissions and
13 | * limitations under the License.
14 | */
15 |
16 | // A basic definition of what a counter class is, and a trivial,
17 | // non-performant implementation using a simple hash map to store
18 | // counters. More sophisticated implementations might export stats to
19 | // a thrift server or other external source.
20 |
21 | #ifndef HBASE_SRC_COUNTERS_H
22 | #define HBASE_SRC_COUNTERS_H
23 |
24 | #include
25 | #include