├── .github └── workflows │ └── go-test.yml ├── LICENSE ├── Makefile ├── README.md ├── go.mod ├── go.sum ├── main.go ├── raft ├── snapshot.go └── state_machine.go ├── store ├── stable_store.go └── store.go └── transport └── redis.go /.github/workflows/go-test.yml: -------------------------------------------------------------------------------- 1 | on: [ push ] 2 | 3 | concurrency: 4 | group: ${{ github.workflow }}-${{ github.ref }}-go-test-push 5 | 6 | name: Test 7 | jobs: 8 | test: 9 | strategy: 10 | matrix: 11 | os: [ [ubuntu-latest] ] 12 | runs-on: ${{ matrix.os }} 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: actions/setup-go@v5 16 | with: 17 | go-version-file: 'go.mod' 18 | - run: go test -race ./... 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | 3 | .PHONY: run prepare clean runA runB runC 4 | 5 | # runA runB runC を同時に実行する 6 | run: prepare runA runB runC 7 | 8 | prepare: 9 | @echo "Preparing..." 10 | rm -rf /tmp/my-raft-cluster/ 11 | mkdir -p /tmp/my-raft-cluster/{nodeA,nodeB,nodeC} 12 | @echo "Prepared" 13 | 14 | runA: 15 | go run main.go --server_id=nodeA --address=localhost:50051 --redis_address=localhost:63791 --data_dir /tmp/my-raft-cluster/nodeA --initial_peers "nodeB=localhost:50052|localhost:63792,nodeC=localhost:50053|localhost:63793" 16 | runB: 17 | go run main.go --server_id=nodeB --address=localhost:50052 --redis_address=localhost:63792 --data_dir /tmp/my-raft-cluster/nodeB --initial_peers "nodeA=localhost:50051|localhost:63791,nodeC=localhost:50053|localhost:63793" 18 | runC: 19 | go run main.go --server_id=nodeC --address=localhost:50053 --redis_address=localhost:63793 --data_dir /tmp/my-raft-cluster/nodeC --initial_peers "nodeA=localhost:50051|localhost:63791,nodeB=localhost:50052|localhost:63792" 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # raft-redis-cluster 2 | 3 | 実装時に使用するライブラリにいついてはこちらのリポジトリで公開しております。 4 | https://github.com/bootjp/go-kvlib 5 | 6 | 7 | ```bash 8 | make -j 3 run 9 | ``` 10 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module raft-redis-cluster 2 | 3 | go 1.22.2 4 | 5 | require ( 6 | github.com/bootjp/go-kvlib v0.0.0-20240406094546-4db695714980 7 | github.com/hashicorp/raft v1.6.1 8 | github.com/hashicorp/raft-boltdb v0.0.0-20231211162105-6c830fa4535e 9 | github.com/redis/go-redis/v9 v9.5.1 10 | github.com/stretchr/testify v1.9.0 11 | github.com/tidwall/redcon v1.6.2 12 | ) 13 | 14 | require ( 15 | github.com/armon/go-metrics v0.4.1 // indirect 16 | github.com/boltdb/bolt v1.3.1 // indirect 17 | github.com/cespare/xxhash/v2 v2.2.0 // indirect 18 | github.com/davecgh/go-spew v1.1.1 // indirect 19 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect 20 | github.com/fatih/color v1.16.0 // indirect 21 | github.com/hashicorp/go-hclog v1.6.3 // indirect 22 | github.com/hashicorp/go-immutable-radix v1.3.1 // indirect 23 | github.com/hashicorp/go-msgpack v0.5.5 // indirect 24 | github.com/hashicorp/go-msgpack/v2 v2.1.2 // indirect 25 | github.com/hashicorp/golang-lru v1.0.2 // indirect 26 | github.com/mattn/go-colorable v0.1.13 // indirect 27 | github.com/mattn/go-isatty v0.0.20 // indirect 28 | github.com/pmezard/go-difflib v1.0.0 // indirect 29 | github.com/spaolacci/murmur3 v1.1.0 // indirect 30 | github.com/tidwall/btree v1.7.0 // indirect 31 | github.com/tidwall/match v1.1.1 // indirect 32 | go.etcd.io/bbolt v1.3.9 // indirect 33 | golang.org/x/sys v0.20.0 // indirect 34 | gopkg.in/yaml.v3 v3.0.1 // indirect 35 | ) 36 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/DataDog/datadog-go v2.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= 2 | github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= 3 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 4 | github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 5 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 6 | github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 7 | github.com/armon/go-metrics v0.0.0-20190430140413-ec5e00d3c878/go.mod h1:3AMJUQhVx52RsWOnlkpikZr01T/yAVN2gn0861vByNg= 8 | github.com/armon/go-metrics v0.3.8/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc= 9 | github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= 10 | github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= 11 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 12 | github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= 13 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= 14 | github.com/boltdb/bolt v1.3.1 h1:JQmyP4ZBrce+ZQu0dY660FMfatumYDLun9hBCUVIkF4= 15 | github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= 16 | github.com/bootjp/go-kvlib v0.0.0-20240406094546-4db695714980 h1:wvU+EFDDSzd1YY25x0Tv3wQ88Kjbf721lre2TIDTTC8= 17 | github.com/bootjp/go-kvlib v0.0.0-20240406094546-4db695714980/go.mod h1:9RZurnCSaobEiLqryIccAhFlJhF/dvvO6fnJiSdhlBE= 18 | github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= 19 | github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= 20 | github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= 21 | github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= 22 | github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 23 | github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= 24 | github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 25 | github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag= 26 | github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= 27 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 28 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 29 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 30 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= 31 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= 32 | github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= 33 | github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= 34 | github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= 35 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 36 | github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 37 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= 38 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= 39 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= 40 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 41 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 42 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 43 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 44 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 45 | github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 46 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 47 | github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= 48 | github.com/hashicorp/go-hclog v0.9.1/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= 49 | github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= 50 | github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= 51 | github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= 52 | github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= 53 | github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= 54 | github.com/hashicorp/go-msgpack v0.5.5 h1:i9R9JSrqIz0QVLz3sz+i3YJdT7TTSLcfLLzJi9aZTuI= 55 | github.com/hashicorp/go-msgpack v0.5.5/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= 56 | github.com/hashicorp/go-msgpack/v2 v2.1.2 h1:4Ee8FTp834e+ewB71RDrQ0VKpyFdrKOjvYtnQ/ltVj0= 57 | github.com/hashicorp/go-msgpack/v2 v2.1.2/go.mod h1:upybraOAblm4S7rx0+jeNy+CWWhzywQsSRV5033mMu4= 58 | github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= 59 | github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM= 60 | github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= 61 | github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= 62 | github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c= 63 | github.com/hashicorp/golang-lru v1.0.2/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= 64 | github.com/hashicorp/raft v1.1.0/go.mod h1:4Ak7FSPnuvmb0GV6vgIAJ4vYT4bek9bb6Q+7HVbyzqM= 65 | github.com/hashicorp/raft v1.6.1 h1:v/jm5fcYHvVkL0akByAp+IDdDSzCNCGhdO6VdB56HIM= 66 | github.com/hashicorp/raft v1.6.1/go.mod h1:N1sKh6Vn47mrWvEArQgILTyng8GoDRNYlgKyK7PMjs0= 67 | github.com/hashicorp/raft-boltdb v0.0.0-20231211162105-6c830fa4535e h1:SK4y8oR4ZMHPvwVHryKI88kJPJda4UyWYvG5A6iEQxc= 68 | github.com/hashicorp/raft-boltdb v0.0.0-20231211162105-6c830fa4535e/go.mod h1:EMz/UIuG93P0MBeHh6CbXQAEe8ckVJLZjhD17lBzK5Q= 69 | github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= 70 | github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 71 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= 72 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 73 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= 74 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 75 | github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= 76 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 77 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 78 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 79 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 80 | github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= 81 | github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= 82 | github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= 83 | github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= 84 | github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= 85 | github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= 86 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= 87 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 88 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 89 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 90 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 91 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 92 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 93 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 94 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= 95 | github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= 96 | github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= 97 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 98 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 99 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 100 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 101 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 102 | github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM= 103 | github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= 104 | github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= 105 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 106 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 107 | github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 108 | github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= 109 | github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= 110 | github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= 111 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 112 | github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 113 | github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= 114 | github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= 115 | github.com/redis/go-redis/v9 v9.5.1 h1:H1X4D3yHPaYrkL5X06Wh6xNVM/pX0Ft4RV0vMGvLBh8= 116 | github.com/redis/go-redis/v9 v9.5.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= 117 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= 118 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= 119 | github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= 120 | github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= 121 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 122 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 123 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 124 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 125 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 126 | github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= 127 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 128 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 129 | github.com/tidwall/btree v1.1.0/go.mod h1:TzIRzen6yHbibdSfK6t8QimqbUnoxUSrZfeW7Uob0q4= 130 | github.com/tidwall/btree v1.7.0 h1:L1fkJH/AuEh5zBnnBbmTwQ5Lt+bRJ5A8EWecslvo9iI= 131 | github.com/tidwall/btree v1.7.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= 132 | github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= 133 | github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= 134 | github.com/tidwall/redcon v1.6.2 h1:5qfvrrybgtO85jnhSravmkZyC0D+7WstbfCs3MmPhow= 135 | github.com/tidwall/redcon v1.6.2/go.mod h1:p5Wbsgeyi2VSTBWOcA5vRXrOb9arFTcU2+ZzFjqV75Y= 136 | github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= 137 | go.etcd.io/bbolt v1.3.9 h1:8x7aARPEXiXbHmtUwAIv7eV2fQFHrLLavdiJ3uzJXoI= 138 | go.etcd.io/bbolt v1.3.9/go.mod h1:zaO32+Ti0PK1ivdPtgMESzuzL2VPoIG1PCQNvOdo/dE= 139 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 140 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 141 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 142 | golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 143 | golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 144 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 145 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 146 | golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 147 | golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= 148 | golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 149 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 150 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 151 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 152 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 153 | golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 154 | golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 155 | golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 156 | golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 157 | golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 158 | golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 159 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 160 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 161 | golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= 162 | golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 163 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 164 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 165 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= 166 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 167 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 168 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 169 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 170 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 171 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 172 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 173 | gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 174 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 175 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 176 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "flag" 6 | "fmt" 7 | "log" 8 | "net" 9 | "os" 10 | "path/filepath" 11 | "raft-redis-cluster/raft" 12 | "raft-redis-cluster/store" 13 | "raft-redis-cluster/transport" 14 | "strings" 15 | "time" 16 | 17 | hraft "github.com/hashicorp/raft" 18 | raftboltdb "github.com/hashicorp/raft-boltdb" 19 | ) 20 | 21 | // initialPeersList nodeID->address mapping 22 | type initialPeersList []Peer 23 | 24 | type Peer struct { 25 | NodeID string 26 | RaftAddr string 27 | RedisAddr string 28 | } 29 | 30 | // Set initialPeersList 31 | // nodeID=raftAddress|RedisAddress,nodeID=raftAddress|RedisAddress... 32 | func (i *initialPeersList) Set(value string) error { 33 | node := strings.Split(value, ",") 34 | for _, n := range node { 35 | nodes := strings.Split(n, "=") 36 | if len(nodes) != 2 { 37 | return errors.New("invalid peer format. expected nodeID=raftAddress|RedisAddress") 38 | } 39 | 40 | address := strings.Split(nodes[1], "|") 41 | if len(address) != 2 { 42 | fmt.Println(address) 43 | return errors.New("invalid peer format. expected nodeID=raftAddress|RedisAddress") 44 | } 45 | 46 | *i = append(*i, Peer{ 47 | NodeID: nodes[0], 48 | RaftAddr: address[0], 49 | RedisAddr: address[1], 50 | }) 51 | } 52 | return nil 53 | } 54 | 55 | func (i *initialPeersList) String() string { 56 | return fmt.Sprintf("%v", *i) 57 | } 58 | 59 | var ( 60 | raftAddr = flag.String("address", "localhost:50051", "TCP host+port for this raft node") 61 | redisAddr = flag.String("redis_address", "localhost:6379", "TCP host+port for redis") 62 | serverID = flag.String("server_id", "", "Node id used by Raft") 63 | dataDir = flag.String("data_dir", "", "Raft data dir") 64 | initialPeers = initialPeersList{} 65 | ) 66 | 67 | func init() { 68 | flag.Var(&initialPeers, "initial_peers", "Initial peers for the Raft cluster") 69 | flag.Parse() 70 | validateFlags() 71 | } 72 | 73 | func validateFlags() { 74 | if *serverID == "" { 75 | log.Fatalf("flag --server_id is required") 76 | } 77 | 78 | if *raftAddr == "" { 79 | log.Fatalf("flag --address is required") 80 | } 81 | 82 | if *redisAddr == "" { 83 | log.Fatalf("flag --redis_address is required") 84 | } 85 | 86 | if *dataDir == "" { 87 | log.Fatalf("flag --data_dir is required") 88 | } 89 | } 90 | 91 | func main() { 92 | datastore := store.NewMemoryStore() 93 | st := raft.NewStateMachine(datastore) 94 | r, sdb, err := NewRaft(*dataDir, *serverID, *raftAddr, st, initialPeers) 95 | if err != nil { 96 | log.Fatalln(err) 97 | } 98 | 99 | redis := transport.NewRedis(hraft.ServerID(*serverID), r, datastore, sdb) 100 | err = redis.Serve(*redisAddr) 101 | if err != nil { 102 | log.Fatalln(err) 103 | } 104 | } 105 | 106 | // snapshotRetainCount スナップショットの保持数 107 | const snapshotRetainCount = 2 108 | 109 | func NewRaft(baseDir string, id string, address string, fsm hraft.FSM, nodes initialPeersList) (*hraft.Raft, hraft.StableStore, error) { 110 | c := hraft.DefaultConfig() 111 | c.LocalID = hraft.ServerID(id) 112 | 113 | ldb, err := raftboltdb.NewBoltStore(filepath.Join(baseDir, "logs.dat")) 114 | if err != nil { 115 | return nil, nil, err 116 | } 117 | 118 | sdb, err := raftboltdb.NewBoltStore(filepath.Join(baseDir, "stable.dat")) 119 | if err != nil { 120 | return nil, nil, err 121 | } 122 | 123 | fss, err := hraft.NewFileSnapshotStore(baseDir, snapshotRetainCount, os.Stderr) 124 | if err != nil { 125 | return nil, nil, err 126 | } 127 | 128 | tcpAddr, err := net.ResolveTCPAddr("tcp", address) 129 | if err != nil { 130 | return nil, nil, err 131 | } 132 | 133 | tm, err := hraft.NewTCPTransport(address, tcpAddr, 10, time.Second*10, os.Stderr) 134 | if err != nil { 135 | return nil, nil, err 136 | } 137 | 138 | r, err := hraft.NewRaft(c, fsm, ldb, sdb, fss, tm) 139 | if err != nil { 140 | return nil, nil, err 141 | } 142 | 143 | cfg := hraft.Configuration{ 144 | Servers: []hraft.Server{ 145 | { 146 | Suffrage: hraft.Voter, 147 | ID: hraft.ServerID(id), 148 | Address: hraft.ServerAddress(address), 149 | }, 150 | }, 151 | } 152 | 153 | // 自分以外の initialPeers を追加 154 | for _, peer := range nodes { 155 | sid := hraft.ServerID(peer.NodeID) 156 | cfg.Servers = append(cfg.Servers, hraft.Server{ 157 | Suffrage: hraft.Voter, 158 | ID: sid, 159 | Address: hraft.ServerAddress(peer.RaftAddr), 160 | }) 161 | 162 | err := store.SetRedisAddrByNodeID(sdb, sid, peer.RedisAddr) 163 | if err != nil { 164 | return nil, nil, err 165 | } 166 | } 167 | 168 | f := r.BootstrapCluster(cfg) 169 | if err := f.Error(); err != nil { 170 | return nil, nil, err 171 | } 172 | 173 | return r, sdb, nil 174 | } 175 | -------------------------------------------------------------------------------- /raft/snapshot.go: -------------------------------------------------------------------------------- 1 | package raft 2 | 3 | import ( 4 | "io" 5 | 6 | "github.com/hashicorp/raft" 7 | ) 8 | 9 | var _ raft.FSMSnapshot = (*KVSnapshot)(nil) 10 | 11 | type KVSnapshot struct { 12 | io.ReadWriter 13 | } 14 | 15 | func (f *KVSnapshot) Persist(sink raft.SnapshotSink) error { 16 | defer sink.Close() 17 | _, err := io.Copy(sink, f) 18 | return err 19 | } 20 | 21 | func (f *KVSnapshot) Release() { 22 | } 23 | -------------------------------------------------------------------------------- /raft/state_machine.go: -------------------------------------------------------------------------------- 1 | package raft 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "errors" 7 | "io" 8 | "raft-redis-cluster/store" 9 | 10 | "github.com/hashicorp/raft" 11 | ) 12 | 13 | var _ raft.FSM = (*StateMachine)(nil) 14 | 15 | type Op int 16 | 17 | const ( 18 | Put Op = iota 19 | Del 20 | ) 21 | 22 | type KVCmd struct { 23 | Op Op `json:"op"` 24 | Key []byte `json:"key"` 25 | Val []byte `json:"val"` 26 | } 27 | 28 | func NewStateMachine(store store.Store) *StateMachine { 29 | return &StateMachine{store} 30 | } 31 | 32 | type StateMachine struct { 33 | store store.Store 34 | } 35 | 36 | // Apply applies a Raft log entry to the key-value store. 37 | func (s *StateMachine) Apply(log *raft.Log) any { 38 | ctx := context.Background() 39 | c := KVCmd{} 40 | 41 | err := json.Unmarshal(log.Data, &c) 42 | if err != nil { 43 | return err 44 | } 45 | 46 | return s.handleRequest(ctx, c) 47 | } 48 | 49 | // Restore stores the key-value store to a previous state. 50 | func (s *StateMachine) Restore(rc io.ReadCloser) error { 51 | return s.store.Restore(rc) 52 | } 53 | 54 | // Snapshot returns a KVSnapshot of the key-value store. 55 | func (s *StateMachine) Snapshot() (raft.FSMSnapshot, error) { 56 | rc, err := s.store.Snapshot() 57 | if err != nil { 58 | return nil, err 59 | } 60 | 61 | return &KVSnapshot{rc}, nil 62 | } 63 | 64 | var ErrUnknownOp = errors.New("unknown op") 65 | 66 | func (s *StateMachine) handleRequest(ctx context.Context, cmd KVCmd) error { 67 | switch cmd.Op { 68 | case Put: 69 | return s.store.Put(ctx, cmd.Key, cmd.Val) 70 | case Del: 71 | return s.store.Delete(ctx, cmd.Key) 72 | default: 73 | return ErrUnknownOp 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /store/stable_store.go: -------------------------------------------------------------------------------- 1 | package store 2 | 3 | import hraft "github.com/hashicorp/raft" 4 | 5 | var prefixRedisAddr = []byte("___redisAddr") 6 | 7 | func GetRedisAddrByNodeID(store hraft.StableStore, lid hraft.ServerID) (string, error) { 8 | v, err := store.Get(append(prefixRedisAddr, []byte(lid)...)) 9 | if err != nil { 10 | return "", err 11 | } 12 | 13 | return string(v), nil 14 | } 15 | 16 | func SetRedisAddrByNodeID(store hraft.StableStore, lid hraft.ServerID, addr string) error { 17 | return store.Set(append(prefixRedisAddr, []byte(lid)...), []byte(addr)) 18 | } 19 | -------------------------------------------------------------------------------- /store/store.go: -------------------------------------------------------------------------------- 1 | package store 2 | 3 | import ( 4 | "context" 5 | "io" 6 | 7 | "github.com/bootjp/go-kvlib/store" 8 | ) 9 | 10 | // Txn は、トランザクション用のインターフェースを定義する 11 | // Storeの実装を自身で用意する場合は、store.Txn と同等のインターフェースを定義しこちらは削除する 12 | type Txn = store.Txn 13 | 14 | /* 15 | // Storeを自身で用意する場合は、以下のインターフェースを定義する 16 | type Txn interface{ 17 | Get(ctx context.Context, key []byte) ([]byte, error) 18 | Put(ctx context.Context, key []byte, value []byte) error 19 | Delete(ctx context.Context, key []byte) error 20 | Exists(ctx context.Context, key []byte) (bool, error) 21 | } 22 | */ 23 | 24 | // Store は、キーバリューストアのインターフェースを定義する 25 | // Get, Put, Delete, Exists, Snapshot, Restore, Txn, Close の関数を提供する 26 | // このインターフェースを実装することで、任意のキーバリューストアを利用できる 27 | type Store interface { 28 | Get(ctx context.Context, key []byte) ([]byte, error) 29 | Put(ctx context.Context, key []byte, value []byte) error 30 | Delete(ctx context.Context, key []byte) error 31 | Exists(ctx context.Context, key []byte) (bool, error) 32 | Snapshot() (io.ReadWriter, error) 33 | Restore(buf io.Reader) error 34 | // Txn トランザクション用の関数を提供する 35 | // トランザクション内で複数の操作をまとめて実行するために使用する 36 | // トランザクション内でエラーが発生した場合、トランザクションはロールバックされる 37 | // トランザクション内でエラーが発生しなかった場合、トランザクションはコミットされる 38 | // トランザクション内で発生したエラーは呼び出し元に返される 39 | Txn(ctx context.Context, f func(ctx context.Context, txn Txn) error) error 40 | Close() error 41 | } 42 | 43 | var ErrKeyNotFound = store.ErrKeyNotFound 44 | 45 | func NewMemoryStore() Store { 46 | return store.NewMemoryStore() 47 | } 48 | -------------------------------------------------------------------------------- /transport/redis.go: -------------------------------------------------------------------------------- 1 | package transport 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "errors" 7 | "log" 8 | "net" 9 | "raft-redis-cluster/raft" 10 | "raft-redis-cluster/store" 11 | "strings" 12 | "time" 13 | 14 | hraft "github.com/hashicorp/raft" 15 | "github.com/tidwall/redcon" 16 | ) 17 | 18 | type Redis struct { 19 | listen net.Listener 20 | store store.Store 21 | stableStore hraft.StableStore 22 | id hraft.ServerID 23 | raft *hraft.Raft 24 | } 25 | 26 | // NewRedis creates a new Redis transport. 27 | func NewRedis(id hraft.ServerID, raft *hraft.Raft, store store.Store, stableStore hraft.StableStore) *Redis { 28 | return &Redis{ 29 | store: store, 30 | raft: raft, 31 | id: id, 32 | stableStore: stableStore, 33 | } 34 | } 35 | 36 | func (r *Redis) Serve(addr string) error { 37 | var err error 38 | r.listen, err = net.Listen("tcp", addr) 39 | if err != nil { 40 | return err 41 | } 42 | return r.handle() 43 | } 44 | 45 | func (r *Redis) handle() error { 46 | return redcon.Serve(r.listen, 47 | func(conn redcon.Conn, cmd redcon.Command) { 48 | err := r.validateCmd(cmd) 49 | if err != nil { 50 | conn.WriteError(err.Error()) 51 | return 52 | } 53 | r.processCmd(conn, cmd) 54 | }, 55 | func(conn redcon.Conn) bool { 56 | return true 57 | }, 58 | func(conn redcon.Conn, err error) { 59 | if err != nil { 60 | log.Default().Println("error:", err) 61 | } 62 | }, 63 | ) 64 | } 65 | 66 | var argsLen = map[string]int{ 67 | "GET": 2, 68 | "SET": 3, 69 | "DEL": 2, 70 | } 71 | 72 | const ( 73 | commandName = 0 74 | keyName = 1 75 | value = 2 76 | ) 77 | 78 | var ErrArgsLen = errors.New("ERR wrong number of arguments for command") 79 | 80 | func (r *Redis) validateCmd(cmd redcon.Command) error { 81 | if len(cmd.Args) == 0 { 82 | return ErrArgsLen 83 | } 84 | 85 | if len(cmd.Args) < argsLen[string(cmd.Args[commandName])] { 86 | return ErrArgsLen 87 | } 88 | 89 | // check args length 90 | plainCmd := strings.ToUpper(string(cmd.Args[commandName])) 91 | if len(cmd.Args) != argsLen[plainCmd] { 92 | return ErrArgsLen 93 | } 94 | 95 | return nil 96 | } 97 | 98 | func (r *Redis) processCmd(conn redcon.Conn, cmd redcon.Command) { 99 | ctx := context.Background() 100 | 101 | // check if the node is the leader 102 | if r.raft.State() != hraft.Leader { 103 | _, lid := r.raft.LeaderWithID() 104 | add, err := store.GetRedisAddrByNodeID(r.stableStore, lid) 105 | if err != nil { 106 | conn.WriteError(err.Error()) 107 | return 108 | } 109 | 110 | conn.WriteError("MOVED -1 " + add) 111 | return 112 | } 113 | 114 | plainCmd := strings.ToUpper(string(cmd.Args[commandName])) 115 | switch plainCmd { 116 | case "GET": 117 | val, err := r.store.Get(ctx, cmd.Args[keyName]) 118 | if err != nil { 119 | switch { 120 | case errors.Is(err, store.ErrKeyNotFound): 121 | conn.WriteNull() 122 | return 123 | default: 124 | conn.WriteError(err.Error()) 125 | return 126 | } 127 | } 128 | conn.WriteBulk(val) 129 | case "SET": 130 | kvCmd := &raft.KVCmd{ 131 | Op: raft.Put, 132 | Key: cmd.Args[keyName], 133 | Val: cmd.Args[value], 134 | } 135 | 136 | b, err := json.Marshal(kvCmd) 137 | if err != nil { 138 | conn.WriteError(err.Error()) 139 | return 140 | } 141 | 142 | f := r.raft.Apply(b, time.Second*1) 143 | if f.Error() != nil { 144 | conn.WriteError(f.Error().Error()) 145 | return 146 | } 147 | 148 | conn.WriteString("OK") 149 | case "DEL": 150 | kvCmd := &raft.KVCmd{ 151 | Op: raft.Del, 152 | Key: cmd.Args[keyName], 153 | } 154 | 155 | b, err := json.Marshal(kvCmd) 156 | if err != nil { 157 | conn.WriteError(err.Error()) 158 | return 159 | } 160 | 161 | f := r.raft.Apply(b, time.Second*1) 162 | if f.Error() != nil { 163 | conn.WriteError(f.Error().Error()) 164 | return 165 | } 166 | 167 | res := f.Response() 168 | 169 | err, ok := res.(error) 170 | if ok { 171 | conn.WriteError(err.Error()) 172 | return 173 | } 174 | 175 | conn.WriteInt(1) 176 | default: 177 | conn.WriteError("ERR unknown command '" + string(cmd.Args[0]) + "'") 178 | } 179 | } 180 | 181 | func (r *Redis) Close() error { 182 | return r.listen.Close() 183 | } 184 | 185 | func (r *Redis) Addr() net.Addr { 186 | return r.listen.Addr() 187 | } 188 | --------------------------------------------------------------------------------