├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── COPYING ├── Gopkg.lock ├── Gopkg.toml ├── Makefile ├── README.md ├── client.go ├── client_test.go ├── config.go ├── consumer.go ├── docs ├── designs │ └── design-rafka-rethinking.rst └── server-shutdown.rst ├── errors.go ├── librdkafka.json.sample ├── main.go ├── main_test.go ├── producer.go ├── server.go ├── stats.go └── test ├── Dockerfile ├── Gemfile ├── Gemfile.lock ├── README.md ├── docker-compose.yml ├── end-to-end ├── kafka_helpers.rb ├── librdkafka.test.json ├── skroutz-pu.list ├── skroutz-stable.list └── test_helper.rb /.gitignore: -------------------------------------------------------------------------------- 1 | .vimrc 2 | *dump.rdb 3 | core 4 | librdkafka.json 5 | rafka 6 | test/.bundle 7 | vendor 8 | *.swp 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | branches: 2 | only: 3 | - master 4 | - debian/stretch 5 | - debian/buster 6 | language: go 7 | go: 8 | - "1.11.x" 9 | services: 10 | - docker 11 | before_install: 12 | - curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh 13 | - dep ensure -v 14 | before_script: 15 | - git clone https://github.com/skroutz/kafka-cluster-testbed.git kafkaclustertestbed 16 | - cd kafkaclustertestbed 17 | - docker-compose up --no-start zoo1 zoo2 zoo3 kc1.docker kc2.docker 18 | - docker-compose start 19 | - cd $TRAVIS_BUILD_DIR 20 | script: 21 | - make test 22 | matrix: 23 | include: 24 | - env: "DIST=stretch RDKAFKA_VERSION=v0.11.6" 25 | - env: "DIST=stretch RDKAFKA_VERSION=v1.2.2" 26 | - env: "DIST=buster RDKAFKA_VERSION=v0.11.6" 27 | - env: "DIST=buster RDKAFKA_VERSION=v1.2.2" 28 | jobs: 29 | allow_failures: 30 | - env: "DIST=stretch RDKAFKA_VERSION=v1.2.2" 31 | - env: "DIST=buster RDKAFKA_VERSION=v0.11.6" 32 | - env: "DIST=buster RDKAFKA_VERSION=v1.2.2" 33 | notifications: 34 | slack: 35 | secure: KDA5GK4A6P3rBWlS+UpU5jVTXKWlbljEB9cpdkX23geCPZXuhYKsr50wXPACN0cCLwH+v3LPyfBS7UGCP1I9OjK0/7ersOc+laQl9R75oNTxrlNgVsi9y23cNtBHmBpqFUAYNsXH7Why4+AdF6n/PnlOTFgUgiUwL5X8CIIYmRdOWCsQVCv7ZV1JzGUx7E3fXRr5QIWlqh7/xTGcQoyuKr11Rb/H4Q1hIA5OPgmecfjeMCsnXTv73OqFYoqEj5Kk2koRPFw7Z3G4QecIPdkhApA+M037gjZWCzXXiDysfgESDtE3XAgj4rMNnUMwTH8C68ftH1LtGd5eBwp98wmtj4mMJKue0RQrgxBqoxsyHpZJJ2dSERh78zy+G6guzm7EXkb8hy+OMJr1MZhWZ1FjLpZxQdKVF0cOgGvn+C0qgna8418kfZRBqosK2aHFPW2FjFMEOK0FkCNSE3g8uiobS0plZMTu7Cwu3uI95nmJ0x+05w7nFZM9CkPa2ZE1rcneKDJmNuoexP3TlCxX1FY8MXjC+XIVGGNSiA/tgRD+uivrZicY6NLMfy7WFLez1nBZPDGer0Uj1SCgw0M0wh3vKfwqZQuzhuHVgDNHKvPKdnswut3tuG7Mx83H9XNrm7OVCseDskFkRg+aUcquTWF2gPsJQW+FkvJ3gBUMOZqUaM4= 36 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | Breaking changes are prefixed with a "[BREAKING]" label. 4 | 5 | 6 | ## master (unreleased) 7 | 8 | ## 0.6.2 (2020-10-23) 9 | 10 | - Do not log unknown events as producer errors. Introduce new stats key for 11 | keeping track of unknown producer events. These events do not 12 | include "Connection reset by peers" connection errors. [[#90](https://github.com/skroutz/rafka/pull/90)]. 13 | 14 | ## 0.6.1 (2019-10-09) 15 | 16 | This is a maintenance release with no changes. 17 | 18 | ## 0.6.0 (2019-10-08) 19 | 20 | This is a release refactoring the internal data structures of Rafka as detailed in [Rafka 21 | Rethinking](https://github.com/skroutz/rafka/blob/master/docs/designs/design-rafka-rethinking.rst) 22 | design doc. 23 | 24 | ### Changed 25 | 26 | - [BREAKING] Drop support for multiple Consumers per Client. From now on, only a [single Consumer can be 27 | associated with a Client instance](https://github.com/skroutz/rafka/blob/master/docs/designs/design-rafka-rethinking.rst#redefine-rafka-scope) 28 | 29 | - [INTERNAL] The ConsumerManager module as well as the respective functionality for managing 30 | Consumers has been [completely dropped from the 31 | source](https://github.com/skroutz/rafka/blob/master/docs/designs/design-rafka-rethinking.rst#drop-redundant-functionality). 32 | Now, the handling of Consumers is split between the Server and the respective Client instances. 33 | 34 | 35 | ## 0.5.0 (2019-08-29) 36 | 37 | ### Added 38 | 39 | - Add support for the MONITOR command [[#80](https://github.com/skroutz/rafka/pull/80)] 40 | 41 | ### Changed 42 | 43 | - [BREAKING] Drop support for librdkafka 0.11.4 and before. librdkafka 0.11.5 or later 44 | is now required [[#76](https://github.com/skroutz/rafka/pull/76)] 45 | 46 | - The consumer will now strip "unset" offsets (aka those of `OffsetInvalid` type) from the logging 47 | output [[#79](https://github.com/skroutz/rafka/pull/79)] 48 | 49 | ## 0.4.0 (2019-05-24) 50 | 51 | ### Fixed 52 | 53 | - With librdkafka 0.11.6 and 1.0.0, consumers could block indefinitely in BLPOP, 54 | resulting in rafka being unable to shutdown [[#77](https://github.com/skroutz/rafka/pull/77)] 55 | 56 | ### Added 57 | 58 | - "Unsupported command" errors now contain the actual command that was 59 | attempted by the client [[fa45217](https://github.com/skroutz/rafka/commit/fa45217c8c451591a009dc1398a6d0813916d5bb)] 60 | 61 | ### Changed 62 | 63 | - If there are no messages to be consumed, BLPOP returns a "null array" instead 64 | of a "null string", adhering to the Redis protocol. This is an internal change 65 | that shouldn't affect clients [[adf3650](https://github.com/skroutz/rafka/commit/adf365095ee006a5a0fe31ea633c9038f5f2ec70)] 66 | 67 | - Connection write/flush errors are not logged anymore [[686af22](https://github.com/skroutz/rafka/commit/686af22073877159849d716659e6db2206962d8a)] 68 | 69 | 70 | ## 0.3.0 (2019-05-14) 71 | 72 | ### Added 73 | 74 | - The server now logs errors during writing or flushing a response to the 75 | client [[71aacf5](https://github.com/skroutz/rafka/commit/71aacf59b12d31d5beee905c26b6c1f6d3715a59)] 76 | 77 | ### Changed 78 | 79 | - Incoming message size limit is bumped from 64kB to 32MB [[75fa7ef](https://github.com/skroutz/rafka/commit/75fa7ef023ec55d3c60b1e08e72f0afd127cd92a)] 80 | 81 | ### Fixed 82 | 83 | - Properly return _all_ parse errors to clients [[db39b5f](https://github.com/skroutz/rafka/commit/db39b5f978e39e9bd91017cba94b312a8014dca6)] 84 | 85 | 86 | ## 0.2.0 (2018-10-01) 87 | 88 | ### Added 89 | 90 | - Support for listing topics [[#66](https://github.com/skroutz/rafka/pull/66)] 91 | - Flag for displaying the rafka version (`--version/-v`) [[c650dd0](https://github.com/skroutz/rafka/commit/c650dd063d3468e80e3b7d96549285ffa1d7c951)] 92 | 93 | ### Changed 94 | 95 | - Shutdown process is more robust with less downtime for producers [[#68](https://github.com/skroutz/rafka/pull/68)] 96 | 97 | 98 | ## 0.1.0 (2018-09-24) 99 | 100 | ### Fixed 101 | 102 | - Ignore non-critical "Poll GroupCoordinator" errors [[#69](https://github.com/skroutz/rafka/pull/69)] 103 | 104 | ### Changed 105 | 106 | - [BREAKING] `--kafka/-k` flag is renamed to `--config/-c` [[9be4ea8](https://github.com/skroutz/rafka/commit/9be4ea84d2e7ddf8b33d90e0f6489dd07335dfef)] 107 | 108 | 109 | ## 0.0.16 (2018-06-07) 110 | 111 | ### Fixed 112 | 113 | - Consumers failed to start if librdkafka configuration provided from 114 | clients contained numeric values [[118c36a](https://github.com/skroutz/rafka/commit/118c36af1969b1df81ce0d29f1a36696f94e8a2a)] 115 | 116 | 117 | ## 0.0.15 (2018-06-05) 118 | 119 | This is a maintenance release with no changes. 120 | 121 | 122 | ## 0.0.14 (2018-06-05) 123 | 124 | ### Added 125 | 126 | - Accept configuration from clients [[#40](https://github.com/skroutz/rafka/issues/40)] 127 | 128 | ### Fixed 129 | 130 | - Consumer could hang indefinitely when closing [[#59](https://github.com/skroutz/rafka/issues/59)] 131 | 132 | 133 | ## 0.0.13 (2018-06-05) 134 | 135 | ### Added 136 | 137 | - Offset commit results are now visible in the logs [[c73dae](https://github.com/skroutz/rafka/commit/c73dae044be7903d6b11109cc5cc366d61d98228)] 138 | 139 | 140 | ## 0.0.12 (2018-05-22) 141 | 142 | ### Changed 143 | 144 | - Use librdkafka auto commit and offset store functionality 145 | 146 | 147 | ## 0.0.11 (2018-05-18) 148 | 149 | ### Changed 150 | 151 | - Depend on librdkafka 0.11.4 and confluent-kafka-go 0.11.4 152 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | branch = "master" 6 | name = "github.com/agis/spawn" 7 | packages = ["."] 8 | revision = "2b1649feb264e6da334b227f2233b76b8d88c96c" 9 | 10 | [[projects]] 11 | name = "github.com/confluentinc/confluent-kafka-go" 12 | packages = ["kafka"] 13 | revision = "460e8e43b282a1a68219df600ef63442b81faf5f" 14 | version = "v0.11.6" 15 | 16 | [[projects]] 17 | name = "github.com/go-redis/redis" 18 | packages = [".","internal","internal/consistenthash","internal/hashtag","internal/pool","internal/proto"] 19 | revision = "da63fe7def48e378caf9539abf64b9b1e37bc01e" 20 | version = "v6.5.3" 21 | 22 | [[projects]] 23 | name = "github.com/secmask/go-redisproto" 24 | packages = ["."] 25 | revision = "14323b204640af1628764b06726c64fe040998e1" 26 | 27 | [[projects]] 28 | name = "github.com/urfave/cli" 29 | packages = ["."] 30 | revision = "a14d7d367bc02b1f57d88de97926727f2d936387" 31 | version = "v1.18.1" 32 | 33 | [solve-meta] 34 | analyzer-name = "dep" 35 | analyzer-version = 1 36 | inputs-digest = "b731e47c90c1ef552af3fedbf2e9bd578fa77c9925781c83042ed47bbec9f2f0" 37 | solver-name = "gps-cdcl" 38 | solver-version = 1 39 | -------------------------------------------------------------------------------- /Gopkg.toml: -------------------------------------------------------------------------------- 1 | [[constraint]] 2 | name = "github.com/confluentinc/confluent-kafka-go" 3 | version = "=0.11.6" 4 | 5 | [[constraint]] 6 | name = "github.com/urfave/cli" 7 | version = "1.18.1" 8 | 9 | [[constraint]] 10 | name = "github.com/secmask/go-redisproto" 11 | revision = "14323b204640af1628764b06726c64fe040998e1" 12 | 13 | [[constraint]] 14 | name = "github.com/go-redis/redis" 15 | version = "6.5.3" 16 | 17 | [[constraint]] 18 | branch = "master" 19 | name = "github.com/agis/spawn" 20 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: install dep build test teste2e testunit lint fmt clean run-rafka run-rafka-local testunit-local teste2e-local 2 | 3 | default: fmt install test 4 | 5 | install: 6 | go install -v 7 | 8 | dep: 9 | dep ensure -v 10 | 11 | build: fmt 12 | CGO_ENABLED=1 go build -v -ldflags '-X main.VersionSuffix=$(shell git rev-parse HEAD)' 13 | 14 | testunit-local: 15 | go test -race 16 | 17 | teste2e-local: 18 | cd test && bundle install --frozen && ./end-to-end -v 19 | 20 | lint: 21 | golint 22 | 23 | fmt: 24 | test -z `go fmt 2>&1` 25 | 26 | clean: 27 | go clean 28 | 29 | run-rafka-local: build 30 | ./rafka -c test/librdkafka.test.json 31 | 32 | run-rafka: dep 33 | docker-compose -f test/docker-compose.yml up --no-start --build 34 | docker-compose -f test/docker-compose.yml start 35 | 36 | testunit: run-rafka 37 | docker-compose -f test/docker-compose.yml exec rafka make testunit-local 38 | 39 | teste2e: run-rafka 40 | docker-compose -f test/docker-compose.yml exec rafka make teste2e-local 41 | 42 | test: run-rafka 43 | docker-compose -f test/docker-compose.yml exec rafka make testunit-local teste2e-local 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | rafka 2 | ===== 3 | 4 | [![Build Status](https://api.travis-ci.org/skroutz/rafka.svg?branch=master)](https://travis-ci.org/skroutz/rafka) 5 | [![Go report](https://goreportcard.com/badge/github.com/skroutz/rafka)](https://goreportcard.com/report/github.com/skroutz/rafka) 6 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 7 | 8 | #### Table of Contents 9 | 10 | - [Rationale](#rationale) 11 | - [Requirements](#requirements) 12 | - [Getting Started](#getting-started) 13 | - [Design](#design) 14 | - [Protocol](#protocol) 15 | - [Consumer](#consumer) 16 | - [Producer](#producer) 17 | - [API](#api) 18 | - [Protocol](#protocol) 19 | - [Consumer](#consumer) 20 | - [Generic](#generic) 21 | - [Client libraries](#client-libraries) 22 | - [Development](#development) 23 | - [License](#license) 24 | 25 | 26 | rafka is a gateway service that exposes Kafka using simple semantics. 27 | 28 | It implements a small subset of the [Redis protocol](https://redis.io/topics/protocol), so that it 29 | can be used by leveraging existing Redis client libraries. 30 | 31 | Rationale 32 | --------- 33 | 34 | Using Kafka with languages that lack a reliable, solid client library can be a problem for 35 | mission-critical applications. 36 | 37 | Using rafka we can: 38 | 39 | - Hide Kafka low-level details from the application and provide sane defaults, backed by the 40 | excellent [librdkafka](https://github.com/edenhill/librdkafka). 41 | - Use a Redis client instead of a Kafka client. This is particularly useful in languages that lack a 42 | proper Kafka client library or do not provide concurrency primitives to implement buffering and 43 | other optimizations. Furthermore, writing a rafka client is much easier than writing a Kafka 44 | client. For a list of available client libraries see [_Client libraries_](#client-libraries). 45 | 46 | Refer to [*"Introducing Kafka to a Rails application"*](https://engineering.skroutz.gr/blog/kafka-rails-integration/) 47 | for more background and how rafka is used in a production environment. 48 | 49 | Requirements 50 | ------------ 51 | 52 | - [librdkafka](https://github.com/edenhill/librdkafka) 0.11.5 or later 53 | - A Kafka cluster 54 | 55 | Getting Started 56 | ------------ 57 | 58 | 1. Install [librdkafka](https://github.com/edenhill/librdkafka): 59 | 60 | ```shell 61 | # debian 62 | $ sudo apt-get install librdkafka-dev 63 | 64 | # macOS 65 | $ brew install librdkafka 66 | ``` 67 | 68 | 2. Install rafka: 69 | 70 | ```shell 71 | $ go get -u github.com/skroutz/rafka 72 | ``` 73 | 74 | 3. Run it: 75 | 76 | ```shell 77 | $ rafka -c librdkafka.json.sample 78 | [rafka] 2017/06/26 11:07:23 Spawning Consumer Manager (librdkafka 0.11.0)... 79 | [server] 2017/06/26 11:07:23 Listening on 0.0.0.0:6380 80 | ``` 81 | 82 | Design 83 | ------ 84 | 85 | ### Protocol 86 | 87 | rafka exposes a subset of the [Redis protocol](https://redis.io/topics/protocol) and tries to keep 88 | Redis semantics where possible. 89 | 90 | We also try to design the protocol in a way that rafka can be replaced by a plain Redis instance so 91 | that it's easier to test client code and libraries. 92 | 93 | ### Consumer 94 | 95 | In Kafka, each consumer represents a worker processing messages. That worker sends heartbeats and 96 | is de-pooled from its group when it misbehaves. 97 | 98 | Those semantics are preserved in rafka by using _stateful connections_. In rafka, each connection 99 | is tied with a set of Kafka consumers. Consumers are not shared between connections and once the 100 | connection closes, the respective consumers are gracefully shut down too. 101 | 102 | Each consumer must identify itself upon connection, by using `client setname :`. 103 | Then it can begin processing messages by issuing `blpop` calls on the desired topics. Each message 104 | should be explicitly acknowledged so it can be committed to Kafka. Acks are `rpush`ed to the 105 | special `acks` key. 106 | 107 | For more info refer to [API - Consumer](https://github.com/skroutz/rafka#consumer-1). 108 | 109 | #### Caveats 110 | 111 | rafka periodically calls [`Consumer.StoreOffsets()`](https://docs.confluent.io/current/clients/confluent-kafka-go/index.html#Consumer.StoreOffsets) 112 | under the hood. This means consumers must be configured accordingly: 113 | 114 | - `enable.auto.commit` must be set to `true` 115 | - `enable.auto.offset.store` [must](https://github.com/edenhill/librdkafka/blob/v0.11.4/src/rdkafka.h#L2665) be set to `false` 116 | 117 | For more info see https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md. 118 | 119 | ### Producer 120 | 121 | - Each client connection is tied to a single Producer. 122 | - Producers are not shared between connections and once the connection closes, its producer is also 123 | shutdown gracefully. 124 | - Producers produce messages using `RPUSHX`. 125 | - Produced messages are buffered in rafka and are eventually flushed to Kafka. However, `DUMP` can 126 | be used to force a synchronous flush of any outstanding messages. 127 | 128 | For more info refer to [API - Producer](https://github.com/skroutz/rafka#producer-1). 129 | 130 | #### Caveats 131 | 132 | There is currently is an upper message limit of **32MB** to the messages that may be produced. It 133 | is controlled by `go-redisproto.MaxBulkSize`. 134 | 135 | API 136 | --- 137 | 138 | ### Producer 139 | 140 | - `RPUSHX topics: ` produce a message 141 | - `RPUSHX topics:: ` produce a message with a partition key. Messages with 142 | the same key will always be assigned to the same partition. 143 | - `DUMP ` flush any outstanding messages to Kafka. This is a blocking operation; it 144 | returns until all buffered messages are flushed or the timeoutMs exceeds 145 | 146 | Example using redis-cli: 147 | 148 | ```shell 149 | 127.0.0.1:6380> rpushx topics:greetings "hello there!" 150 | "OK" 151 | ``` 152 | 153 | ### Consumer 154 | 155 | - `CLIENT SETNAME :` sets the consumer group and name 156 | - `CLIENT GETNAME` 157 | - `BLPOP topics:: ` consume the next message from 158 | topic 159 | - `RPUSH acks ::` commit the offset for the given topic/partition 160 | 161 | Example using redis-cli: 162 | 163 | ```shell 164 | 127.0.0.1:6380> client setname myapp:a-consumer 165 | "OK" 166 | 127.0.0.1:6380> blpop topics:greetings 1000 167 | 1) "topic" 168 | 2) "greetings" 169 | 3) "partition" 170 | 4) (integer) 2 171 | 5) "offset" 172 | 6) (integer) 10 173 | 7) "value" 174 | 8) "hello there!" 175 | # ... do some work with the greeting... 176 | 127.0.0.1:6380> rpush acks greetings:2:10 177 | "OK" 178 | ``` 179 | 180 | ### Generic 181 | 182 | - [`PING`](https://redis.io/commands/ping) 183 | - [`QUIT`](https://redis.io/commands/quit) 184 | - [`MONITOR`](https://redis.io/commands/monitor) 185 | - `HGETALL stats` get monitoring statistics monitoring 186 | - `KEYS topics:` list all topics 187 | - `DEL stats` reset the monitoring statistics 188 | 189 | Client libraries 190 | ---------------- 191 | 192 | - Ruby: [rafka-rb](https://github.com/skroutz/rafka-rb) 193 | 194 | Development 195 | ----------- 196 | 197 | If this is your first time setting up development on rafka, ensure that you have all the build 198 | dependencies via [dep](https://github.com/golang/dep): 199 | 200 | ```shell 201 | $ dep ensure 202 | ``` 203 | 204 | To run all the tests (Go + end-to-end) do: 205 | 206 | ```shell 207 | $ DIST=buster RDKAFKA_VERSION=v1.2.1 make test 208 | ``` 209 | 210 | License 211 | ------- 212 | 213 | rafka is released under the GNU General Public License version 3. See [COPYING](COPYING). 214 | -------------------------------------------------------------------------------- /client.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017-2019 Skroutz S.A. 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | package main 16 | 17 | import ( 18 | "bufio" 19 | "context" 20 | "errors" 21 | "fmt" 22 | "log" 23 | "net" 24 | "os" 25 | "strings" 26 | "sync" 27 | 28 | rdkafka "github.com/confluentinc/confluent-kafka-go/kafka" 29 | redisproto "github.com/secmask/go-redisproto" 30 | ) 31 | 32 | type Client struct { 33 | id string 34 | conn net.Conn 35 | cfg Config 36 | ctx context.Context 37 | log *log.Logger 38 | monitorChan chan string 39 | 40 | consGID string 41 | consReady bool 42 | 43 | consWg *sync.WaitGroup 44 | 45 | consumer *Consumer 46 | producer *Producer 47 | } 48 | 49 | // NewClient returns a new client. After it's no longer needed, the client 50 | // should be closed with Close(). 51 | func NewClient(ctx context.Context, conn net.Conn, cfg Config) *Client { 52 | id := conn.RemoteAddr().String() 53 | 54 | client := &Client{ 55 | id: id, 56 | monitorChan: make(chan string, 1000), 57 | conn: conn, 58 | cfg: cfg, 59 | ctx: ctx, 60 | log: log.New(os.Stderr, fmt.Sprintf("[client-%s] ", id), log.Ldate|log.Ltime), 61 | } 62 | 63 | go client.monitorWriter() 64 | 65 | return client 66 | } 67 | 68 | // monitorWriter streams any monitor strings written to the client's monitor channel. 69 | func (c *Client) monitorWriter() { 70 | writer := redisproto.NewWriter(bufio.NewWriter(c.conn)) 71 | for monitorOutput := range c.monitorChan { 72 | writer.WriteSimpleString(monitorOutput) 73 | writer.Flush() 74 | } 75 | } 76 | 77 | // SetID sets the id for c. It returns an error if id is not in the form of 78 | // :. 79 | func (c *Client) SetID(id string) error { 80 | if c.consReady { 81 | return errors.New("Client ID is already set to " + c.id) 82 | } 83 | 84 | parts := strings.SplitN(id, ":", 2) 85 | if len(parts) != 2 { 86 | return errors.New("Cannot parse group.id") 87 | } 88 | 89 | c.id = id 90 | c.consGID = parts[0] 91 | c.log.SetPrefix(fmt.Sprintf("[client-%s] ", c.id)) 92 | c.consReady = true 93 | return nil 94 | } 95 | 96 | func (c *Client) String() string { 97 | return c.id 98 | } 99 | 100 | // registerConsumer registers a new Consumer denoted by cid. 101 | func (c *Client) registerConsumer( 102 | cid ConsumerID, gid string, topics []string, cfg rdkafka.ConfigMap) (*Consumer, error) { 103 | 104 | if gid == "" { 105 | return nil, errors.New("Failed to register Consumer (attr: `group.id` is missing)") 106 | } 107 | 108 | // apparently, reusing the same config between consumers silently makes them non-operational 109 | kafkaCfg := rdkafka.ConfigMap{} 110 | for k, v := range c.cfg.Librdkafka.Consumer { 111 | err := kafkaCfg.SetKey(k, v) 112 | if err != nil { 113 | return nil, err 114 | } 115 | } 116 | for k, v := range cfg { 117 | err := kafkaCfg.SetKey(k, v) 118 | if err != nil { 119 | return nil, err 120 | } 121 | } 122 | err := kafkaCfg.SetKey("group.id", gid) 123 | if err != nil { 124 | return nil, err 125 | } 126 | 127 | // Extract the consumer name from the client id. 128 | // We know by client.Consumer() that cid is in the form of `|` 129 | cidNoTopics := strings.Split(strings.Split(string(cid), "|")[0], ":")[1] 130 | err = kafkaCfg.SetKey("client.id", cidNoTopics) 131 | if err != nil { 132 | return nil, err 133 | } 134 | 135 | ctx, consumerCancel := context.WithCancel(c.ctx) 136 | cons, err := NewConsumer(cid, topics, kafkaCfg) 137 | if err != nil { 138 | return nil, err 139 | } 140 | cons.cancel = consumerCancel 141 | 142 | c.consWg.Add(1) 143 | go func(ctx context.Context) { 144 | defer c.consWg.Done() 145 | cons.Run(ctx) 146 | }(ctx) 147 | 148 | return cons, nil 149 | } 150 | 151 | // Consumer method will either create a new consumer via the registerConsumer method, or it will 152 | // simple return the already registered Consumer for the current Client. 153 | func (c *Client) Consumer(topics []string, cfg rdkafka.ConfigMap) (*Consumer, error) { 154 | if !c.consReady { 155 | return nil, errors.New("Connection not ready. Identify yourself using `CLIENT SETNAME` first") 156 | } 157 | 158 | cid := ConsumerID(fmt.Sprintf("%s|%s", c.id, strings.Join(topics, ","))) 159 | 160 | if c.consumer == nil { 161 | cons, err := c.registerConsumer(cid, c.consGID, topics, cfg) 162 | if err != nil { 163 | return nil, fmt.Errorf("Failed to register Consumer '%s' for Client '%s'", cid, c.id) 164 | } 165 | c.consumer = cons 166 | } else if cid != c.consumer.id { 167 | return nil, fmt.Errorf("Client '%s' has Consumer '%s' registered (new consID: '%s')", c.id, 168 | c.consumer.id, cid) 169 | } 170 | 171 | return c.consumer, nil 172 | } 173 | 174 | // Producer returns c's producer. If c does not have a producer assigned yet, 175 | // a new one is created and assigned to it. 176 | func (c *Client) Producer(cfg rdkafka.ConfigMap) (*Producer, error) { 177 | var err error 178 | 179 | if c.producer != nil { 180 | return c.producer, nil 181 | } 182 | 183 | // reusing the same config between producers causes: 184 | // fatal error: concurrent map read and map write 185 | kafkaCfg := rdkafka.ConfigMap{} 186 | for k, v := range cfg { 187 | err := kafkaCfg.SetKey(k, v) 188 | if err != nil { 189 | c.log.Printf("Error configuring producer: %s", err) 190 | } 191 | } 192 | 193 | c.producer, err = NewProducer(kafkaCfg) 194 | if err != nil { 195 | return nil, err 196 | } 197 | 198 | return c.producer, nil 199 | } 200 | 201 | // Close closes producers, consumers and the connection of c. 202 | // Calling Close on an already closed client will result in a panic. 203 | func (c *Client) Close() { 204 | if c.consumer != nil { 205 | c.consumer.cancel() 206 | } 207 | 208 | if c.producer != nil { 209 | c.producer.Close() 210 | } 211 | 212 | close(c.monitorChan) 213 | c.conn.Close() 214 | } 215 | -------------------------------------------------------------------------------- /client_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/go-redis/redis" 8 | ) 9 | 10 | func TestSetIDTwice(t *testing.T) { 11 | c := redis.NewClient(&redis.Options{ 12 | Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), 13 | OnConnect: func(c *redis.Conn) error { 14 | res := c.ClientSetName("foobar:foo2") 15 | if res.Err() != nil { 16 | t.Fatal(res.Err()) 17 | } 18 | 19 | if c.ClientSetName("foobar:foo3").Err() == nil { 20 | t.Fatal("Expected error, got nothing") 21 | } 22 | return nil 23 | }}) 24 | 25 | c.Ping().Result() 26 | } 27 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017-2019 Skroutz S.A. 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | package main 16 | 17 | import ( 18 | rdkafka "github.com/confluentinc/confluent-kafka-go/kafka" 19 | ) 20 | 21 | type Config struct { 22 | Host string 23 | Port int 24 | 25 | Librdkafka struct { 26 | General rdkafka.ConfigMap `json:"general"` 27 | Consumer rdkafka.ConfigMap `json:"consumer"` 28 | Producer rdkafka.ConfigMap `json:"producer"` 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /consumer.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017-2019 Skroutz S.A. 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | package main 16 | 17 | import ( 18 | "context" 19 | "errors" 20 | "fmt" 21 | "log" 22 | "os" 23 | "sync" 24 | 25 | rdkafka "github.com/confluentinc/confluent-kafka-go/kafka" 26 | ) 27 | 28 | type ConsumerID string 29 | 30 | type Consumer struct { 31 | id ConsumerID 32 | consumer *rdkafka.Consumer 33 | topics []string 34 | cfg rdkafka.ConfigMap 35 | cancel context.CancelFunc 36 | log *log.Logger 37 | 38 | mu *sync.Mutex 39 | terminated bool 40 | } 41 | 42 | type TopicPartition struct { 43 | Topic string 44 | Partition int32 45 | } 46 | 47 | type OffsetEntry struct { 48 | tp TopicPartition 49 | offset rdkafka.Offset 50 | } 51 | 52 | func NewConsumer(id ConsumerID, topics []string, cfg rdkafka.ConfigMap) (*Consumer, error) { 53 | var err error 54 | 55 | c := Consumer{ 56 | id: id, 57 | topics: topics, 58 | cfg: cfg, 59 | log: log.New(os.Stderr, fmt.Sprintf("[consumer-%s] ", id), log.Ldate|log.Ltime), 60 | mu: new(sync.Mutex), 61 | } 62 | 63 | c.consumer, err = rdkafka.NewConsumer(&cfg) 64 | if err != nil { 65 | return nil, err 66 | } 67 | 68 | return &c, nil 69 | } 70 | 71 | func (c *Consumer) Run(ctx context.Context) { 72 | c.consumer.SubscribeTopics(c.topics, nil) 73 | 74 | c.log.Printf("Started working (%v)...", c.cfg) 75 | <-ctx.Done() 76 | 77 | c.mu.Lock() 78 | defer c.mu.Unlock() 79 | // Close() will also trigger a commit since enable.auto.commit is true 80 | // so we don't need to commit explicitly 81 | err := c.consumer.Close() 82 | if err != nil { 83 | c.log.Printf("Error closing: %s", err) 84 | } 85 | c.terminated = true 86 | c.log.Println("Bye") 87 | } 88 | 89 | // filterOutInvalidOffsets filters out any Offsets of type OffsetInvalid from the given OffsetsCommitted argument. 90 | func filterOutInvalidOffsets(offsets rdkafka.OffsetsCommitted) rdkafka.OffsetsCommitted { 91 | updatedParts := []rdkafka.TopicPartition{} 92 | for _, part := range offsets.Offsets { 93 | if part.Offset != rdkafka.OffsetInvalid { 94 | updatedParts = append(updatedParts, part) 95 | } 96 | } 97 | return rdkafka.OffsetsCommitted{offsets.Error, updatedParts} 98 | } 99 | 100 | func (c *Consumer) Poll(timeoutMS int) (*rdkafka.Message, error) { 101 | c.mu.Lock() 102 | defer c.mu.Unlock() 103 | 104 | if c.terminated { 105 | return nil, nil 106 | } 107 | 108 | ev := c.consumer.Poll(timeoutMS) 109 | if ev == nil { 110 | return nil, nil 111 | } 112 | 113 | switch e := ev.(type) { 114 | case *rdkafka.Message: 115 | return e, nil 116 | case rdkafka.OffsetsCommitted: 117 | c.log.Print(filterOutInvalidOffsets(e)) 118 | case rdkafka.Error: 119 | // Treat errors with error code ErrTransport as transient And just log them. 120 | // For now all other errors cause a failure. 121 | // https://github.com/edenhill/librdkafka/issues/1987#issuecomment-422008750 122 | if e.Code() != rdkafka.ErrTransport { 123 | return nil, errors.New(e.String()) 124 | } 125 | 126 | c.log.Printf("Consumer: Poll: Transient error: %s , code: %d", e.String(), e.Code()) 127 | default: 128 | c.log.Printf("Unknown event type: %T", e) 129 | } 130 | 131 | return nil, nil 132 | } 133 | 134 | // SetOffset sets the offset for the given topic and partition to pos. 135 | // Commiting the offset to Kafka is handled by librdkafka in the background. 136 | func (c *Consumer) SetOffset(topic string, partition int32, pos rdkafka.Offset) error { 137 | if pos < 0 { 138 | return fmt.Errorf("offset cannot be negative, got %d", pos) 139 | } 140 | 141 | // Calling StoreOffsets manually prohibits the caller from using 142 | // `enable.auto.offset.store` option. 143 | // See https://github.com/edenhill/librdkafka/blob/v0.11.4/src/rdkafka.h#L2665 144 | _, err := c.consumer.StoreOffsets([]rdkafka.TopicPartition{ 145 | { 146 | Topic: &topic, 147 | Partition: partition, 148 | Offset: pos, 149 | }, 150 | }) 151 | return err 152 | } 153 | -------------------------------------------------------------------------------- /docs/designs/design-rafka-rethinking.rst: -------------------------------------------------------------------------------- 1 | ================== 2 | Rethinking Rafka 3 | ================== 4 | 5 | .. contents:: :depth: 3 6 | 7 | This is a design document detailing the plan for refactoring the internal structure of Rafka. Also, 8 | the new simplified design will allow to provide the required native support for performance metrics 9 | for the Rafka server. 10 | 11 | 12 | Current state and shortcomings 13 | ============================== 14 | 15 | The main rationale behind Rafka is to expose a subset of the Kafka API, i.e., the `Consumer` and 16 | `Producer` API, by taking advantage of the Redis protocol and leveraging the already existing Redis 17 | client libraries, mainly targeting languages that lack of a Kafka client library with proper 18 | concurrency primitives. `However, the initial design decision for a simple and straightforward API 19 | is not reflected in the internal structure of Rafka`. 20 | 21 | Shortly, in order to implement the (simple) Rafka API, we internally maintain `five` primary 22 | structs; the `Server`, `Client`, `Consumer`, `Producer`, and the `ConsumerManager`. Those structs 23 | work interchangeably by operating on common data structures, which apparently translates to a lot 24 | of extra lines of code for synchronizing and properly orchestrating the requests handling. Besides 25 | the error-prone nature of that extra complexity, it proved to be quite difficult to follow the 26 | execution flow and most important to isolate the interested parties in case of a bug or failure. 27 | 28 | Furthermore, an important feature that Rafka currently lacks of, is the support of proper 29 | monitoring primitives and metrics. There's no way to monitor the server's status, inspect the 30 | Rafka-to-Kafka interaction, follow a request's life-cycle, and generally monitoring the server's 31 | performance. There are a lot of incidents reported lately about lost messages on high-traffic 32 | production setups and it is currently impossible to identify the root cause of those failures. 33 | 34 | 35 | Background 36 | ========== 37 | 38 | This section provides some extra information about Rafka internals, in order to facilitate the 39 | reading of the rest of this design document. 40 | 41 | Core components 42 | --------------- 43 | 44 | The majority of Rafka functionality is internally handled by the following `5` major components. A 45 | short description of each of those components, follows: 46 | 47 | * ``Producer``, the interface used to send data streams to Kafka. It is allowed to produce to any 48 | Kafka topic using the same `Producer` instance. 49 | 50 | * ``Consumer``, it allows reading data streams from Kafka. A `Consumer` is allowed to be subscribed 51 | to either one topic or a list of Kafka topics. 52 | 53 | * ``ConsumerManager``, it maintains a mapping of **all** registered `Consumers` in the server. It 54 | uses this mapping to return the appropriate `Consumer` to the requested `Client`. There's a 55 | single `ConsumerManager` object per server and so it's scope is global. 56 | 57 | * ``Client``, it is created upon a new connection to Rafka and can currently serve a `Producer` 58 | and/or one (or more) `Consumer` processes. It is associated with a client ID which apparently is 59 | unique across the server (this is ensured via the ``ClientByID`` server's field). Also note that 60 | each `Client` instance holds a reference to the global `ConsumerManager` object, too. 61 | 62 | * ``Server``, it maintains a map with **all** registered `Clients`. It holds a reference to the 63 | global `ConsumerManager` object, just like the registered `Clients` do. It also takes over the 64 | Redis command handling. 65 | 66 | Assumptions 67 | ----------- 68 | 69 | As already mentioned, a `Client` can be mapped to a single `Producer` instance. At the same time, 70 | the same `Client` object can be mapped to more than one `Consumer` instances, too. A new `Consumer` 71 | instance will be created per subscribed Kafka topic (or topics). The subscribed topic(s) are also 72 | included in the `ConsumerID`, which has the following format: 73 | 74 | 75 | ``|`` 76 | 77 | Apparently, it is not allowed to create two consumers for the same topic for the same `Client` 78 | instance. To better visualize this behavior, consider the following snippet using the common Redis 79 | client: 80 | 81 | .. code-block:: shell 82 | 83 | # Set the consumer group-id and name (client setname :) 84 | 127.0.0.1:6380> client setname myapp:a-consumer 85 | "OK" 86 | # Create a consumer subscribed to topic test_topic_1 87 | # consumerID: `myapp:a-consumer|test_topic_1` 88 | 127.0.0.1:6380> blpop topics:test_topic_1 5 89 | (nil) 90 | (5.01s) 91 | # Create a consumer subscribed to topics test_topic_2 & test_topic_3 92 | # consumerID: `myapp:a-consumer|test_topic_2,test_topic_3` 93 | 127.0.0.1:6380> blpop topics:test_topic_2,test_topic_3 5 94 | (nil) 95 | (5.01s) 96 | # Try to create a consumer to the already subscribed topic test_topic_3 97 | 127.0.0.1:6380> blpop topics:test_topic_3 5 98 | (error) CONS Topic test_topic_3 has another consumer 99 | 100 | .. note:: 101 | 102 | Note that when Rafka is used via the official Ruby client (aka `rafka-rb`_), it is not 103 | possible to create more than one consumers for the same connection (aka `Client`). The 104 | ``Rafka::Consumer`` API is mapped to a single Rafka `Client`, using a single `Consumer` instance, 105 | which is subscribed to a given list of topics. Using a tool like `redis-client` which allows 106 | operating on the same connection, is currently the only way to assign more than one consumers to 107 | a single `Client` instance. 108 | 109 | .. _`rafka-rb`: https://github.com/skroutz/rafka-rb 110 | 111 | 112 | Proposed changes 113 | ================ 114 | 115 | This document proposes a more simplified Rafka design; in order to make the source code more robust 116 | and maintainable, we should decouple the primary Rafka structs from any extra logic as well as drop 117 | the redundant synchronization functionality that we currently maintain. In short, the primary Rafka 118 | structures should be abstracted further and become completely self-contained, if possible. This 119 | refactoring will also translate to a lighter server implementation since we can move the Redis 120 | command handling to the responsible modules. Finally, by limiting the project's scope and by 121 | separating the modules' responsibilities, we ease the implementation of proper performance metrics' 122 | support for the Rafka server. 123 | 124 | The current proposal suggests splitting the implementation into 4 logical phases in order to ensure 125 | a smoother transition to the new design. Finally, note that the external API and generally any 126 | interaction with existing functionality won't be affected. 127 | 128 | Redefine Rafka scope 129 | -------------------- 130 | 131 | Rafka's main target is to expose a simple API to interact with Kafka. To keep it simply internally, 132 | we could start with revisiting the `Consumer`-specific `Assumptions`_ we maintain for the `Client` 133 | struct. The question we should answer first is if there are any valid reasons to maintain this 134 | `one-to-many` relationship between `Clients` and `Consumers`. `rafka-rb`_ already maintains an 135 | `one-to-one` relationship between a `Client` and a `Consumer` and the only way to create a second 136 | consumer for the same connection would be by using a tool which allow us to operate on the same 137 | connection, like the `redis-client` for example. In short, we maintain a lot of extra logic for a 138 | feature which is not likely to be used on production setups; it is impractical, never used, and we 139 | should stop supporting it. 140 | 141 | An immediate benefit of this modification is that the `Client` struct will be simplified 142 | significantly, since the functionality related to this feature will be dropped completely, starting 143 | with the ``consByTopic`` and ``consumers`` `Client` fields, as well as all the related parties. Of 144 | course, for the same reason there's no way to support the creation of both a `Producer` and a 145 | `Consumer` for the same `Client` object and this feature should be stopped supported, too. 146 | 147 | Short story after; a `Client` would be mapped to either a single `Producer` instance or to a single 148 | `Consumer` which can (apparently) be able to be subscribed to one or more topics. 149 | 150 | Drop redundant functionality 151 | ---------------------------- 152 | 153 | Following the previous section's modifications, it allows us to get rid of the ``ConsumerManager`` 154 | module completely. Since the `Client` could only be mapped to a single `Consumer` at a time, the 155 | `ConsumerManager` module becomes redundant. On the contrary, the `Client` module will become the 156 | primary authoritative structure for handling its registered `Consumer` object, as it is 157 | semantically expected to happen. It will take over the tasks to create, destroy, stop, or cancel a 158 | registered `Consumer` without the extra overhead of the ``ConsumerManager`` logic. 159 | 160 | Separation of concerns 161 | ---------------------- 162 | 163 | Moving a step forward, we can further abstract the internal API of the `Client` struct. What a 164 | `Client` should actually know, is the connection and the ID that Rafka associates with it. The 165 | implementation details of whether a `Client` corresponds to a `Producer` or a `Consumer` instance 166 | should be moved away from this module by taking advantage of Go's interfaces and common Factory 167 | method patterns. Separating the actions from the data will allow us to also make the ``MONITOR`` 168 | logic a first-class citizen similar to the `Producer` and `Consumer` ones. 169 | 170 | Moreover, we could decouple the `Server` from the end-to-end handling of the supported Redis 171 | commands. Ideally, each component (`Consumer`, `Producer`, `Monitor`) should be authoritative of 172 | the Redis commands it can handle. For example, an incoming `BLPOP` request should not be handled by 173 | the `Server` directly; instead, it should be forwarded to the interested party (aka the `Consumer` 174 | in that case), which should properly process the command, create the write buffers, and respond 175 | appropriately. 176 | 177 | Performance metrics 178 | ------------------- 179 | 180 | A production Rafka setup may handle a quite significant amount of traffic. Exporting metrics about 181 | the server's state, is the only way to ensure that Rafka performs and operates smoothly. We could 182 | expose metrics in various areas like: 183 | 184 | - **Health metrics**, such as health and/or availability stats for the server 185 | - **Server metrics**, such as clients connections, global requests count, etc 186 | - **Client metrics**, such as producer metrics (number of messages received from a client, 187 | acknowledged, flushed to Kafka, etc), consumer-specific stats, etc 188 | 189 | .. TODO: Implementation details of the current feature and enhanced metrics' list 190 | 191 | 192 | Future enhancements 193 | =================== 194 | 195 | Implementing **Error handling** primitives is a challenging task; Rafka currently lacks of proper 196 | error handling techniques to handle and respond to such erroneous conditions. Decoupling the custom 197 | error logic to a separate module, and creating proper error codes and handlers, will help in 198 | maintaining the normal program's flow. We could probably combine such feature with the new `Error 199 | Wrapping`_ feature which was introduced on `Go v1.13`. 200 | 201 | .. TODO: More details about Error Handling in Rafka 202 | 203 | .. _`Error Wrapping`: https://golang.org/doc/go1.13#error_wrapping 204 | 205 | 206 | .. vim: set textwidth=99 : 207 | .. Local Variables: 208 | .. mode: rst 209 | .. fill-column: 99 210 | .. End: 211 | -------------------------------------------------------------------------------- /docs/server-shutdown.rst: -------------------------------------------------------------------------------- 1 | ====================== 2 | Server Shutdown Flow 3 | ====================== 4 | 5 | This document details the sequence of operations executed when Rafka server receives a shutdown 6 | signal. The steps executed by the `Server` are summarized in the following list: 7 | 8 | #. Receives the shutdown request 9 | #. Stops accepting new `Consumers` 10 | #. Closes all `Clients` with an active `Consumer` instance 11 | #. Waits for all `Consumers` to terminate 12 | #. Stops accepting new `Clients` 13 | #. Closes `Clients` with an active `Producer` instance 14 | #. Terminates 15 | 16 | In the above rules set, there's a (rare) case which affects the described flow. Rafka currently 17 | allows a single `Client` instance to maintain both a `Consumer` as well as a `Producer` instance. 18 | When such `Client` is requested to close (3), its associated `Producer` will close too, without 19 | waiting for all `Consumers` to terminate. 20 | 21 | Furthermore, we should clarify that as soon as we're waiting for active `Consumers` to terminate, 22 | new `Producers` can be registered. Based on Rafka server's load, a `Consumer` terminate operation 23 | may last longer than expected; in that case we don't want to block the `Producers`, and so we allow 24 | new `Producer` connections to be created. 25 | 26 | .. vim: set textwidth=99 : 27 | .. Local Variables: 28 | .. mode: rst 29 | .. fill-column: 99 30 | .. End: 31 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "errors" 4 | 5 | var ErrShutdown = errors.New("shutdown") 6 | -------------------------------------------------------------------------------- /librdkafka.json.sample: -------------------------------------------------------------------------------- 1 | { 2 | "general": { 3 | "api.version.request": true, 4 | "bootstrap.servers": "kafka-1.example.com,kafka-2.example.com", 5 | "session.timeout.ms": 6000, 6 | "log.connection.close": false 7 | }, 8 | "consumer": { 9 | "go.events.channel.enable": false, 10 | "go.application.rebalance.enable": false, 11 | "enable.auto.commit": true, 12 | "auto.commit.interval.ms": 10000, 13 | "enable.auto.offset.store": false, 14 | "auto.offset.reset": "latest", 15 | "enable.partition.eof": false 16 | }, 17 | "producer": { 18 | "go.delivery.reports": true, 19 | "go.events.channel.size": 1000 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Rafka: Kafka exposed with a Redis API 2 | // 3 | // Copyright 2017-2019 Skroutz S.A. 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | package main 18 | 19 | import ( 20 | "context" 21 | "encoding/json" 22 | "errors" 23 | "fmt" 24 | "log" 25 | "os" 26 | "os/signal" 27 | "sync" 28 | "syscall" 29 | "time" 30 | 31 | rdkafka "github.com/confluentinc/confluent-kafka-go/kafka" 32 | "github.com/urfave/cli" 33 | ) 34 | 35 | const Version = "0.6.2" 36 | 37 | var ( 38 | cfg Config 39 | stats Stats 40 | shutdown = make(chan os.Signal, 1) 41 | 42 | // populated at build-time with -ldflags 43 | VersionSuffix string 44 | ) 45 | 46 | func main() { 47 | signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM) 48 | 49 | app := cli.NewApp() 50 | app.Name = "rafka" 51 | app.Usage = "Kafka with a Redis API" 52 | app.HideVersion = false 53 | app.Version = Version 54 | if VersionSuffix != "" { 55 | app.Version = Version + "-" + VersionSuffix[:7] 56 | } 57 | app.Flags = []cli.Flag{ 58 | cli.StringFlag{ 59 | Name: "host", 60 | Usage: "Host to listen to", 61 | Value: "0.0.0.0", 62 | }, 63 | cli.IntFlag{ 64 | Name: "port, p", 65 | Usage: "Port to listen to", 66 | Value: 6380, 67 | }, 68 | cli.StringFlag{ 69 | Name: "config, c", 70 | Usage: "Path to librdkafka configuration file", 71 | Value: "librdkafka.json", 72 | }, 73 | } 74 | 75 | app.Before = func(c *cli.Context) error { 76 | if c.String("config") == "" { 77 | return cli.NewExitError("No librdkafka configuration provided", 1) 78 | } 79 | 80 | f, err := os.Open(c.String("config")) 81 | if err != nil { 82 | return err 83 | } 84 | defer f.Close() 85 | 86 | dec := json.NewDecoder(f) 87 | dec.UseNumber() 88 | err = dec.Decode(&cfg.Librdkafka) 89 | if err != nil { 90 | return err 91 | } 92 | 93 | // cfg might be set before main() runs (eg. while testing) 94 | if cfg.Host == "" { 95 | cfg.Host = c.String("host") 96 | } 97 | if cfg.Port == 0 { 98 | cfg.Port = c.Int("port") 99 | } 100 | 101 | // republish config using rdkafka.SetKey() for proper error checking 102 | for _, config := range []rdkafka.ConfigMap{cfg.Librdkafka.Consumer, cfg.Librdkafka.Producer} { 103 | // merge general configuration 104 | for k, v := range cfg.Librdkafka.General { 105 | if config[k] != nil { 106 | continue 107 | } 108 | err = config.SetKey(k, v) 109 | if err != nil { 110 | return fmt.Errorf("Error in librdkafka config (%s): %s", k, err) 111 | } 112 | } 113 | 114 | for k, v := range config { 115 | err = config.SetKey(k, v) 116 | if err != nil { 117 | return fmt.Errorf("Error in librdkafka config (%s): %s", k, err) 118 | } 119 | } 120 | } 121 | 122 | if cfg.Librdkafka.Consumer["go.events.channel.size"] != nil { 123 | chSizeNumber, ok := cfg.Librdkafka.Consumer["go.events.channel.size"].(json.Number) 124 | if !ok { 125 | return errors.New("Error converting go.events.channel.size to int") 126 | } 127 | chSize, err := chSizeNumber.Int64() 128 | if err != nil { 129 | return fmt.Errorf("Error converting go.events.channel.size to int: %s", err) 130 | } 131 | err = cfg.Librdkafka.Consumer.SetKey("go.events.channel.size", int(chSize)) 132 | if err != nil { 133 | return fmt.Errorf("Error setting go.events.channel.size: %s", err) 134 | } 135 | } 136 | 137 | if cfg.Librdkafka.Producer["go.events.channel.size"] != nil { 138 | chSizeNumber, ok := cfg.Librdkafka.Producer["go.events.channel.size"].(json.Number) 139 | if !ok { 140 | return errors.New("Error converting go.events.channel.size to int") 141 | } 142 | chSize, err := chSizeNumber.Int64() 143 | if err != nil { 144 | return fmt.Errorf("Error converting go.events.channel.size to int: %s", err) 145 | } 146 | err = cfg.Librdkafka.Producer.SetKey("go.events.channel.size", int(chSize)) 147 | if err != nil { 148 | return fmt.Errorf("Error setting go.events.channel.size: %s", err) 149 | } 150 | } 151 | 152 | // We don't use the channel-based producer API, but even then 153 | // confluent-kafka-go still preallocates a channel with the 154 | // default buffer size of 1000000. Thus, this reduces memory 155 | // usage significantly, especially in the case of many, 156 | // short-lived producers. 157 | // 158 | // NOTE: If we ever want to change to the channel-based 159 | // producer API, this should be set via the config file 160 | // instead. 161 | err = cfg.Librdkafka.Producer.SetKey("go.produce.channel.size", 0) 162 | if err != nil { 163 | return fmt.Errorf("Error setting go.produce.channel.size: %s", err) 164 | } 165 | 166 | return nil 167 | } 168 | 169 | app.Action = func(c *cli.Context) error { 170 | run(c) 171 | return nil 172 | } 173 | 174 | app.Run(os.Args) 175 | } 176 | 177 | func run(c *cli.Context) { 178 | var srvWg sync.WaitGroup 179 | ctx, srvShutdown := context.WithCancel(context.Background()) 180 | _, rdkafkaVer := rdkafka.LibraryVersion() 181 | 182 | log.Printf("librdkafka %s | %v", rdkafkaVer, cfg) 183 | 184 | srvWg.Add(1) 185 | go func() { 186 | defer srvWg.Done() 187 | err := NewServer(5*time.Second).ListenAndServe(ctx, fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)) 188 | if err != nil { 189 | log.Fatal(err) 190 | } 191 | 192 | }() 193 | 194 | <-shutdown 195 | log.Println("Shutting down...") 196 | srvShutdown() 197 | srvWg.Wait() 198 | } 199 | -------------------------------------------------------------------------------- /main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "os" 8 | "reflect" 9 | "strconv" 10 | "strings" 11 | "sync" 12 | "testing" 13 | "time" 14 | 15 | "github.com/agis/spawn" 16 | rdkafka "github.com/confluentinc/confluent-kafka-go/kafka" 17 | "github.com/go-redis/redis" 18 | ) 19 | 20 | func TestMain(m *testing.M) { 21 | cmd := spawn.New(main, "-p", "6383", "-c", "test/librdkafka.test.json") 22 | 23 | // start rafka 24 | ctx, cancel := context.WithCancel(context.Background()) 25 | err := cmd.Start(ctx) 26 | if err != nil { 27 | log.Fatal(err) 28 | } 29 | 30 | c := newClient("wait:for-rafka") 31 | serverReady := false 32 | for i := 0; i <= 3 && !serverReady; i++ { 33 | serverReady = c.Ping().Val() == "PONG" 34 | time.Sleep(300 * time.Millisecond) 35 | } 36 | 37 | if !serverReady { 38 | log.Fatal("Server not ready in time") 39 | os.Exit(1) 40 | } 41 | 42 | result := m.Run() 43 | 44 | cancel() 45 | err = cmd.Wait() 46 | if err != nil { 47 | log.Fatal(err) 48 | } 49 | 50 | os.Exit(result) 51 | } 52 | 53 | // TODO(agis) Move this to an end-to-end test when rafka-rb is able to consume 54 | // multiple topics from the same client instance. 55 | func TestConsumerTopicExclusive(t *testing.T) { 56 | id := "bar:baz" 57 | c := newClient(id) 58 | _, err := c.BLPop(1*time.Second, "topics:foo").Result() 59 | if err != nil && err != redis.Nil { 60 | t.Fatal(err) 61 | } 62 | 63 | consID := "bar:baz|foo" 64 | newConsID := "bar:baz|foo,foo2" 65 | expErr := fmt.Sprintf("CONS Client '%s' has Consumer '%s' registered (new consID: '%s')", id, consID, newConsID) 66 | _, err = c.BLPop(1*time.Second, "topics:foo,foo2").Result() 67 | if err.Error() != expErr { 68 | t.Errorf("Expected error: `%s`, was `%s`", expErr, err) 69 | } 70 | 71 | err = c.Close() 72 | if err != nil { 73 | t.Error(err) 74 | } 75 | } 76 | 77 | func TestConsumerConfig(t *testing.T) { 78 | c := newClient("foo:bar1") 79 | _, err := c.BLPop(1*time.Second, `topics:foo:{"auto.offset.reset": "latest"}`).Result() 80 | if err != nil && err != redis.Nil { 81 | t.Fatal(err) 82 | } 83 | 84 | // configuration only applies in the 1st operation 85 | _, err = c.BLPop(1*time.Second, `topics:foo:{"auto.offset.reset": "malformed"}`).Result() 86 | if err != nil && err != redis.Nil { 87 | t.Fatal(err) 88 | } 89 | 90 | err = c.Close() 91 | if err != nil { 92 | t.Error(err) 93 | } 94 | 95 | c = newClient("foo2:bar2") 96 | _, err = c.BLPop(1*time.Second, `topics:foo:{"invalid_option":"1"}`).Result() 97 | if err == nil { 98 | t.Fatal("Expected invalid configuration error, got nothing") 99 | } 100 | } 101 | 102 | // RPUSH 103 | func TestConsumerOffsetCommit(t *testing.T) { 104 | cases := [][]string{ 105 | {"acks", "sometopic:1:-5"}, 106 | {"acks", "sometopic:1:foo"}, 107 | {"acks", "sometopic:10"}, 108 | {"acks", "sometopic"}, 109 | {"wrongkey", "sometopic:1:5"}, 110 | } 111 | 112 | c := newClient("foo:offset") 113 | // spawn the consumer 114 | c.BLPop(1*time.Second, "topics:sometopic").Result() 115 | 116 | for _, args := range cases { 117 | _, err := c.RPush(args[0], args[1]).Result() 118 | if err == nil { 119 | t.Errorf("Expected error for `%v %v`, got nothing", args[0], args[1]) 120 | } 121 | } 122 | } 123 | 124 | // RPUSHX 125 | func TestProduceErr(t *testing.T) { 126 | c := newClient("some:producer:" + t.Name()) 127 | 128 | _, err := c.RPushX("invalid-arg", "a msg").Result() 129 | if err == nil { 130 | t.Error("Expected error, got nothing") 131 | } 132 | 133 | err = c.Close() 134 | if err != nil { 135 | t.Error(err) 136 | } 137 | } 138 | 139 | func TestProduceWithKey(t *testing.T) { 140 | c := newClient("some:producer:" + t.Name()) 141 | 142 | _, err := c.RPushX("topic:foo:bar", "a msg").Result() 143 | if err != nil { 144 | t.Error(err) 145 | } 146 | 147 | err = c.Close() 148 | if err != nil { 149 | t.Error(err) 150 | } 151 | } 152 | 153 | // SETNAME 154 | func TestClientID(t *testing.T) { 155 | numReq := 100 156 | replies := make(chan string) 157 | 158 | expected := 0 159 | for i := 0; i < numReq; i++ { 160 | expected += i 161 | go func(n int) { 162 | c := newClient((fmt.Sprintf("foo:bar-%d", n))) 163 | 164 | res, err := c.ClientGetName().Result() 165 | if err != nil { 166 | t.Error(err) 167 | } 168 | 169 | replies <- res 170 | 171 | err = c.Close() 172 | if err != nil { 173 | t.Error(err) 174 | } 175 | }(i) 176 | } 177 | 178 | actual := 0 179 | for i := 0; i < numReq; i++ { 180 | n, err := strconv.Atoi(strings.Split(<-replies, "-")[1]) 181 | if err != nil { 182 | t.Fatal(err) 183 | } 184 | actual += n 185 | } 186 | 187 | if actual != expected { 188 | t.Errorf("Expected %d, got %d", expected, actual) 189 | } 190 | } 191 | 192 | func TestConcurrentProducers(t *testing.T) { 193 | var wg sync.WaitGroup 194 | numProd := 5 195 | 196 | wg.Add(numProd) 197 | 198 | for i := 0; i < numProd; i++ { 199 | go func(n int) { 200 | defer wg.Done() 201 | 202 | c := newClient(fmt.Sprintf("some:producer-%d", n)) 203 | 204 | c.RPushX("topic:foo", "a msg").Result() 205 | 206 | err := c.Close() 207 | if err != nil { 208 | t.Error(err) 209 | } 210 | }(i) 211 | } 212 | wg.Wait() 213 | } 214 | 215 | // HGETALL 216 | func TestStatsQuery(t *testing.T) { 217 | p := newClient("someone:foo") 218 | v, err := p.HGetAll("stats").Result() 219 | if err != nil { 220 | t.Error(err) 221 | } 222 | 223 | _, err = strconv.Atoi(v["producer.delivery.errors"]) 224 | if err != nil { 225 | t.Error(err) 226 | } 227 | 228 | _, err = strconv.Atoi(v["producer.unflushed.messages"]) 229 | if err != nil { 230 | t.Error(err) 231 | } 232 | } 233 | 234 | func TestParseTopics(t *testing.T) { 235 | cases := map[string][]string{ 236 | "topics:bar": {"bar"}, 237 | "topics:foo,bar": {"foo", "bar"}, 238 | "topics:baz:": {"baz"}, 239 | "topics:baz,foo:": {"baz", "foo"}, 240 | } 241 | 242 | for input, expected := range cases { 243 | actual, _, err := parseTopicsAndConfig(input) 244 | if err != nil { 245 | t.Fatal(err) 246 | } 247 | if !reflect.DeepEqual(actual, expected) { 248 | t.Fatalf("Expected %v, got %v", expected, actual) 249 | } 250 | } 251 | } 252 | 253 | func TestParseConfig(t *testing.T) { 254 | cases := map[string]rdkafka.ConfigMap{ 255 | `topics:bar:{"cfg":"foo"}`: {"cfg": "foo"}, 256 | `topics:bar:{"a":"b","c":"d","e":"f"}`: {"a": "b", "c": "d", "e": "f"}, 257 | } 258 | 259 | for input, expected := range cases { 260 | _, actual, err := parseTopicsAndConfig(input) 261 | if err != nil { 262 | t.Fatal(err) 263 | } 264 | if !reflect.DeepEqual(actual, expected) { 265 | t.Fatalf("Expected %v, got %v", expected, actual) 266 | } 267 | } 268 | } 269 | 270 | // KEYS 271 | func TestMetadataQuery(t *testing.T) { 272 | c := newClient("someone:random_producer") 273 | 274 | _, err := c.Keys("topics:").Result() 275 | if err != nil { 276 | t.Errorf("Could not execute KEYS command: `%s`", err) 277 | } 278 | } 279 | 280 | func newClient(id string) *redis.Client { 281 | return redis.NewClient(&redis.Options{ 282 | // TODO Add the ability to read host and port from a cfg file 283 | Addr: fmt.Sprintf("%s:%d", "localhost", 6383), 284 | OnConnect: setName(id)}) 285 | } 286 | 287 | func setName(id string) func(*redis.Conn) error { 288 | return func(c *redis.Conn) error { 289 | res := c.ClientSetName(id) 290 | if res.Err() != nil { 291 | log.Fatalf("%s", res.Err()) 292 | } 293 | return nil 294 | } 295 | } 296 | -------------------------------------------------------------------------------- /producer.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017-2019 Skroutz S.A. 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | package main 16 | 17 | import ( 18 | "fmt" 19 | "log" 20 | "os" 21 | "strings" 22 | "sync" 23 | "sync/atomic" 24 | 25 | rdkafka "github.com/confluentinc/confluent-kafka-go/kafka" 26 | ) 27 | 28 | type Producer struct { 29 | id string 30 | rdProd *rdkafka.Producer 31 | log *log.Logger 32 | started bool 33 | wg sync.WaitGroup 34 | } 35 | 36 | func NewProducer(cfg rdkafka.ConfigMap) (*Producer, error) { 37 | rdProd, err := rdkafka.NewProducer(&cfg) 38 | if err != nil { 39 | return nil, err 40 | } 41 | 42 | id := strings.TrimPrefix(rdProd.String(), "rdkafka#") 43 | 44 | return &Producer{ 45 | id: id, 46 | rdProd: rdProd, 47 | log: log.New(os.Stderr, fmt.Sprintf("[%s] ", id), log.Ldate|log.Ltime), 48 | started: false}, nil 49 | 50 | } 51 | 52 | func (p *Producer) String() string { 53 | return p.id 54 | } 55 | 56 | func (p *Producer) Produce(msg *rdkafka.Message) error { 57 | if !p.started { 58 | p.wg.Add(1) 59 | go p.consumeDeliveries() 60 | p.started = true 61 | p.log.Printf("Started working...") 62 | } 63 | 64 | return p.rdProd.Produce(msg, nil) 65 | } 66 | 67 | // Flush flushes any remaining messages. It blocks until all messages are 68 | // delivered or timeoutMs elapses and returns the number of 69 | // outstanding messages. 70 | func (p *Producer) Flush(timeoutMs int) int { 71 | return p.rdProd.Flush(timeoutMs) 72 | } 73 | 74 | // Close stops p after flushing any buffered messages. It is a blocking 75 | // operation. 76 | func (p *Producer) Close() { 77 | unflushed := p.Flush(5000) 78 | if unflushed > 0 { 79 | p.log.Printf("Error flushing: %d unflushed events", unflushed) 80 | atomic.AddUint64(&stats.producerUnflushed, uint64(unflushed)) 81 | } 82 | // signal consumeDeliveries() to exit by closing p.rdProd.Events() 83 | // channel 84 | p.rdProd.Close() 85 | p.wg.Wait() 86 | p.log.Print("Bye") 87 | } 88 | 89 | func (p *Producer) consumeDeliveries() { 90 | defer p.wg.Done() 91 | 92 | for ev := range p.rdProd.Events() { 93 | msg, ok := ev.(*rdkafka.Message) 94 | if ok { 95 | if err := msg.TopicPartition.Error; err != nil { 96 | p.log.Printf("Error delivering `%s` to %s: %s", msg.Value, msg, err) 97 | atomic.AddUint64(&stats.producerErr, 1) 98 | } 99 | } else { 100 | p.log.Printf("Error consuming delivery event: Unknown event type (%s)", ev) 101 | 102 | // We can ignore 'connection reset by peer' connection errors. 103 | // See https://github.com/edenhill/librdkafka/wiki/FAQ#why-am-i-seeing-receive-failed-disconnected 104 | // See https://github.com/skroutz/rafka/pull/90 105 | if strings.Contains(ev.String(), "Connection reset by peer") { 106 | continue 107 | } 108 | 109 | atomic.AddUint64(&stats.producerUnknownEvents, 1) 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /server.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2017-2019 Skroutz S.A. 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | // 16 | // +build go1.9 17 | 18 | package main 19 | 20 | import ( 21 | "bufio" 22 | "bytes" 23 | "context" 24 | "encoding/json" 25 | "fmt" 26 | "log" 27 | "net" 28 | "os" 29 | "strconv" 30 | "strings" 31 | "sync" 32 | "time" 33 | 34 | rdkafka "github.com/confluentinc/confluent-kafka-go/kafka" 35 | redisproto "github.com/secmask/go-redisproto" 36 | ) 37 | 38 | type monitorReply struct { 39 | timestamp int64 40 | monitorString string 41 | } 42 | 43 | type Server struct { 44 | log *log.Logger 45 | listener net.Listener 46 | 47 | // default timeout for consumer poll 48 | timeout time.Duration 49 | 50 | // currently connected clients 51 | clientByID sync.Map // map[string]*Client 52 | 53 | // wait group to manage the active consumers 54 | consumersWg sync.WaitGroup 55 | 56 | // server's main monitor channel 57 | srvMonitorChan chan monitorReply 58 | 59 | // monitor channels of connected monitoring clients 60 | monitorChans sync.Map // map[string](chan string) 61 | 62 | // boolean flag denoting whether a server shutdown is in-progress 63 | teardown bool 64 | teardownLock sync.RWMutex 65 | } 66 | 67 | func NewServer(timeout time.Duration) *Server { 68 | // The default is 64kB, however Kafka messages might typically be 69 | // much larger than this, so we bump the limit to 32MB. 70 | // 71 | // Keep in mind that the Redis protocol specifies strings may be 72 | // up to 512MB, although there are plans to make them even bigger 73 | // (see https://github.com/antirez/redis/issues/757). 74 | redisproto.MaxBulkSize = 32 * 1024 * 1000 75 | 76 | return &Server{ 77 | timeout: timeout, 78 | log: log.New(os.Stderr, "[server] ", log.Ldate|log.Ltime), 79 | srvMonitorChan: make(chan monitorReply, 1000), 80 | teardown: false, 81 | } 82 | } 83 | 84 | // formatMonitorCommand simply wraps the Redis command and its arguments into double quotes. 85 | func formatMonitorCommand(cmd *redisproto.Command) string { 86 | commandStr := fmt.Sprintf("\"%s\"", string(cmd.Get(0))) 87 | for i := 1; i < cmd.ArgCount(); i++ { 88 | commandStr += fmt.Sprintf(" \"%s\"", string(cmd.Get(i))) 89 | } 90 | return commandStr 91 | } 92 | 93 | // monitorHandler outputs every command processed by Rafka server to the monitor channels of the 94 | // connected monitoring clients. 95 | func (s *Server) monitorHandler() { 96 | for monReply := range s.srvMonitorChan { 97 | s.monitorChans.Range(func(id, channel interface{}) bool { 98 | clientMonitorChan, ok := channel.(chan string) 99 | if !ok { 100 | s.log.Printf("Couldn't cast %#v to chan string", channel) 101 | return false 102 | } 103 | 104 | select { 105 | case clientMonitorChan <- fmt.Sprintf("%.6f [0 %s] %s", 106 | float64(monReply.timestamp)/1e+9, 107 | id, 108 | monReply.monitorString): 109 | default: 110 | s.log.Printf("Failed to write monitor string to client '%s'\n", id) 111 | } 112 | 113 | return true 114 | }) 115 | } 116 | } 117 | 118 | func (s *Server) Handle(ctx context.Context, conn net.Conn) { 119 | c := NewClient(ctx, conn, cfg) 120 | c.consWg = &s.consumersWg 121 | defer c.Close() 122 | 123 | s.clientByID.Store(c.id, c) 124 | defer func() { 125 | s.clientByID.Delete(c.id) 126 | s.monitorChans.Delete(c.id) 127 | }() 128 | 129 | parser := redisproto.NewParser(conn) 130 | writer := redisproto.NewWriter(bufio.NewWriter(conn)) 131 | 132 | var parseErr, writeErr error 133 | var monitorStrCommand string 134 | 135 | for { 136 | var command *redisproto.Command 137 | command, parseErr = parser.ReadCommand() 138 | if parseErr != nil { 139 | writeErr = writer.WriteError(parseErr.Error()) 140 | } else { 141 | monitorStrCommand = formatMonitorCommand(command) 142 | select { 143 | case s.srvMonitorChan <- monitorReply{ 144 | timestamp: time.Now().UnixNano(), 145 | monitorString: monitorStrCommand, 146 | }: 147 | default: 148 | s.log.Printf("Could not write redis Command to channel: '%s'\n", monitorStrCommand) 149 | } 150 | 151 | cmd := strings.ToUpper(string(command.Get(0))) 152 | switch cmd { 153 | // Consume the next message from one or more topics 154 | // 155 | // BLPOP topics:: 156 | case "BLPOP": 157 | arg1 := string(command.Get(1)) 158 | topics, cfg, err := parseTopicsAndConfig(arg1) 159 | if err != nil { 160 | writeErr = writer.WriteError("CONS " + err.Error()) 161 | break 162 | } 163 | 164 | // We need to hold the teardownLock in read-mode, while we're registering a new 165 | // Consumer. This way we ensure that no Consumer will be registered **after** a 166 | // server shutdown signal is handled. 167 | s.teardownLock.RLock() 168 | if s.teardown { 169 | // server shutdown, release the read-lock and return 170 | writeErr = writer.WriteError("CONS Server shutdown") 171 | s.teardownLock.RUnlock() 172 | break 173 | } 174 | 175 | cons, err := c.Consumer(topics, cfg) 176 | if err != nil { 177 | writeErr = writer.WriteError("CONS " + err.Error()) 178 | s.teardownLock.RUnlock() 179 | break 180 | } 181 | s.teardownLock.RUnlock() 182 | 183 | // Setup timeout: Check the last argument for 184 | // an int or use the default. 185 | // Note: We do not support 0 as infinity. 186 | timeout := s.timeout 187 | lastIdx := command.ArgCount() - 1 188 | secs, err := strconv.Atoi(string(command.Get(lastIdx))) 189 | if err == nil { 190 | timeout = time.Duration(secs) * time.Second 191 | } 192 | ticker := time.NewTicker(timeout) 193 | 194 | ConsLoop: 195 | for { 196 | select { 197 | case <-ctx.Done(): 198 | writeErr = writer.WriteError("CONS Server shutdown") 199 | break ConsLoop 200 | case <-ticker.C: 201 | // WriteBulkStrings() is the only method 202 | // that returns what the Redis Protocol 203 | // calls a "null array" (i.e. "*-1\r\n") 204 | // 205 | // see https://github.com/secmask/go-redisproto/issues/4 206 | writeErr = writer.WriteBulkStrings(nil) 207 | break ConsLoop 208 | default: 209 | // we set a small timeout since 210 | // Poll holds a lock that 211 | // prevents the consumer to 212 | // terminate until Poll returns 213 | ev, err := cons.Poll(100) 214 | if err != nil { 215 | writeErr = writer.WriteError("CONS Poll " + err.Error()) 216 | break ConsLoop 217 | } 218 | if ev == nil { 219 | continue 220 | } 221 | writeErr = writer.WriteObjects(msgToRedis(ev)...) 222 | break ConsLoop 223 | } 224 | } 225 | ticker.Stop() 226 | // Get producer/consumer statistics 227 | // 228 | // HGETALL stats 229 | case "HGETALL": 230 | key := strings.ToUpper(string(command.Get(1))) 231 | if key != "STATS" { 232 | writeErr = writer.WriteError("ERR Expected key to be 'stats', got " + key) 233 | break 234 | } 235 | writeErr = writer.WriteObjects(stats.toRedis()...) 236 | // List all topics 237 | // 238 | // KEYS 239 | case "KEYS": 240 | arg1 := string(command.Get(1)) 241 | if arg1 != "topics:" { 242 | writeErr = writer.WriteError("ERR Expected argument to be 'topics:', got " + arg1) 243 | break 244 | } 245 | 246 | prod, err := c.Producer(cfg.Librdkafka.Producer) 247 | if err != nil { 248 | writeErr = writer.WriteError("ERR Error spawning producer: " + err.Error()) 249 | break 250 | } 251 | 252 | metadata, err := prod.rdProd.GetMetadata(nil, true, 100) 253 | if err != nil { 254 | writeErr = writer.WriteError("ERR Error getting metadata: " + err.Error()) 255 | break 256 | } 257 | 258 | var topic_names []interface{} 259 | 260 | for topic_name, _ := range metadata.Topics { 261 | topic_names = append(topic_names, "topics:"+topic_name) 262 | } 263 | 264 | if len(topic_names) > 0 { 265 | writeErr = writer.WriteObjects(topic_names...) 266 | } else { 267 | // we need to return empty array here 268 | _, writeErr = writer.Write([]byte{'*', '0', '\r', '\n'}) 269 | } 270 | // Reset producer/consumer statistics 271 | // 272 | // DEL stats 273 | case "DEL": 274 | key := strings.ToUpper(string(command.Get(1))) 275 | if key != "STATS" { 276 | writeErr = writer.WriteError("ERR Expected key to be 'stats', got " + key) 277 | break 278 | } 279 | stats.Reset() 280 | writeErr = writer.WriteInt(1) 281 | // Commit offsets for the given topic/partition 282 | // 283 | // RPUSH acks :: 284 | case "RPUSH": 285 | key := strings.ToUpper(string(command.Get(1))) 286 | if key != "ACKS" { 287 | writeErr = writer.WriteError("CONS You can only RPUSH to the 'acks' key") 288 | break 289 | } 290 | 291 | topic, partition, offset, err := parseAck(string(command.Get(2))) 292 | if err != nil { 293 | writeErr = writer.WriteError("CONS " + err.Error()) 294 | break 295 | } 296 | 297 | if c.consumer == nil { 298 | writeErr = writer.WriteError("CONS No consumer registered for Client " + c.id) 299 | break 300 | } 301 | 302 | err = c.consumer.SetOffset(topic, partition, offset+1) 303 | if err != nil { 304 | writeErr = writer.WriteError("CONS " + err.Error()) 305 | break 306 | } 307 | 308 | writeErr = writer.WriteInt(1) 309 | // Produce a message 310 | // 311 | // RPUSHX topics: 312 | case "RPUSHX": 313 | argc := command.ArgCount() - 1 314 | if argc != 2 { 315 | writeErr = writer.WriteError("PROD RPUSHX accepts 2 arguments, got " + strconv.Itoa(argc)) 316 | break 317 | } 318 | 319 | parts := bytes.Split(command.Get(1), []byte(":")) 320 | if len(parts) != 2 && len(parts) != 3 { 321 | errMsg := "PROD First argument must be in the form of 'topics:' or 'topics::'" 322 | writeErr = writer.WriteError(errMsg) 323 | break 324 | } 325 | topic := string(parts[1]) 326 | tp := rdkafka.TopicPartition{Topic: &topic, Partition: rdkafka.PartitionAny} 327 | kafkaMsg := &rdkafka.Message{TopicPartition: tp, Value: command.Get(2)} 328 | 329 | if len(parts) == 3 { 330 | kafkaMsg.Key = parts[2] 331 | } 332 | 333 | prod, err := c.Producer(cfg.Librdkafka.Producer) 334 | if err != nil { 335 | writeErr = writer.WriteError("PROD Error spawning producer: " + err.Error()) 336 | break 337 | } 338 | 339 | err = prod.Produce(kafkaMsg) 340 | if err != nil { 341 | writeErr = writer.WriteError("PROD " + err.Error()) 342 | break 343 | } 344 | writeErr = writer.WriteInt(1) 345 | // Flush the producer 346 | // 347 | // DUMP 348 | case "DUMP": 349 | if c.producer == nil { 350 | writeErr = writer.WriteInt(0) 351 | break 352 | } 353 | 354 | argc := command.ArgCount() - 1 355 | if argc != 1 { 356 | writeErr = writer.WriteError("PROD DUMP accepts 1 argument, got " + strconv.Itoa(argc)) 357 | break 358 | } 359 | 360 | timeoutMs, err := strconv.Atoi(string(command.Get(1))) 361 | if err != nil { 362 | writeErr = writer.WriteError("PROD NaN") 363 | break 364 | } 365 | writeErr = writer.WriteInt(int64(c.producer.Flush(timeoutMs))) 366 | case "CLIENT": 367 | subcmd := strings.ToUpper(string(command.Get(1))) 368 | switch subcmd { 369 | // Set the consumer group.id and name 370 | // 371 | // CLIENT SETNAME : 372 | case "SETNAME": 373 | prevID := c.id 374 | newID := string(command.Get(2)) 375 | 376 | _, ok := s.clientByID.Load(newID) 377 | if ok { 378 | writeErr = writer.WriteError(fmt.Sprintf("CONS id %s is already taken", newID)) 379 | break 380 | } 381 | 382 | err := c.SetID(newID) 383 | if err != nil { 384 | writeErr = writer.WriteError("CONS " + err.Error()) 385 | break 386 | } 387 | s.clientByID.Store(newID, c) 388 | s.clientByID.Delete(prevID) 389 | writeErr = writer.WriteBulkString("OK") 390 | // Get the consumer group.id and name 391 | case "GETNAME": 392 | writeErr = writer.WriteBulkString(c.id) 393 | default: 394 | writeErr = writer.WriteError("Command not supported: " + subcmd) 395 | } 396 | case "QUIT": 397 | writer.WriteBulkString("OK") 398 | writer.Flush() 399 | return 400 | case "PING": 401 | writeErr = writer.WriteSimpleString("PONG") 402 | // Stream back every command processed by the Rafka server. 403 | // 404 | // MONITOR 405 | case "MONITOR": 406 | argCnt := command.ArgCount() 407 | if argCnt > 1 { 408 | writeErr = writer.WriteError("ERR command 'monitor' does not accept any extra arguments") 409 | break 410 | } 411 | s.monitorChans.Store(c.id, c.monitorChan) 412 | s.log.Printf("New monitor client: %s (active monitors: %d)\n", c.id, s.activeMonitors()) 413 | writer.WriteSimpleString("OK") 414 | default: 415 | writeErr = writer.WriteError("Command not supported: " + cmd) 416 | } 417 | } 418 | if parseErr != nil || command.IsLast() { 419 | writer.Flush() 420 | } 421 | if parseErr != nil || writeErr != nil { 422 | // parse errors are returned to the client and write 423 | // errors are non-issues, since they just indicate 424 | // the client closed the connection. That's why 425 | // we don't log anything. 426 | // 427 | // Instead, we close the connection. Clients should 428 | // establish the connections anew if needed. 429 | break 430 | } 431 | } 432 | } 433 | 434 | func (s *Server) ListenAndServe(ctx context.Context, hostport string) error { 435 | var wg, inflightWg sync.WaitGroup 436 | var err error 437 | 438 | s.listener, err = net.Listen("tcp", hostport) 439 | if err != nil { 440 | return err 441 | } 442 | s.log.Print("Listening on " + hostport) 443 | 444 | wg.Add(1) 445 | go func() { 446 | defer wg.Done() 447 | s.monitorHandler() 448 | }() 449 | 450 | wg.Add(1) 451 | go func() { 452 | defer wg.Done() 453 | <-ctx.Done() 454 | s.shutdown() 455 | }() 456 | 457 | Loop: 458 | for { 459 | select { 460 | case <-ctx.Done(): 461 | break Loop 462 | default: 463 | conn, err := s.listener.Accept() 464 | if err != nil { 465 | // we know that closing a listener that blocks 466 | // on Accept() will return this error 467 | if !strings.Contains(err.Error(), "use of closed network connection") { 468 | s.log.Println("Accept error: ", err) 469 | } 470 | } else { 471 | inflightWg.Add(1) 472 | go func() { 473 | defer inflightWg.Done() 474 | s.Handle(ctx, conn) 475 | }() 476 | } 477 | } 478 | } 479 | 480 | wg.Wait() 481 | inflightWg.Wait() 482 | return nil 483 | } 484 | 485 | // shutdown closes current clients and also stops accepting new clients in a 486 | // non-blocking manner 487 | func (s *Server) shutdown() { 488 | // Stop accepting new consumers while a server shutdown operation is in-progress. 489 | s.teardownLock.Lock() 490 | s.teardown = true 491 | s.teardownLock.Unlock() 492 | 493 | // Close clients with at least 1 consumer. These clients may have 494 | // producers too, but we assume that they are non-critical so we close 495 | // them at this point too, which is earlier than the others (see below). 496 | s.clientByID.Range(func(id, client interface{}) bool { 497 | c, ok := client.(*Client) 498 | if !ok { 499 | s.log.Printf("Couldn't convert %#v to Client", c) 500 | return false 501 | } 502 | 503 | if c.consumer != nil { 504 | // This ugliness is due to the go-redisproto parser's 505 | // not having a selectable channel for reading input. 506 | // We're stuck with blocking on ReadCommand() and 507 | // unblocking it by closing the client's connection. 508 | c.conn.Close() 509 | } 510 | 511 | return true 512 | }) 513 | 514 | // wait for consumers to actually close 515 | s.consumersWg.Wait() 516 | 517 | // stop accepting new clients and unblock Accept() 518 | err := s.listener.Close() 519 | if err != nil { 520 | log.Printf("error closing listener: %s", err) 521 | } 522 | 523 | // close the rest of the clients (ie. those that have only producers). 524 | s.clientByID.Range(func(id, client interface{}) bool { 525 | c, ok := client.(*Client) 526 | if !ok { 527 | s.log.Printf("Couldn't convert %#v to Client", c) 528 | return false 529 | } 530 | // This ugliness is due to the go-redisproto parser's 531 | // not having a selectable channel for reading input. 532 | // We're stuck with blocking on ReadCommand() and 533 | // unblocking it by closing the client's connection. 534 | c.conn.Close() 535 | return true 536 | }) 537 | 538 | // ensure that the server's monitoring channel is closed 539 | close(s.srvMonitorChan) 540 | } 541 | 542 | // parseTopicsAndConfig parses the "topics:topic1,topic2:{config}" into 543 | // an array of topics and a config map 544 | func parseTopicsAndConfig(s string) ([]string, rdkafka.ConfigMap, error) { 545 | parts := strings.SplitN(s, ":", 3) 546 | if len(parts) < 2 || parts[0] != "topics" { 547 | return nil, nil, fmt.Errorf("Cannot parse topics from `%s`", s) 548 | } 549 | 550 | topics := strings.Split(parts[1], ",") 551 | if len(topics) == 0 { 552 | return nil, nil, fmt.Errorf("Not enough topics in `%s`", s) 553 | } 554 | 555 | var rdconfig rdkafka.ConfigMap 556 | if len(parts) == 3 && parts[2] != "" { 557 | dec := json.NewDecoder(strings.NewReader(parts[2])) 558 | dec.UseNumber() 559 | err := dec.Decode(&rdconfig) 560 | if err != nil { 561 | return nil, nil, fmt.Errorf("Error parsing configuration from '%s'; %s", parts[2], err) 562 | } 563 | } 564 | 565 | return topics, rdconfig, nil 566 | } 567 | 568 | func parseAck(ack string) (string, int32, rdkafka.Offset, error) { 569 | parts := strings.SplitN(ack, ":", 3) 570 | if len(parts) != 3 { 571 | return "", 0, 0, fmt.Errorf("Cannot parse ack: '%s'", ack) 572 | } 573 | 574 | var err error 575 | 576 | partition64, err := strconv.ParseInt(parts[1], 10, 32) 577 | if err != nil { 578 | return "", 0, 0, err 579 | } 580 | partition := int32(partition64) 581 | 582 | offset, err := strconv.ParseInt(parts[2], 0, 64) 583 | if err != nil { 584 | return "", 0, rdkafka.Offset(0), err 585 | } 586 | 587 | return parts[0], partition, rdkafka.Offset(offset), nil 588 | } 589 | 590 | func msgToRedis(msg *rdkafka.Message) []interface{} { 591 | tp := msg.TopicPartition 592 | 593 | return []interface{}{ 594 | "topic", 595 | *tp.Topic, 596 | "partition", 597 | int64(tp.Partition), 598 | "offset", 599 | int64(tp.Offset), 600 | "value", 601 | msg.Value} 602 | } 603 | 604 | // activeMonitors returns the connected monitoring client count. 605 | func (s *Server) activeMonitors() int { 606 | monitorCnt := 0 607 | 608 | s.monitorChans.Range(func(id, channel interface{}) bool { 609 | _, ok := channel.(chan string) 610 | if !ok { 611 | s.log.Printf("Couldn't cast %#v to chan string", channel) 612 | return false 613 | } 614 | 615 | monitorCnt += 1 616 | return true 617 | }) 618 | 619 | return monitorCnt 620 | } 621 | -------------------------------------------------------------------------------- /stats.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017-2019 Skroutz S.A. 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | package main 16 | 17 | import ( 18 | "strconv" 19 | "sync/atomic" 20 | ) 21 | 22 | type Stats struct { 23 | producerUnflushed uint64 24 | producerErr uint64 25 | producerUnknownEvents uint64 26 | } 27 | 28 | func (s *Stats) toRedis() []interface{} { 29 | return []interface{}{ 30 | "producer.unflushed.messages", 31 | strconv.FormatUint(atomic.LoadUint64(&s.producerUnflushed), 10), 32 | "producer.delivery.errors", 33 | strconv.FormatUint(atomic.LoadUint64(&s.producerErr), 10), 34 | "producer.unknown.events", 35 | strconv.FormatUint(atomic.LoadUint64(&s.producerUnknownEvents), 10), 36 | } 37 | } 38 | 39 | func (s *Stats) Reset() { 40 | atomic.StoreUint64(&s.producerUnflushed, 0) 41 | atomic.StoreUint64(&s.producerErr, 0) 42 | atomic.StoreUint64(&s.producerUnknownEvents, 0) 43 | } 44 | -------------------------------------------------------------------------------- /test/Dockerfile: -------------------------------------------------------------------------------- 1 | # DIST and RDKAFKA_VERSION are required build arguments. 2 | ARG DIST 3 | FROM debian:${DIST} 4 | 5 | ARG RDKAFKA_VERSION 6 | 7 | RUN apt-get update && \ 8 | apt-get install -y --no-install-recommends \ 9 | procps \ 10 | curl gnupg \ 11 | build-essential 12 | 13 | ADD skroutz-stable.list /etc/apt/sources.list.d/ 14 | ADD skroutz-pu.list /etc/apt/sources.list.d/ 15 | RUN curl -sSL http://debian.skroutz.gr/skroutz.asc | apt-key add - 16 | 17 | RUN apt-get update && \ 18 | apt-get install -y \ 19 | golang \ 20 | go-dep \ 21 | git \ 22 | ruby-full \ 23 | bundler \ 24 | confluent-kafka-2.11 \ 25 | default-jre 26 | 27 | # build librdkafka 28 | RUN git clone git://github.com/edenhill/librdkafka /tmp/librdkafka 29 | WORKDIR /tmp/librdkafka 30 | RUN git checkout ${RDKAFKA_VERSION} && ./configure --libdir=/usr/lib/$(dpkg-architecture -q DEB_HOST_GNU_TYPE) && make && make install 31 | 32 | ENV GOPATH /root/go 33 | ENV RAFKA rafka:6380 34 | VOLUME $GOPATH/src/github.com/skroutz/rafka 35 | WORKDIR $GOPATH/src/github.com/skroutz/rafka 36 | 37 | EXPOSE 6380 38 | 39 | CMD ["make", "run-rafka-local"] 40 | -------------------------------------------------------------------------------- /test/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gem "rafka", "0.5.0" 4 | gem "minitest" 5 | -------------------------------------------------------------------------------- /test/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | minitest (5.11.3) 5 | rafka (0.5.0) 6 | redis (>= 3.3.2) 7 | redis (4.1.3) 8 | 9 | PLATFORMS 10 | ruby 11 | 12 | DEPENDENCIES 13 | minitest 14 | rafka (= 0.5.0) 15 | 16 | BUNDLED WITH 17 | 1.17.3 18 | -------------------------------------------------------------------------------- /test/README.md: -------------------------------------------------------------------------------- 1 | This directory contains Rafka's end-to-end tests. They test a full Rafka/Kafka 2 | cluster using the [Rafka ruby driver](https://github.com/skroutz/rafka-rb). 3 | 4 | Dependencies: 5 | 6 | * Ruby & [bundler](http://bundler.io/) 7 | * A Kafka cluster. [kafka-cluster-testbed](https://github.com/skroutz/kafka-cluster-testbed) provides a Dockerized setup and 8 | is the recommended way to test Rafka. 9 | 10 | ## Setup 11 | 12 | Run `$ bundle` in this directory to ensure test dependencies are satisfied. 13 | 14 | ## Usage 15 | 16 | The easiest way to run the tests is by using Docker and 17 | [kafka-cluster-testbed](https://github.com/skroutz/kafka-cluster-testbed): 18 | 19 | First, start the Kafka cluster from kafka-cluster-testbed: 20 | ```shell 21 | kafka-cluster-testbed/ $ docker-compose up 22 | ``` 23 | 24 | Then start the Rafka container (inside this directory): 25 | ```shell 26 | $ docker-compose up 27 | ``` 28 | 29 | Finally, run the tests: 30 | ```shell 31 | $ ./end-to-end 32 | ``` 33 | 34 | To run a specific test: 35 | ```shell 36 | $ ./end-to-end --name 37 | ``` 38 | 39 | Specifying the Rafka server to connect to (default is "localhost:6380"): 40 | ```shell 41 | $ RAFKA=127.0.0.1:6381 ./end-to-end 42 | ``` 43 | 44 | ## Updating dependencies 45 | To update dependencies (eg. when a new librdkafka version is out) you have to 46 | rebuild the docker image without using the cache: 47 | 48 | ```shell 49 | $ docker-compose build --no-cache 50 | ``` 51 | 52 | It's good to do this once in a while since there may be new versions out. 53 | 54 | 55 | -------------------------------------------------------------------------------- /test/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | rafka: 4 | image: skroutz/rafka 5 | build: 6 | context: . 7 | args: 8 | - DIST 9 | - RDKAFKA_VERSION 10 | volumes: 11 | - ${GOPATH}/src/github.com/skroutz/rafka:/root/go/src/github.com/skroutz/rafka 12 | container_name: rafka 13 | hostname: rafka 14 | ports: 15 | - 6381:6380 16 | ulimits: 17 | core: -1 18 | stack: 1082768 19 | 20 | networks: 21 | default: 22 | external: 23 | name: kafkaclustertestbed_default 24 | -------------------------------------------------------------------------------- /test/end-to-end: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("Gemfile", File.dirname(__FILE__)) 3 | 4 | require "bundler/setup" 5 | Bundler.setup(:default) 6 | require "securerandom" 7 | require "minitest/autorun" 8 | require "rafka" 9 | require_relative "test_helper" 10 | 11 | host_port = (ENV["RAFKA"] || "localhost:6381").split(":") 12 | host, port = host_port[0], Integer(host_port[1]) 13 | 14 | CLIENT_DEFAULTS = { host: host, port: port, redis: { reconnect_attempts: 5 } } 15 | FLUSH_TIMEOUT = 5000 16 | CONSUME_RETRIES = 3 17 | CONSUME_TIMEOUT = 5 18 | 19 | class TestRafka < Minitest::Test 20 | def setup 21 | @prod = Rafka::Producer.new(CLIENT_DEFAULTS) 22 | end 23 | 24 | def test_consume_many 25 | with_new_topic(consumer: true) do |topic, cons| 26 | start_consumer!(cons) 27 | 28 | 3.times { |i| @prod.produce(topic, i) } 29 | assert_flushed @prod 30 | 31 | replies = [] 32 | 3.times do |i| 33 | msg = consume_with_retry(cons) 34 | assert_rafka_msg msg 35 | replies << msg.value 36 | end 37 | 38 | assert_equal ["0", "1", "2"], replies.sort 39 | end 40 | end 41 | 42 | def test_produce_with_key 43 | with_new_topic(consumer: true) do |topic, cons| 44 | start_consumer!(cons) 45 | 46 | 100.times { |i| @prod.produce(topic, i, key: 'foo') } 47 | assert_flushed @prod 48 | 49 | partitions = [] 50 | 100.times do |i| 51 | msg = consume_with_retry(cons) 52 | assert_rafka_msg msg 53 | partitions << msg.partition 54 | end 55 | 56 | assert_equal 1, partitions.uniq.size 57 | end 58 | end 59 | 60 | def test_many_consumers_same_topic 61 | with_new_topic do |topic| 62 | gid = rand_id 63 | cons1 = Rafka::Consumer.new(CLIENT_DEFAULTS.merge(topic: topic, group: gid, id: "cons1")) 64 | cons2 = Rafka::Consumer.new(CLIENT_DEFAULTS.merge(topic: topic, group: gid, id: "cons2")) 65 | start_consumer!(cons1) 66 | start_consumer!(cons2) 67 | 68 | msgs = ["a", "b"] 69 | msgs.each { |msg| @prod.produce(topic, msg) } 70 | assert_flushed @prod 71 | 72 | replies = [] 73 | tries = 0 74 | 75 | while replies.size < 2 && tries < 10 76 | tries += 1 77 | 78 | msg = cons1.consume(1) || cons2.consume(1) 79 | next if !msg 80 | 81 | replies << msg.value 82 | replies.uniq! 83 | end 84 | 85 | assert_equal msgs.sort, replies.sort 86 | end 87 | end 88 | 89 | def test_consumer_group_rebalance 90 | with_new_topic do |topic| 91 | gid = rand_id 92 | cons1 = Rafka::Consumer.new(CLIENT_DEFAULTS.merge(topic: topic, group: gid, id: "cons1")) 93 | cons2 = Rafka::Consumer.new(CLIENT_DEFAULTS.merge(topic: topic, group: gid, id: "cons2")) 94 | msg1 = "hi" 95 | msg2 = "hello" 96 | 97 | start_consumer!(cons1) 98 | produce_and_flush!(@prod, topic, msg1) 99 | assert_rafka_msg_equal msg1, consume_with_retry(cons1) 100 | 101 | # commit offsets and shutdown so that cons2 gets all the partitions 102 | cons1.close 103 | start_consumer!(cons2) 104 | 105 | produce_and_flush!(@prod, topic, msg2) 106 | 107 | incoming = consume_with_retry(cons2) 108 | assert_rafka_msg incoming 109 | 110 | if incoming.value != msg2 111 | # it means cons2 was assigned the partition before cons1's offsets 112 | # were commited 113 | assert_rafka_msg_equal msg1, incoming 114 | assert_rafka_msg_equal msg2, consume_with_retry(cons2) 115 | else 116 | assert_rafka_msg_equal msg2, incoming 117 | end 118 | end 119 | end 120 | 121 | def test_many_consumers_different_topics 122 | with_new_topic(consumer: true) do |topic1, cons1| 123 | with_new_topic(consumer: true) do |topic2, cons2| 124 | start_consumer!(cons1) 125 | start_consumer!(cons2) 126 | 127 | @prod.produce(topic1, "I'm Mr. Meeseeks") 128 | @prod.produce(topic2, "Look at me") 129 | assert_flushed @prod 130 | 131 | assert_rafka_msg_equal "I'm Mr. Meeseeks", consume_with_retry(cons1) 132 | assert_rafka_msg_equal "Look at me", consume_with_retry(cons2) 133 | end 134 | end 135 | end 136 | 137 | def test_produce_wrong_topic 138 | assert_raises Rafka::ProduceError do 139 | # TODO(agis): first produce won't do it. This is a Rafka issue. 140 | @prod.produce("idontexist", "foo") 141 | @prod.flush 142 | @prod.produce("idontexist", "foo") 143 | end 144 | end 145 | 146 | def test_cgroup_reconnect_single_partition 147 | with_new_topic(partitions: 1) do |topic| 148 | produce_and_flush!(@prod, topic, "foo") 149 | group_a = "a_group" 150 | cons = new_consumer(topic: topic, group: group_a) 151 | assert_rafka_msg_equal "foo", consume_with_retry(cons) 152 | cons.close 153 | 154 | produce_and_flush!(@prod, topic, "bar") 155 | 156 | assert_rafka_msg_equal "bar", consume_with_retry( 157 | new_consumer(topic: topic, group: group_a)) 158 | 159 | cons = new_consumer(topic: topic, group: "another_group") 160 | assert_rafka_msg_equal "foo", consume_with_retry(cons) 161 | assert_rafka_msg_equal "bar", consume_with_retry(cons) 162 | end 163 | end 164 | 165 | # This tests a real-world scenario where a client app restarts (eg. during 166 | # deployment), thus stopping and restarting its consumers. 167 | # 168 | # The flow is the following: 169 | # 170 | # 1. Consumers of a group (we call it cgroup) are consuming from topic Y 171 | # 2. Values are produced to topic Y 172 | # 3. cgroup consumes the produced values 173 | # 4. cgroup is restarted (ie. app is deployed) 174 | # 5. More values are produced to topic Y 175 | # 6. cgroup continues consuming from the last position, ie. it doesn't 176 | # reconsume values from step (2) but only from (5) 177 | def test_cgroup_reconnect_many_partitions 178 | partitions = 4 179 | input_size = 20 180 | reconsumes_tolerated = partitions + 2 181 | flunk "input_size must be even, given: #{input_size}" if input_size.odd? 182 | 183 | with_new_topic(partitions: partitions) do |topic| 184 | group = "cgroupA" 185 | input = (1..input_size) 186 | input_a, input_b = input.each_slice(input_size/2).to_a 187 | output = Hash.new(0) 188 | 189 | # produce some input and consume it 190 | cgroup = Array.new(2) { new_consumer(topic: topic, group: group) } 191 | cgroup.each { |c| start_consumer!(c) } 192 | input_a.each { |i| @prod.produce(topic, i) } 193 | assert_flushed @prod 194 | 195 | while output.size < input_a.size 196 | cgroup.each do |c| 197 | msg = c.consume(1) 198 | output[msg.value.to_i] += 1 if msg 199 | end 200 | end 201 | 202 | assert_equal input_a.to_a, output.keys.sort 203 | 204 | # restart cgroup to simulate client app deployment 205 | cgroup.each { |c| c.close } 206 | 207 | sleep 2 # sleep more than the auto.commit interval so that a commit will kick in 208 | 209 | # produce some more input and assert cgroup continues where it left 210 | # position (ie. does not re-consume input_a) 211 | cgroup = Array.new(2) { new_consumer(topic: topic, group: group) } 212 | cgroup.each { |c| start_consumer!(c) } 213 | input_b.each { |i| @prod.produce(topic, i) } 214 | assert_flushed @prod 215 | 216 | while output.size < input_size 217 | cgroup.each do |c| 218 | msg = c.consume(1) 219 | output[msg.value.to_i] += 1 if msg 220 | end 221 | end 222 | 223 | assert_equal input.to_a, output.keys.sort 224 | 225 | actual_reconsumes = output.values.inject(:+) - input_size 226 | assert actual_reconsumes <= reconsumes_tolerated, 227 | "Expected reconsumes to be <= #{reconsumes_tolerated}, " \ 228 | "was #{actual_reconsumes}" 229 | end 230 | end 231 | 232 | def test_consumer_id_reclaim 233 | group, id = rand_id, rand_id 234 | cons = new_consumer(topic: "a-topic", group: group, id: id) 235 | cons.consume(1) 236 | cons.close 237 | 238 | cons = new_consumer(topic: "a-topic", group: group, id: id) 239 | cons.consume(1) 240 | end 241 | 242 | def test_consumer_id_uniqueness 243 | group, id = rand_id, rand_id 244 | cons1 = new_consumer(topic: "a-topic", group: group, id: id) 245 | cons1.consume(1) 246 | 247 | cons2 = new_consumer(topic: "a-topic", group: group, id: id) 248 | assert_raises Rafka::ConsumeError do 249 | cons2.consume(1) 250 | end 251 | end 252 | 253 | def test_stats 254 | stats = @prod.redis.hgetall("stats") 255 | assert stats.size > 0 256 | stats.keys.each { |k| assert_kind_of String, k } 257 | stats.values.each { |v| assert_kind_of Integer, Integer(v) } 258 | end 259 | 260 | def test_stats_reset 261 | @prod.redis.del("stats") 262 | @prod.produce("foo", "asemas") 263 | sleep 0.5 264 | assert_equal @prod.redis.hgetall("stats")["producer.delivery.errors"], "1" 265 | 266 | @prod.redis.del("stats") 267 | assert @prod.redis.hgetall("stats")["producer.delivery.errors"], "0" 268 | end 269 | 270 | def test_consumer_manual_commit 271 | n = 50 272 | abort "n (#{n}) must be an even number" if n.odd? 273 | gid = rand_id 274 | 275 | with_new_topic(consumer: true, partitions: 2) do |topic| 276 | cons = Rafka::Consumer.new(CLIENT_DEFAULTS.merge( 277 | topic: topic, group: gid, id: "a", auto_commit: false)) 278 | start_consumer!(cons) 279 | 280 | n.times { |i| @prod.produce(topic, i) } 281 | assert_flushed @prod 282 | 283 | msg = nil 284 | 285 | # do a plain consume of all messages, without committing offsets 286 | n.times do 287 | msg = consume_with_retry(cons) 288 | assert_rafka_msg(msg) 289 | assert Integer(msg.value) < n 290 | end 291 | 292 | # restart consumer; we should start without any initial offsets since 293 | # we didn't commit 294 | cons.close 295 | msg = consume_with_retry(cons) 296 | assert_equal 0, msg.offset 297 | 298 | # restart and consume again; this time commit offsets 299 | cons.close 300 | msgs = [] 301 | n.times do 302 | msg = consume_with_retry(cons) 303 | assert_rafka_msg(msg) 304 | msgs << msg 305 | end 306 | res = cons.commit(*msgs) 307 | 308 | # close causes rafka to issue a commit offsets request 309 | cons.close 310 | 311 | # restart and consume some newly-produced messages; we expect to 312 | # start with the previous offsets since we did commit. There's still 313 | # a small window until the offsets are actually committed to Kafka and 314 | # if we hit it, we expect the following assertions to fail. 315 | n.times { |i| @prod.produce(topic, n+i) } 316 | assert_flushed @prod 317 | 318 | n.times do 319 | msg = consume_with_retry(cons) 320 | assert_rafka_msg(msg) 321 | assert Integer(msg.value) >= n 322 | end 323 | 324 | cons.close 325 | end 326 | end 327 | 328 | def test_consumer_batch 329 | with_new_topic(consumer: true) do |topic, cons| 330 | 50.times { |i| @prod.produce(topic, i) } 331 | assert_flushed @prod 332 | 333 | msgs = cons.consume_batch(timeout: 0.3, batch_size: 30, batching_max_sec: 5) 334 | assert_equal 30, msgs.size 335 | 336 | msgs = cons.consume_batch(timeout: 0.3, batch_size: 9999, batching_max_sec: 2) 337 | assert_equal 20, msgs.size 338 | 339 | 50.times { |i| @prod.produce(topic, i) } 340 | assert_flushed @prod 341 | 342 | msgs = cons.consume_batch(timeout: 0.3, batch_size: 30, batching_max_sec: 0) 343 | assert_equal 30, msgs.size 344 | 345 | msgs = cons.consume_batch(timeout: 0.3, batch_size: 0, batching_max_sec: 2) 346 | assert_equal 20, msgs.size 347 | end 348 | end 349 | 350 | def test_consumer_batch_commit 351 | with_new_topic(consumer: true, partitions: 1) do |topic, cons| 352 | 50.times { |i| @prod.produce(topic, i) } 353 | assert_flushed @prod 354 | 355 | msgs = cons.consume_batch(timeout: 0.3, batch_size: 10) 356 | msgs.map! { |m| Integer(m.value) }.sort! 357 | assert_equal 9, msgs.last 358 | 359 | # close and re-consume; we should start from the previous point 360 | cons.close 361 | msgs = cons.consume_batch(timeout: 0.3, batch_size: 5) 362 | msgs.map! { |m| Integer(m.value) }.sort! 363 | assert_equal 14, msgs.last 364 | 365 | 366 | assert_raises RuntimeError do 367 | # close and re-consume with a block; we should start from the previous 368 | # point 369 | cons.close 370 | cons.consume_batch(timeout: 0.3, batch_size: 5) do |msgs| 371 | results = msgs.map { |m| Integer(m.value) }.sort 372 | assert_equal 19, results.last 373 | 374 | # raise an error to avoid committing the offsets 375 | raise "foo" 376 | end 377 | end 378 | 379 | # close and re-consume; we should get again the same messages since 380 | # the previous consume didn't commit offsets 381 | cons.close 382 | msgs = cons.consume_batch(timeout: 0.3, batch_size: 5) 383 | msgs.map! { |m| Integer(m.value) }.sort! 384 | assert_equal 19, msgs.last 385 | end 386 | end 387 | 388 | def test_consume_with_block 389 | with_new_topic(consumer: true, partitions: 1) do |topic, cons| 390 | 10.times { |i| @prod.produce(topic, i) } 391 | assert_flushed @prod 392 | 393 | msg = nil 394 | 395 | assert_rafka_msg(cons.consume) 396 | cons.consume do |msg| 397 | assert_equal 1, Integer(msg.value) 398 | end 399 | 400 | # close and restart; we should continue from where we left 401 | cons.close 402 | cons.consume do |msg| 403 | assert_equal 2, Integer(msg.value) 404 | end 405 | 406 | # consume with a block that raises an error; offsets shouldn't be 407 | # committed 408 | cons.close 409 | assert_raises RuntimeError do 410 | cons.consume do |msg| 411 | assert_equal 3, Integer(msg.value) 412 | 413 | # raise an error to avoid committing the offsets 414 | raise "foo" 415 | end 416 | end 417 | 418 | # close and re-consume; we should start again from the already consumed 419 | # messages b/c offsets weren't committed 420 | cons.close 421 | assert_equal 3, Integer(cons.consume.value) 422 | end 423 | end 424 | 425 | def test_consumer_librdkafka_config 426 | invalid_configs = [ 427 | { "foo": "bar" }, 428 | { "session.timeout.ms": true }, 429 | ] 430 | 431 | invalid_configs.each do |cfg| 432 | assert_raises Rafka::ConsumeError do 433 | start_consumer!(new_consumer(topic: "foo", librdkafka: cfg)) 434 | end 435 | end 436 | 437 | valid_configs = [ 438 | {}, 439 | {"session.timeout.ms": 12345, "log.connection.close": false}, 440 | ] 441 | 442 | valid_configs.each do |cfg| 443 | start_consumer!(new_consumer(topic: "foo", librdkafka: cfg)) 444 | end 445 | 446 | with_new_topic do |topic| 447 | produce_and_flush!(@prod, topic, "foo") 448 | 449 | cons = new_consumer(topic: topic, librdkafka: { "auto.offset.reset" => "latest" }) 450 | assert_nil cons.consume(5) 451 | 452 | produce_and_flush!(@prod, topic, "bar") 453 | assert_rafka_msg_equal "bar", cons.consume(5) 454 | end 455 | end 456 | end 457 | 458 | puts "\nRunning on #{host_port.join(":")} " \ 459 | "(rafka-rb #{Rafka::VERSION}, redis-rb #{Redis::VERSION} " \ 460 | "CONSUME_RETRIES=#{CONSUME_RETRIES}, CONSUME_TIMEOUT=#{CONSUME_TIMEOUT})..." 461 | 462 | retries = 0 463 | rafka_up = false 464 | 465 | while retries < 4 && !rafka_up 466 | retries += 1 467 | 468 | begin 469 | rafka_up = Rafka::Producer.new(CLIENT_DEFAULTS).ping == "PONG" 470 | rescue => Redis::CannotConnectError 471 | rafka_up = false 472 | sleep 1 473 | end 474 | end 475 | 476 | abort "Could not PING Rafka server. Is it up?" if !rafka_up 477 | 478 | $topics = [] 479 | 480 | MiniTest.after_run do 481 | puts "Deleting (#{$topics.count}) test topics..." 482 | $topics.each { |t| delete_kafka_topic!(t) } 483 | end 484 | -------------------------------------------------------------------------------- /test/kafka_helpers.rb: -------------------------------------------------------------------------------- 1 | def create_topic!(topic, partitions:, replication_factor:) 2 | success = system( 3 | "kafka-topics --create --topic #{topic} " \ 4 | "--partitions #{partitions} --replication-factor #{replication_factor} " \ 5 | "--zookeeper \"zoo1,zoo2,zoo3\"" 6 | ) 7 | raise "Error creating topic #{topic}" if !success 8 | end 9 | 10 | def delete_topic!(topic) 11 | success = system( 12 | "kafka-topics --delete --topic #{topic} --if-exists " \ 13 | "--zookeeper \"zoo1,zoo2,zoo3\"" 14 | ) 15 | raise "Error deleting topic #{topic}" if !success 16 | end 17 | -------------------------------------------------------------------------------- /test/librdkafka.test.json: -------------------------------------------------------------------------------- 1 | { 2 | "general": { 3 | "api.version.request": true, 4 | "bootstrap.servers": "kc1.docker,kc2.docker", 5 | "session.timeout.ms": 2000, 6 | "log.connection.close": false, 7 | "heartbeat.interval.ms": 500, 8 | "log_level": 0 9 | }, 10 | "consumer": { 11 | "go.events.channel.enable": false, 12 | "go.application.rebalance.enable": false, 13 | "enable.auto.commit": true, 14 | "auto.commit.interval.ms": 1000, 15 | "enable.auto.offset.store": false, 16 | "auto.offset.reset": "earliest", 17 | "enable.partition.eof": false 18 | }, 19 | "producer": { 20 | "go.delivery.reports": true, 21 | "queue.buffering.max.ms": 0, 22 | "message.send.max.retries": 2, 23 | "retry.backoff.ms": 100 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /test/skroutz-pu.list: -------------------------------------------------------------------------------- 1 | deb http://debian.skroutz.gr/debian/ stretch-skroutz-proposed-updates main non-free 2 | -------------------------------------------------------------------------------- /test/skroutz-stable.list: -------------------------------------------------------------------------------- 1 | deb http://debian.skroutz.gr/debian/ stretch-skroutz main non-free 2 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | def rand_id 2 | SecureRandom.hex(3) 3 | end 4 | 5 | def new_consumer(topic:, group: rand_id, id: rand_id, librdkafka: {}) 6 | Rafka::Consumer.new( 7 | CLIENT_DEFAULTS.merge(topic: topic, group: group, id: id, librdkafka: librdkafka) 8 | ) 9 | end 10 | 11 | # @return [nil, Rafka::Message] 12 | def consume_with_retry(consumer, timeout: CONSUME_TIMEOUT, retries: CONSUME_RETRIES) 13 | res = nil 14 | retries.times do 15 | res = consumer.consume(timeout) 16 | return res if res 17 | end 18 | res 19 | end 20 | 21 | def produce_and_flush!(prod, topic, msg) 22 | prod.produce(topic, msg) 23 | assert_flushed prod 24 | end 25 | 26 | def start_consumer!(cons) 27 | cons.consume(1) 28 | end 29 | 30 | # Creates a new topic and optionally a consumer to consume from it. 31 | def with_new_topic(topic: "r-#{rand_id}", partitions: 4, replication_factor: 2, 32 | consumer: false) 33 | create_kafka_topic!(topic, partitions, replication_factor) 34 | $topics << topic 35 | 36 | consumer = if consumer == true 37 | new_consumer(topic: topic) 38 | elsif consumer.is_a?(Hash) 39 | new_consumer(topic: topic, librdkafka: consumer) 40 | else 41 | nil 42 | end 43 | 44 | yield topic, consumer 45 | end 46 | 47 | def create_kafka_topic!(topic, part, repl_factor) 48 | out = `kafka-topics --create --topic #{topic} \ 49 | --partitions #{part} --replication-factor #{repl_factor} \ 50 | --zookeeper \"zoo1,zoo2,zoo3\"` 51 | 52 | raise "Error creating topic #{topic}: #{out}" if !$?.success? 53 | end 54 | 55 | def delete_kafka_topic!(topic) 56 | out = `kafka-topics --delete --topic #{topic} --if-exists \ 57 | --zookeeper \"zoo1,zoo2,zoo3\"` 58 | 59 | raise "Error deleting topic #{topic}: #{out}" if !$?.success? 60 | end 61 | 62 | # ASSERTIONS 63 | def assert_rafka_msg(msg) 64 | assert_kind_of Rafka::Message, msg 65 | end 66 | 67 | def assert_rafka_msg_equal(exp, act, msg=nil) 68 | assert_rafka_msg(act) 69 | assert_equal exp, act.value 70 | end 71 | 72 | def assert_flushed(producer) 73 | assert_equal 0, producer.flush(FLUSH_TIMEOUT) 74 | end 75 | 76 | --------------------------------------------------------------------------------