├── .circleci └── config.yml ├── .github └── workflows │ └── go.yml ├── .gitignore ├── .idea ├── amazonriver.iml ├── modules.xml └── vcs.xml ├── LICENSE ├── README.md ├── README_EN.md ├── conf └── conf.go ├── doc ├── arch.png ├── es.md ├── grafana.png ├── kafka.md ├── pg.md ├── prometheus.md └── test.md ├── dump ├── dump.go ├── parser.go └── parser_test.go ├── go.mod ├── go.sum ├── handler ├── handler.go ├── handlerWrapper.go └── output │ ├── es.go │ ├── fake.go │ ├── kafka.go │ └── output.go ├── log └── log.go ├── main.go ├── model ├── consts.go ├── decode.go ├── decode_test.go ├── wal.go └── wal_test.go ├── monitor └── prometheus.go ├── river ├── amazon.go └── stream.go └── util ├── hack.go ├── hack_test.go ├── retry.go ├── retry_test.go ├── wildcard.go └── wildcard_test.go /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Golang CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-go/ for more details 4 | version: 2 5 | jobs: 6 | build: 7 | docker: 8 | # specify the version 9 | - image: circleci/golang:1.13 10 | 11 | # Specify service dependencies here if necessary 12 | # CircleCI maintains a library of pre-built images 13 | # documented at https://circleci.com/docs/2.0/circleci-images/ 14 | # - image: circleci/postgres:9.4 15 | 16 | #### TEMPLATE_NOTE: go expects specific checkout path representing url 17 | #### expecting it in the form of 18 | #### /go/src/github.com/circleci/go-tool 19 | #### /go/src/bitbucket.org/circleci/go-tool 20 | working_directory: /go/proj/github.com/hellobike/amazonriver 21 | steps: 22 | - checkout 23 | 24 | # specify any bash command here prefixed with `run: ` 25 | - run: go get -u github.com/mattn/goveralls 26 | - run: go get -u golang.org/x/tools/cmd/cover 27 | - run: GO111MODULE=on go mod vendor 28 | - run: go test -v -covermode=count -coverprofile=coverage.out ./... 29 | - run: goveralls -coverprofile=coverage.out -service=circleci -repotoken $COVERALLS_TOKEN -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | on: [push] 3 | jobs: 4 | 5 | build: 6 | name: Build 7 | runs-on: ubuntu-latest 8 | steps: 9 | 10 | - name: Set up Go 1.13 11 | uses: actions/setup-go@v1 12 | with: 13 | go-version: 1.13 14 | id: go 15 | 16 | - name: Check out code into the Go module directory 17 | uses: actions/checkout@v1 18 | 19 | - name: Get dependencies 20 | run: | 21 | go get -v -t -d ./... 22 | if [ -f Gopkg.toml ]; then 23 | curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh 24 | dep ensure 25 | fi 26 | 27 | - name: Build 28 | run: go build -v . 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/go,osx,linux,windows,sublimetext,visualstudiocode 3 | # Edit at https://www.gitignore.io/?templates=go,osx,linux,windows,sublimetext,visualstudiocode 4 | 5 | ### Go ### 6 | # Binaries for programs and plugins 7 | *.exe 8 | *.exe~ 9 | *.dll 10 | *.so 11 | *.dylib 12 | 13 | # Test binary, built with `go test -c` 14 | *.test 15 | 16 | # Output of the go coverage tool, specifically when used with LiteIDE 17 | *.out 18 | 19 | ### Go Patch ### 20 | /vendor/ 21 | /Godeps/ 22 | 23 | ### Linux ### 24 | *~ 25 | 26 | # temporary files which can be created if a process still has a handle open of a deleted file 27 | .fuse_hidden* 28 | 29 | # KDE directory preferences 30 | .directory 31 | 32 | # Linux trash folder which might appear on any partition or disk 33 | .Trash-* 34 | 35 | # .nfs files are created when an open file is removed but is still being accessed 36 | .nfs* 37 | 38 | ### OSX ### 39 | # General 40 | .DS_Store 41 | .AppleDouble 42 | .LSOverride 43 | 44 | # Icon must end with two \r 45 | Icon 46 | 47 | # Thumbnails 48 | ._* 49 | 50 | # Files that might appear in the root of a volume 51 | .DocumentRevisions-V100 52 | .fseventsd 53 | .Spotlight-V100 54 | .TemporaryItems 55 | .Trashes 56 | .VolumeIcon.icns 57 | .com.apple.timemachine.donotpresent 58 | 59 | # Directories potentially created on remote AFP share 60 | .AppleDB 61 | .AppleDesktop 62 | Network Trash Folder 63 | Temporary Items 64 | .apdisk 65 | 66 | ### SublimeText ### 67 | # Cache files for Sublime Text 68 | *.tmlanguage.cache 69 | *.tmPreferences.cache 70 | *.stTheme.cache 71 | 72 | # Workspace files are user-specific 73 | *.sublime-workspace 74 | 75 | # Project files should be checked into the repository, unless a significant 76 | # proportion of contributors will probably not be using Sublime Text 77 | # *.sublime-project 78 | 79 | # SFTP configuration file 80 | sftp-config.json 81 | 82 | # Package control specific files 83 | Package Control.last-run 84 | Package Control.ca-list 85 | Package Control.ca-bundle 86 | Package Control.system-ca-bundle 87 | Package Control.cache/ 88 | Package Control.ca-certs/ 89 | Package Control.merged-ca-bundle 90 | Package Control.user-ca-bundle 91 | oscrypto-ca-bundle.crt 92 | bh_unicode_properties.cache 93 | 94 | # Sublime-github package stores a github token in this file 95 | # https://packagecontrol.io/packages/sublime-github 96 | GitHub.sublime-settings 97 | 98 | ### VisualStudioCode ### 99 | .vscode/* 100 | !.vscode/settings.json 101 | !.vscode/tasks.json 102 | !.vscode/launch.json 103 | !.vscode/extensions.json 104 | 105 | ### VisualStudioCode Patch ### 106 | # Ignore all local history of files 107 | .history 108 | 109 | ### Windows ### 110 | # Windows thumbnail cache files 111 | Thumbs.db 112 | ehthumbs.db 113 | ehthumbs_vista.db 114 | 115 | # Dump file 116 | *.stackdump 117 | 118 | # Folder config file 119 | [Dd]esktop.ini 120 | 121 | # Recycle Bin used on file shares 122 | $RECYCLE.BIN/ 123 | 124 | # Windows Installer files 125 | *.cab 126 | *.msi 127 | *.msix 128 | *.msm 129 | *.msp 130 | 131 | # Windows shortcuts 132 | *.lnk 133 | 134 | # End of https://www.gitignore.io/api/go,osx,linux,windows,sublimetext,visualstudiocode 135 | .idea/inspectionProfiles/ 136 | .idea/workspace.xml 137 | amazonriver -------------------------------------------------------------------------------- /.idea/amazonriver.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # amazonriver [![CircleCI](https://circleci.com/gh/hellobike/amazonriver.svg?style=svg)](https://circleci.com/gh/hellobike/amazonriver) [![Actions Status](https://github.com/hellobike/amazonriver/workflows/Go/badge.svg)](https://github.com/hellobike/amazonriver/actions) 2 | 3 | [English doc](./README_EN.md) 4 | 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/hellobike/amazonriver)](https://goreportcard.com/report/github.com/hellobike/amazonriver) 6 | [![golang](https://img.shields.io/badge/Language-Go-green.svg?style=flat)](https://golang.org) 7 | [![GoDoc](https://godoc.org/github.com/hellobike/amazonriver?status.svg)](https://godoc.org/github.com/hellobike/amazonriver) 8 | [![GitHub release](https://img.shields.io/github/release/hellobike/amazonriver.svg)](https://github.com/hellobike/amazonriver/releases) 9 | 10 | amazonriver 是一个将postgresql的实时数据同步到es或kafka的服务 11 | 12 | ## 版本支持 13 | 14 | - Postgresql 9.4 or later 15 | - Kafka 0.8 or later 16 | - ElasticSearch 5.x 17 | 18 | ## 架构图 19 | 20 | ![架构图](./doc/arch.png) 21 | 22 | ## 原理 23 | 24 | amazonriver 利用pg内部的逻辑复制功能,通过在pg创建逻辑复制槽,接收数据库的逻辑变更,通过解析test_decoding特定格式的消息,得到逻辑数据 25 | 26 | ## 安装使用 27 | 28 | ### 安装 29 | 30 | ```shell 31 | $git clone https://github.com/hellobike/amazonriver 32 | $cd amazonriver 33 | $go install 34 | ``` 35 | 36 | ### 使用 37 | 38 | amazonriver -config config.json 39 | 40 | ## PG 配置 41 | 42 | PG数据库需要预先开启逻辑复制[pg配置](./doc/pg.md) 43 | 44 | ## amazonriver 配置 45 | 46 | ### 监控 47 | 48 | amazonriver支持使用prometheus来监控同步数据状态,[配置Grafana监控](./doc/prometheus.md) 49 | 50 | ### 同步到 elasticsearch 51 | 52 | [同步到elasticsearch](./doc/es.md) 53 | 54 | ### 同步到 kafka 55 | 56 | [同步到kafka](./doc/kafka.md) 57 | 58 | ## 性能测试 59 | 60 | [性能测试](./doc/test.md) 61 | 62 | ## 许可 63 | 64 | amazonriver 使用 Apache License 2 许可 65 | -------------------------------------------------------------------------------- /README_EN.md: -------------------------------------------------------------------------------- 1 | # amazonriver [![CircleCI](https://circleci.com/gh/hellobike/amazonriver.svg?style=svg)](https://circleci.com/gh/hellobike/amazonriver) 2 | 3 | [![Go Report Card](https://goreportcard.com/badge/github.com/hellobike/amazonriver)](https://goreportcard.com/report/github.com/hellobike/amazonriver) 4 | [![golang](https://img.shields.io/badge/Language-Go-green.svg?style=flat)](https://golang.org) 5 | [![GoDoc](https://godoc.org/github.com/hellobike/amazonriver?status.svg)](https://godoc.org/github.com/hellobike/amazonriver) 6 | [![GitHub release](https://img.shields.io/github/release/hellobike/amazonriver.svg)](https://github.com/hellobike/amazonriver/releases) 7 | 8 | amazonriver utilize the postgresql logical replication to sync realtime data into elasticsearch or kafka... 9 | 10 | ## architecture 11 | 12 | ![architecture](./doc/arch.png) 13 | 14 | ## Required 15 | 16 | - Postgresql 9.4 or later 17 | - Kafka 0.8 or later 18 | - ElasticSearch 6.x 19 | 20 | ## Howto 21 | 22 | ### Install 23 | 24 | ```shell 25 | $git clone https://github.com/hellobike/amazonriver 26 | $cd amazonriver 27 | $go install 28 | ``` 29 | 30 | ### Use amazonriver 31 | 32 | amazonriver -config config.json 33 | 34 | ## PG config 35 | 36 | [pg config](./doc/pg.md) 37 | 38 | ## amazonriver config 39 | 40 | ### Monitor 41 | 42 | amazonriver has built-in support for prometheus [How to config](./doc/prometheus.md) 43 | 44 | ### Elasticsearch 45 | 46 | [sync to elastic search](./doc/es.md) 47 | 48 | ### Kafka 49 | 50 | [sync to kafka](./doc/kafka.md) 51 | 52 | ## License 53 | 54 | amazonriver released under Apache License 2 -------------------------------------------------------------------------------- /conf/conf.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package conf 18 | 19 | // Conf ... 20 | type Conf struct { 21 | // PgDumpExec pg_dump 可执行文件路径 22 | PgDumpExec string `json:"pg_dump_path"` 23 | // Subscribes 订阅规则 24 | Subscribes []*Subscribe `json:"subscribes"` 25 | // PrometheusAddress prometheus 26 | PrometheusAddress string `json:"prometheus_address"` 27 | } 28 | 29 | // ESConf es 配置 30 | type ESConf struct { 31 | // Addrs es 地址 32 | Addrs string `json:"addrs"` 33 | // User es username 34 | User string `json:"user"` 35 | // Password es password 36 | Password string `json:"password"` 37 | } 38 | 39 | // PGConnConf of pg 40 | type PGConnConf struct { 41 | // Host 地址 42 | Host string `json:"host"` 43 | // Port 端口 44 | Port uint16 `json:"port"` 45 | // Database database 46 | Database string `json:"database"` 47 | // Schema schema 48 | Schema string `json:"schema"` 49 | // User user 50 | User string `json:"user"` 51 | // Password password 52 | Password string `json:"password"` 53 | } 54 | 55 | // Subscribe 订阅一个数据库中的表的wal,根据规则保存到es里相应的index,type中 56 | type Subscribe struct { 57 | // Dump 创建复制槽成功后,是否 dump 历史数据 58 | Dump bool `json:"dump"` 59 | // SlotName 逻辑复制槽 60 | SlotName string `json:"slotName"` 61 | // PGConnConf pg 连接配置 62 | PGConnConf *PGConnConf `json:"pgConnConf"` 63 | // Rules 订阅规则 64 | Rules []*Rule `json:"rules"` 65 | // ESConf ES 配置 66 | ESConf *ESConf `json:"esConf"` 67 | // KafkaConf kafka 配置 68 | KafkaConf *KafkaConf `json:"kafkaConf"` 69 | // Retry 重试次数 -1:无限重试 70 | Retry int `json:"retry"` 71 | } 72 | 73 | // KafkaConf kafka 配置 74 | type KafkaConf struct { 75 | // Addrs kafka集群地址 76 | Addrs []string `json:"addrs"` 77 | } 78 | 79 | // Rule 同步规则 80 | type Rule struct { 81 | // Table 订阅数据表,支持 ?* 通配符匹配 82 | Table string `json:"table"` 83 | // PKs 表的主键 84 | PKs []string `json:"pks"` 85 | 86 | // 下面几项同步到es中时需配置 87 | // ESID 用作es中id的字段,多个字段内容会连在一起 88 | ESID []string `json:"esid"` 89 | // Index es中的idex 90 | Index string `json:"index"` 91 | // Type es中的type 92 | Type string `json:"type"` 93 | 94 | // 下面几项同步到kafka中时需要配置 95 | // Topic ... 96 | Topic string `json:"topic"` 97 | } 98 | -------------------------------------------------------------------------------- /doc/arch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hellobike/amazonriver/f148e7520fcfcee1ed709451d141a3b6cadb838f/doc/arch.png -------------------------------------------------------------------------------- /doc/es.md: -------------------------------------------------------------------------------- 1 | # 同步到es配置 2 | 3 | 如下面的配置文件,配置了一个把 test.student_name 中的实时数据同步到es中student_name的索引中 4 | 5 | ```json 6 | { 7 | # pg_dump 可执行文件path,如pg_dump在 $PATH 路径下面,则不需配置 8 | "pg_dump_path": "", 9 | "subscribes": [{ 10 | # 是否dump 历史数据,如只需要实时数据,可以不配或配置为false,默认false 11 | "dump": false, 12 | # 逻辑复制槽名称,确保唯一 13 | "slotName": "slot_for_es", 14 | # pg 连接配置 15 | "pgConnConf": { 16 | "host": "127.0.0.1", 17 | "port": 5432, 18 | "database": "test", 19 | "user": "postgres", 20 | "password": "admin" 21 | }, 22 | # 同步规则配置 23 | "rules": [ 24 | { 25 | # 表名匹配,支持通配符 26 | "table": "student_name", 27 | # 表的主键配置 28 | "pks": ["id"], 29 | # es的id值配置,如配置 "id" 则会把表中的id字段作为es的_id 30 | "esid": ["id"], 31 | # es的索引配置 32 | "index": "student_name", 33 | # es的type配置 34 | "type": "logs" 35 | } 36 | ], 37 | # es 连接配置 38 | "esConf": { 39 | "addrs": "http://localhost:9200", 40 | "user": "", 41 | "password": "" 42 | }, 43 | # 错误重试配置,0为不重试,-1会一直重试直到成功 44 | "retry": 0 45 | }], 46 | # 监控抓取地址配置 47 | "prometheus_address": ":8080" 48 | } 49 | ``` -------------------------------------------------------------------------------- /doc/grafana.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hellobike/amazonriver/f148e7520fcfcee1ed709451d141a3b6cadb838f/doc/grafana.png -------------------------------------------------------------------------------- /doc/kafka.md: -------------------------------------------------------------------------------- 1 | # 同步到kafka配置 2 | 3 | 如下面的配置文件,配置了一个把 test.student_name 中的实时数据同步到kafka中student_name_logs的topic中 4 | 5 | ```json 6 | { 7 | # pg_dump 可执行文件path,如pg_dump在 $PATH 路径下面,则不需配置 8 | "pg_dump_path": "", 9 | "subscribes": [{ 10 | # 是否dump 历史数据,如只需要实时数据,可以不配或配置为false,默认false 11 | "dump": false, 12 | # 逻辑复制槽名称,确保唯一 13 | "slotName": "slot_for_kafka", 14 | # pg 连接配置 15 | "pgConnConf": { 16 | "host": "127.0.0.1", 17 | "port": 5432, 18 | "database": "test", 19 | "user": "postgres", 20 | "password": "admin" 21 | }, 22 | # 同步规则配置 23 | "rules": [ 24 | { 25 | # 表名匹配,支持通配符 26 | "table": "student_name", 27 | # 表的主键配置 28 | "pks": ["id"], 29 | # kafka topic 30 | "topic": "student_name_logs" 31 | } 32 | ], 33 | # kafka 连接配置 34 | "kafkaConf": { 35 | "addrs": ["127.0.0.1:9092"] 36 | }, 37 | # 错误重试配置,0为不重试,-1会一直重试直到成功 38 | "retry": 0 39 | }], 40 | # 监控抓取地址配置 41 | "prometheus_address": ":8080" 42 | } 43 | ``` -------------------------------------------------------------------------------- /doc/pg.md: -------------------------------------------------------------------------------- 1 | # PostgreSQL 配置 2 | 3 | ## 参数修改 4 | 5 | ``` 6 | wal_level = 'logical'; 7 | max_replication_slots = 5; #该值要大于1 8 | ``` 9 | 10 | **修改后需要重启才能生效** 11 | 12 | ## 创建有replication权限的用户 13 | 14 | ```sql 15 | CREATE ROLE test_rep LOGIN ENCRYPTED PASSWORD 'xxxx' REPLICATION; 16 | GRANT CONNECT ON DATABASE test_database to test_rep; 17 | ``` 18 | 19 | ## 修改白名单配置 20 | 21 | 在 pg_hba.conf 中增加配置: ```host replication test_rep all md5``` 22 | 23 | **修改后需要reload才能生效** 24 | -------------------------------------------------------------------------------- /doc/prometheus.md: -------------------------------------------------------------------------------- 1 | # prometheus 监控配置 2 | 3 | ## amazonriver prometheus抓取地址配置 4 | 5 | 在amazonriver的配置文件中 6 | 7 | ``` go 8 | // PrometheusAddress prometheus 9 | PrometheusAddress string `json:"prometheus_address"` 10 | ``` 11 | 12 | 配置暴露的prometheus抓取地址,如 13 | 14 | ```json 15 | { 16 | ... 17 | "prometheus_address":":9527", 18 | ... 19 | } 20 | ``` 21 | 22 | 可以通过 localhost:9527/metrics 可以获取到相关监控项 23 | 24 | ## prometheus 配置 25 | 26 | 根据文档配置yml配置文件 27 | [如何配置](https://prometheus.io/docs/prometheus/latest/configuration/configuration/) 28 | 29 | ## 监控项 30 | 31 | 除了golang本身的监控项外,主要提供了以下的监控项。 32 | 33 | - amazonriver_success 成功同步数据数 34 | 35 | ``` 36 | # HELP amazonriver_success success count 37 | # TYPE amazonriver_success counter 38 | amazonriver_success{slot_name="slot_for_es"} 14.0 39 | ``` 40 | 41 | - amazonriver_error 错误数 42 | 43 | ``` 44 | # HELP amazonriver_error error count 45 | # TYPE amazonriver_error counter 46 | amazonriver_error{slot_name="slot_for_es"} 14.0 47 | ``` 48 | 49 | ## grafana 监控 50 | 51 | grafana中添加 52 | 53 | - rate(amazonriver_success[1m]) 来监控成功写入tps 54 | - rate(amazonriver_error[1m]) 来监控错误数 55 | 56 | ![grafana监控](./grafana.png) -------------------------------------------------------------------------------- /doc/test.md: -------------------------------------------------------------------------------- 1 | # 性能测试 2 | 3 | ## 测试环境 4 | 5 | APP: 6 | 7 | |类别|名称| 8 | |---|---| 9 | |OS | centos 6.5 | 10 | |CPU |Common KVM CPU 8 CORE| 11 | |RAM |16GB| 12 | |DISK |100GB| 13 | 14 | PG: 15 | 16 | |类别|名称| 17 | |---|---| 18 | |PG |9.4| 19 | |OS | centos 6.5 | 20 | |CPU |Common KVM CPU 16 CORE| 21 | |RAM |32GB| 22 | |DISK |500GB| 23 | 24 | ES: 25 | 26 | |类别|名称| 27 | |---|---| 28 | | ES | 5.6.3 | 29 | |OS | centos 6.5 | 30 | |CPU |Common KVM CPU 8 CORE| 31 | |RAM |64GB| 32 | |DISK |1788G SSD| 33 | |NODE |3| 34 | 35 | KAFKA: 36 | 37 | |类别|名称| 38 | |---|---| 39 | | KAFKA | 0.9 | 40 | |OS | centos 6.5 | 41 | |CPU |Common KVM CPU 4 CORE| 42 | |RAM |8GB| 43 | |DISK | 500G| 44 | |NODE |2| 45 | 46 | ## 性能需求 47 | 48 | - 测试wal没有积压的情况下,dml的tps峰值 49 | 50 | ## 测试用例 51 | 52 | 单个表约5个字段,每个事务insert单条数据,分别同步到es与kafka,在没有wal积压的情况下,测试峰值tps 53 | 54 | ## ES 55 | 56 | 1. 单事务单表同步,app cpu ≈ 20.08%,load 峰值1.03,mem ≈ 700MB;内网 net/io in ≈ 154.95Mb,net/io out ≈ 23.32Mb,ES先出现瓶颈; 57 | 2. 压测端压力峰值约 17k/s,DB tps ≈ 18k,es avg rate index ≈ 13k/s; 58 | 3. 单事务多表同步,app cpu、es index rate不会明显提升; 59 | 4. 补充4c8g服务器的资源消耗对比:cpu ≈ 28.86%,load峰值0.6,mem ≈ 48MB;内网 net/io in ≈ 114.77Mb,net/io out ≈ 18.7Mb。 60 | 61 | ## kafka 62 | 63 | 1. 单事务单表同步,cpu ≈ 28.15%,load 峰值0.4,mem ≈ 30MB;内网 net/io in ≈ 253.66Mb,net/io out ≈ 28.53Mb;压测端压力峰值约 23k/s,DB tps ≈ 23k,kafka rate ≈ 23k; 64 | 2. 单事务多表同步,cpu ≈ 35.38%,load 峰值0.09,mem ≈ 30MB;内网 net/io in ≈ 292.71Mb,net/io out ≈ 37.99Mb;压测端压力峰值约 21k/s,DB tps ≈ 40k,kafka rate ≈ 40k; 65 | 综述 66 | 1. 应用会过滤 slot配置的数据库内所有表的DML操作,消耗cpu ≈ 17%; 67 | 2. es 同步速率远逊于kafka 同步速率,前提是 应用服务器和DB服务没有瓶颈。在我们的测试环境,受限于基础配置,只能体现es和kafka部分性能差异; 68 | 3. 当日志级别为error时,同步过程中服务器的cpu、mem、net io消耗均比较低,mem占用取决于wal堆积的大小; 69 | 70 | -------------------------------------------------------------------------------- /dump/dump.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package dump 18 | 19 | import ( 20 | "fmt" 21 | "io" 22 | "os" 23 | "os/exec" 24 | 25 | "github.com/hellobike/amazonriver/conf" 26 | "github.com/hellobike/amazonriver/handler" 27 | ) 28 | 29 | // Dumper dump database 30 | type Dumper struct { 31 | pgDump string 32 | sub *conf.Subscribe 33 | } 34 | 35 | // New create a Dumper 36 | func New(pgDump string, sub *conf.Subscribe) *Dumper { 37 | if pgDump == "" { 38 | pgDump = "pg_dump" 39 | } 40 | path, _ := exec.LookPath(pgDump) 41 | return &Dumper{pgDump: path, sub: sub} 42 | } 43 | 44 | // Dump database with snapshot, parse sql then write to handler 45 | func (d *Dumper) Dump(snapshotID string, h handler.Handler) error { 46 | 47 | if d.pgDump == "" { 48 | return nil 49 | } 50 | 51 | args := make([]string, 0, 16) 52 | 53 | // Common args 54 | args = append(args, fmt.Sprintf("--host=%s", d.sub.PGConnConf.Host)) 55 | args = append(args, fmt.Sprintf("--port=%d", d.sub.PGConnConf.Port)) 56 | 57 | args = append(args, fmt.Sprintf("--username=%s", d.sub.PGConnConf.User)) 58 | 59 | args = append(args, d.sub.PGConnConf.Database) 60 | args = append(args, "--data-only") 61 | args = append(args, "--column-inserts") 62 | 63 | args = append(args, fmt.Sprintf("--schema=%s", d.sub.PGConnConf.Schema)) 64 | for _, rule := range d.sub.Rules { 65 | args = append(args, fmt.Sprintf(`--table=%s`, rule.Table)) 66 | } 67 | args = append(args, fmt.Sprintf("--snapshot=%s", snapshotID)) 68 | 69 | cmd := exec.Command(d.pgDump, args...) 70 | if d.sub.PGConnConf.Password != "" { 71 | cmd.Env = append(cmd.Env, fmt.Sprintf("PGPASSWORD=%s", d.sub.PGConnConf.Password)) 72 | } 73 | r, w := io.Pipe() 74 | 75 | cmd.Stdout = w 76 | cmd.Stderr = os.Stderr 77 | 78 | errCh := make(chan error) 79 | parser := newParser(r) 80 | go func() { 81 | err := parser.parse(h) 82 | errCh <- err 83 | }() 84 | 85 | err := cmd.Run() 86 | w.CloseWithError(err) 87 | 88 | err = <-errCh 89 | return err 90 | } 91 | -------------------------------------------------------------------------------- /dump/parser.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package dump 18 | 19 | import ( 20 | "bufio" 21 | "fmt" 22 | "io" 23 | "strconv" 24 | "strings" 25 | 26 | "github.com/hellobike/amazonriver/handler" 27 | "github.com/hellobike/amazonriver/model" 28 | 29 | "github.com/xwb1989/sqlparser" 30 | ) 31 | 32 | type parser struct { 33 | r io.Reader 34 | } 35 | 36 | func newParser(r io.Reader) *parser { 37 | return &parser{r: r} 38 | } 39 | 40 | func (p *parser) parse(h handler.Handler) error { 41 | rb := bufio.NewReaderSize(p.r, 1024*16) 42 | for { 43 | 44 | line, err := rb.ReadString('\n') 45 | if err != nil { 46 | if err == io.EOF { 47 | break 48 | } 49 | return err 50 | } 51 | 52 | data := p.parseSql(line) 53 | if data == nil { 54 | continue 55 | } 56 | if err := h.Handle(data); err != nil { 57 | return err 58 | } 59 | 60 | } 61 | return nil 62 | } 63 | 64 | func (p *parser) parseSql(line string) *model.WalData { 65 | if !strings.HasPrefix(line, "INSERT") { 66 | return nil 67 | } 68 | 69 | stmt, err := sqlparser.Parse(line) 70 | if err != nil { 71 | fmt.Println(err) 72 | return nil 73 | } 74 | switch row := stmt.(type) { 75 | case *sqlparser.Insert: 76 | 77 | var data = map[string]interface{}{} 78 | var columns []string 79 | for _, clm := range row.Columns { 80 | columns = append(columns, clm.String()) 81 | } 82 | if values, ok := row.Rows.(sqlparser.Values); ok { 83 | 84 | value := values[0] 85 | for i, col := range value { 86 | name := columns[i] 87 | switch val := col.(type) { 88 | case *sqlparser.SQLVal: 89 | data[name] = p.parseSQLVal(val) 90 | case *sqlparser.NullVal: 91 | data[name] = nil 92 | } 93 | } 94 | return &model.WalData{OperationType: model.Insert, Schema: row.Table.Qualifier.String(), Table: row.Table.Name.String(), Data: data} 95 | } 96 | } 97 | return nil 98 | } 99 | 100 | func (p *parser) parseSQLVal(val *sqlparser.SQLVal) interface{} { 101 | switch val.Type { 102 | case sqlparser.StrVal: 103 | return string(val.Val) 104 | case sqlparser.IntVal: 105 | ret, _ := strconv.ParseInt(string(val.Val), 10, 64) 106 | return ret 107 | case sqlparser.FloatVal: 108 | ret, _ := strconv.ParseFloat(string(val.Val), 64) 109 | return ret 110 | case sqlparser.HexNum: 111 | return string(val.Val) 112 | case sqlparser.HexVal: 113 | return string(val.Val) 114 | case sqlparser.ValArg: 115 | return string(val.Val) 116 | case sqlparser.BitVal: 117 | return string(val.Val) 118 | 119 | } 120 | return string(val.Val) 121 | } 122 | -------------------------------------------------------------------------------- /dump/parser_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package dump 18 | 19 | import ( 20 | "io" 21 | "reflect" 22 | "testing" 23 | 24 | "github.com/hellobike/amazonriver/model" 25 | ) 26 | 27 | func Test_parser_parseWalData(t *testing.T) { 28 | type fields struct { 29 | r io.Reader 30 | } 31 | type args struct { 32 | line string 33 | } 34 | tests := []struct { 35 | name string 36 | fields fields 37 | args args 38 | want *model.WalData 39 | }{ 40 | { 41 | name: "test1", 42 | fields: fields{ 43 | r: nil, 44 | }, 45 | args: args{ 46 | line: `INSERT INTO test.test_table (id, name) VALUES (1,"amazonriver");`, 47 | }, 48 | want: &model.WalData{ 49 | OperationType: model.Insert, 50 | Schema: "test", 51 | Table: "test_table", 52 | Data: map[string]interface{}{"id": int64(1), "name": "amazonriver"}, 53 | Timestamp: 0, 54 | Pos: 0, 55 | Rule: nil, 56 | }, 57 | }, 58 | { 59 | name: "test2", 60 | fields: fields{ 61 | r: nil, 62 | }, 63 | args: args{ 64 | line: `DELETE FROM test.test_table WHERE id = 1;`, 65 | }, 66 | want: nil, 67 | }, 68 | } 69 | for _, tt := range tests { 70 | t.Run(tt.name, func(t *testing.T) { 71 | p := &parser{ 72 | r: tt.fields.r, 73 | } 74 | if got := p.parseSql(tt.args.line); !reflect.DeepEqual(got, tt.want) { 75 | t.Errorf("parser.parseWalData() = %v, want %v", got, tt.want) 76 | } 77 | }) 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/hellobike/amazonriver 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/Shopify/sarama v1.23.1 7 | github.com/cockroachdb/apd v1.1.0 // indirect 8 | github.com/fortytw2/leaktest v1.3.0 // indirect 9 | github.com/jackc/fake v0.0.0-20150926172116-812a484cc733 // indirect 10 | github.com/jackc/pgx v3.5.0+incompatible 11 | github.com/json-iterator/go v1.1.7 12 | github.com/lib/pq v1.2.0 // indirect 13 | github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e // indirect 14 | github.com/nickelser/parselogical v0.0.0-20171014195826-b07373e53c91 15 | github.com/olivere/elastic v6.2.23+incompatible 16 | github.com/prometheus/client_golang v1.1.0 17 | github.com/satori/go.uuid v1.2.0 // indirect 18 | github.com/shopspring/decimal v0.0.0-20190905144223-a36b5d85f337 // indirect 19 | github.com/sirupsen/logrus v1.4.2 20 | github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2 21 | gopkg.in/jcmturner/goidentity.v3 v3.0.0 // indirect 22 | ) 23 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/DataDog/zstd v1.3.6-0.20190409195224-796139022798 h1:2T/jmrHeTezcCM58lvEQXs0UpQJCo5SoGAcg+mbSTIg= 2 | github.com/DataDog/zstd v1.3.6-0.20190409195224-796139022798/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= 3 | github.com/Shopify/sarama v1.23.1/go.mod h1:XLH1GYJnLVE0XCr6KdJGVJRTwY30moWNJ4sERjXX6fs= 4 | github.com/Shopify/toxiproxy v2.1.4+incompatible h1:TKdv8HiTLgE5wdJuEML90aBgNWsokNbMijUGhmcoBJc= 5 | github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= 6 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 7 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 8 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 9 | github.com/beorn7/perks v1.0.0 h1:HWo1m869IqiPhD389kmkxeTalrjNbbJTC8LXupb+sl0= 10 | github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= 11 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= 12 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= 13 | github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I= 14 | github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= 15 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 16 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 17 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 18 | github.com/eapache/go-resiliency v1.1.0 h1:1NtRmCAqadE2FN4ZcN6g90TP3uk8cg9rn9eNK2197aU= 19 | github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= 20 | github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 h1:YEetp8/yCZMuEPMUDHG0CW/brkkEp8mzqk2+ODEitlw= 21 | github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= 22 | github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= 23 | github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= 24 | github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= 25 | github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= 26 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 27 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= 28 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= 29 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= 30 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 31 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 32 | github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= 33 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 34 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 35 | github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= 36 | github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 37 | github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= 38 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 39 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 40 | github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= 41 | github.com/jackc/fake v0.0.0-20150926172116-812a484cc733 h1:vr3AYkKovP8uR8AvSGGUK1IDqRa5lAAvEkZG1LKaCRc= 42 | github.com/jackc/fake v0.0.0-20150926172116-812a484cc733/go.mod h1:WrMFNQdiFJ80sQsxDoMokWK1W5TQtxBFNpzWTD84ibQ= 43 | github.com/jackc/pgx v3.5.0+incompatible h1:BRJ4G3UPtvml5R1ey0biqqGuYUGayMYekm3woO75orY= 44 | github.com/jackc/pgx v3.5.0+incompatible/go.mod h1:0ZGrqGqkRlliWnWB4zKnWtjbSWbGkVEFm4TeybAXq+I= 45 | github.com/jcmturner/gofork v0.0.0-20190328161633-dc7c13fece03/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o= 46 | github.com/json-iterator/go v1.1.6 h1:MrUvLMLTMxbqFJ9kzlvat/rYZqZnW3u4wkLzWTaFwKs= 47 | github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= 48 | github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 49 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= 50 | github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= 51 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 52 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= 53 | github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= 54 | github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= 55 | github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e h1:hB2xlXdHp/pmPZq0y3QnmWAArdw9PqbmotexnWx/FU8= 56 | github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= 57 | github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= 58 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 59 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 60 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 61 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 62 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 63 | github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= 64 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 65 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= 66 | github.com/nickelser/parselogical v0.0.0-20171014195826-b07373e53c91 h1:xeJWBTrDLjgYa3AY4fO0DFDsunzmzkmzLVyZEjcIzdw= 67 | github.com/nickelser/parselogical v0.0.0-20171014195826-b07373e53c91/go.mod h1:YRjwqwchea1kJ+rhRSOFfAjjLRiN/nG0s+5IJv3YYdw= 68 | github.com/olivere/elastic v6.2.23+incompatible h1:oRGUA/8fKcnkDcqLuwGb5YCzgbgEBo+Y9gamsWqZ0qU= 69 | github.com/olivere/elastic v6.2.23+incompatible/go.mod h1:J+q1zQJTgAz9woqsbVRqGeB5G1iqDKVBWLNSYW8yfJ8= 70 | github.com/pierrec/lz4 v0.0.0-20190327172049-315a67e90e41 h1:GeinFsrjWz97fAxVUEd748aV0cYL+I6k44gFJTCVvpU= 71 | github.com/pierrec/lz4 v0.0.0-20190327172049-315a67e90e41/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= 72 | github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= 73 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 74 | github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= 75 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 76 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 77 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 78 | github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= 79 | github.com/prometheus/client_golang v1.1.0 h1:BQ53HtBmfOitExawJ6LokA4x8ov/z0SYYb0+HxJfRI8= 80 | github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= 81 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 82 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90 h1:S/YWwWx/RA8rT8tKFRuGUZhuA90OyIBpPCXkcbwU8DE= 83 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 84 | github.com/prometheus/common v0.4.1 h1:K0MGApIoQvMw27RTdJkPbr3JZ7DNbtxQNyi5STVM6Kw= 85 | github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= 86 | github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= 87 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 88 | github.com/prometheus/procfs v0.0.2 h1:6LJUbpNm42llc4HRCuvApCSWB/WfhuNo9K98Q9sNGfs= 89 | github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= 90 | github.com/prometheus/procfs v0.0.3 h1:CTwfnzjQ+8dS6MhHHu4YswVAD99sL2wjPqP+VkURmKE= 91 | github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= 92 | github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a h1:9ZKAASQSHhDYGoxY8uLVpewe1GDZ2vu2Tr/vTdVAkFQ= 93 | github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= 94 | github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= 95 | github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= 96 | github.com/shopspring/decimal v0.0.0-20190905144223-a36b5d85f337 h1:Da9XEUfFxgyDOqUfwgoTDcWzmnlOnCGi6i4iPS+8Fbw= 97 | github.com/shopspring/decimal v0.0.0-20190905144223-a36b5d85f337/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= 98 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= 99 | github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= 100 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= 101 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 102 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 103 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 104 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= 105 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 106 | github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I= 107 | github.com/xdg/stringprep v1.0.0/go.mod h1:Jhud4/sHMO4oL310DaZAKk9ZaJ08SJfe+sJh0HrGL1Y= 108 | github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2 h1:zzrxE1FKn5ryBNl9eKOeqQ58Y/Qpo3Q9QNxKHX5uzzQ= 109 | github.com/xwb1989/sqlparser v0.0.0-20180606152119-120387863bf2/go.mod h1:hzfGeIUDq/j97IG+FhNqkowIyEcD88LrW6fyU3K3WqY= 110 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 111 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 112 | golang.org/x/crypto v0.0.0-20190404164418-38d8ce5564a5 h1:bselrhR0Or1vomJZC8ZIjWtbDmn9OYFLX5Ik9alpJpE= 113 | golang.org/x/crypto v0.0.0-20190404164418-38d8ce5564a5/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= 114 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 115 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ= 116 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 117 | golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 118 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 119 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 120 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 121 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 122 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 123 | golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 124 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= 125 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 126 | golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 127 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= 128 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 129 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= 130 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 131 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 132 | gopkg.in/jcmturner/aescts.v1 v1.0.1/go.mod h1:nsR8qBOg+OucoIW+WMhB3GspUQXq9XorLnQb9XtvcOo= 133 | gopkg.in/jcmturner/dnsutils.v1 v1.0.1/go.mod h1:m3v+5svpVOhtFAP/wSz+yzh4Mc0Fg7eRhxkJMWSIz9Q= 134 | gopkg.in/jcmturner/goidentity.v3 v3.0.0/go.mod h1:oG2kH0IvSYNIu80dVAyu/yoefjq1mNfM5bm88whjWx4= 135 | gopkg.in/jcmturner/gokrb5.v7 v7.2.3/go.mod h1:l8VISx+WGYp+Fp7KRbsiUuXTTOnxIc3Tuvyavf11/WM= 136 | gopkg.in/jcmturner/rpc.v1 v1.1.0/go.mod h1:YIdkC4XfD6GXbzje11McwsDuOlZQSb9W4vfLvuNnlv8= 137 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 138 | -------------------------------------------------------------------------------- /handler/handler.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package handler 18 | 19 | import ( 20 | "context" 21 | 22 | "github.com/hellobike/amazonriver/conf" 23 | "github.com/hellobike/amazonriver/handler/output" 24 | "github.com/hellobike/amazonriver/model" 25 | ) 26 | 27 | // Handler handle dump data 28 | type Handler interface { 29 | // Handle row data 30 | Handle(wal ...*model.WalData) error 31 | Stop() 32 | } 33 | 34 | // PosCallback for handler 35 | type PosCallback func(uint64) 36 | 37 | // NewHandler create wal handler with subscribe config 38 | func NewHandler(sub *conf.Subscribe, callback PosCallback) Handler { 39 | ret := &handlerWrapper{ 40 | dataCh: make(chan []*model.WalData, 20480), 41 | callback: callback, 42 | rules: sub.Rules, 43 | sub: sub, 44 | ruleCache: map[string]*conf.Rule{}, 45 | skipCache: map[string]struct{}{}, 46 | done: make(chan struct{}), 47 | } 48 | 49 | ret.output = output.NewOutput(sub) 50 | 51 | ctx, cancel := context.WithCancel(context.Background()) 52 | ret.cancel = cancel 53 | go ret.runloop(ctx) 54 | return ret 55 | } 56 | -------------------------------------------------------------------------------- /handler/handlerWrapper.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package handler 18 | 19 | import ( 20 | "context" 21 | "time" 22 | 23 | "github.com/hellobike/amazonriver/monitor" 24 | 25 | "github.com/hellobike/amazonriver/conf" 26 | "github.com/hellobike/amazonriver/handler/output" 27 | "github.com/hellobike/amazonriver/model" 28 | "github.com/hellobike/amazonriver/util" 29 | ) 30 | 31 | type handlerWrapper struct { 32 | output output.Output 33 | dataCh chan []*model.WalData 34 | datas []*model.WalData 35 | maxPos uint64 36 | callback PosCallback 37 | sub *conf.Subscribe 38 | rules []*conf.Rule 39 | ruleCache map[string]*conf.Rule 40 | skipCache map[string]struct{} 41 | cancel context.CancelFunc 42 | done chan struct{} 43 | } 44 | 45 | func (h *handlerWrapper) runloop(ctx context.Context) { 46 | defer close(h.done) 47 | 48 | timer := time.NewTimer(time.Second) 49 | for { 50 | var needflush bool 51 | 52 | select { 53 | case <-ctx.Done(): 54 | return 55 | case <-timer.C: 56 | needflush = true 57 | case datas := <-h.dataCh: 58 | for _, data := range datas { 59 | if data.Pos > h.maxPos { 60 | h.maxPos = data.Pos 61 | } 62 | 63 | if rule, matched := h.filterData(data); matched { 64 | data.Rule = rule 65 | h.datas = append(h.datas, data) 66 | } 67 | 68 | } 69 | needflush = len(h.datas) >= 20000 70 | } 71 | 72 | if needflush { 73 | h.flush() 74 | resetTimer(timer, time.Second) 75 | } 76 | } 77 | } 78 | 79 | func resetTimer(t *time.Timer, d time.Duration) { 80 | // reset timer 81 | select { 82 | case <-t.C: 83 | default: 84 | } 85 | t.Reset(d) 86 | } 87 | 88 | func (h *handlerWrapper) flush() (err error) { 89 | defer func() { 90 | if len(h.datas) > 0 { 91 | if err != nil { 92 | monitor.IncreaseErrorCount(h.sub.SlotName, 1) 93 | } else { 94 | monitor.IncreaseSuccessCount(h.sub.SlotName, len(h.datas)) 95 | } 96 | } 97 | 98 | h.callback(h.maxPos) 99 | h.datas = nil 100 | }() 101 | 102 | if len(h.datas) == 0 { 103 | return nil 104 | } 105 | 106 | return h.output.Write(h.datas...) 107 | } 108 | 109 | func (h *handlerWrapper) filterData(data *model.WalData) (matchedRule *conf.Rule, matched bool) { 110 | if len(data.Data) == 0 { 111 | return 112 | } 113 | 114 | if _, skip := h.skipCache[data.Table]; skip { 115 | return 116 | } 117 | 118 | matchedRule, matched = h.ruleCache[data.Table] 119 | if !matched { 120 | for _, rule := range h.rules { 121 | if util.MatchSimple(rule.Table, data.Table) { 122 | matched = true 123 | matchedRule = rule 124 | break 125 | } 126 | } 127 | 128 | if !matched { 129 | h.skipCache[data.Table] = struct{}{} 130 | return 131 | } 132 | h.ruleCache[data.Table] = matchedRule 133 | return 134 | } 135 | return 136 | } 137 | 138 | func (h *handlerWrapper) Handle(datas ...*model.WalData) error { 139 | 140 | h.dataCh <- datas 141 | return nil 142 | } 143 | 144 | func (h *handlerWrapper) Stop() { 145 | h.cancel() 146 | <-h.done 147 | h.output.Close() 148 | } 149 | -------------------------------------------------------------------------------- /handler/output/es.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package output 18 | 19 | import ( 20 | "bytes" 21 | "context" 22 | "fmt" 23 | "strings" 24 | 25 | "github.com/hellobike/amazonriver/conf" 26 | "github.com/hellobike/amazonriver/log" 27 | "github.com/hellobike/amazonriver/model" 28 | "github.com/hellobike/amazonriver/util" 29 | 30 | "github.com/olivere/elastic" 31 | ) 32 | 33 | type esHandler struct { 34 | client *elastic.Client 35 | sub *conf.Subscribe 36 | } 37 | 38 | // newESOutput create handler write data to es 39 | func newESOutput(sub *conf.Subscribe) Output { 40 | if sub.ESConf == nil { 41 | panic("es conf is nil") 42 | } 43 | 44 | client, err := elastic.NewSimpleClient(elastic.SetURL(strings.Split(sub.ESConf.Addrs, ",")...), elastic.SetBasicAuth(sub.ESConf.User, sub.ESConf.Password)) 45 | if err != nil { 46 | panic(err) 47 | } 48 | 49 | handler := &esHandler{ 50 | client: client, 51 | sub: sub, 52 | } 53 | 54 | return handler 55 | } 56 | 57 | func (e *esHandler) Write(datas ...*model.WalData) error { 58 | numReqs := len(datas) 59 | if numReqs == 0 { 60 | return nil 61 | } 62 | 63 | var reqs = make([]elastic.BulkableRequest, 0, numReqs) 64 | for _, data := range datas { 65 | if req := e.makeRequest(data); req != nil { 66 | reqs = append(reqs, req) 67 | } 68 | } 69 | 70 | if len(reqs) == 0 { 71 | return nil 72 | } 73 | 74 | bulk := e.client.Bulk().Add(reqs...).Refresh("true") 75 | 76 | return util.WithRetry(e.sub.Retry, func() error { 77 | if _, err := bulk.Do(context.Background()); err != nil { 78 | log.Logger.Errorf("write es bulk request err: %v", err) 79 | return err 80 | } 81 | return nil 82 | }) 83 | } 84 | 85 | func (e *esHandler) Close() { 86 | e.client.Stop() 87 | } 88 | 89 | func (e *esHandler) makeRequest(data *model.WalData) elastic.BulkableRequest { 90 | defer model.PutWalData(data) 91 | 92 | matchedRule := data.Rule 93 | 94 | var idBuf bytes.Buffer 95 | 96 | for _, field := range matchedRule.ESID { 97 | idBuf.WriteString(fmt.Sprint(data.Data[field])) 98 | } 99 | 100 | id := idBuf.String() 101 | if id == "" { 102 | return nil 103 | } 104 | 105 | switch data.OperationType { 106 | case model.Insert, model.Update: 107 | return elastic.NewBulkIndexRequest(). 108 | Index(matchedRule.Index). 109 | Type(matchedRule.Type). 110 | Id(id). 111 | Doc(data.Data) 112 | case model.Delete: 113 | return elastic.NewBulkDeleteRequest(). 114 | Index(matchedRule.Index). 115 | Type(matchedRule.Type). 116 | Id(id) 117 | } 118 | return nil 119 | } 120 | -------------------------------------------------------------------------------- /handler/output/fake.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package output 18 | 19 | import ( 20 | "github.com/hellobike/amazonriver/conf" 21 | "github.com/hellobike/amazonriver/log" 22 | "github.com/hellobike/amazonriver/model" 23 | ) 24 | 25 | // newFakeHandler create a Handler print all data 26 | func newFakeHandler(_ *conf.Subscribe) Output { 27 | return &fakeHandler{} 28 | } 29 | 30 | type fakeHandler struct{} 31 | 32 | func (l *fakeHandler) Write(datas ...*model.WalData) error { 33 | for _, data := range datas { 34 | log.Logger.Infof("TYPE:%s SCHEME:%s TABLE:%s DATA:%#v\n", data.OperationType.String(), data.Schema, data.Table, data.Data) 35 | } 36 | return nil 37 | } 38 | 39 | func (l *fakeHandler) Close() {} 40 | -------------------------------------------------------------------------------- /handler/output/kafka.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package output 18 | 19 | import ( 20 | "bytes" 21 | "fmt" 22 | "time" 23 | 24 | "github.com/hellobike/amazonriver/conf" 25 | "github.com/hellobike/amazonriver/log" 26 | "github.com/hellobike/amazonriver/model" 27 | "github.com/hellobike/amazonriver/util" 28 | 29 | "github.com/Shopify/sarama" 30 | "github.com/json-iterator/go" 31 | ) 32 | 33 | type kafkaHandler struct { 34 | sub *conf.Subscribe 35 | kafka sarama.SyncProducer 36 | } 37 | 38 | type kafkaMessage struct { 39 | Schema string `json:"schema"` 40 | Table string `json:"table"` 41 | Operation string `json:"operation"` 42 | Data map[string]interface{} `json:"data"` 43 | OperateTime int64 `json:"operateTime"` 44 | } 45 | 46 | func newKafkaOutput(sub *conf.Subscribe) Output { 47 | config := sarama.NewConfig() 48 | config.Producer.Compression = sarama.CompressionSnappy // Compress messages 49 | config.Producer.Flush.Frequency = 10 * time.Millisecond // Flush batches every 10ms 50 | config.Producer.Flush.MaxMessages = 1 << 29 51 | config.Producer.RequiredAcks = sarama.NoResponse 52 | config.Producer.Return.Successes = true 53 | sarama.Logger = log.Logger 54 | config.Producer.Retry.Max = 3 55 | if sub.Retry > 0 { 56 | config.Producer.Retry.Max = sub.Retry 57 | } 58 | config.Producer.Partitioner = sarama.NewHashPartitioner 59 | producer, err := sarama.NewSyncProducer(sub.KafkaConf.Addrs, config) 60 | if err != nil { 61 | panic(err) 62 | } 63 | 64 | ret := &kafkaHandler{ 65 | kafka: producer, 66 | sub: sub, 67 | } 68 | 69 | return ret 70 | } 71 | 72 | func fromData(data *model.WalData) (key []byte, topic string, msg *kafkaMessage) { 73 | defer model.PutWalData(data) 74 | 75 | if len(data.Data) == 0 { 76 | return nil, "", nil 77 | } 78 | 79 | var keyb bytes.Buffer 80 | var connector string 81 | for _, f := range data.Rule.PKs { 82 | fmt.Fprint(&keyb, connector) 83 | fmt.Fprintf(&keyb, "%v", data.Data[f]) 84 | connector = "-" 85 | } 86 | 87 | return keyb.Bytes(), data.Rule.Topic, &kafkaMessage{ 88 | Schema: data.Schema, 89 | Table: data.Table, 90 | Data: data.Data, 91 | Operation: data.OperationType.String(), 92 | OperateTime: data.Timestamp, 93 | } 94 | } 95 | 96 | func (k *kafkaHandler) Write(datas ...*model.WalData) error { 97 | 98 | if len(datas) == 0 { 99 | return nil 100 | } 101 | 102 | var msgs = make([]*sarama.ProducerMessage, 0, len(datas)) 103 | for _, data := range datas { 104 | key, topic, msg := fromData(data) 105 | if msg == nil { 106 | continue 107 | } 108 | bts, err := jsoniter.Marshal(msg) 109 | if err != nil { 110 | continue 111 | } 112 | 113 | m := &sarama.ProducerMessage{ 114 | Topic: topic, 115 | Key: sarama.ByteEncoder(key), 116 | Value: sarama.ByteEncoder(bts), 117 | } 118 | 119 | msgs = append(msgs, m) 120 | } 121 | 122 | if len(msgs) == 0 { 123 | return nil 124 | } 125 | 126 | return util.WithRetry(k.sub.Retry, func() error { 127 | if err := k.kafka.SendMessages(msgs); err != nil { 128 | log.Logger.Errorf("write kafka msg err: %v", err) 129 | return err 130 | } 131 | 132 | return nil 133 | }) 134 | } 135 | 136 | func (k *kafkaHandler) Close() { 137 | k.kafka.Close() 138 | } 139 | -------------------------------------------------------------------------------- /handler/output/output.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package output 18 | 19 | import ( 20 | "github.com/hellobike/amazonriver/conf" 21 | "github.com/hellobike/amazonriver/model" 22 | ) 23 | 24 | // Output for write wal data 25 | type Output interface { 26 | // Handle row data 27 | Write(wal ...*model.WalData) error 28 | Close() 29 | } 30 | 31 | // NewOutput create new output 32 | func NewOutput(sub *conf.Subscribe) Output { 33 | 34 | switch { 35 | case sub.ESConf != nil: 36 | return newESOutput(sub) 37 | case sub.KafkaConf != nil: 38 | return newKafkaOutput(sub) 39 | } 40 | 41 | return newFakeHandler(nil) 42 | } 43 | -------------------------------------------------------------------------------- /log/log.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package log 18 | 19 | import ( 20 | "os" 21 | 22 | "github.com/sirupsen/logrus" 23 | ) 24 | 25 | // Logger is a shared logger 26 | var Logger = logrus.New() 27 | 28 | func init() { 29 | Logger.SetNoLock() 30 | Logger.Out = os.Stdout 31 | } 32 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "flag" 21 | "io/ioutil" 22 | 23 | "github.com/hellobike/amazonriver/conf" 24 | "github.com/hellobike/amazonriver/log" 25 | "github.com/hellobike/amazonriver/river" 26 | 27 | "github.com/json-iterator/go" 28 | "github.com/sirupsen/logrus" 29 | ) 30 | 31 | var configfile = flag.String("config", "", "config") 32 | var loglevel = flag.String("level", "debug", "log level") 33 | func main() { 34 | flag.Parse() 35 | 36 | lv, err := logrus.ParseLevel(*loglevel) 37 | if err != nil { 38 | panic(err) 39 | } 40 | log.Logger.SetLevel(lv) 41 | 42 | data, err := ioutil.ReadFile(*configfile) 43 | if err != nil { 44 | panic(err) 45 | } 46 | 47 | var config conf.Conf 48 | if err := jsoniter.Unmarshal(data, &config); err != nil { 49 | panic(err) 50 | } 51 | 52 | amazon := river.New(&config) 53 | amazon.Start() 54 | 55 | // block forever 56 | select {} 57 | } 58 | -------------------------------------------------------------------------------- /model/consts.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package model 18 | 19 | // Operation type 20 | type Operation uint8 21 | 22 | const ( 23 | // Insert operation 24 | Insert Operation = iota 25 | // Delete operation 26 | Delete 27 | // Update operation 28 | Update 29 | // Begin transaction 30 | Begin 31 | // Commit transaction 32 | Commit 33 | // Unknow operation 34 | Unknow 35 | ) 36 | 37 | func (o Operation) String() string { 38 | switch o { 39 | case Insert: 40 | return "INSERT" 41 | case Delete: 42 | return "DELETE" 43 | case Update: 44 | return "UPDATE" 45 | case Begin: 46 | return "BEGIN" 47 | case Commit: 48 | return "COMMIT" 49 | } 50 | 51 | return "UNKNOW" 52 | } 53 | -------------------------------------------------------------------------------- /model/decode.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package model 18 | 19 | import ( 20 | "strconv" 21 | "strings" 22 | 23 | "github.com/hellobike/amazonriver/util" 24 | "github.com/jackc/pgx" 25 | "github.com/nickelser/parselogical" 26 | ) 27 | 28 | // Parse test_decoding format wal to WalData 29 | func Parse(msg *pgx.WalMessage) (*WalData, error) { 30 | result := parselogical.NewParseResult(util.Bytes2String(msg.WalData)) 31 | if err := result.Parse(); err != nil { 32 | return nil, err 33 | } 34 | var ret = NewWalData() 35 | 36 | var schema, table string 37 | if result.Relation != "" { 38 | i := strings.IndexByte(result.Relation, '.') 39 | if i < 0 { 40 | table = result.Relation 41 | } else { 42 | schema = result.Relation[:i] 43 | table = result.Relation[i+1:] 44 | } 45 | 46 | ret.Schema = schema 47 | ret.Table = table 48 | } 49 | ret.Pos = msg.WalStart 50 | switch result.Operation { 51 | case "INSERT": 52 | ret.OperationType = Insert 53 | case "UPDATE": 54 | ret.OperationType = Update 55 | case "DELETE": 56 | ret.OperationType = Delete 57 | case "BEGIN": 58 | ret.OperationType = Begin 59 | case "COMMIT": 60 | ret.OperationType = Commit 61 | } 62 | 63 | if len(result.Columns) > 0 { 64 | ret.Data = make(map[string]interface{}, len(result.Columns)) 65 | } 66 | for key, column := range result.Columns { 67 | if column.Quoted { 68 | ret.Data[key] = column.Value 69 | continue 70 | } 71 | 72 | if column.Value == "null" { 73 | ret.Data[key] = nil 74 | continue 75 | } 76 | 77 | if val, err := strconv.ParseInt(column.Value, 10, 64); err == nil { 78 | ret.Data[key] = val 79 | continue 80 | } 81 | if val, err := strconv.ParseFloat(column.Value, 64); err == nil { 82 | ret.Data[key] = val 83 | continue 84 | } 85 | ret.Data[key] = column.Value 86 | } 87 | 88 | return ret, nil 89 | } 90 | -------------------------------------------------------------------------------- /model/decode_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package model 18 | 19 | import ( 20 | "reflect" 21 | "testing" 22 | 23 | "github.com/jackc/pgx" 24 | ) 25 | 26 | func TestParse(t *testing.T) { 27 | 28 | tcs := []struct { 29 | name string 30 | src *pgx.WalMessage 31 | want *WalData 32 | wantErr bool 33 | }{ 34 | { 35 | name: "DELETE", 36 | src: &pgx.WalMessage{WalData: []byte("table public.source: DELETE: id[integer]:0"), WalStart: 11}, 37 | want: &WalData{OperationType: Delete, Pos: 11, Schema: "public", Table: "source", Data: map[string]interface{}{"id": int64(0)}}, 38 | wantErr: false, 39 | }, 40 | { 41 | name: "INSERT", 42 | src: &pgx.WalMessage{WalData: []byte("table public.source: INSERT: id[integer]:0"), WalStart: 11}, 43 | want: &WalData{OperationType: Insert, Pos: 11, Schema: "public", Table: "source", Data: map[string]interface{}{"id": int64(0)}}, 44 | wantErr: false, 45 | }, 46 | { 47 | name: "INSERT MULTI COLUMNS", 48 | src: &pgx.WalMessage{WalData: []byte("table public.source: INSERT: id[integer]:0 name[text]:'phil'"), WalStart: 11}, 49 | want: &WalData{OperationType: Insert, Pos: 11, Schema: "public", Table: "source", Data: map[string]interface{}{"id": int64(0), "name": "phil"}}, 50 | wantErr: false, 51 | }, 52 | 53 | { 54 | name: "UPDATE", 55 | src: &pgx.WalMessage{WalData: []byte("table public.source: UPDATE: id[integer]:0"), WalStart: 11}, 56 | want: &WalData{OperationType: Update, Pos: 11, Schema: "public", Table: "source", Data: map[string]interface{}{"id": int64(0)}}, 57 | wantErr: false, 58 | }, 59 | { 60 | name: "UPDATE MULTI COLUMNS", 61 | src: &pgx.WalMessage{WalData: []byte("table public.source: UPDATE: id[integer]:0 name[text]:'phil'"), WalStart: 11}, 62 | want: &WalData{OperationType: Update, Pos: 11, Schema: "public", Table: "source", Data: map[string]interface{}{"id": int64(0), "name": "phil"}}, 63 | wantErr: false, 64 | }, 65 | { 66 | name: "BEGIN", 67 | src: &pgx.WalMessage{WalData: []byte("BEGIN 1024"), WalStart: 11}, 68 | want: &WalData{OperationType: Begin, Pos: 11}, 69 | wantErr: false, 70 | }, 71 | { 72 | name: "COMMIT", 73 | src: &pgx.WalMessage{WalData: []byte("COMMIT 1024"), WalStart: 11}, 74 | want: &WalData{OperationType: Commit, Pos: 11}, 75 | wantErr: false, 76 | }, 77 | } 78 | 79 | for _, tc := range tcs { 80 | t.Run(tc.name, func(t *testing.T) { 81 | got, err := Parse(tc.src) 82 | if (err != nil) != tc.wantErr { 83 | t.Errorf("test %s wantErr %v, got %v", tc.name, tc.wantErr, err) 84 | return 85 | } 86 | if !reflect.DeepEqual(tc.want, got) { 87 | t.Errorf("test %s want %#v, got %#v", tc.name, tc.want, got) 88 | return 89 | } 90 | }) 91 | } 92 | } 93 | 94 | func BenchmarkParse(b *testing.B) { 95 | src := &pgx.WalMessage{WalData: []byte("table public.source: UPDATE: id[integer]:0 name[text]:'phil'"), WalStart: 11} 96 | 97 | b.ResetTimer() 98 | for i := 0; i < b.N; i++ { 99 | 100 | got, err := Parse(src) 101 | if err != nil { 102 | b.Error(err) 103 | return 104 | } 105 | _ = got 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /model/wal.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package model 18 | 19 | import ( 20 | "sync" 21 | 22 | "github.com/hellobike/amazonriver/conf" 23 | ) 24 | 25 | // WalData represent parsed wal log data 26 | type WalData struct { 27 | OperationType Operation 28 | Schema string 29 | Table string 30 | Data map[string]interface{} 31 | Timestamp int64 32 | Pos uint64 33 | Rule *conf.Rule 34 | } 35 | 36 | // Reset for reuse 37 | func (d *WalData) Reset() { 38 | d.OperationType = Unknow 39 | d.Schema = "" 40 | d.Table = "" 41 | d.Data = nil 42 | d.Timestamp = 0 43 | d.Pos = 0 44 | d.Rule = nil 45 | } 46 | 47 | var waldatapool = sync.Pool{New: func() interface{} { return &WalData{} }} 48 | 49 | // NewWalData get data from pool 50 | func NewWalData() *WalData { 51 | data := waldatapool.Get().(*WalData) 52 | data.Reset() 53 | return data 54 | } 55 | 56 | // PutWalData putback data to pool 57 | func PutWalData(data *WalData) { 58 | waldatapool.Put(data) 59 | } 60 | -------------------------------------------------------------------------------- /model/wal_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package model 18 | 19 | import ( 20 | "reflect" 21 | "testing" 22 | 23 | "github.com/hellobike/amazonriver/conf" 24 | ) 25 | 26 | func TestWalData_Reset(t *testing.T) { 27 | 28 | var empty = &WalData{} 29 | empty.Reset() 30 | 31 | type fields struct { 32 | OperationType Operation 33 | Schema string 34 | Table string 35 | Data map[string]interface{} 36 | Timestamp int64 37 | Pos uint64 38 | Rule *conf.Rule 39 | } 40 | tests := []struct { 41 | name string 42 | fields fields 43 | }{ 44 | { 45 | name: "test1", 46 | fields: fields{ 47 | OperationType: Insert, 48 | Schema: "test1", 49 | Table: "test1_table", 50 | Data: map[string]interface{}{"id": 1, "data": "test1"}, 51 | Timestamp: 100, 52 | Pos: 100, 53 | }, 54 | }, 55 | } 56 | for _, tt := range tests { 57 | t.Run(tt.name, func(t *testing.T) { 58 | d := &WalData{ 59 | OperationType: tt.fields.OperationType, 60 | Schema: tt.fields.Schema, 61 | Table: tt.fields.Table, 62 | Data: tt.fields.Data, 63 | Timestamp: tt.fields.Timestamp, 64 | Pos: tt.fields.Pos, 65 | Rule: tt.fields.Rule, 66 | } 67 | d.Reset() 68 | 69 | if !reflect.DeepEqual(d, empty) { 70 | t.Errorf("after d.Reset, should equal to emtyp, got: %v", d) 71 | } 72 | }) 73 | } 74 | } 75 | 76 | func TestNewWalData(t *testing.T) { 77 | var empty = &WalData{} 78 | empty.Reset() 79 | 80 | tests := []struct { 81 | name string 82 | want *WalData 83 | }{ 84 | { 85 | name: "test1", 86 | want: empty, 87 | }, 88 | } 89 | for _, tt := range tests { 90 | t.Run(tt.name, func(t *testing.T) { 91 | got := NewWalData() 92 | if !reflect.DeepEqual(got, tt.want) { 93 | t.Errorf("NewWalData() = %v, want %v", got, tt.want) 94 | } 95 | PutWalData(got) 96 | }) 97 | } 98 | } 99 | 100 | func BenchmarkNewWalData(b *testing.B) { 101 | for i := 0; i < b.N; i++ { 102 | data := NewWalData() 103 | PutWalData(data) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /monitor/prometheus.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package monitor 18 | 19 | import ( 20 | "github.com/prometheus/client_golang/prometheus" 21 | ) 22 | 23 | func init() { 24 | prometheus.MustRegister(successCounterVec) 25 | prometheus.MustRegister(errorCounterVec) 26 | } 27 | 28 | // successCounterVec monitor success count 29 | var successCounterVec = prometheus.NewCounterVec(prometheus.CounterOpts{ 30 | Name: "amazonriver_success", 31 | Help: "success count", 32 | }, []string{"slot_name"}) 33 | 34 | // errorCounterVec monitor error count 35 | var errorCounterVec = prometheus.NewCounterVec(prometheus.CounterOpts{ 36 | Name: "amazonriver_error", 37 | Help: "error count", 38 | }, []string{"slot_name"}) 39 | 40 | // IncreaseSuccessCount increase success count for slotname 41 | func IncreaseSuccessCount(slotname string, count int) { 42 | successCounterVec.WithLabelValues(slotname).Add(float64(count)) 43 | } 44 | 45 | // IncreaseErrorCount increase error count for slotname 46 | func IncreaseErrorCount(slotname string, count int) { 47 | errorCounterVec.WithLabelValues(slotname).Add(float64(count)) 48 | } 49 | -------------------------------------------------------------------------------- /river/amazon.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package river 18 | 19 | import ( 20 | "context" 21 | "net/http" 22 | "sync" 23 | 24 | "github.com/hellobike/amazonriver/log" 25 | 26 | "github.com/hellobike/amazonriver/conf" 27 | "github.com/prometheus/client_golang/prometheus/promhttp" 28 | ) 29 | 30 | // this is a static check 31 | var _ Interface = (*river)(nil) 32 | 33 | // Interface of river 34 | type Interface interface { 35 | Start() error 36 | Stop() 37 | Update(config *conf.Conf) 38 | } 39 | 40 | type river struct { 41 | conf *conf.Conf 42 | ctx context.Context 43 | cancel context.CancelFunc 44 | wg *sync.WaitGroup 45 | } 46 | 47 | // New create river from conf 48 | func New(conf *conf.Conf) Interface { 49 | return &river{conf: conf} 50 | } 51 | 52 | // Start flow the river 53 | func (r *river) Start() error { 54 | r.wg = new(sync.WaitGroup) 55 | r.ctx, r.cancel = context.WithCancel(context.Background()) 56 | if r.conf != nil { 57 | for _, sub := range r.conf.Subscribes { 58 | r.wg.Add(1) 59 | stream := newStream(r.conf.PgDumpExec, sub) 60 | go stream.start(r.ctx, r.wg) 61 | } 62 | } 63 | 64 | if r.conf.PrometheusAddress != "" { 65 | log.Logger.Info("start prometheus handler") 66 | // prometheus exporter 67 | http.Handle("/metrics", promhttp.Handler()) 68 | go http.ListenAndServe(r.conf.PrometheusAddress, nil) 69 | } 70 | 71 | log.Logger.Info("start amazon...") 72 | return nil 73 | } 74 | 75 | func (r *river) Update(config *conf.Conf) { 76 | // stop running streams 77 | r.Stop() 78 | 79 | r.conf = config 80 | r.wg = new(sync.WaitGroup) 81 | r.ctx, r.cancel = context.WithCancel(context.Background()) 82 | for _, sub := range config.Subscribes { 83 | r.wg.Add(1) 84 | stream := newStream(r.conf.PgDumpExec, sub) 85 | go stream.start(r.ctx, r.wg) 86 | } 87 | } 88 | 89 | func (r *river) Stop() { 90 | r.cancel() 91 | r.wg.Wait() 92 | } 93 | -------------------------------------------------------------------------------- /river/stream.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package river 18 | 19 | import ( 20 | "context" 21 | "fmt" 22 | "sync" 23 | "sync/atomic" 24 | "time" 25 | 26 | "github.com/hellobike/amazonriver/log" 27 | 28 | "github.com/hellobike/amazonriver/conf" 29 | "github.com/hellobike/amazonriver/dump" 30 | "github.com/hellobike/amazonriver/handler" 31 | "github.com/hellobike/amazonriver/model" 32 | "github.com/jackc/pgx" 33 | ) 34 | 35 | type stream struct { 36 | // pg_dump 可执行文件的path 37 | pgDump string 38 | // dump 是否dump历史数据 39 | dump bool 40 | // 订阅配置 41 | sub *conf.Subscribe 42 | // 当前 wal 位置 43 | receivedWal uint64 44 | flushWal uint64 45 | // 复制连接 46 | replicationConn *pgx.ReplicationConn 47 | // 消息处理 48 | handler handler.Handler 49 | // 取消 50 | cancel context.CancelFunc 51 | // ack 锁 52 | sendStatusLock sync.Mutex 53 | // buffered data 54 | datas []*model.WalData 55 | } 56 | 57 | func (s *stream) getReceivedWal() uint64 { 58 | return atomic.LoadUint64(&s.receivedWal) 59 | } 60 | 61 | func (s *stream) setReceivedWal(val uint64) { 62 | atomic.StoreUint64(&s.receivedWal, val) 63 | } 64 | 65 | func (s *stream) getFlushWal() uint64 { 66 | return atomic.LoadUint64(&s.flushWal) 67 | } 68 | 69 | func (s *stream) setFlushWal(val uint64) { 70 | atomic.StoreUint64(&s.flushWal, val) 71 | } 72 | 73 | func (s *stream) getStatus() (*pgx.StandbyStatus, error) { 74 | return pgx.NewStandbyStatus(s.getReceivedWal(), s.getFlushWal(), s.getFlushWal()) 75 | } 76 | 77 | func newStream(pgDump string, sub *conf.Subscribe) *stream { 78 | var ret = &stream{pgDump: pgDump, sub: sub, dump: sub.Dump} 79 | ret.handler = handler.NewHandler(sub, ret.setFlushWal) 80 | 81 | return ret 82 | } 83 | 84 | func (s *stream) start(ctx context.Context, wg *sync.WaitGroup) error { 85 | defer wg.Done() 86 | 87 | log.Logger.Infof("start stream for %s", s.sub.SlotName) 88 | ctx, s.cancel = context.WithCancel(ctx) 89 | 90 | config := pgx.ConnConfig{Host: s.sub.PGConnConf.Host, Port: s.sub.PGConnConf.Port, Database: s.sub.PGConnConf.Database, User: s.sub.PGConnConf.User, Password: s.sub.PGConnConf.Password} 91 | conn, err := pgx.ReplicationConnect(config) 92 | if err != nil { 93 | log.Logger.Errorf("create replication connection err: %v", err) 94 | return err 95 | } 96 | 97 | s.replicationConn = conn 98 | 99 | slotname := s.sub.SlotName 100 | 101 | _, snapshotID, err := conn.CreateReplicationSlotEx(slotname, "test_decoding") 102 | if err != nil { 103 | // 42710 means replication slot already exists 104 | if pgerr, ok := err.(pgx.PgError); !ok || pgerr.Code != "42710" { 105 | log.Logger.Errorf("create replication slot err: %v", err) 106 | return fmt.Errorf("failed to create replication slot: %s", err) 107 | } 108 | } 109 | 110 | _ = s.sendStatus() 111 | 112 | // Handle old data from db 113 | if err := s.exportSnapshot(snapshotID); err != nil { 114 | log.Logger.Errorf("export snapshot %s err: %v", snapshotID, err) 115 | return fmt.Errorf("slot name %s, err export snapshot: %v", s.sub.SlotName, err) 116 | } 117 | 118 | if err := conn.StartReplication(slotname, 0, -1); err != nil { 119 | log.Logger.Errorf("start replication err: %v", err) 120 | return err 121 | } 122 | 123 | return s.runloop(ctx) 124 | } 125 | 126 | func (s *stream) stop() error { 127 | s.cancel() 128 | s.handler.Stop() 129 | return s.replicationConn.Close() 130 | } 131 | 132 | func (s *stream) exportSnapshot(snapshotID string) error { 133 | // replication slot already exists 134 | if snapshotID == "" || !s.dump { 135 | return nil 136 | } 137 | dumper := dump.New(s.pgDump, s.sub) 138 | return dumper.Dump(snapshotID, s.handler) 139 | } 140 | 141 | func (s *stream) runloop(ctx context.Context) error { 142 | defer s.stop() 143 | 144 | go func() { 145 | ticker := time.NewTicker(5 * time.Second) 146 | for { 147 | select { 148 | case <-ticker.C: 149 | _ = s.sendStatus() 150 | case <-ctx.Done(): 151 | return 152 | } 153 | } 154 | }() 155 | 156 | for { 157 | msg, err := s.replicationConn.WaitForReplicationMessage(ctx) 158 | if err != nil { 159 | if err == ctx.Err() { 160 | return err 161 | } 162 | if err := s.checkAndResetConn(); err != nil { 163 | log.Logger.Errorf("reset replication connection err: %v", err) 164 | } 165 | continue 166 | } 167 | 168 | if msg == nil { 169 | continue 170 | } 171 | 172 | if err := s.replicationMsgHandle(msg); err != nil { 173 | log.Logger.Errorf("handle replication msg err: %v", err) 174 | continue 175 | } 176 | } 177 | } 178 | 179 | func (s *stream) checkAndResetConn() error { 180 | if s.replicationConn != nil && s.replicationConn.IsAlive() { 181 | return nil 182 | } 183 | 184 | time.Sleep(time.Second * 10) 185 | 186 | config := pgx.ConnConfig{ 187 | Host: s.sub.PGConnConf.Host, 188 | Port: s.sub.PGConnConf.Port, 189 | Database: s.sub.PGConnConf.Database, 190 | User: s.sub.PGConnConf.User, 191 | Password: s.sub.PGConnConf.Password, 192 | } 193 | conn, err := pgx.ReplicationConnect(config) 194 | if err != nil { 195 | return err 196 | } 197 | 198 | if _, _, err := conn.CreateReplicationSlotEx(s.sub.SlotName, "test_decoding"); err != nil { 199 | if pgerr, ok := err.(pgx.PgError); !ok || pgerr.Code != "42710" { 200 | return fmt.Errorf("failed to create replication slot: %s", err) 201 | } 202 | } 203 | 204 | if err := conn.StartReplication(s.sub.SlotName, 0, -1); err != nil { 205 | _ = conn.Close() 206 | return err 207 | } 208 | 209 | s.replicationConn = conn 210 | 211 | return nil 212 | } 213 | 214 | // ReplicationMsgHandle handle replication msg 215 | func (s *stream) replicationMsgHandle(msg *pgx.ReplicationMessage) error { 216 | 217 | // 回复心跳 218 | if msg.ServerHeartbeat != nil { 219 | 220 | if msg.ServerHeartbeat.ServerWalEnd > s.getReceivedWal() { 221 | s.setReceivedWal(msg.ServerHeartbeat.ServerWalEnd) 222 | } 223 | if msg.ServerHeartbeat.ReplyRequested == 1 { 224 | _ = s.sendStatus() 225 | } 226 | } 227 | 228 | if msg.WalMessage != nil { 229 | 230 | logmsg, err := model.Parse(msg.WalMessage) 231 | if err != nil { 232 | return fmt.Errorf("invalid pgoutput msg: %s", err) 233 | } 234 | 235 | logmsg.Timestamp = time.Now().UnixNano() / int64(time.Millisecond) 236 | if err := s.handleMessage(logmsg); err != nil { 237 | return err 238 | } 239 | } 240 | 241 | return nil 242 | } 243 | 244 | func (s *stream) handleMessage(data *model.WalData) (err error) { 245 | log.Logger.Infof("handle wal data: %v", data) 246 | var needFlush bool 247 | switch data.OperationType { 248 | 249 | // 事务开始 250 | case model.Begin: 251 | // 事务结束 252 | case model.Commit: 253 | needFlush = true 254 | default: 255 | s.datas = append(s.datas, data) 256 | // 防止大事务耗尽内存 257 | needFlush = len(s.datas) > 1000 258 | } 259 | 260 | if needFlush { 261 | _ = s.flush() 262 | } 263 | 264 | return nil 265 | } 266 | 267 | func (s *stream) flush() error { 268 | if len(s.datas) > 0 { 269 | _ = s.handler.Handle(s.datas...) 270 | s.datas = nil 271 | } 272 | return nil 273 | } 274 | 275 | // 发送心跳 276 | func (s *stream) sendStatus() error { 277 | s.sendStatusLock.Lock() 278 | defer s.sendStatusLock.Unlock() 279 | 280 | log.Logger.Debug("send heartbeat") 281 | status, err := s.getStatus() 282 | if err != nil { 283 | return err 284 | } 285 | return s.replicationConn.SendStandbyStatus(status) 286 | } 287 | -------------------------------------------------------------------------------- /util/hack.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package util 18 | 19 | import ( 20 | "unsafe" 21 | ) 22 | 23 | // String2Bytes convert string to bytes 24 | func String2Bytes(s string) []byte { 25 | x := (*[2]uintptr)(unsafe.Pointer(&s)) 26 | h := [3]uintptr{x[0], x[1], x[1]} 27 | return *(*[]byte)(unsafe.Pointer(&h)) 28 | } 29 | 30 | // Bytes2String convert bytes to string 31 | func Bytes2String(b []byte) string { 32 | return *(*string)(unsafe.Pointer(&b)) 33 | } 34 | -------------------------------------------------------------------------------- /util/hack_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package util 18 | 19 | import ( 20 | "reflect" 21 | "testing" 22 | ) 23 | 24 | func TestString2Bytes(t *testing.T) { 25 | type args struct { 26 | s string 27 | } 28 | tests := []struct { 29 | name string 30 | args args 31 | want []byte 32 | }{ 33 | { 34 | name: "test1", 35 | args: args{s: "test1"}, 36 | want: []byte("test1"), 37 | }, 38 | { 39 | name: "test2", 40 | args: args{s: "The quick brown fox jumps over the lazy dog"}, 41 | want: []byte("The quick brown fox jumps over the lazy dog"), 42 | }, 43 | } 44 | for _, tt := range tests { 45 | t.Run(tt.name, func(t *testing.T) { 46 | if got := String2Bytes(tt.args.s); !reflect.DeepEqual(got, tt.want) { 47 | t.Errorf("String2Bytes() = %v, want %v", got, tt.want) 48 | } 49 | }) 50 | } 51 | } 52 | 53 | func TestBytes2String(t *testing.T) { 54 | type args struct { 55 | b []byte 56 | } 57 | tests := []struct { 58 | name string 59 | args args 60 | want string 61 | }{ 62 | { 63 | name: "test1", 64 | args: args{b: []byte("test1")}, 65 | want: "test1", 66 | }, 67 | { 68 | name: "test2", 69 | args: args{b: []byte("The quick brown fox jumps over the lazy dog")}, 70 | want: "The quick brown fox jumps over the lazy dog", 71 | }, 72 | } 73 | for _, tt := range tests { 74 | t.Run(tt.name, func(t *testing.T) { 75 | if got := Bytes2String(tt.args.b); got != tt.want { 76 | t.Errorf("Bytes2String() = %v, want %v", got, tt.want) 77 | } 78 | }) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /util/retry.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package util 18 | 19 | // WithRetry retry util job succeeded or retry count limit exceed 20 | func WithRetry(retry int, job func() error) error { 21 | var retrys int 22 | for { 23 | retrys++ 24 | if err := job(); err != nil { 25 | if retry == -1 || (retry > 0 && retrys <= retry) { 26 | continue 27 | } 28 | return err 29 | } 30 | return nil 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /util/retry_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 Shanghai Junzheng Network Technology Co.,Ltd. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package util 18 | 19 | import ( 20 | "errors" 21 | "testing" 22 | ) 23 | 24 | func TestWithRetry(t *testing.T) { 25 | if err := WithRetry(1, func() error { 26 | return nil 27 | }); err != nil { 28 | t.Error(err) 29 | } 30 | 31 | var i int 32 | if err := WithRetry(3, func() error { 33 | i++ 34 | if i < 3 { 35 | return errors.New("less than 3") 36 | } 37 | return nil 38 | }); err != nil { 39 | t.Error(err) 40 | } 41 | 42 | var j int 43 | if err := WithRetry(3, func() error { 44 | j++ 45 | if j < 5 { 46 | return errors.New("less than 5") 47 | } 48 | return nil 49 | }); err == nil { 50 | t.Errorf("errro should not be nil") 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /util/wildcard.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Minio Cloud Storage, (C) 2015, 2016 Minio, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package util 18 | 19 | // MatchSimple - finds whether the text matches/satisfies the pattern string. 20 | // supports only '*' wildcard in the pattern. 21 | // considers a file system path as a flat name space. 22 | func MatchSimple(pattern, name string) bool { 23 | if pattern == "" { 24 | return name == pattern 25 | } 26 | if pattern == "*" { 27 | return true 28 | } 29 | rname := make([]rune, 0, len(name)) 30 | rpattern := make([]rune, 0, len(pattern)) 31 | for _, r := range name { 32 | rname = append(rname, r) 33 | } 34 | for _, r := range pattern { 35 | rpattern = append(rpattern, r) 36 | } 37 | simple := true // Does only wildcard '*' match. 38 | return deepMatchRune(rname, rpattern, simple) 39 | } 40 | 41 | // Match - finds whether the text matches/satisfies the pattern string. 42 | // supports '*' and '?' wildcards in the pattern string. 43 | // unlike path.Match(), considers a path as a flat name space while matching the pattern. 44 | // The difference is illustrated in the example here https://play.golang.org/p/Ega9qgD4Qz . 45 | func Match(pattern, name string) (matched bool) { 46 | if pattern == "" { 47 | return name == pattern 48 | } 49 | if pattern == "*" { 50 | return true 51 | } 52 | rname := make([]rune, 0, len(name)) 53 | rpattern := make([]rune, 0, len(pattern)) 54 | for _, r := range name { 55 | rname = append(rname, r) 56 | } 57 | for _, r := range pattern { 58 | rpattern = append(rpattern, r) 59 | } 60 | simple := false // Does extended wildcard '*' and '?' match. 61 | return deepMatchRune(rname, rpattern, simple) 62 | } 63 | 64 | func deepMatchRune(str, pattern []rune, simple bool) bool { 65 | for len(pattern) > 0 { 66 | switch pattern[0] { 67 | default: 68 | if len(str) == 0 || str[0] != pattern[0] { 69 | return false 70 | } 71 | case '?': 72 | if len(str) == 0 && !simple { 73 | return false 74 | } 75 | case '*': 76 | return deepMatchRune(str, pattern[1:], simple) || 77 | (len(str) > 0 && deepMatchRune(str[1:], pattern, simple)) 78 | } 79 | str = str[1:] 80 | pattern = pattern[1:] 81 | } 82 | return len(str) == 0 && len(pattern) == 0 83 | } 84 | -------------------------------------------------------------------------------- /util/wildcard_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Minio Cloud Storage, (C) 2015, 2016 Minio, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package util_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/hellobike/amazonriver/util" 23 | ) 24 | 25 | // TestMatch - Tests validate the logic of wild card matching. 26 | // `Match` supports '*' and '?' wildcards. 27 | // Sample usage: In resource matching for bucket policy validation. 28 | func TestMatch(t *testing.T) { 29 | testCases := []struct { 30 | pattern string 31 | text string 32 | matched bool 33 | }{ 34 | // Test case - 1. 35 | // Test case with pattern "*". Expected to match any text. 36 | { 37 | pattern: "*", 38 | text: "s3:GetObject", 39 | matched: true, 40 | }, 41 | // Test case - 2. 42 | // Test case with empty pattern. This only matches empty string. 43 | { 44 | pattern: "", 45 | text: "s3:GetObject", 46 | matched: false, 47 | }, 48 | // Test case - 3. 49 | // Test case with empty pattern. This only matches empty string. 50 | { 51 | pattern: "", 52 | text: "", 53 | matched: true, 54 | }, 55 | // Test case - 4. 56 | // Test case with single "*" at the end. 57 | { 58 | pattern: "s3:*", 59 | text: "s3:ListMultipartUploadParts", 60 | matched: true, 61 | }, 62 | // Test case - 5. 63 | // Test case with a no "*". In this case the pattern and text should be the same. 64 | { 65 | pattern: "s3:ListBucketMultipartUploads", 66 | text: "s3:ListBucket", 67 | matched: false, 68 | }, 69 | // Test case - 6. 70 | // Test case with a no "*". In this case the pattern and text should be the same. 71 | { 72 | pattern: "s3:ListBucket", 73 | text: "s3:ListBucket", 74 | matched: true, 75 | }, 76 | // Test case - 7. 77 | // Test case with a no "*". In this case the pattern and text should be the same. 78 | { 79 | pattern: "s3:ListBucketMultipartUploads", 80 | text: "s3:ListBucketMultipartUploads", 81 | matched: true, 82 | }, 83 | // Test case - 8. 84 | // Test case with pattern containing key name with a prefix. Should accept the same text without a "*". 85 | { 86 | pattern: "my-bucket/oo*", 87 | text: "my-bucket/oo", 88 | matched: true, 89 | }, 90 | // Test case - 9. 91 | // Test case with "*" at the end of the pattern. 92 | { 93 | pattern: "my-bucket/In*", 94 | text: "my-bucket/India/Karnataka/", 95 | matched: true, 96 | }, 97 | // Test case - 10. 98 | // Test case with prefixes shuffled. 99 | // This should fail. 100 | { 101 | pattern: "my-bucket/In*", 102 | text: "my-bucket/Karnataka/India/", 103 | matched: false, 104 | }, 105 | // Test case - 11. 106 | // Test case with text expanded to the wildcards in the pattern. 107 | { 108 | pattern: "my-bucket/In*/Ka*/Ban", 109 | text: "my-bucket/India/Karnataka/Ban", 110 | matched: true, 111 | }, 112 | // Test case - 12. 113 | // Test case with the keyname part is repeated as prefix several times. 114 | // This is valid. 115 | { 116 | pattern: "my-bucket/In*/Ka*/Ban", 117 | text: "my-bucket/India/Karnataka/Ban/Ban/Ban/Ban/Ban", 118 | matched: true, 119 | }, 120 | // Test case - 13. 121 | // Test case to validate that `*` can be expanded into multiple prefixes. 122 | { 123 | pattern: "my-bucket/In*/Ka*/Ban", 124 | text: "my-bucket/India/Karnataka/Area1/Area2/Area3/Ban", 125 | matched: true, 126 | }, 127 | // Test case - 14. 128 | // Test case to validate that `*` can be expanded into multiple prefixes. 129 | { 130 | pattern: "my-bucket/In*/Ka*/Ban", 131 | text: "my-bucket/India/State1/State2/Karnataka/Area1/Area2/Area3/Ban", 132 | matched: true, 133 | }, 134 | // Test case - 15. 135 | // Test case where the keyname part of the pattern is expanded in the text. 136 | { 137 | pattern: "my-bucket/In*/Ka*/Ban", 138 | text: "my-bucket/India/Karnataka/Bangalore", 139 | matched: false, 140 | }, 141 | // Test case - 16. 142 | // Test case with prefixes and wildcard expanded for all "*". 143 | { 144 | pattern: "my-bucket/In*/Ka*/Ban*", 145 | text: "my-bucket/India/Karnataka/Bangalore", 146 | matched: true, 147 | }, 148 | // Test case - 17. 149 | // Test case with keyname part being a wildcard in the pattern. 150 | { 151 | pattern: "my-bucket/*", 152 | text: "my-bucket/India", 153 | matched: true, 154 | }, 155 | // Test case - 18. 156 | { 157 | pattern: "my-bucket/oo*", 158 | text: "my-bucket/odo", 159 | matched: false, 160 | }, 161 | 162 | // Test case with pattern containing wildcard '?'. 163 | // Test case - 19. 164 | // "my-bucket?/" matches "my-bucket1/", "my-bucket2/", "my-bucket3" etc... 165 | // doesn't match "mybucket/". 166 | { 167 | pattern: "my-bucket?/abc*", 168 | text: "mybucket/abc", 169 | matched: false, 170 | }, 171 | // Test case - 20. 172 | { 173 | pattern: "my-bucket?/abc*", 174 | text: "my-bucket1/abc", 175 | matched: true, 176 | }, 177 | // Test case - 21. 178 | { 179 | pattern: "my-?-bucket/abc*", 180 | text: "my--bucket/abc", 181 | matched: false, 182 | }, 183 | // Test case - 22. 184 | { 185 | pattern: "my-?-bucket/abc*", 186 | text: "my-1-bucket/abc", 187 | matched: true, 188 | }, 189 | // Test case - 23. 190 | { 191 | pattern: "my-?-bucket/abc*", 192 | text: "my-k-bucket/abc", 193 | matched: true, 194 | }, 195 | // Test case - 24. 196 | { 197 | pattern: "my??bucket/abc*", 198 | text: "mybucket/abc", 199 | matched: false, 200 | }, 201 | // Test case - 25. 202 | { 203 | pattern: "my??bucket/abc*", 204 | text: "my4abucket/abc", 205 | matched: true, 206 | }, 207 | // Test case - 26. 208 | { 209 | pattern: "my-bucket?abc*", 210 | text: "my-bucket/abc", 211 | matched: true, 212 | }, 213 | // Test case 27-28. 214 | // '?' matches '/' too. (works with s3). 215 | // This is because the namespace is considered flat. 216 | // "abc?efg" matches both "abcdefg" and "abc/efg". 217 | { 218 | pattern: "my-bucket/abc?efg", 219 | text: "my-bucket/abcdefg", 220 | matched: true, 221 | }, 222 | { 223 | pattern: "my-bucket/abc?efg", 224 | text: "my-bucket/abc/efg", 225 | matched: true, 226 | }, 227 | // Test case - 29. 228 | { 229 | pattern: "my-bucket/abc????", 230 | text: "my-bucket/abc", 231 | matched: false, 232 | }, 233 | // Test case - 30. 234 | { 235 | pattern: "my-bucket/abc????", 236 | text: "my-bucket/abcde", 237 | matched: false, 238 | }, 239 | // Test case - 31. 240 | { 241 | pattern: "my-bucket/abc????", 242 | text: "my-bucket/abcdefg", 243 | matched: true, 244 | }, 245 | // Test case 32-34. 246 | // test case with no '*'. 247 | { 248 | pattern: "my-bucket/abc?", 249 | text: "my-bucket/abc", 250 | matched: false, 251 | }, 252 | { 253 | pattern: "my-bucket/abc?", 254 | text: "my-bucket/abcd", 255 | matched: true, 256 | }, 257 | { 258 | pattern: "my-bucket/abc?", 259 | text: "my-bucket/abcde", 260 | matched: false, 261 | }, 262 | // Test case 35. 263 | { 264 | pattern: "my-bucket/mnop*?", 265 | text: "my-bucket/mnop", 266 | matched: false, 267 | }, 268 | // Test case 36. 269 | { 270 | pattern: "my-bucket/mnop*?", 271 | text: "my-bucket/mnopqrst/mnopqr", 272 | matched: true, 273 | }, 274 | // Test case 37. 275 | { 276 | pattern: "my-bucket/mnop*?", 277 | text: "my-bucket/mnopqrst/mnopqrs", 278 | matched: true, 279 | }, 280 | // Test case 38. 281 | { 282 | pattern: "my-bucket/mnop*?", 283 | text: "my-bucket/mnop", 284 | matched: false, 285 | }, 286 | // Test case 39. 287 | { 288 | pattern: "my-bucket/mnop*?", 289 | text: "my-bucket/mnopq", 290 | matched: true, 291 | }, 292 | // Test case 40. 293 | { 294 | pattern: "my-bucket/mnop*?", 295 | text: "my-bucket/mnopqr", 296 | matched: true, 297 | }, 298 | // Test case 41. 299 | { 300 | pattern: "my-bucket/mnop*?and", 301 | text: "my-bucket/mnopqand", 302 | matched: true, 303 | }, 304 | // Test case 42. 305 | { 306 | pattern: "my-bucket/mnop*?and", 307 | text: "my-bucket/mnopand", 308 | matched: false, 309 | }, 310 | // Test case 43. 311 | { 312 | pattern: "my-bucket/mnop*?and", 313 | text: "my-bucket/mnopqand", 314 | matched: true, 315 | }, 316 | // Test case 44. 317 | { 318 | pattern: "my-bucket/mnop*?", 319 | text: "my-bucket/mn", 320 | matched: false, 321 | }, 322 | // Test case 45. 323 | { 324 | pattern: "my-bucket/mnop*?", 325 | text: "my-bucket/mnopqrst/mnopqrs", 326 | matched: true, 327 | }, 328 | // Test case 46. 329 | { 330 | pattern: "my-bucket/mnop*??", 331 | text: "my-bucket/mnopqrst", 332 | matched: true, 333 | }, 334 | // Test case 47. 335 | { 336 | pattern: "my-bucket/mnop*qrst", 337 | text: "my-bucket/mnopabcdegqrst", 338 | matched: true, 339 | }, 340 | // Test case 48. 341 | { 342 | pattern: "my-bucket/mnop*?and", 343 | text: "my-bucket/mnopqand", 344 | matched: true, 345 | }, 346 | // Test case 49. 347 | { 348 | pattern: "my-bucket/mnop*?and", 349 | text: "my-bucket/mnopand", 350 | matched: false, 351 | }, 352 | // Test case 50. 353 | { 354 | pattern: "my-bucket/mnop*?and?", 355 | text: "my-bucket/mnopqanda", 356 | matched: true, 357 | }, 358 | // Test case 51. 359 | { 360 | pattern: "my-bucket/mnop*?and", 361 | text: "my-bucket/mnopqanda", 362 | matched: false, 363 | }, 364 | // Test case 52. 365 | 366 | { 367 | pattern: "my-?-bucket/abc*", 368 | text: "my-bucket/mnopqanda", 369 | matched: false, 370 | }, 371 | } 372 | // Iterating over the test cases, call the function under test and asert the output. 373 | for i, testCase := range testCases { 374 | actualResult := util.Match(testCase.pattern, testCase.text) 375 | if testCase.matched != actualResult { 376 | t.Errorf("Test %d: Expected the result to be `%v`, but instead found it to be `%v`", i+1, testCase.matched, actualResult) 377 | } 378 | } 379 | } 380 | 381 | // TestMatchSimple - Tests validate the logic of wild card matching. 382 | // `MatchSimple` supports matching for only '*' in the pattern string. 383 | func TestMatchSimple(t *testing.T) { 384 | testCases := []struct { 385 | pattern string 386 | text string 387 | matched bool 388 | }{ 389 | // Test case - 1. 390 | // Test case with pattern "*". Expected to match any text. 391 | { 392 | pattern: "*", 393 | text: "s3:GetObject", 394 | matched: true, 395 | }, 396 | // Test case - 2. 397 | // Test case with empty pattern. This only matches empty string. 398 | { 399 | pattern: "", 400 | text: "s3:GetObject", 401 | matched: false, 402 | }, 403 | // Test case - 3. 404 | // Test case with empty pattern. This only matches empty string. 405 | { 406 | pattern: "", 407 | text: "", 408 | matched: true, 409 | }, 410 | // Test case - 4. 411 | // Test case with single "*" at the end. 412 | { 413 | pattern: "s3:*", 414 | text: "s3:ListMultipartUploadParts", 415 | matched: true, 416 | }, 417 | // Test case - 5. 418 | // Test case with a no "*". In this case the pattern and text should be the same. 419 | { 420 | pattern: "s3:ListBucketMultipartUploads", 421 | text: "s3:ListBucket", 422 | matched: false, 423 | }, 424 | // Test case - 6. 425 | // Test case with a no "*". In this case the pattern and text should be the same. 426 | { 427 | pattern: "s3:ListBucket", 428 | text: "s3:ListBucket", 429 | matched: true, 430 | }, 431 | // Test case - 7. 432 | // Test case with a no "*". In this case the pattern and text should be the same. 433 | { 434 | pattern: "s3:ListBucketMultipartUploads", 435 | text: "s3:ListBucketMultipartUploads", 436 | matched: true, 437 | }, 438 | // Test case - 8. 439 | // Test case with pattern containing key name with a prefix. Should accept the same text without a "*". 440 | { 441 | pattern: "my-bucket/oo*", 442 | text: "my-bucket/oo", 443 | matched: true, 444 | }, 445 | // Test case - 9. 446 | // Test case with "*" at the end of the pattern. 447 | { 448 | pattern: "my-bucket/In*", 449 | text: "my-bucket/India/Karnataka/", 450 | matched: true, 451 | }, 452 | // Test case - 10. 453 | // Test case with prefixes shuffled. 454 | // This should fail. 455 | { 456 | pattern: "my-bucket/In*", 457 | text: "my-bucket/Karnataka/India/", 458 | matched: false, 459 | }, 460 | // Test case - 11. 461 | // Test case with text expanded to the wildcards in the pattern. 462 | { 463 | pattern: "my-bucket/In*/Ka*/Ban", 464 | text: "my-bucket/India/Karnataka/Ban", 465 | matched: true, 466 | }, 467 | // Test case - 12. 468 | // Test case with the keyname part is repeated as prefix several times. 469 | // This is valid. 470 | { 471 | pattern: "my-bucket/In*/Ka*/Ban", 472 | text: "my-bucket/India/Karnataka/Ban/Ban/Ban/Ban/Ban", 473 | matched: true, 474 | }, 475 | // Test case - 13. 476 | // Test case to validate that `*` can be expanded into multiple prefixes. 477 | { 478 | pattern: "my-bucket/In*/Ka*/Ban", 479 | text: "my-bucket/India/Karnataka/Area1/Area2/Area3/Ban", 480 | matched: true, 481 | }, 482 | // Test case - 14. 483 | // Test case to validate that `*` can be expanded into multiple prefixes. 484 | { 485 | pattern: "my-bucket/In*/Ka*/Ban", 486 | text: "my-bucket/India/State1/State2/Karnataka/Area1/Area2/Area3/Ban", 487 | matched: true, 488 | }, 489 | // Test case - 15. 490 | // Test case where the keyname part of the pattern is expanded in the text. 491 | { 492 | pattern: "my-bucket/In*/Ka*/Ban", 493 | text: "my-bucket/India/Karnataka/Bangalore", 494 | matched: false, 495 | }, 496 | // Test case - 16. 497 | // Test case with prefixes and wildcard expanded for all "*". 498 | { 499 | pattern: "my-bucket/In*/Ka*/Ban*", 500 | text: "my-bucket/India/Karnataka/Bangalore", 501 | matched: true, 502 | }, 503 | // Test case - 17. 504 | // Test case with keyname part being a wildcard in the pattern. 505 | { 506 | pattern: "my-bucket/*", 507 | text: "my-bucket/India", 508 | matched: true, 509 | }, 510 | // Test case - 18. 511 | { 512 | pattern: "my-bucket/oo*", 513 | text: "my-bucket/odo", 514 | matched: false, 515 | }, 516 | // Test case - 11. 517 | { 518 | pattern: "my-bucket/oo?*", 519 | text: "my-bucket/oo???", 520 | matched: true, 521 | }, 522 | // Test case - 12: 523 | { 524 | pattern: "my-bucket/oo??*", 525 | text: "my-bucket/odo", 526 | matched: false, 527 | }, 528 | // Test case - 13: 529 | { 530 | pattern: "?h?*", 531 | text: "?h?hello", 532 | matched: true, 533 | }, 534 | } 535 | // Iterating over the test cases, call the function under test and asert the output. 536 | for i, testCase := range testCases { 537 | actualResult := util.MatchSimple(testCase.pattern, testCase.text) 538 | if testCase.matched != actualResult { 539 | t.Errorf("Test %d: Expected the result to be `%v`, but instead found it to be `%v`", i+1, testCase.matched, actualResult) 540 | } 541 | } 542 | } 543 | --------------------------------------------------------------------------------