├── .gitignore ├── LICENSE ├── README.md ├── build.sh ├── go-zookeeper-LICENSE ├── go.mod ├── go.sum ├── main.go ├── output └── output.go ├── wercker.yml └── zk └── zk.go /.gitignore: -------------------------------------------------------------------------------- 1 | #### zkcli #### 2 | 3 | zkcli 4 | 5 | #### joe made this: https://goel.io/joe 6 | 7 | #####=== Go ===##### 8 | 9 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 10 | *.o 11 | *.a 12 | *.so 13 | 14 | # Folders 15 | _obj 16 | _test 17 | 18 | # Architecture specific extensions/prefixes 19 | *.[568vq] 20 | [568vq].out 21 | 22 | *.cgo1.go 23 | *.cgo2.c 24 | _cgo_defun.c 25 | _cgo_gotypes.go 26 | _cgo_export.* 27 | 28 | _testmain.go 29 | 30 | *.exe 31 | *.test 32 | *.prof 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2014 Outbrain Ltd. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zkcli 2 | 3 | Simple, lightweight, dependable CLI for ZooKeeper 4 | 5 | **zkcli** is a non-interactive command line client for [ZooKeeper](http://zookeeper.apache.org/). It provides with: 6 | 7 | * Basic CRUD-like operations: `create`, `set`, `delete`, `exists`, `get`, `ls` (aka `children`). 8 | * Extended operations: `lsr` (ls recursive), `creater` (create recursively) 9 | * Well formatted and controlled output: supporting either `txt` or `json` format 10 | * Single, no-dependencies binary file, based on a native Go ZooKeeper library 11 | by [github.com/samuel/go-zookeeper](http://github.com/samuel/go-zookeeper) ([LICENSE](https://github.com/go-zkcli/zkcli/blob/master/go-zookeeper-LICENSE)) 12 | 13 | ### Download & Install 14 | 15 | There are [pre built binaries](https://github.com/go-zkcli/zkcli/releases) for download. 16 | You can find `RPM` and `deb` packages, as well as pre-compiled, dependency free `zkcli` executable binary. 17 | In fact, the only file installed by the pre-built `RPM` and `deb` packages is said executable binary file. 18 | 19 | Otherwise the source code is freely available; you will need `git` installed as well as `go`, and you're on your own. 20 | 21 | ### Usage: 22 | 23 | 24 | ``` 25 | NAME: 26 | zkcli - zkcli is a non-interactive command line client for ZooKeeper 27 | 28 | USAGE: 29 | zkcli [global options] command [command options] [arguments...] 30 | 31 | VERSION: 32 | 1.1.0 33 | 34 | AUTHOR(S): 35 | 36 | COMMANDS: 37 | exists zkcli excists 38 | get zkcli get 39 | set zkcli set [data] 40 | create zkcli create [command options] 41 | list, ls zkcli list [command options] [path] 42 | delete, del, rm, remove 43 | help, h Shows a list of commands or help for one command 44 | 45 | GLOBAL OPTIONS: 46 | --servers "localhost:2181" ZK Server list in format: srv1[:port1][,srv2[:port2]...] [$ZKC_SERVERS] 47 | --format "txt" Output format [$ZKC_FORMAT] 48 | --help, -h show help 49 | --version, -v print the version 50 | ``` 51 | 52 | 53 | ### Examples: 54 | 55 | 56 | ``` 57 | 58 | $ zkcli --servers srv-1,srv-2,srv-3 -c create /demo_only some_value 59 | 60 | # Servers can also be define using environment varaible 61 | $ export ZKC_SERVERS=srv-1,srv-2,srv-3 62 | 63 | # Default port is 2181. The above is equivalent to: 64 | $ zkcli create /demo_only some_value 65 | 66 | $ zkcli --format=txt get /demo_only 67 | some_value 68 | 69 | # Same as above, JSON format output: 70 | $ zkcli --format=json get /demo_only 71 | "some_value" 72 | 73 | # exists exits with exit code 0 when path exists, 1 when path does not exist 74 | $ zkcli exists /demo_only 75 | true 76 | 77 | $ zkcli set /demo_only another_value 78 | 79 | $ zkcli --format=json get /demo_only 80 | "another_value" 81 | 82 | $ zkcli delete /demo_only 83 | 84 | $ zkcli get /demo_only 85 | 2014-09-15 04:07:16 FATAL zk: node does not exist 86 | 87 | $ zkcli create /demo_only "path placeholder" 88 | $ zkcli create /demo_only/key1 "value1" 89 | $ zkcli create /demo_only/key2 "value2" 90 | $ zkcli create /demo_only/key3 "value3" 91 | 92 | $ zkcli ls /demo_only 93 | key3 94 | key2 95 | key1 96 | 97 | # Same as above, JSON format output: 98 | $ zkcli --format=json ls /demo_only 99 | ["key3","key2","key1"] 100 | 101 | $ zkcli delete /demo_only 102 | 2014-09-15 08:26:31 FATAL zk: node has children 103 | 104 | $ zkcli delete /demo_only/key1 105 | $ zkcli delete /demo_only/key2 106 | $ zkcli delete /demo_only/key3 107 | $ zkcli delete /demo_only 108 | 109 | # /demo_only path now does not exist. 110 | 111 | # Create recursively a path: 112 | $ zkcli create -f "/demo_only/child/key1" "val1" 113 | $ zkcli create -f "/demo_only/child/key2" "val2" 114 | 115 | $ zkcli get "/demo_only/child/key1" 116 | val1 117 | 118 | # This path was auto generated due to recursive create: 119 | $ zkcli get "/demo_only" 120 | zkcli auto-generated 121 | 122 | # ls recursively a path and all sub children: 123 | $ zkcli ls -r "/demo_only" 124 | child 125 | child/key1 126 | child/key2 127 | ``` 128 | 129 | 130 | The tool was built in order to allow with shell scripting seamless 131 | integration with ZooKeeper. There is another, official command line 132 | tool for ZooKeeper that the orginal author found inadequate in terms of 133 | output format and output control, as well as large footprint. **zkcli** 134 | overcomes those limitations and provides with quick, well formatted 135 | output as well as enhanced functionality. 136 | 137 | ### License 138 | 139 | Release under the [Apache 2.0 license](https://github.com/go-zkcli/zkcli/blob/master/LICENSE) 140 | 141 | Authored by [Shlomi Noach](https://github.com/shlomi-noach) at [Outbrain](https://github.com/outbrain) 142 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Simple packaging of zkcli 4 | # 5 | # Requires fpm: https://github.com/jordansissel/fpm 6 | # 7 | 8 | release_version="1.0.5" 9 | release_dir=/tmp/zkcli 10 | rm -rf $release_dir/* 11 | mkdir -p $release_dir 12 | 13 | cd $(dirname $0) 14 | for f in $(find . -name "*.go"); do go fmt $f; done 15 | 16 | GOPATH=/usr/share/golang:$(pwd) 17 | go build -o $release_dir/zkcli ./main.go 18 | 19 | if [[ $? -ne 0 ]] ; then 20 | exit 1 21 | fi 22 | 23 | cd $release_dir 24 | # rpm packaging 25 | fpm -v "${release_version}" -f -s dir -t rpm -n zkcli -C $release_dir --prefix=/usr/bin . 26 | fpm -v "${release_version}" -f -s dir -t deb -n zkcli -C $release_dir --prefix=/usr/bin . 27 | 28 | echo "---" 29 | echo "Done. Find releases in $release_dir" 30 | -------------------------------------------------------------------------------- /go-zookeeper-LICENSE: -------------------------------------------------------------------------------- 1 | This license is copied from https://github.com/samuel/go-zookeeper/blob/master/LICENSE 2 | ====================================================================================== 3 | 4 | Copyright (c) 2013, Samuel Stauffer 5 | All rights reserved. 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | * Neither the name of the author nor the 14 | names of its contributors may be used to endorse or promote products 15 | derived from this software without specific prior written permission. 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/go-zkcli/zkcli 2 | 3 | go 1.20 4 | 5 | require ( 6 | github.com/outbrain/golib v0.0.0-20200503083229-2531e5dbcc71 7 | github.com/samuel/go-zookeeper v0.0.0-20201211165307-7117e9ea2414 8 | github.com/urfave/cli v1.22.13 9 | ) 10 | 11 | require ( 12 | github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect 13 | github.com/russross/blackfriday/v2 v2.1.0 // indirect 14 | ) 15 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= 2 | github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= 3 | github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 4 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 6 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 7 | github.com/outbrain/golib v0.0.0-20200503083229-2531e5dbcc71 h1:5FSwz/q8DhpkUsq8cqRN7gRVWWnfXfjeOeB8Bhj5ARc= 8 | github.com/outbrain/golib v0.0.0-20200503083229-2531e5dbcc71/go.mod h1:JDhu//MMvcPVPH889Xr7DyamEbTLumgDBALGUyXrz1g= 9 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 10 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 11 | github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= 12 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 13 | github.com/samuel/go-zookeeper v0.0.0-20201211165307-7117e9ea2414 h1:AJNDS0kP60X8wwWFvbLPwDuojxubj9pbfK7pjHw0vKg= 14 | github.com/samuel/go-zookeeper v0.0.0-20201211165307-7117e9ea2414/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= 15 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 16 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 17 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 18 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 19 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 20 | github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= 21 | github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 22 | github.com/urfave/cli v1.22.13 h1:wsLILXG8qCJNse/qAgLNf23737Cx05GflHg/PJGe1Ok= 23 | github.com/urfave/cli v1.22.13/go.mod h1:VufqObjsMTF2BBwKawpx9R8eAneNEWhoO0yx8Vd+FkE= 24 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 25 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 26 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 27 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 28 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 29 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2014 Outbrain 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 main 18 | 19 | import ( 20 | "io/ioutil" 21 | "os" 22 | "strings" 23 | 24 | "github.com/go-zkcli/zkcli/output" 25 | "github.com/go-zkcli/zkcli/zk" 26 | "github.com/outbrain/golib/log" 27 | "github.com/urfave/cli" 28 | ) 29 | 30 | var ( 31 | version = "1.1.0" 32 | ) 33 | 34 | func main() { 35 | 36 | var format string 37 | app := cli.NewApp() 38 | app.Version = version 39 | app.Name = "zkcli" 40 | app.Usage = "zkcli is a non-interactive command line client for ZooKeeper" 41 | app.Flags = []cli.Flag{ 42 | cli.StringFlag{ 43 | Name: "servers", 44 | Value: "localhost:2181", 45 | Usage: "ZK Server list in format: srv1[:port1][,srv2[:port2]...]", 46 | EnvVar: "ZKC_SERVERS", 47 | }, 48 | cli.StringFlag{ 49 | Name: "format", 50 | Value: "txt", 51 | Usage: "Output format", 52 | EnvVar: "ZKC_FORMAT", 53 | }, 54 | } 55 | app.Before = func(c *cli.Context) error { 56 | if c.GlobalString("servers") == "" { 57 | log.Fatal("Expected comma delimited list of servers via --servers|$ZKC_SERVERS") 58 | } 59 | serversArray := strings.Split(c.GlobalString("servers"), ",") 60 | if len(serversArray) == 0 { 61 | log.Fatal("Expected comma delimited list of servers via --servers") 62 | } 63 | zk.SetServers(serversArray) 64 | 65 | switch c.GlobalString("format") { 66 | case "json", "txt": 67 | format = c.GlobalString("format") 68 | default: 69 | log.Fatalf("Format %s is not in list: json,text", c.GlobalString("format")) 70 | 71 | } 72 | return nil 73 | } 74 | app.Commands = []cli.Command{ 75 | { 76 | Name: "exists", 77 | Usage: "zkcli excists ", 78 | Description: "Does znode at exist. Exit with error code 0 if present code 1 if not.", 79 | Action: func(c *cli.Context) { 80 | if exists, err := zk.Exists(c.Args().First()); err == nil && exists { 81 | output.PrintString([]byte("true"), format) 82 | } else { 83 | log.Fatale(err) 84 | } 85 | }, 86 | }, 87 | { 88 | Name: "get", 89 | Usage: "zkcli get ", 90 | Description: "Get value on znode at .", 91 | Action: func(c *cli.Context) { 92 | if result, err := zk.Get(c.Args().First()); err == nil { 93 | output.PrintString(result, format) 94 | } else { 95 | log.Fatale(err) 96 | } 97 | 98 | }, 99 | }, 100 | { 101 | Name: "set", 102 | Usage: "zkcli set [data]", 103 | Description: "Set value on znode at . If data not present on cli it's read from stdin", 104 | Action: func(c *cli.Context) { 105 | var info []byte 106 | if len(c.Args()) > 1 { 107 | info = []byte(c.Args().Get(1)) 108 | } else { 109 | var err error 110 | info, err = ioutil.ReadAll(os.Stdin) 111 | if err != nil { 112 | log.Fatale(err) 113 | } 114 | } 115 | if result, err := zk.Set(c.Args().Get(0), info); err == nil { 116 | log.Infof("Set %+v", result) 117 | } else { 118 | log.Fatale(err) 119 | } 120 | 121 | }, 122 | }, 123 | { 124 | Name: "create", 125 | Usage: "zkcli create [command options] ", 126 | Description: "Create data in znode at path", 127 | Flags: []cli.Flag{ 128 | cli.BoolFlag{ 129 | Name: "force", 130 | Usage: "Force create", 131 | }, 132 | }, 133 | Action: func(c *cli.Context) { 134 | if len(c.Args()) < 2 { 135 | log.Fatal("Expected data argument") 136 | } 137 | if result, err := zk.Create(c.Args().First(), []byte(c.Args().Get(1)), c.Bool("force")); err == nil { 138 | log.Infof("Created %+v", result) 139 | } else { 140 | log.Fatale(err) 141 | } 142 | }, 143 | }, 144 | { 145 | Name: "list", 146 | Aliases: []string{"ls"}, 147 | Usage: "zkcli list [command options] [path]", 148 | Description: "list znode at [path]", 149 | Flags: []cli.Flag{ 150 | cli.BoolFlag{ 151 | Name: "recusive, r", 152 | Usage: "Recusive list", 153 | }, 154 | }, 155 | Action: func(c *cli.Context) { 156 | x := zk.Children 157 | if c.Bool("recusive") { 158 | x = zk.ChildrenRecursive 159 | } 160 | if result, err := x(c.Args().First()); err == nil { 161 | output.PrintStringArray(result, format) 162 | } else { 163 | log.Fatale(err) 164 | } 165 | 166 | }, 167 | }, 168 | { 169 | Name: "delete", 170 | Aliases: []string{"del", "rm", "remove"}, 171 | Usage: "zkcli delete [command options] [path]", 172 | Description: "delete znode at [path]", 173 | Flags: []cli.Flag{ 174 | cli.BoolFlag{ 175 | Name: "force", 176 | Usage: "Force delete", 177 | }, 178 | }, 179 | Action: func(c *cli.Context) { 180 | if err := zk.Delete(c.Args().First()); err != nil { 181 | log.Fatale(err) 182 | } 183 | }, 184 | }, 185 | { 186 | Name: "deleteall", 187 | Aliases: []string{"rmr"}, 188 | Usage: "zkcli deleteall [command options] [path]", 189 | Description: "delete znode at [path] with all its descendants", 190 | Flags: []cli.Flag{ 191 | cli.BoolFlag{ 192 | Name: "force", 193 | Usage: "Force delete", 194 | }, 195 | }, 196 | Action: func(c *cli.Context) { 197 | if err := zk.DeleteAll(c.Args().First()); err != nil { 198 | log.Fatale(err) 199 | } 200 | }, 201 | }, 202 | } 203 | app.Run(os.Args) 204 | } 205 | -------------------------------------------------------------------------------- /output/output.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2014 Outbrain 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 | // output provides with controlled printing functions 18 | package output 19 | 20 | import ( 21 | "encoding/json" 22 | "fmt" 23 | "strings" 24 | ) 25 | 26 | // PrintString prints a single string to standard output, in either plaintext format or JSON format 27 | func PrintString(data []byte, formatType string) { 28 | 29 | switch formatType { 30 | case "txt": 31 | fmt.Println(fmt.Sprintf("%s", data)) 32 | case "json": 33 | s, _ := json.Marshal(string(data)) 34 | fmt.Println(string(s)) 35 | } 36 | } 37 | 38 | // PrintString prints a string array to standard output, in either plaintext format (one string per row) or JSON format 39 | func PrintStringArray(stringArray []string, formatType string) { 40 | 41 | switch formatType { 42 | case "txt": 43 | fmt.Println(strings.Join(stringArray, "\n")) 44 | case "json": 45 | s, _ := json.Marshal(stringArray) 46 | fmt.Println(string(s)) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /wercker.yml: -------------------------------------------------------------------------------- 1 | box: tcnksm/gox 2 | build: 3 | steps: 4 | - setup-go-workspace 5 | - script: 6 | name: go get 7 | code: | 8 | go get -t ./... 9 | # - tcnksm/goveralls: 10 | # token: $COVERALLS_TOKEN 11 | - tcnksm/gox 12 | - tcnksm/zip: 13 | input: ${WERCKER_OUTPUT_DIR}/pkg 14 | output: ${WERCKER_OUTPUT_DIR}/dist 15 | 16 | -------------------------------------------------------------------------------- /zk/zk.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2014 Outbrain 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 | // zk provides with higher level commands over the lower level zookeeper connector 18 | package zk 19 | 20 | import ( 21 | "github.com/outbrain/golib/log" 22 | "github.com/samuel/go-zookeeper/zk" 23 | gopath "path" 24 | "sort" 25 | "time" 26 | ) 27 | 28 | var servers []string 29 | 30 | // We assume complete access to all 31 | var flags int32 = int32(0) 32 | var acl []zk.ACL = zk.WorldACL(zk.PermAll) 33 | 34 | // SetServers sets the list of servers for the zookeeper client to connect to. 35 | // Each element in the array should be in either of following forms: 36 | // - "servername" 37 | // - "servername:port" 38 | func SetServers(serversArray []string) { 39 | servers = serversArray 40 | } 41 | 42 | // connect 43 | func connect() (*zk.Conn, error) { 44 | conn, _, err := zk.Connect(servers, time.Second) 45 | return conn, err 46 | } 47 | 48 | // Exists returns true when the given path exists 49 | func Exists(path string) (bool, error) { 50 | connection, err := connect() 51 | if err != nil { 52 | return false, err 53 | } 54 | defer connection.Close() 55 | 56 | exists, _, err := connection.Exists(path) 57 | return exists, err 58 | } 59 | 60 | // Get returns value associated with given path, or error if path does not exist 61 | func Get(path string) ([]byte, error) { 62 | connection, err := connect() 63 | if err != nil { 64 | return []byte{}, err 65 | } 66 | defer connection.Close() 67 | 68 | data, _, err := connection.Get(path) 69 | return data, err 70 | } 71 | 72 | // Children returns sub-paths of given path, optionally empty array, or error if path does not exist 73 | func Children(path string) ([]string, error) { 74 | connection, err := connect() 75 | if err != nil { 76 | return []string{}, err 77 | } 78 | defer connection.Close() 79 | 80 | children, _, err := connection.Children(path) 81 | return children, err 82 | } 83 | 84 | // childrenRecursiveInternal: internal implementation of recursive-children query. 85 | func childrenRecursiveInternal(connection *zk.Conn, path string, incrementalPath string) ([]string, error) { 86 | children, _, err := connection.Children(path) 87 | if err != nil { 88 | return children, err 89 | } 90 | sort.Sort(sort.StringSlice(children)) 91 | recursiveChildren := []string{} 92 | for _, child := range children { 93 | incrementalChild := gopath.Join(incrementalPath, child) 94 | recursiveChildren = append(recursiveChildren, incrementalChild) 95 | log.Debugf("incremental child: %+v", incrementalChild) 96 | incrementalChildren, err := childrenRecursiveInternal(connection, gopath.Join(path, child), incrementalChild) 97 | if err != nil { 98 | return children, err 99 | } 100 | recursiveChildren = append(recursiveChildren, incrementalChildren...) 101 | } 102 | return recursiveChildren, err 103 | } 104 | 105 | // ChildrenRecursive returns list of all descendants of given path (optionally empty), or error if the path 106 | // does not exist. 107 | // Every element in result list is a relative subpath for the given path. 108 | func ChildrenRecursive(path string) ([]string, error) { 109 | connection, err := connect() 110 | if err != nil { 111 | return []string{}, err 112 | } 113 | defer connection.Close() 114 | 115 | result, err := childrenRecursiveInternal(connection, path, "") 116 | return result, err 117 | } 118 | 119 | // createInternal: create a new path 120 | func createInternal(connection *zk.Conn, path string, data []byte, force bool) (string, error) { 121 | if path == "/" { 122 | return "/", nil 123 | } 124 | log.Debugf("creating: %s", path) 125 | attempts := 0 126 | for { 127 | attempts += 1 128 | returnValue, err := connection.Create(path, data, flags, acl) 129 | log.Debugf("create status for %s: %s, %+v", path, returnValue, err) 130 | if err != nil && force && attempts < 2 { 131 | returnValue, err = createInternal(connection, gopath.Dir(path), []byte("zookeepercli auto-generated"), force) 132 | } else { 133 | return returnValue, err 134 | } 135 | } 136 | return "", nil 137 | } 138 | 139 | // Create will create a new path, or exit with error should the path exist. 140 | // The "force" param controls the behavior when path's parent directory does not exist. 141 | // When "force" is false, the function returns with error/ When "force" is true, it recursively 142 | // attempts to create required parent directories. 143 | func Create(path string, data []byte, force bool) (string, error) { 144 | connection, err := connect() 145 | if err != nil { 146 | return "", err 147 | } 148 | defer connection.Close() 149 | 150 | return createInternal(connection, path, data, force) 151 | } 152 | 153 | // Set updates a value for a given path, or returns with error if the path does not exist 154 | func Set(path string, data []byte) (*zk.Stat, error) { 155 | connection, err := connect() 156 | if err != nil { 157 | return nil, err 158 | } 159 | defer connection.Close() 160 | 161 | return connection.Set(path, data, -1) 162 | } 163 | 164 | // Delete removes a path entry. It exits with error if the path does not exist, or has subdirectories. 165 | func Delete(path string) error { 166 | connection, err := connect() 167 | if err != nil { 168 | return err 169 | } 170 | defer connection.Close() 171 | 172 | return connection.Delete(path, -1) 173 | } 174 | 175 | func DeleteAll(path string) error { 176 | connection, err := connect() 177 | if err != nil { 178 | return err 179 | } 180 | defer connection.Close() 181 | 182 | all, err := ChildrenRecursive(path) 183 | if err != nil { 184 | return err 185 | } 186 | 187 | for i := len(all) - 1; i >= 0; i-- { 188 | e := all[i] 189 | err := connection.Delete(path+"/"+e, -1) 190 | if err != nil { 191 | return err 192 | } 193 | } 194 | 195 | return connection.Delete(path, -1) 196 | } 197 | --------------------------------------------------------------------------------