├── .github ├── FUNDING.yml ├── build ├── run-tests.sh └── workflows │ ├── pull_request.yml │ ├── push.yml │ └── release.yml ├── .gitignore ├── LICENSE ├── PARSING.md ├── README.md ├── cmd_lex.go ├── cmd_parse.go ├── cmd_run.go ├── cmd_version.go ├── evaluator └── evaluator.go ├── examples ├── README.md ├── overseer │ ├── README.md │ ├── deploy.recipe │ └── lib │ │ └── systemd │ │ └── system │ │ ├── overseer-enqueue.service │ │ ├── overseer-enqueue.timer │ │ ├── overseer-worker.service │ │ └── purppura-bridge.service ├── puppet-summary │ ├── README.md │ ├── deploy.recipe │ └── lib │ │ └── systemd │ │ └── system │ │ └── puppet-summary.service ├── simple │ ├── deploy.recipe │ └── example.recipe.template └── sudo │ └── deploy.recipe ├── go.mod ├── go.sum ├── lexer ├── lexer.go └── lexer_test.go ├── main.go ├── parser ├── parser.go └── parser_test.go ├── statement └── statement.go ├── token ├── token.go └── token_test.go └── util ├── util.go ├── util_test.go ├── util_unix.go └── util_windows.go /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | github: skx 3 | custom: https://steve.fi/donate/ 4 | -------------------------------------------------------------------------------- /.github/build: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # The basename of our binary 4 | BASE="deployr" 5 | 6 | # I don't even .. 7 | go env -w GOFLAGS="-buildvcs=false" 8 | 9 | D=$(pwd) 10 | 11 | # 12 | # We build on multiple platforms/archs 13 | # 14 | BUILD_PLATFORMS="linux darwin freebsd" 15 | BUILD_ARCHS="amd64 386" 16 | 17 | # For each platform 18 | for OS in ${BUILD_PLATFORMS[@]}; do 19 | 20 | # For each arch 21 | for ARCH in ${BUILD_ARCHS[@]}; do 22 | 23 | cd ${D} 24 | 25 | # Setup a suffix for the binary 26 | SUFFIX="${OS}" 27 | 28 | # i386 is better than 386 29 | if [ "$ARCH" = "386" ]; then 30 | SUFFIX="${SUFFIX}-i386" 31 | else 32 | SUFFIX="${SUFFIX}-${ARCH}" 33 | fi 34 | 35 | # Windows binaries should end in .EXE 36 | if [ "$OS" = "windows" ]; then 37 | SUFFIX="${SUFFIX}.exe" 38 | fi 39 | 40 | echo "Building for ${OS} [${ARCH}] -> ${BASE}-${SUFFIX}" 41 | 42 | # Run the build 43 | export GOARCH=${ARCH} 44 | export GOOS=${OS} 45 | export CGO_ENABLED=0 46 | 47 | # Build the main-binary 48 | go build -ldflags "-X main.version=$(git describe --tags 2>/dev/null || echo 'master')" -o "${BASE}-${SUFFIX}" 49 | done 50 | done 51 | -------------------------------------------------------------------------------- /.github/run-tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | 4 | # I don't even .. 5 | go env -w GOFLAGS="-buildvcs=false" 6 | 7 | # Install the lint-tool, and the shadow-tool 8 | go install golang.org/x/lint/golint@latest 9 | go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest 10 | go install honnef.co/go/tools/cmd/staticcheck@latest 11 | 12 | 13 | # Run the static-check tool. 14 | t=$(mktemp) 15 | staticcheck -checks all ./... > $t 16 | if [ -s $t ]; then 17 | echo "Found errors via 'staticcheck'" 18 | cat $t 19 | rm $t 20 | exit 1 21 | fi 22 | rm $t 23 | 24 | # At this point failures cause aborts 25 | set -e 26 | 27 | # Run the linter 28 | echo "Launching linter .." 29 | golint -set_exit_status ./... 30 | echo "Completed linter .." 31 | 32 | # Run the shadow-checker 33 | echo "Launching shadowed-variable check .." 34 | go vet -vettool=$(which shadow) ./... 35 | echo "Completed shadowed-variable check .." 36 | 37 | # Run golang tests 38 | go test ./... 39 | -------------------------------------------------------------------------------- /.github/workflows/pull_request.yml: -------------------------------------------------------------------------------- 1 | on: pull_request 2 | name: Pull Request 3 | jobs: 4 | test: 5 | name: Test 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@master 9 | - name: Test 10 | uses: skx/github-action-tester@master 11 | -------------------------------------------------------------------------------- /.github/workflows/push.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - master 5 | name: Push Event 6 | jobs: 7 | test: 8 | name: Test 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@master 12 | - name: Test 13 | uses: skx/github-action-tester@master 14 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | on: release 2 | name: Handle Release 3 | jobs: 4 | upload: 5 | name: Upload 6 | runs-on: ubuntu-latest 7 | steps: 8 | - name: Checkout the repository 9 | uses: actions/checkout@master 10 | - name: Generate the artifacts 11 | uses: skx/github-action-build@master 12 | - name: Upload the artifacts 13 | uses: skx/github-action-publish-binaries@master 14 | env: 15 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 16 | with: 17 | args: deployr-* 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | deployr 2 | deployr-* 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /PARSING.md: -------------------------------------------------------------------------------- 1 | # Parsing Overview 2 | 3 | When a file is loaded it is split up into a series of tokens via the lexer: 4 | 5 | * The token-types are basically "built-ins", "identifiers", or "strings". 6 | * These are defined in [token/token.go](token/token.go) 7 | 8 | The lexer itself may be found in the file [lexer/lexer.go](lexer/lexer.go). 9 | 10 | To execute the recipe we _could_ interpret each of the tokens the lexer 11 | produced in-turn, because we have no loops, conditionals, or other 12 | control-flow statements our program will always be executed from start to 13 | finish. 14 | 15 | However if we execute our tokens directly we will not be able to catch 16 | syntax-errors until we reach them, and this would be unfortunate. 17 | 18 | The following valid program: 19 | 20 | #!/usr/bin/env deployr 21 | # A comment 22 | Set greeting "Hello, world!" 23 | 24 | Becomes this series of (valid) tokens: 25 | 26 | * `{Set Set}` 27 | * `{IDENT greeting}` 28 | * `{STRING Hello, world!}` 29 | 30 | Processing a stream of tokens like this, taking different action depending upon 31 | the type of the token, and fetching successive arguments appropriately, would 32 | work just fine for valid programs. 33 | 34 | The following broken program shows what could go wrong though: 35 | 36 | Run "some command" 37 | Set greeting 38 | Run "another" 39 | 40 | Our token-list would be: 41 | 42 | * `{Run Run}` 43 | * `{STRING "some command"}` 44 | * `{Set Set}` 45 | * `{IDENT greeting}` 46 | * `{Run Run}` 47 | * `{STRING "another"}` 48 | 49 | Here we're missing a value to the Set-command, and we would only learn this 50 | at the point we came to evaluate the `Set` command: 51 | 52 | * Find `Run`. 53 | * Get the string-argument which is expected. 54 | * Execute the command. 55 | * Find `Set`. 56 | * Fetch the next token. 57 | * Which we would assume is an ident (i.e. variable-name). 58 | * Fetch the next token. 59 | * Which we assume would be a string (i.e. the value we store in the variable). 60 | 61 | Oops! The second-fetch would find `Run` instead. The program would have to 62 | abort, mid-execution. 63 | 64 | > It is __horrid__ to abort a recipe half-way through, because we might set the remote host into a broken state. 65 | 66 | 67 | ## Error Detection 68 | 69 | To catch errors in our input, before we execute it, we must consume our 70 | stream of tokens entirely, then parse them for sanity and correctness into a 71 | series of statements, which we'll execute in the future. 72 | 73 | The parsing process will build up a structure which we'll actually execute, 74 | and that will ensure that we don't execute programs that are invalid 75 | because the parsing process will catch that for us before we come to 76 | run them. 77 | 78 | Our parser is located beneath [parser/parser.go](parser/parser.go) and 79 | builds up an array of statements to execute. Since we don't allow 80 | control-flow, looping, or other complex facilities we only have to parse 81 | statements minimally - validating the type of arguments to the various 82 | primitives. 83 | 84 | (i.e. We don't need to define an AST, we can continue to use the token-types 85 | that the lexer gave us. I see no value in wrapping them any further, given 86 | that we only deal with strings, built-ins, and idents.) 87 | 88 | A statement will consist of just an action (read token) and a set of 89 | optional arguments: 90 | 91 | * The `Run`-command takes a single-string argument. 92 | * As does `IfChanged`. 93 | * The `Set`-command takes a pair of arguments. 94 | * An identifier and a string. 95 | * No command takes more than two arguments. 96 | 97 | 98 | ## Actual Execution 99 | 100 | Finally once we've parsed our lexed-tokens into a series of statements 101 | with the parser we can execute them. 102 | 103 | For completeness the evaluator is located in [evaluator/evaluator.go](evaluator/evaluator.go). 104 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Go Report Card](https://goreportcard.com/badge/github.com/skx/deployr)](https://goreportcard.com/report/github.com/skx/deployr) 2 | [![license](https://img.shields.io/github/license/skx/deployr.svg)](https://github.com/skx/deployr/blob/master/LICENSE) 3 | [![Release](https://img.shields.io/github/release/skx/deployr.svg)](https://github.com/skx/deployr/releases/latest) 4 | 5 | 6 | 7 | Table of Contents 8 | ================= 9 | 10 | * [deployr](#deployr) 11 | * [Installation & Dependencies](#installation--dependencies) 12 | * [Source Installation go <= 1.11](#source-installation-go---111) 13 | * [Source installation go >= 1.12](#source-installation-go---112) 14 | * [Overview](#overview) 15 | * [Authentication](#authentication) 16 | * [Examples](#examples) 17 | * [File Globs](#file-globs) 18 | * [Variables](#variables) 19 | * [Predefined Variables](#predefined-variables) 20 | * [Template Expansion](#template-expansion) 21 | * [Missing Primitives?](#missing-primitives) 22 | * [Alternatives](#alternatives) 23 | * [Github Setup](#github-setup) 24 | 25 | 26 | # deployr 27 | 28 | `deployr` is a simple utility which is designed to allow you to easily automate simple application-deployment via SSH. 29 | 30 | The core idea behind `deployr` is that installing (simple) software upon remote hosts frequently consists of a small number of steps: 31 | 32 | * Uploading a small number of files, for example: 33 | * A binary application. 34 | * A configuration-file. 35 | * A systemd unit-file 36 | * etc. 37 | * Running a small number of commands, some conditionally, for example: 38 | * Enable the systemd unit-file. 39 | * Start the service. 40 | 41 | This is particularly true for golang-based applications which frequently consist of an single binary, a single configuration file, and an init-file to ensure the service can be controlled. 42 | 43 | If you want to keep your deployment recipes automatable, and reproducible, then scripting them with a tool like this is ideal. (Though you might prefer something more popular & featureful such as `ansible`, `fabric`, `salt`, etc.) 44 | 45 | "Competing" systems tend to offer more facilities, such as the ability to add Unix users, setup MySQL database, add cron-entries, etc. Although it isn't impossible to do those things in `deployr` it is not as natural as other solutions. (For example you can add a cron-entry by uploading a file to `/etc/cron.d/my-service`, or you can add a user via `Run adduser bob 2>/dev/null`.) 46 | 47 | One obvious facility that most similar systems, such as ansible, offer is the ability to perform looping operations, and comparisons. We don't offer that and I'm not sure we ever will - even if we did add the ability to add cronjobs, etc. 48 | 49 | In short think of this as an alternative to using a bash-script, which invokes scp/rsync/ssh. It is not going to compete with ansible, or similar. (Though it is reasonably close in spirit to `fabric` albeit with a smaller set of primitives.) 50 | 51 | 52 | 53 | ## Installation & Dependencies 54 | 55 | There are two ways to install this project from source, which depend on the version of the [go](https://golang.org/) version you're using. 56 | 57 | 58 | ### Source Installation go <= 1.11 59 | 60 | If you're using `go` before 1.11 then the following command should fetch/update `deployr`, and install it upon your system: 61 | 62 | $ go get -u github.com/skx/deployr 63 | 64 | ### Source installation go >= 1.12 65 | 66 | If you're using a more recent version of `go` (which is _highly_ recommended), you need to clone to a directory which is not present upon your `GOPATH`: 67 | 68 | git clone https://github.com/skx/deployr 69 | cd deployr 70 | go install 71 | 72 | 73 | If you don't have a golang environment setup you should be able to download a binary for GNU/Linux from [our release page](https://github.com/skx/deployr/releases). 74 | 75 | 76 | 77 | ## Overview 78 | 79 | `deployr` has various sub-commands, the most useful is the `run` command which 80 | allows you to execute a recipe-file: 81 | 82 | $ deployr run [options] recipe1 recipe2 .. recipeN 83 | 84 | Each specified recipe is parsed and the primitives inside them are then executed line by line. The following primitives/commands are available: 85 | 86 | * `CopyFile local/path remote/path` 87 | * Copy the specified local file to the specified path on the remote system. 88 | * If the local & remote files were identical, such that no change was made, then this fact will be noted. 89 | * See later note on globs. 90 | * `CopyTemplate local/path remote/path` 91 | * Copy the specified local file to the specified path on the remote system, expanding variables prior to running the copy. 92 | * If the local & remote files were identical, such that no change was made, then this fact will be noted. 93 | * See later note on globs. 94 | * `DeployTo [user@]hostname[:port]` 95 | * Specify the details of the host to connect to, this is useful if a particular recipe should only be applied against a single host. 96 | * If you don't specify a target within your recipe itself you can instead pass it upon the command-line via the `-target` flag. 97 | * `IfChanged "Command"` 98 | * The `CopyFile` and `CopyTemplate` primitives record whether they made a change to the remote system. 99 | * The `IfChanged` primitive will execute the specified command if the previous copy-operation resulted in the remote system being changed. 100 | * `Run "Command"` 101 | * Run the given command (unconditionally) upon the remote-host. 102 | * `Set name "value"` 103 | * Set the variable "name" to have the value "value". 104 | * Once set a variable can be used in the recipe, or as part of template-expansion. 105 | * `Sudo` may be added as a prefix to `Run` and `IfChanged`. 106 | * If present this will ensure the specified command runs as `root`. 107 | * The sudo example found beneath [examples/sudo/](examples/sudo/) demonstrates usage. 108 | 109 | 110 | 111 | ### Authentication 112 | 113 | Public-Key authentication is only supported mechanism for connecting to a remote host, or remote hosts. There is zero support for authentication via passwords. 114 | 115 | By default `~/.ssh/id_rsa` will be used as the key to connect with, but if you prefer you can specify a different private-key with the `-identity` flag to the run sub-command: 116 | 117 | $ deployr run -identity ~/.ssh/host 118 | 119 | In addition to using a key specified via the command-line deployr also supports the use of `ssh-agent`. Simply set the environmental-variable `SSH_AUTH_SOCK` to the path of your agent's socket. 120 | On Windows deployr supports `pageant`, which is a Windows-specific implementation of SSH Agent. If pageant is running, deployr will detect it and use it for authentication. 121 | 122 | 123 | 124 | ### Examples 125 | 126 | There are several examples included beneath [examples/](examples/), the shortest one [examples/simple/](examples/simple/) is a particularly good recipe to examine to get a feel for the system: 127 | 128 | $ cd ./examples/simple/ 129 | $ deployr run -target [user@]host.example.com[:port] ./deployr.recipe 130 | 131 | For more verbose output the `-verbose` flag may be added: 132 | 133 | $ cd ./examples/simple/ 134 | $ deployr run -target [user@]host.example.com[:port] -verbose ./deployr.recipe 135 | 136 | Some other flags are also available, consult "`deployr help run`" for details. 137 | 138 | 139 | ### File Globs 140 | 141 | Both the `CopyFile` and `CopyTemplate` primitives allow the use of file-globs, 142 | which allows you to write a line like this: 143 | 144 | CopyFile lib/systemd/system/* /lib/systemd/system/ 145 | 146 | Assuming you have the following input this will copy all the files, as you 147 | would expect: 148 | 149 | ├── deploy.recipe 150 | └── lib 151 | └── systemd 152 | └── system 153 | ├── overseer-enqueue.service 154 | ├── overseer-enqueue.timer 155 | ├── overseer-worker.service 156 | └── purppura-bridge.service 157 | 158 | **NOTE** That this wildcard support is _not_ the same as a recursive copy, 159 | that is not supported. 160 | 161 | The `IfChanged` primitive will regard a previous copy operation as having 162 | resulted in a change if any single file changes during the run of a copy 163 | operation that involves a glob. 164 | 165 | 166 | ## Variables 167 | 168 | It is often useful to allow values to be stored in variables, for example if you're used to pulling a file from a remote host you might make the version of that release a variable. 169 | 170 | Variables are defined with the `Set` primitive, which takes two arguments: 171 | 172 | * The name of the variable. 173 | * The value to set for that variable. 174 | * Values will be set as strings, in fact our mini-language only understands strings. 175 | 176 | In the following example we declare the variable called "RELEASE" to have the value "1.2", and then use it in a command-execution: 177 | 178 | Set RELEASE "1.2" 179 | Run "wget -O /usr/local/bin/app-${RELEASE} \ 180 | https://example.com/dist/app-${RELEASE}" 181 | 182 | It is possible to override the value of a particular variable via a command-line argument, for example: 183 | 184 | $ deployr run --set "ENVIRONMENT=PRODUCTION" ... 185 | 186 | If you do this any attempt to `Set` the variable inside the recipe itself will be silently ignored. (i.e. A variable which is set on the command-line will become essentially read-only.) This is useful if you have a recipe where the only real difference is the set of configuration files, and the destination host. For example you could write all your copies like so: 187 | 188 | # 189 | # Lack of recursive copy is a pain here. 190 | # See: 191 | # https://github.com/skx/deployr/issues/6 192 | # 193 | CopyFile files/${ENVIRONMENT}/etc/apache2.conf /etc/apache2/conf 194 | CopyFile files/${ENVIRONMENT}/etc/redis.conf /etc/redis/redis.conf 195 | .. 196 | 197 | Then have a tree of files: 198 | 199 | ├── files 200 | ├── development 201 | │ ├── apache2.conf 202 | │ └── redis.conf 203 | └── production 204 | ├── apache2.conf 205 | └── redis.conf 206 | 207 | Another case where this come in handy is when dealing the secrets. Pass your secrets via command-line arguments instead of setting them in the recipe so you don't commit them by mistake, for example: 208 | 209 | $ deployr run --set "API_KEY=foobar" ... 210 | 211 | Then use the `API_KEY`: 212 | 213 | Run "curl api.example.com/releases/latest -H 'Authorization: Bearer ${API_KEY}'" 214 | 215 | In a CI environnement, use command-line arguments to retrieve environnement variables available in the CI. 216 | 217 | $ deployr run --set "RELEASE=$CI_COMMIT_TAG" ... 218 | 219 | ### Predefined Variables 220 | 221 | The following variables are defined by default: 222 | 223 | * `host` 224 | * The host being deployed to. 225 | * `now` 226 | * An instance of the golang [time](https://golang.org/pkg/time/) object. 227 | * `port` 228 | * The port used to connect to the remote host (22 by default). 229 | * `user` 230 | * The username we login to the remote host as (root by default). 231 | 232 | 233 | 234 | ## Template Expansion 235 | 236 | In addition to copying files literally from the local system to the remote 237 | host it is also possible perform some limited template-expansion. 238 | 239 | To copy a file literally you'd use the `CopyFile` primitive which copies the 240 | file with no regards to the contents (handling binary content): 241 | 242 | CopyFile local.txt /tmp/remote.txt 243 | 244 | To copy a file with template-expansion you should use the `CopyTemplate` primitive instead: 245 | 246 | CopyTemplate local.txt /tmp/remote.txt 247 | 248 | The file being copied will then be processed with the `text/template` library 249 | which means you can access values like so: 250 | 251 | # 252 | # This is a configuration file blah.conf 253 | # We can expand variables like so: 254 | # 255 | # Deployed version {{get "RELEASE"}} on Host:{{get "host"}}:{{get "port"}} 256 | # at {{now.UTC.Day}} {{now.UTC.Month}} {{now.UTC.Year}} 257 | # 258 | 259 | In short you write `{{get "variable-name-here"}}` and the value of the variable 260 | will be output inline. 261 | 262 | Any variable defined with `Set` (or via a command-line argument) will be available to you, as well as the 263 | [predefined variables](#predefined-variables) noted above. 264 | 265 | 266 | 267 | ## Missing Primitives? 268 | 269 | If there are primitives you think would be useful to add then please do 270 | [file a bug](http://github.com/skx/deployr/issues). 271 | 272 | 273 | ### Alternatives 274 | 275 | There are many alternatives to this simple approach. The most obvious two 276 | would be: 277 | 278 | * [ansible](https://www.ansible.com/) 279 | * Uses YAML to let you run commands on multiple remote hosts via SSH. 280 | * Very featureful, but also a bit hard to be readable due to the YAML use. 281 | * [fabric](http://www.fabfile.org/) 282 | * Another Python-based project, which defines some simple primitive functions such as `run` and `put` to run commands, and upload files respectively. 283 | 284 | As a very simple alternative I put together [marionette](https://github.com/skx/marionette/) which allows running commands, and setting file-content, but this works on the __local__ system only - no SSH involved. 285 | 286 | For large-scale deployments you'll probably want to consider Puppet, Chef, or something more established and powerful. Still this system has its place. 287 | 288 | 289 | 290 | ## Github Setup 291 | 292 | This repository is configured to run tests upon every commit, and when 293 | pull-requests are created/updated. The testing is carried out via 294 | [.github/run-tests.sh](.github/run-tests.sh) which is used by the 295 | [github-action-tester](https://github.com/skx/github-action-tester) action. 296 | 297 | Releases are automated in a similar fashion via [.github/build](.github/build), 298 | and the [github-action-publish-binaries](https://github.com/skx/github-action-publish-binaries) action. 299 | 300 | Steve 301 | -- 302 | -------------------------------------------------------------------------------- /cmd_lex.go: -------------------------------------------------------------------------------- 1 | // 2 | // Invoke our lexer on the specified input-file(s) and dump the output. 3 | // 4 | 5 | package main 6 | 7 | import ( 8 | "context" 9 | "flag" 10 | "fmt" 11 | "io/ioutil" 12 | 13 | "github.com/google/subcommands" 14 | "github.com/skx/deployr/lexer" 15 | "github.com/skx/deployr/util" 16 | ) 17 | 18 | // 19 | // lexCmd is the structure for this sub-command. 20 | // 21 | type lexCmd struct { 22 | } 23 | 24 | // 25 | // Glue 26 | // 27 | func (*lexCmd) Name() string { return "lex" } 28 | func (*lexCmd) Synopsis() string { return "Show our lexer output." } 29 | func (*lexCmd) Usage() string { 30 | return `lex : 31 | Show the output of running our lexer on the given file(s). 32 | ` 33 | } 34 | 35 | // 36 | // Flag setup 37 | // 38 | func (p *lexCmd) SetFlags(f *flag.FlagSet) { 39 | } 40 | 41 | // 42 | // Lex the given recipe 43 | // 44 | func (p *lexCmd) Lex(file string) { 45 | 46 | // 47 | // Read the file contents. 48 | // 49 | dat, err := ioutil.ReadFile(file) 50 | if err != nil { 51 | fmt.Printf("Error reading file %s - %s\n", file, err.Error()) 52 | return 53 | } 54 | 55 | // 56 | // Create a lexer object with those contents. 57 | // 58 | l := lexer.New(string(dat)) 59 | 60 | // 61 | // Dump the tokens. 62 | // 63 | l.Dump() 64 | } 65 | 66 | // 67 | // Entry-point. 68 | // 69 | func (p *lexCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus { 70 | 71 | // 72 | // For each file we've been passed. 73 | // 74 | for _, file := range f.Args() { 75 | p.Lex(file) 76 | } 77 | 78 | // 79 | // Fallback. 80 | // 81 | if len(f.Args()) < 1 { 82 | if util.FileExists("deploy.recipe") { 83 | p.Lex("deploy.recipe") 84 | } 85 | } 86 | 87 | return subcommands.ExitSuccess 88 | } 89 | -------------------------------------------------------------------------------- /cmd_parse.go: -------------------------------------------------------------------------------- 1 | // 2 | // Show the result of invoking our parser on the given input-file(s). 3 | // 4 | 5 | package main 6 | 7 | import ( 8 | "context" 9 | "flag" 10 | "fmt" 11 | "io/ioutil" 12 | 13 | "github.com/google/subcommands" 14 | "github.com/skx/deployr/lexer" 15 | "github.com/skx/deployr/parser" 16 | "github.com/skx/deployr/util" 17 | ) 18 | 19 | // 20 | // parseCmd is the structure for this sub-command. 21 | // 22 | type parseCmd struct { 23 | } 24 | 25 | // 26 | // Glue 27 | // 28 | func (*parseCmd) Name() string { return "parse" } 29 | func (*parseCmd) Synopsis() string { return "Show our parser output." } 30 | func (*parseCmd) Usage() string { 31 | return `parser : 32 | Show the output of running our parser on the given file(s). 33 | ` 34 | } 35 | 36 | // 37 | // Flag setup 38 | // 39 | func (p *parseCmd) SetFlags(f *flag.FlagSet) { 40 | } 41 | 42 | // 43 | // Parse the given file. 44 | // 45 | func (p *parseCmd) Parse(file string) { 46 | // 47 | // Read the contents of the file. 48 | // 49 | dat, err := ioutil.ReadFile(file) 50 | if err != nil { 51 | fmt.Printf("Error reading file %s - %s\n", file, err.Error()) 52 | return 53 | } 54 | 55 | // 56 | // Create a lexer object with those contents. 57 | // 58 | l := lexer.New(string(dat)) 59 | 60 | // 61 | // Create a parser, using the lexer. 62 | // 63 | pa := parser.New(l) 64 | 65 | // 66 | // Parse the program, looking for errors. 67 | // 68 | statements, err := pa.Parse() 69 | if err != nil { 70 | fmt.Printf("Error parsing program: %s\n", err.Error()) 71 | return 72 | } 73 | 74 | // 75 | // No errors? Great. 76 | // 77 | // We can dump the parsed statements. 78 | // 79 | for _, statement := range statements { 80 | fmt.Printf("%v\n", statement) 81 | } 82 | } 83 | 84 | // 85 | // Entry-point. 86 | // 87 | func (p *parseCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus { 88 | 89 | // 90 | // For each file we were given. 91 | // 92 | for _, file := range f.Args() { 93 | p.Parse(file) 94 | } 95 | 96 | // 97 | // Fallback. 98 | // 99 | if len(f.Args()) < 1 { 100 | if util.FileExists("deploy.recipe") { 101 | p.Parse("deploy.recipe") 102 | } 103 | } 104 | 105 | return subcommands.ExitSuccess 106 | } 107 | -------------------------------------------------------------------------------- /cmd_run.go: -------------------------------------------------------------------------------- 1 | // 2 | // Execute the recipe from the given file(s). 3 | // 4 | 5 | package main 6 | 7 | import ( 8 | "context" 9 | "flag" 10 | "fmt" 11 | "io/ioutil" 12 | "regexp" 13 | "strings" 14 | 15 | "github.com/google/subcommands" 16 | "github.com/skx/deployr/evaluator" 17 | "github.com/skx/deployr/lexer" 18 | "github.com/skx/deployr/parser" 19 | "github.com/skx/deployr/util" 20 | ) 21 | 22 | // arrayFlags is the type of a flag that can be duplicated 23 | type arrayFlags []string 24 | 25 | // String returns a human-readable version of the flags-set 26 | func (i *arrayFlags) String() string { 27 | return strings.Join(*i, ",") 28 | } 29 | 30 | // Set updates the value of this flag, by appending to the list. 31 | func (i *arrayFlags) Set(value string) error { 32 | *i = append(*i, value) 33 | return nil 34 | } 35 | 36 | // 37 | // runCmd holds the state for this sub-command. 38 | // 39 | type runCmd struct { 40 | // nop is true if we should pretend to run commands, not actually 41 | // run them for real. 42 | nop bool 43 | 44 | // identity holds the SSH identity file to use. 45 | identity string 46 | 47 | // target allows the target against which the recipe runs to be 48 | // set on the command-line. 49 | target string 50 | 51 | // vars stores any variables which are specified on the command-line. 52 | vars arrayFlags 53 | 54 | // verbose is true if we should be extra-verbose when running. 55 | verbose bool 56 | } 57 | 58 | // 59 | // Glue 60 | // 61 | func (*runCmd) Name() string { return "run" } 62 | func (*runCmd) Synopsis() string { return "Run the specified recipe(s)." } 63 | func (*runCmd) Usage() string { 64 | return `run : 65 | Load and execute the recipe in the specified file(s). 66 | ` 67 | } 68 | 69 | // 70 | // Flag setup 71 | // 72 | func (r *runCmd) SetFlags(f *flag.FlagSet) { 73 | f.BoolVar(&r.nop, "nop", false, "No operation - just pretend to run.") 74 | f.BoolVar(&r.verbose, "verbose", false, "Run verbosely.") 75 | f.StringVar(&r.identity, "identity", "", "The identity file to use for key-based authentication.") 76 | f.StringVar(&r.target, "target", "", "The target host to execute the recipe against.") 77 | f.Var(&r.vars, "set", "Set the value of a particular variable. (May be repeated.)") 78 | } 79 | 80 | // 81 | // Run the given recipe 82 | // 83 | func (r *runCmd) Run(file string) { 84 | 85 | // 86 | // Read the contents of the file. 87 | // 88 | dat, err := ioutil.ReadFile(file) 89 | if err != nil { 90 | fmt.Printf("Error reading file %s - %s\n", file, err.Error()) 91 | return 92 | } 93 | 94 | // 95 | // Create a lexer object with those contents. 96 | // 97 | l := lexer.New(string(dat)) 98 | 99 | // 100 | // Create a parser, using the lexer. 101 | // 102 | p := parser.New(l) 103 | 104 | // 105 | // Parse the program, looking for errors. 106 | // 107 | statements, err := p.Parse() 108 | if err != nil { 109 | fmt.Printf("Error parsing program: %s\n", err.Error()) 110 | return 111 | } 112 | 113 | // 114 | // No errors? Great. 115 | // 116 | // Create the evaluator - which will run the statements. 117 | // 118 | e := evaluator.New(statements) 119 | 120 | // 121 | // Set the target, if we've been given one. 122 | // 123 | if r.target != "" { 124 | err = e.ConnectTo(r.target) 125 | if err != nil { 126 | fmt.Printf("Failed to connect to target: %s\n", err.Error()) 127 | return 128 | 129 | } 130 | } 131 | 132 | // 133 | // Set our flags verbosity-level 134 | // 135 | e.SetVerbose(r.verbose) 136 | if r.nop { 137 | e.SetVerbose(true) 138 | e.SetNOP(true) 139 | } 140 | 141 | // 142 | // Save the identity-flag - the default is ~/.ssh/id_rsa 143 | // 144 | e.SetIdentity(r.identity) 145 | 146 | // 147 | // Are there any variables set on the command-line? 148 | // 149 | re := regexp.MustCompile("^([^=]+)=(.*)$") 150 | for _, set := range r.vars { 151 | 152 | matches := re.FindStringSubmatch(set) 153 | if len(matches) == 3 { 154 | e.SetVariable(matches[1], matches[2]) 155 | } 156 | } 157 | 158 | // 159 | // Now run the program. Hurrah! 160 | // 161 | err = e.Run() 162 | 163 | // 164 | // Errors? Boo! 165 | // 166 | if err != nil { 167 | fmt.Printf("Error running program\n%s\n", err.Error()) 168 | } 169 | } 170 | 171 | // 172 | // Entry-point. 173 | // 174 | func (r *runCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus { 175 | 176 | // 177 | // For each file we were given. 178 | // 179 | for _, file := range f.Args() { 180 | r.Run(file) 181 | } 182 | 183 | // 184 | // Fallback. 185 | // 186 | if len(f.Args()) < 1 { 187 | if util.FileExists("deploy.recipe") { 188 | r.Run("deploy.recipe") 189 | } 190 | } 191 | 192 | return subcommands.ExitSuccess 193 | } 194 | -------------------------------------------------------------------------------- /cmd_version.go: -------------------------------------------------------------------------------- 1 | // 2 | // Show our version. 3 | // 4 | 5 | package main 6 | 7 | import ( 8 | "context" 9 | "flag" 10 | "fmt" 11 | "runtime" 12 | 13 | "github.com/google/subcommands" 14 | ) 15 | 16 | var ( 17 | version = "unreleased" 18 | ) 19 | 20 | type versionCmd struct { 21 | verbose bool 22 | } 23 | 24 | // 25 | // Glue 26 | // 27 | func (*versionCmd) Name() string { return "version" } 28 | func (*versionCmd) Synopsis() string { return "Show our version." } 29 | func (*versionCmd) Usage() string { 30 | return `version : 31 | Report upon our version, and exit. 32 | ` 33 | } 34 | 35 | // 36 | // Flag setup 37 | // 38 | func (p *versionCmd) SetFlags(f *flag.FlagSet) { 39 | f.BoolVar(&p.verbose, "verbose", false, "Show go version the binary was generated with.") 40 | } 41 | 42 | // 43 | // Show the version - using the "out"-writer. 44 | // 45 | func showVersion(verbose bool) { 46 | fmt.Printf("%s\n", version) 47 | if verbose { 48 | fmt.Printf("Built with %s\n", runtime.Version()) 49 | } 50 | } 51 | 52 | // 53 | // Entry-point. 54 | // 55 | func (p *versionCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus { 56 | 57 | showVersion(p.verbose) 58 | return subcommands.ExitSuccess 59 | } 60 | -------------------------------------------------------------------------------- /evaluator/evaluator.go: -------------------------------------------------------------------------------- 1 | // Package evaluator is the core of our run-time. 2 | // 3 | // Given a parsed series of statements we execute each of them in turn. 4 | package evaluator 5 | 6 | import ( 7 | "bytes" 8 | "fmt" 9 | "io/ioutil" 10 | "os" 11 | "path" 12 | "path/filepath" 13 | "regexp" 14 | "strings" 15 | "syscall" 16 | "text/template" 17 | "time" 18 | 19 | "github.com/sfreiberg/simplessh" 20 | "github.com/skx/deployr/statement" 21 | "github.com/skx/deployr/util" 22 | "golang.org/x/term" 23 | ) 24 | 25 | // Evaluator holds our internal state. 26 | type Evaluator struct { 27 | 28 | // Program is our parsed program, which is an array of statements. 29 | Program []statement.Statement 30 | 31 | // Identity holds the SSH key to authenticate with 32 | Identity string 33 | 34 | // Verbose is true if the execution should be verbose. 35 | Verbose bool 36 | 37 | // NOP records if we should pretend to work, or work for real. 38 | NOP bool 39 | 40 | // Variables is a map which holds the names/values of all defined 41 | // variables. (Being declared/set/updated via the 'Set' primitive.) 42 | Variables map[string]string 43 | 44 | // ROVariables is a map which is similar to Variables, but only 45 | // contains values set on the command-line. Variables are looked 46 | // for here first. 47 | ROVariables map[string]string 48 | 49 | // Connection holds the SSH-connection to the remote-host. 50 | Connection *simplessh.Client 51 | 52 | // Changed records whether the last copy operaton resulted in a change. 53 | Changed bool 54 | } 55 | 56 | // New creates our evaluator object, which will execute the supplied 57 | // statements. 58 | func New(program []statement.Statement) *Evaluator { 59 | p := &Evaluator{Program: program} 60 | 61 | // Setup the maps for storing variable names & values. 62 | p.Variables = make(map[string]string) 63 | p.ROVariables = make(map[string]string) 64 | 65 | return p 66 | } 67 | 68 | // SetIdentity specifies the SSH identity file to authenticate with 69 | func (e *Evaluator) SetIdentity(file string) { 70 | if file != "" { 71 | e.Identity = file 72 | } else { 73 | e.Identity = os.Getenv("HOME") + "/.ssh/id_rsa" 74 | } 75 | } 76 | 77 | // SetNOP specifies whether we should run for real, or not at all. 78 | func (e *Evaluator) SetNOP(verb bool) { 79 | e.NOP = verb 80 | } 81 | 82 | // SetVerbose specifies whether we should run verbosely or not. 83 | func (e *Evaluator) SetVerbose(verb bool) { 84 | e.Verbose = verb 85 | } 86 | 87 | // ConnectTo opens the SSH connection to the specified target-host. 88 | // 89 | // If a connection is already open then it is maintained, and not replaced. 90 | // This allows the command-line to override the destination which might be 91 | // baked into a configuration-recipe. 92 | func (e *Evaluator) ConnectTo(target string) error { 93 | var err error 94 | 95 | if e.Connection != nil { 96 | fmt.Printf("Ignoring request to change target mid-run!\n") 97 | return nil 98 | } 99 | 100 | // 101 | // Default username + port 102 | // 103 | user := "root" 104 | port := "22" 105 | host := "" 106 | 107 | // 108 | // Setup the user if we have it 109 | // 110 | if strings.Contains(target, "@") { 111 | fields := strings.Split(target, "@") 112 | user = fields[0] 113 | host = fields[1] 114 | } else { 115 | host = target 116 | } 117 | 118 | // 119 | // Setup the port if we have it 120 | // 121 | if strings.Contains(host, ":") { 122 | fields := strings.Split(host, ":") 123 | host = fields[0] 124 | port = fields[1] 125 | } 126 | 127 | // 128 | // Store our connection-details in the variable-list 129 | // 130 | e.Variables["host"] = host 131 | e.Variables["port"] = port 132 | e.Variables["user"] = user 133 | 134 | // 135 | // Setup our destination with the host/port 136 | // 137 | destination := fmt.Sprintf("%s:%s", host, port) 138 | 139 | // 140 | // Finally connect. 141 | // 142 | if util.HasSSHAgent() { 143 | e.Connection, err = simplessh.ConnectWithAgent(destination, user) 144 | } else { 145 | e.Connection, err = simplessh.ConnectWithKeyFile(destination, user, e.Identity) 146 | } 147 | if err != nil { 148 | return err 149 | } 150 | 151 | return nil 152 | } 153 | 154 | // Run evaluates our program, continuing until all statements have been 155 | // executed - unless an error was encountered. 156 | func (e *Evaluator) Run() error { 157 | 158 | // 159 | // Do any of our program-statements require the use of Sudo? 160 | // 161 | sudo := false 162 | for _, statement := range e.Program { 163 | if statement.Sudo { 164 | sudo = true 165 | } 166 | } 167 | 168 | // 169 | // OK we need a sudo-password. So prompt for it. 170 | // 171 | sudoPassword := "" 172 | if sudo { 173 | fmt.Printf("Please enter your password for sudo: ") 174 | 175 | text, err := term.ReadPassword(int(syscall.Stdin)) 176 | if err != nil { 177 | return err 178 | } 179 | fmt.Printf("\n") 180 | sudoPassword = string(text) 181 | } 182 | 183 | // 184 | // For each statement .. 185 | // 186 | for _, statement := range e.Program { 187 | 188 | // 189 | // The action to be taken will depend upon the type 190 | // of the token. 191 | // 192 | switch statement.Token.Type { 193 | 194 | case "CopyTemplate": 195 | 196 | // 197 | // Ensure we're connected. 198 | // 199 | if e.Connection == nil { 200 | return fmt.Errorf("tried to run a command, but not connected to a target") 201 | } 202 | 203 | // 204 | // Get the arguments and run the copy. 205 | // 206 | src := e.expandString(statement.Arguments[0].Literal) 207 | dst := e.expandString(statement.Arguments[1].Literal) 208 | if e.Verbose { 209 | fmt.Printf("CopyTemplate(\"%s\", \"%s\")\n", src, dst) 210 | } 211 | 212 | if e.NOP { 213 | break 214 | } 215 | e.Changed = e.copyFiles(src, dst, true) 216 | 217 | case "CopyFile": 218 | 219 | // 220 | // Ensure we're connected. 221 | // 222 | if e.Connection == nil { 223 | return fmt.Errorf("tried to run a command, but not connected to a target") 224 | } 225 | 226 | // 227 | // Get the arguments and run the copy. 228 | // 229 | src := e.expandString(statement.Arguments[0].Literal) 230 | dst := e.expandString(statement.Arguments[1].Literal) 231 | 232 | if e.Verbose { 233 | fmt.Printf("CopyFile(\"%s\", \"%s\")\n", src, dst) 234 | } 235 | 236 | if e.NOP { 237 | break 238 | } 239 | 240 | e.Changed = e.copyFiles(src, dst, false) 241 | 242 | case "DeployTo": 243 | 244 | // 245 | // Get the arguments, and connect. 246 | // 247 | arg := e.expandString(statement.Arguments[0].Literal) 248 | 249 | if e.Verbose { 250 | fmt.Printf("DeployTo(\"%s\")\n", arg) 251 | } 252 | 253 | err := e.ConnectTo(arg) 254 | if err != nil { 255 | return err 256 | } 257 | 258 | case "IfChanged": 259 | 260 | // 261 | // If the previous copy didn't change then we can 262 | // just skip this command. 263 | // 264 | if !e.Changed { 265 | break 266 | } 267 | 268 | // 269 | // Ensure we're connected. 270 | // 271 | if e.Connection == nil { 272 | return fmt.Errorf("tried to run a command, but not connected to a target") 273 | } 274 | 275 | // 276 | // Get the command to execute. 277 | // 278 | cmd := e.expandString(statement.Arguments[0].Literal) 279 | 280 | if e.Verbose { 281 | if statement.Sudo { 282 | fmt.Printf("Sudo ") 283 | } 284 | fmt.Printf("IfChanged(\"%s\")\n", cmd) 285 | } 286 | 287 | if e.NOP { 288 | break 289 | } 290 | 291 | // 292 | // Holder for results of execution. 293 | // 294 | var result []byte 295 | var err error 296 | 297 | // 298 | // Run via sudo or normally. 299 | // 300 | if statement.Sudo { 301 | result, err = e.Connection.ExecSudo(cmd, sudoPassword) 302 | } else { 303 | result, err = e.Connection.Exec(cmd) 304 | } 305 | if err != nil { 306 | return (fmt.Errorf("failed to run command '%s': %s\n%s", cmd, err.Error(), result)) 307 | } 308 | 309 | // 310 | // Show the output 311 | // 312 | fmt.Printf("%s", result) 313 | 314 | case "Run": 315 | 316 | // 317 | // Ensure we're connected. 318 | // 319 | if e.Connection == nil { 320 | return fmt.Errorf("tried to run a command, but not connected to a target") 321 | } 322 | 323 | cmd := e.expandString(statement.Arguments[0].Literal) 324 | 325 | if e.Verbose { 326 | if statement.Sudo { 327 | fmt.Printf("Sudo ") 328 | } 329 | 330 | fmt.Printf("Run(\"%s\")\n", cmd) 331 | } 332 | 333 | if e.NOP { 334 | break 335 | } 336 | 337 | // 338 | // Holder for results of execution. 339 | // 340 | var result []byte 341 | var err error 342 | 343 | // 344 | // Run via sudo or normally. 345 | // 346 | if statement.Sudo { 347 | result, err = e.Connection.ExecSudo(cmd, sudoPassword) 348 | } else { 349 | result, err = e.Connection.Exec(cmd) 350 | } 351 | if err != nil { 352 | return (fmt.Errorf("failed to run command '%s': %s\n%s", cmd, err.Error(), result)) 353 | } 354 | 355 | // 356 | // Show the output 357 | // 358 | fmt.Printf("%s", result) 359 | 360 | case "Set": 361 | 362 | // 363 | // Get the arguments and set the variable. 364 | // 365 | key := statement.Arguments[0].Literal 366 | val := e.expandString(statement.Arguments[1].Literal) 367 | 368 | if e.Verbose { 369 | fmt.Printf("Set(\"%s\", \"%s\")\n", key, val) 370 | } 371 | e.Variables[key] = val 372 | 373 | case "Sudo": 374 | 375 | // 376 | // This is an error? 377 | // 378 | default: 379 | return fmt.Errorf("unhandled statement - %v", statement.Token) 380 | } 381 | } 382 | 383 | // 384 | // Disconnect from the remote host, if we connected. 385 | // 386 | if e.Connection != nil { 387 | if e.Verbose { 388 | fmt.Printf("Disconnecting from remote-host\n") 389 | } 390 | e.Connection.Close() 391 | } 392 | 393 | // 394 | // All done. 395 | // 396 | return nil 397 | } 398 | 399 | // copyFiles is designed to copy a file/template from the local 400 | // system to the remote host. 401 | // 402 | // It might be called with a glob, or with a single file. 403 | func (e *Evaluator) copyFiles(pattern string, destination string, expand bool) bool { 404 | 405 | // 406 | // If our input pattern ends with a "/" we just add "*" 407 | // 408 | if strings.HasSuffix(pattern, "/") { 409 | pattern += "*" 410 | } 411 | 412 | // 413 | // Expand the pattern we received. 414 | // 415 | files, err := filepath.Glob(pattern) 416 | if err != nil { 417 | return false 418 | } 419 | 420 | // 421 | // Did we fail to find file(s)? 422 | // 423 | if len(files) < 1 { 424 | fmt.Printf("Failed to find file(s) matching %s\n", pattern) 425 | return false 426 | } 427 | 428 | // 429 | // Did we receive more than one file? 430 | // 431 | if len(files) == 1 && files[0] == pattern { 432 | 433 | // 434 | // OK just copying a single file. 435 | // 436 | return (e.copyFile(pattern, destination, expand)) 437 | } 438 | 439 | // 440 | // OK we now have to copy each entry. Since we're copying 441 | // from a pattern our destination will need to be updated ensure 442 | // we have a trailing "/" for that. 443 | // 444 | if !strings.HasSuffix(destination, "/") { 445 | destination += "/" 446 | } 447 | 448 | // 449 | // We record a change if we updated ANY of the files. 450 | // 451 | changed := false 452 | 453 | // 454 | // Now process each file. 455 | // 456 | for _, file := range files { 457 | 458 | fi, err := os.Stat(file) 459 | if err != nil { 460 | fmt.Printf("Failed to stat(%s) %s\n", file, err.Error()) 461 | continue 462 | } 463 | switch mode := fi.Mode(); { 464 | case mode.IsDir(): 465 | if e.Verbose { 466 | fmt.Printf("Skipping directory %s\n", file) 467 | } 468 | case mode.IsRegular(): 469 | name := path.Base(file) 470 | c := e.copyFile(file, destination+name, expand) 471 | if c { 472 | changed = c 473 | } 474 | } 475 | } 476 | 477 | // 478 | return changed 479 | } 480 | 481 | // copyFile is designed to copy the local file to the remote system. 482 | // 483 | // It is a little complex because it does two extra things: 484 | // 485 | // * It only copies files if the local/remote differ. 486 | // 487 | // * It optionally expands template-variables. 488 | func (e *Evaluator) copyFile(local string, remote string, expand bool) bool { 489 | 490 | // 491 | // Did we result in a change? 492 | // 493 | changed := false 494 | 495 | if e.Verbose { 496 | if expand { 497 | fmt.Printf("CopyTemplate(\"%s\",\"%s\")\n", local, remote) 498 | } else { 499 | fmt.Printf("CopyFile(\"%s\",\"%s\")\n", local, remote) 500 | } 501 | 502 | } 503 | // 504 | // If we're expanding templates then do that first of all. 505 | // 506 | // * Load the source file. 507 | // 508 | // * Perform the template-expansion of variables. 509 | // 510 | // * Write that expanded result to a temporary file. 511 | // 512 | // * Swap out the local-file name with the temporary-file. 513 | // 514 | if expand { 515 | 516 | // 517 | // Read the input file. 518 | // 519 | data, err := ioutil.ReadFile(local) 520 | 521 | // 522 | // If we can't read the input-file that's a fatal error. 523 | // 524 | if err != nil { 525 | fmt.Printf("Failed to read local file to expand template-variables %s\n", err.Error()) 526 | os.Exit(11) 527 | } 528 | 529 | // 530 | // Define a helper-function that users can call to get 531 | // the variables they've set. 532 | // 533 | funcMap := template.FuncMap{ 534 | "get": func(s string) string { 535 | if len(e.ROVariables[s]) > 0 { 536 | return (e.ROVariables[s]) 537 | } 538 | return (e.Variables[s]) 539 | }, 540 | "now": time.Now, 541 | } 542 | 543 | // 544 | // Load the file as a template. 545 | // 546 | tmpl := template.Must(template.New("tmpl").Funcs(funcMap).Parse(string(data))) 547 | 548 | // 549 | // Now expand the template into a temporary-buffer. 550 | // 551 | buf := &bytes.Buffer{} 552 | tmpl.Execute(buf, e.Variables) 553 | 554 | // 555 | // Finally write that to a temporary file, and ensure 556 | // that is the source of the copy. 557 | // 558 | tmpfile, _ := ioutil.TempFile("", "tmpl") 559 | local = tmpfile.Name() 560 | ioutil.WriteFile(local, buf.Bytes(), 0600) 561 | } 562 | 563 | // 564 | // Copying a file to the remote host is 565 | // very simple - BUT we want to know if the 566 | // remote file changed, so we can make a 567 | // conditional result sometimes. 568 | // 569 | // So we need to hash the local file, and 570 | // the remote (if it exists) and compare 571 | // the two. 572 | // 573 | // 574 | // NOTE: We do this after we've expanded any variables. 575 | // 576 | var hashLocal string 577 | var err error 578 | hashLocal, err = util.HashFile(local) 579 | if err != nil { 580 | fmt.Printf("Failed to hash local file %s\n", err.Error()) 581 | 582 | // 583 | // If we're trying to copy a file that doesn't exist that 584 | // is a fatal error. 585 | // 586 | os.Exit(11) 587 | } 588 | 589 | // 590 | // Now fetch the file from the remote host, if we can. 591 | // 592 | tmpfile, _ := ioutil.TempFile("", "example") 593 | defer os.Remove(tmpfile.Name()) // clean up 594 | 595 | err = e.Connection.Download(remote, tmpfile.Name()) 596 | if err == nil { 597 | 598 | // 599 | // We had no error - so we now have the 600 | // remote file copied here. 601 | // 602 | var hashRemote string 603 | hashRemote, err = util.HashFile(tmpfile.Name()) 604 | if err != nil { 605 | fmt.Printf("Failed to hash remote file %s\n", err.Error()) 606 | 607 | // If expanding variables we replaced our 608 | // input-file with the temporary result of 609 | // expansion. 610 | if expand { 611 | os.Remove(local) 612 | } 613 | return changed 614 | } 615 | 616 | if hashRemote != hashLocal { 617 | if e.Verbose { 618 | fmt.Printf("\tFile on remote host needs replacing.\n") 619 | } 620 | 621 | changed = true 622 | } else { 623 | if e.Verbose { 624 | fmt.Printf("\tFile on remote host doesn't need to be changed.\n") 625 | } 626 | } 627 | } else { 628 | 629 | // 630 | // If we failed to find the file we 631 | // assume thati t doesn't exist 632 | // 633 | if strings.Contains(err.Error(), "not exist") { 634 | changed = true 635 | } 636 | } 637 | 638 | // 639 | // Upload the file, if it changed 640 | // 641 | if changed { 642 | err = e.Connection.Upload(local, remote) 643 | if err != nil { 644 | fmt.Printf("Failed to upload '%s' to '%s': %s\n", local, remote, err.Error()) 645 | 646 | // If expanding variables we replaced our 647 | // input-file with the temporary result of 648 | // expansion. 649 | if expand { 650 | os.Remove(local) 651 | } 652 | 653 | return changed 654 | } 655 | } 656 | // If expanding variables we replaced our 657 | // input-file with the temporary result of 658 | // expansion. 659 | if expand { 660 | os.Remove(local) 661 | } 662 | 663 | return changed 664 | } 665 | 666 | // expandString expands tokens of the form "${blah}" into the 667 | // value of the variable "blah". 668 | func (e *Evaluator) expandString(in string) string { 669 | 670 | // 671 | // Expand any variables which have previously been 672 | // declared. 673 | // 674 | re := regexp.MustCompile(`\$\{([^\}]+)\}`) 675 | in = re.ReplaceAllStringFunc(in, func(in string) string { 676 | 677 | in = strings.TrimPrefix(in, "${") 678 | in = strings.TrimSuffix(in, "}") 679 | 680 | // Look for read-only variables first 681 | if len(e.ROVariables[in]) > 0 { 682 | return (e.ROVariables[in]) 683 | } 684 | 685 | // Now look for normal-variable 686 | if len(e.Variables[in]) > 0 { 687 | return (e.Variables[in]) 688 | } 689 | 690 | // Finally we found neither, just leave the 691 | // expansion alone. 692 | return "${" + in + "}" 693 | }) 694 | 695 | return in 696 | } 697 | 698 | // SetVariable sets the content of a read-only variable 699 | func (e *Evaluator) SetVariable(key string, val string) { 700 | e.ROVariables[key] = val 701 | } 702 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Server Deployment Recipes 2 | 3 | This repository contains a number of simple recipes to be used by 4 | [deployr](https://github.com/skx/deployr). 5 | -------------------------------------------------------------------------------- /examples/overseer/README.md: -------------------------------------------------------------------------------- 1 | # Overseer Overview 2 | 3 | [Overseer](https://github.com/skx/overseer) is a network-testing tool, which allows you to run tests of services on remote hosts. You write your tests as plain-text, and then execute them. 4 | 5 | To allow scaling the execution of tests isn't done directly, instead (parsed) tests are added to a (redis) queue, from where they can be pulled. 6 | 7 | ## Overseer Deployment 8 | 9 | There are two parts to deploying overseer: 10 | 11 | * Fetching the binary. 12 | * Setting up the services. 13 | 14 | There are two services: 15 | 16 | * overseer-enqueue.service 17 | * This adds tests to the queue every two minutes. 18 | * overseer-worker.service 19 | * This launches a worker which will fetch tests from the queue and execute them. 20 | 21 | The recipe in this directory sets up the tests. 22 | -------------------------------------------------------------------------------- /examples/overseer/deploy.recipe: -------------------------------------------------------------------------------- 1 | # 2 | # Deploy overseer - this consists of two files. 3 | # 4 | 5 | # 6 | # Specify the host to which we're deploying. 7 | # 8 | # Public-key authentication is both assumed and required. 9 | # 10 | DeployTo root@alert.steve.fi:2222 11 | 12 | # 13 | # Set the release version as a variable named "RELEASE". 14 | # 15 | Set RELEASE "1.6" 16 | 17 | # 18 | # The path where we deploy applications. 19 | # 20 | Set BIN "/opt/overseer/bin" 21 | 22 | # 23 | # Ensure we have a destination directory 24 | # 25 | Run "mkdir -p /opt/overseer/bin >/dev/null" 26 | 27 | # 28 | # Fetch overseer, copy it into place, and symlink it. 29 | # 30 | Run "wget --quiet -O ${BIN}/tmp.overseer-linux-amd64-${RELEASE} \ 31 | https://github.com/skx/overseer/releases/download/release-${RELEASE}/overseer-linux-amd64" 32 | Run "mv ${BIN}/tmp.overseer-linux-amd64-${RELEASE} \ 33 | ${BIN}/overseer-linux-amd64-${RELEASE}" 34 | Run "ln -sf ${BIN}/overseer-linux-amd64-${RELEASE} \ 35 | ${BIN}/overseer" 36 | 37 | # 38 | # Fetch our bridge, copy it into place, and symlink it. 39 | # 40 | Run "wget --quiet -O ${BIN}/tmp.purppura-bridge-linux-amd64-${RELEASE} \ 41 | https://github.com/skx/overseer/releases/download/release-${RELEASE}/purppura-bridge-linux-amd64" 42 | Run "mv ${BIN}/tmp.purppura-bridge-linux-amd64-${RELEASE} \ 43 | ${BIN}/purppura-bridge-linux-amd64-${RELEASE}" 44 | Run "ln -sf ${BIN}/purppura-bridge-linux-amd64-${RELEASE} \ 45 | ${BIN}/purppura-bridge" 46 | 47 | # 48 | # Ensure the downloaded files are executable. 49 | # 50 | Run "chmod 755 ${BIN}/*" 51 | 52 | # 53 | # Finally we need to make sure there are systemd unit-files in-place, 54 | # for handling the parsing/polling. 55 | # 56 | CopyFile overseer-enqueue.service /lib/systemd/system/overseer-enqueue.service 57 | IfChanged "systemctl daemon-reload" 58 | IfChanged "systemctl enable overseer-enqueue.service" 59 | 60 | CopyFile overseer-enqueue.timer /lib/systemd/system/overseer-enqueue.timer 61 | IfChanged "systemctl daemon-reload" 62 | IfChanged "systemctl enable overseer-enqueue.timer" 63 | 64 | CopyFile overseer-worker.service /lib/systemd/system/overseer-worker.service 65 | IfChanged "systemctl daemon-reload" 66 | IfChanged "systemctl enable overseer-worker.service" 67 | 68 | CopyFile purppura-bridge.service /lib/systemd/system/purppura-bridge.service 69 | IfChanged "systemctl daemon-reload" 70 | IfChanged "systemctl enable purppura-bridge.service" 71 | 72 | # 73 | # Stop + Start the services 74 | # 75 | Run "systemctl stop overseer-worker.service" 76 | Run "systemctl start overseer-worker.service" 77 | Run "systemctl stop purppura-bridge.service" 78 | Run "systemctl start purppura-bridge.service" 79 | -------------------------------------------------------------------------------- /examples/overseer/lib/systemd/system/overseer-enqueue.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Add tests to be executed by oveseer 3 | RefuseManualStart=no 4 | RefuseManualStop=yes 5 | 6 | [Service] 7 | Type=oneshot 8 | ExecStart=/bin/sh -c '/opt/overseer/bin/overseer enqueue -redis-host=localhost:6379 /opt/overseer/tests.d/*.conf' 9 | -------------------------------------------------------------------------------- /examples/overseer/lib/systemd/system/overseer-enqueue.timer: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Populate the overseer work-queue 3 | RefuseManualStart=no 4 | RefuseManualStop=no 5 | 6 | [Timer] 7 | Persistent=false 8 | OnCalendar=*:0/2 9 | Unit=overseer-enqueue.service 10 | 11 | [Install] 12 | WantedBy=default.target 13 | -------------------------------------------------------------------------------- /examples/overseer/lib/systemd/system/overseer-worker.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=overseer worker-service 3 | 4 | [Service] 5 | User=root 6 | WorkingDirectory=/opt/overseer 7 | Environment="METRICS=metrics.steve.fi" 8 | ExecStart=/opt/overseer/bin/overseer worker -redis-host=127.0.0.1:6379 9 | KillMode=process 10 | Restart=always 11 | StartLimitInterval=2 12 | StartLimitBurst=20 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /examples/overseer/lib/systemd/system/purppura-bridge.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=purppura-bridge 3 | 4 | [Service] 5 | User=nobody 6 | WorkingDirectory=/opt/overseer 7 | Environment="METRICS=metrics.steve.fi" 8 | ExecStart=/opt/overseer/bin/purppura-bridge -redis-host=127.0.0.1:6379 -purppura=https://alert.steve.fi/events 9 | KillMode=process 10 | Restart=always 11 | StartLimitInterval=2 12 | StartLimitBurst=20 13 | 14 | [Install] 15 | WantedBy=multi-user.target 16 | -------------------------------------------------------------------------------- /examples/puppet-summary/README.md: -------------------------------------------------------------------------------- 1 | # Puppet-Summary Overview 2 | 3 | [puppet-summary](https://github.com/skx/puppet-summary) presents a simple dashboard showing the activity of a puppet-master. 4 | 5 | In short if you use puppet to control a bunch of hosts the dashboard allows you to view failures/successes in a simple fashion. 6 | 7 | 8 | ## Puppet-Summary Deployment 9 | 10 | There are two parts to deploying overseer: 11 | 12 | * Fetching the binary. 13 | * Setting up the service. 14 | 15 | There is only a single service which launches the deamon, ahead of that is a 16 | public-facing `nginx` proxy-server. (We should configure that with `deployr` 17 | too, but currently we don't.) 18 | -------------------------------------------------------------------------------- /examples/puppet-summary/deploy.recipe: -------------------------------------------------------------------------------- 1 | # 2 | # Deploy Steve's puppet-summary application. 3 | # 4 | # The puppet-summary application is developed on github, and only 5 | # fixed releases are installed via release-page of the project: 6 | # 7 | # https://github.com/skx/puppet-summary/releases 8 | # 9 | # The software is deployed to the single host `master.steve.org.uk` 10 | # and I connect to that host via SSH as the root-user. 11 | # 12 | # At the time of writing the most recent release is version 1.2 13 | # 14 | 15 | 16 | # 17 | # Specify the host to which we're deploying. 18 | # 19 | # Public-key authentication is both assumed and required. 20 | # 21 | DeployTo root@master.steve.org.uk:2222 22 | 23 | # 24 | # Set the release version as a variable named "RELEASE". 25 | # 26 | Set RELEASE "1.3.1" 27 | 28 | # 29 | # Now that RELEASE is defined it can be used as ${RELEASE} in the rest of 30 | # this file. 31 | # 32 | 33 | # 34 | # To deploy the software I need to fetch it. Do that with `wget`: 35 | # 36 | Run "wget --quiet -O /srv/puppet-summary/tmp.puppet-summary-linux-amd64-${RELEASE} \ 37 | https://github.com/skx/puppet-summary/releases/download/release-${RELEASE}/puppet-summary-linux-amd64" 38 | 39 | # 40 | # Copy it into-place 41 | # 42 | Run "mv /srv/puppet-summary/tmp.puppet-summary-linux-amd64-${RELEASE} \ 43 | /srv/puppet-summary/puppet-summary-linux-amd64-${RELEASE}" 44 | 45 | # 46 | # Create a symlink from this versioned download to an unqualified name. 47 | # 48 | Run "ln -sf /srv/puppet-summary/puppet-summary-linux-amd64-${RELEASE} \ 49 | /srv/puppet-summary/puppet-summary" 50 | 51 | 52 | # 53 | # Ensure the downloaded file is executable. 54 | # 55 | Run "chmod 755 /srv/puppet-summary/puppet*" 56 | 57 | # 58 | # Finally we need to make sure there is a systemd unit-file in-place which 59 | # will start the service 60 | # 61 | CopyFile lib/systemd/system/*.service /lib/systemd/system/ 62 | IfChanged "systemctl daemon-reload" 63 | IfChanged "systemctl enable puppet-summary.service" 64 | 65 | # 66 | # And now we should be able to stop/start the service 67 | # 68 | Run "systemctl stop puppet-summary.service" 69 | Run "systemctl start puppet-summary.service" 70 | -------------------------------------------------------------------------------- /examples/puppet-summary/lib/systemd/system/puppet-summary.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=puppet-summary service 3 | 4 | [Service] 5 | WorkingDirectory=/srv/puppet-summary 6 | User=p-s 7 | Environment="METRICS=metrics.steve.fi" 8 | ExecStart=/srv/puppet-summary/puppet-summary serve 9 | Restart=always 10 | StartLimitInterval=2 11 | StartLimitBurst=20 12 | PrivateTmp=yes 13 | RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX 14 | 15 | [Install] 16 | WantedBy=multi-user.target 17 | -------------------------------------------------------------------------------- /examples/simple/deploy.recipe: -------------------------------------------------------------------------------- 1 | # 2 | # This is a simple recipe which shows how deployr could be used. 3 | # 4 | # Launch it like so: 5 | # 6 | # deployr -target root@host.example.com:22 ./deploy.recipe 7 | # 8 | 9 | # 10 | # Set a variable 11 | # 12 | Set greeting "Hello, world!" 13 | 14 | 15 | # 16 | # 17 | # This copies the file `example.recipe.template` to the remote host, 18 | # expanding any variables prior to the copy. 19 | # 20 | CopyTemplate example.recipe.template /tmp/blah 21 | 22 | # 23 | # This will show the contents of that file. 24 | # 25 | Run "cat /tmp/blah" 26 | 27 | # 28 | # The following command will only be executed if the remote file is 29 | # updated. So you'll see the output the first time, but not the second 30 | # time you run this example 31 | # 32 | IfChanged "sha1sum /tmp/blah" 33 | -------------------------------------------------------------------------------- /examples/simple/example.recipe.template: -------------------------------------------------------------------------------- 1 | This file was deployed to {{get "host" }} by deployr! 2 | 3 | Here you see a variable being used which was defined in the recipe itself: 4 | 5 | * {{get "greeting"}} 6 | -------------------------------------------------------------------------------- /examples/sudo/deploy.recipe: -------------------------------------------------------------------------------- 1 | # 2 | # This is a simple recipe which demonstrates the usage of "sudo". 3 | # 4 | # Launch it like so: 5 | # 6 | # $ deployr -target user@host.example.com:22 ./deploy.recipe 7 | # 8 | # Sample output: 9 | # 10 | # $ deployr run -target steve@host.example.com deploy.recipe 11 | # Please enter your password for sudo: s4cr3t 12 | # 13 | # This command runs as "steve" 14 | # uid=1000(steve) gid=100(users) groups=100(users),1007(steve),1034(ssh_users) 15 | # 16 | # This command runs as "root" 17 | # uid=0(root) gid=0(root) groups=0(root),1034(ssh_users) 18 | # 19 | # 20 | 21 | 22 | 23 | # 24 | # "Run" executes a command as the user we connect with. 25 | # 26 | Run "echo 'This command runs as \"${user}\"'" 27 | Run "/usr/bin/id" 28 | 29 | 30 | 31 | # 32 | # "Sudo Run" runs a command as root. 33 | # 34 | Run "echo 'This command runs as \"root\"'" 35 | Sudo Run "/usr/bin/id" 36 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/skx/deployr 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/davidmz/go-pageant v1.0.2 7 | github.com/google/subcommands v1.2.0 8 | github.com/pkg/sftp v1.13.6 // indirect 9 | github.com/sfreiberg/simplessh v0.0.0-20220719182921-185eafd40485 10 | golang.org/x/crypto v0.31.0 // indirect 11 | golang.org/x/term v0.27.0 12 | ) 13 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0= 5 | github.com/davidmz/go-pageant v1.0.2/go.mod h1:P2EDDnMqIwG5Rrp05dTRITj9z2zpGcD9efWSkTNKLIE= 6 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 7 | github.com/google/subcommands v1.2.0 h1:vWQspBTo2nEqTUFita5/KeEWlUL8kQObDFbub/EN9oE= 8 | github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= 9 | github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= 10 | github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= 11 | github.com/pkg/sftp v1.13.4/go.mod h1:LzqnAvaD5TWeNBsZpfKxSYn1MbjWwOsCIAFFJbpIsK8= 12 | github.com/pkg/sftp v1.13.6 h1:JFZT4XbOU7l77xGSpOdW+pwIMqP044IyjXX6FGyEKFo= 13 | github.com/pkg/sftp v1.13.6/go.mod h1:tz1ryNURKu77RL+GuCzmoJYxQczL3wLNNpPWagdg4Qk= 14 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 15 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 16 | github.com/sfreiberg/simplessh v0.0.0-20220719182921-185eafd40485 h1:ZMBZ2DKX1sScUSo9ZUwGI7jCMukslPNQNfZaw9vVyfY= 17 | github.com/sfreiberg/simplessh v0.0.0-20220719182921-185eafd40485/go.mod h1:9qeq2P58+4+LyuncL3waJDG+giOfXgowfrRZZF9XdWk= 18 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 19 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 20 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 21 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 22 | github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= 23 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 24 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 25 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 26 | golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= 27 | golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= 28 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 29 | golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= 30 | golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= 31 | golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= 32 | golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= 33 | golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= 34 | golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= 35 | golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= 36 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 37 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 38 | golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 39 | golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 40 | golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 41 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 42 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 43 | golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 44 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 45 | golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= 46 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 47 | golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= 48 | golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= 49 | golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= 50 | golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= 51 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 52 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 53 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 54 | golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= 55 | golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 56 | golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 57 | golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 58 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 59 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 60 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 61 | golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 62 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 63 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 64 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 65 | golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 66 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 67 | golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 68 | golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 69 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 70 | golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 71 | golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= 72 | golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 73 | golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= 74 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 75 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 76 | golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 77 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 78 | golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= 79 | golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= 80 | golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= 81 | golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= 82 | golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= 83 | golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= 84 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 85 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 86 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 87 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 88 | golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 89 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 90 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 91 | golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= 92 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 93 | golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 94 | golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= 95 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 96 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 97 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 98 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 99 | golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= 100 | golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= 101 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 102 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 103 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 104 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 105 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 106 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 107 | -------------------------------------------------------------------------------- /lexer/lexer.go: -------------------------------------------------------------------------------- 1 | // Package lexer contains a simple lexer for reading an input-string 2 | // and converting it into a series of tokens. 3 | package lexer 4 | 5 | import ( 6 | "errors" 7 | "fmt" 8 | 9 | "github.com/skx/deployr/token" 10 | ) 11 | 12 | // Lexer is used as the lexer for our deployr "language". 13 | type Lexer struct { 14 | position int //current character position 15 | readPosition int //next character position 16 | ch rune //current character 17 | characters []rune //rune slice of input string 18 | } 19 | 20 | // New a Lexer instance from string input. 21 | func New(input string) *Lexer { 22 | l := &Lexer{characters: []rune(input)} 23 | l.readChar() 24 | return l 25 | } 26 | 27 | // Dump outputs the complete stream of tokens from the lexer, 28 | // consuming all input as it does so. 29 | func (l *Lexer) Dump() { 30 | for { 31 | tok := l.NextToken() 32 | fmt.Printf("%v\n", tok) 33 | if tok.Type == "EOF" { 34 | break 35 | } 36 | } 37 | } 38 | 39 | // read one forward character 40 | func (l *Lexer) readChar() { 41 | if l.readPosition >= len(l.characters) { 42 | l.ch = rune(0) 43 | } else { 44 | l.ch = l.characters[l.readPosition] 45 | } 46 | l.position = l.readPosition 47 | l.readPosition++ 48 | } 49 | 50 | // NextToken to read next token, skipping the white space. 51 | func (l *Lexer) NextToken() token.Token { 52 | 53 | var tok token.Token 54 | l.skipWhitespace() 55 | 56 | // skip shebang 57 | if l.ch == rune('#') && l.peekChar() == rune('!') && l.position == 0 { 58 | l.skipComment() 59 | return (l.NextToken()) 60 | } 61 | 62 | // skip single-line comments 63 | if l.ch == rune('#') { 64 | l.skipComment() 65 | return (l.NextToken()) 66 | } 67 | 68 | switch l.ch { 69 | case rune('"'): 70 | str, err := l.readString() 71 | 72 | if err == nil { 73 | tok.Type = token.STRING 74 | tok.Literal = str 75 | } else { 76 | tok.Type = token.ILLEGAL 77 | tok.Literal = err.Error() 78 | } 79 | case rune(0): 80 | tok.Literal = "" 81 | tok.Type = token.EOF 82 | default: 83 | tok.Literal = l.readIdentifier() 84 | tok.Type = token.LookupIdentifier(tok.Literal) 85 | return tok 86 | } 87 | l.readChar() 88 | return tok 89 | } 90 | 91 | // read Identifier 92 | func (l *Lexer) readIdentifier() string { 93 | position := l.position 94 | for isIdentifier(l.ch) { 95 | l.readChar() 96 | } 97 | return string(l.characters[position:l.position]) 98 | } 99 | 100 | // skip white space 101 | func (l *Lexer) skipWhitespace() { 102 | for isWhitespace(l.ch) { 103 | l.readChar() 104 | } 105 | } 106 | 107 | // skip comment (until the end of the line). 108 | func (l *Lexer) skipComment() { 109 | for l.ch != '\n' && l.ch != rune(0) { 110 | l.readChar() 111 | } 112 | l.skipWhitespace() 113 | } 114 | 115 | // read string 116 | func (l *Lexer) readString() (string, error) { 117 | out := "" 118 | 119 | for { 120 | l.readChar() 121 | if l.ch == '"' { 122 | break 123 | } 124 | if l.ch == rune(0) { 125 | return "", errors.New("unterminated string") 126 | } 127 | 128 | // 129 | // Handle \n, \r, \t, \", etc. 130 | // 131 | if l.ch == '\\' { 132 | 133 | // Line ending with "\" + newline 134 | if l.peekChar() == '\n' { 135 | // consume the newline. 136 | l.readChar() 137 | continue 138 | } 139 | 140 | l.readChar() 141 | 142 | if l.ch == rune('n') { 143 | l.ch = '\n' 144 | } 145 | if l.ch == rune('r') { 146 | l.ch = '\r' 147 | } 148 | if l.ch == rune('t') { 149 | l.ch = '\t' 150 | } 151 | if l.ch == rune('"') { 152 | l.ch = '"' 153 | } 154 | if l.ch == rune('\\') { 155 | l.ch = '\\' 156 | } 157 | } 158 | out = out + string(l.ch) 159 | 160 | } 161 | 162 | return out, nil 163 | } 164 | 165 | // peek character 166 | func (l *Lexer) peekChar() rune { 167 | if l.readPosition >= len(l.characters) { 168 | return rune(0) 169 | } 170 | return l.characters[l.readPosition] 171 | } 172 | 173 | // determinate ch is identifier or not 174 | func isIdentifier(ch rune) bool { 175 | return !isWhitespace(ch) && !isEmpty(ch) 176 | } 177 | 178 | // is white space 179 | func isWhitespace(ch rune) bool { 180 | return ch == rune(' ') || ch == rune('\t') || ch == rune('\n') || ch == rune('\r') 181 | } 182 | 183 | // is empty 184 | func isEmpty(ch rune) bool { 185 | return rune(0) == ch 186 | } 187 | -------------------------------------------------------------------------------- /lexer/lexer_test.go: -------------------------------------------------------------------------------- 1 | package lexer 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/skx/deployr/token" 7 | ) 8 | 9 | // TestSomeStrings tests that the input of a pair of strings is tokenized 10 | // appropriately. 11 | func TestSomeStrings(t *testing.T) { 12 | input := `"Steve" "Kemp"` 13 | 14 | tests := []struct { 15 | expectedType token.Type 16 | expectedLiteral string 17 | }{ 18 | {token.STRING, "Steve"}, 19 | {token.STRING, "Kemp"}, 20 | {token.EOF, ""}, 21 | } 22 | l := New(input) 23 | for i, tt := range tests { 24 | tok := l.NextToken() 25 | if tok.Type != tt.expectedType { 26 | t.Fatalf("tests[%d] - tokentype wrong, expected=%q, got=%q", i, tt.expectedType, tok.Type) 27 | } 28 | if tok.Literal != tt.expectedLiteral { 29 | t.Fatalf("tests[%d] - Literal wrong, expected=%q, got=%q", i, tt.expectedLiteral, tok.Literal) 30 | } 31 | } 32 | } 33 | 34 | // TestEscape ensures that strings have escape-characters processed. 35 | func TestStringEscape(t *testing.T) { 36 | input := `"Steve\n\r\\" "Kemp\n\t\n" "Inline \"quotes\"."` 37 | 38 | tests := []struct { 39 | expectedType token.Type 40 | expectedLiteral string 41 | }{ 42 | {token.STRING, "Steve\n\r\\"}, 43 | {token.STRING, "Kemp\n\t\n"}, 44 | {token.STRING, "Inline \"quotes\"."}, 45 | {token.EOF, ""}, 46 | } 47 | l := New(input) 48 | for i, tt := range tests { 49 | tok := l.NextToken() 50 | if tok.Type != tt.expectedType { 51 | t.Fatalf("tests[%d] - tokentype wrong, expected=%q, got=%q", i, tt.expectedType, tok.Type) 52 | } 53 | if tok.Literal != tt.expectedLiteral { 54 | t.Fatalf("tests[%d] - Literal wrong, expected=%q, got=%q", i, tt.expectedLiteral, tok.Literal) 55 | } 56 | } 57 | } 58 | 59 | // TestComments ensures that single-line comments work. 60 | func TestComments(t *testing.T) { 61 | input := `# This is a comment 62 | "Steve" 63 | # This is another comment` 64 | 65 | tests := []struct { 66 | expectedType token.Type 67 | expectedLiteral string 68 | }{ 69 | {token.STRING, "Steve"}, 70 | {token.EOF, ""}, 71 | } 72 | l := New(input) 73 | for i, tt := range tests { 74 | tok := l.NextToken() 75 | if tok.Type != tt.expectedType { 76 | t.Fatalf("tests[%d] - tokentype wrong, expected=%q, got=%q", i, tt.expectedType, tok.Type) 77 | } 78 | if tok.Literal != tt.expectedLiteral { 79 | t.Fatalf("tests[%d] - Literal wrong, expected=%q, got=%q", i, tt.expectedLiteral, tok.Literal) 80 | } 81 | } 82 | } 83 | 84 | // TestShebang skips the shebang 85 | func TestShebang(t *testing.T) { 86 | input := `#!/usr/bin/env deployr 87 | "Steve" 88 | # This is another comment` 89 | 90 | tests := []struct { 91 | expectedType token.Type 92 | expectedLiteral string 93 | }{ 94 | {token.STRING, "Steve"}, 95 | {token.EOF, ""}, 96 | } 97 | l := New(input) 98 | for i, tt := range tests { 99 | tok := l.NextToken() 100 | if tok.Type != tt.expectedType { 101 | t.Fatalf("tests[%d] - tokentype wrong, expected=%q, got=%q", i, tt.expectedType, tok.Type) 102 | } 103 | if tok.Literal != tt.expectedLiteral { 104 | t.Fatalf("tests[%d] - Literal wrong, expected=%q, got=%q", i, tt.expectedLiteral, tok.Literal) 105 | } 106 | } 107 | } 108 | 109 | // TestRun tests a simple run-statement. 110 | func TestRun(t *testing.T) { 111 | input := `#!/usr/bin/env deployr 112 | Run "Steve" 113 | # This is another comment` 114 | 115 | tests := []struct { 116 | expectedType token.Type 117 | expectedLiteral string 118 | }{ 119 | {token.RUN, "Run"}, 120 | {token.STRING, "Steve"}, 121 | {token.EOF, ""}, 122 | } 123 | l := New(input) 124 | for i, tt := range tests { 125 | tok := l.NextToken() 126 | if tok.Type != tt.expectedType { 127 | t.Fatalf("tests[%d] - tokentype wrong, expected=%q, got=%q", i, tt.expectedType, tok.Type) 128 | } 129 | if tok.Literal != tt.expectedLiteral { 130 | t.Fatalf("tests[%d] - Literal wrong, expected=%q, got=%q", i, tt.expectedLiteral, tok.Literal) 131 | } 132 | } 133 | } 134 | 135 | // TestUnterminated string ensures that an unclosed-string is an error 136 | func TestUnterminatedString(t *testing.T) { 137 | input := `#!/usr/bin/env deployr 138 | Run "Steve` 139 | 140 | tests := []struct { 141 | expectedType token.Type 142 | expectedLiteral string 143 | }{ 144 | {token.RUN, "Run"}, 145 | {token.ILLEGAL, "unterminated string"}, 146 | {token.EOF, ""}, 147 | } 148 | l := New(input) 149 | for i, tt := range tests { 150 | tok := l.NextToken() 151 | if tok.Type != tt.expectedType { 152 | t.Fatalf("tests[%d] - tokentype wrong, expected=%q, got=%q", i, tt.expectedType, tok.Type) 153 | } 154 | if tok.Literal != tt.expectedLiteral { 155 | t.Fatalf("tests[%d] - Literal wrong, expected=%q, got=%q", i, tt.expectedLiteral, tok.Literal) 156 | } 157 | } 158 | } 159 | 160 | // TestContinue checks we continue newlines. 161 | func TestContinue(t *testing.T) { 162 | input := `#!/usr/bin/env deployr 163 | Run "This is a test \ 164 | which continues" 165 | ` 166 | 167 | tests := []struct { 168 | expectedType token.Type 169 | expectedLiteral string 170 | }{ 171 | {token.RUN, "Run"}, 172 | {token.STRING, "This is a test which continues"}, 173 | {token.EOF, ""}, 174 | } 175 | l := New(input) 176 | for i, tt := range tests { 177 | tok := l.NextToken() 178 | if tok.Type != tt.expectedType { 179 | t.Fatalf("tests[%d] - tokentype wrong, expected=%q, got=%q", i, tt.expectedType, tok.Type) 180 | } 181 | if tok.Literal != tt.expectedLiteral { 182 | t.Fatalf("tests[%d] - Literal wrong, expected=%q, got=%q", i, tt.expectedLiteral, tok.Literal) 183 | } 184 | } 185 | } 186 | 187 | // TestDump just calls dump on some tokens. 188 | func TestDump(t *testing.T) { 189 | input := `#!/usr/bin/env deployr 190 | # This is another comment` 191 | 192 | l := New(input) 193 | l.Dump() 194 | 195 | // 196 | // Since we've consumed all the input we expect we'll 197 | // read past the input here. 198 | // 199 | if l.peekChar() != rune(0) { 200 | t.Fatalf("We still have input, after dumping our stream") 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Entry-Point to our code. 2 | 3 | package main 4 | 5 | import ( 6 | "context" 7 | "flag" 8 | "os" 9 | 10 | "github.com/google/subcommands" 11 | ) 12 | 13 | // 14 | // Our main-driver. 15 | // 16 | // Load the sub-commands we have available, and pass control appropriately. 17 | // 18 | func main() { 19 | 20 | subcommands.Register(subcommands.HelpCommand(), "") 21 | subcommands.Register(subcommands.FlagsCommand(), "") 22 | subcommands.Register(subcommands.CommandsCommand(), "") 23 | subcommands.Register(&lexCmd{}, "") 24 | subcommands.Register(&parseCmd{}, "") 25 | subcommands.Register(&runCmd{}, "") 26 | subcommands.Register(&versionCmd{}, "") 27 | 28 | flag.Parse() 29 | ctx := context.Background() 30 | os.Exit(int(subcommands.Execute(ctx))) 31 | 32 | } 33 | -------------------------------------------------------------------------------- /parser/parser.go: -------------------------------------------------------------------------------- 1 | // Package parser is the package which parses our input. 2 | // 3 | // Given a lexer, wrapping a given input-file, we parse tokens from 4 | // it into a series of statements which we then return for processing. 5 | package parser 6 | 7 | import ( 8 | "fmt" 9 | 10 | "github.com/skx/deployr/statement" 11 | "github.com/skx/deployr/token" 12 | ) 13 | 14 | // tokenizer is the interface for our tokenzier. 15 | // 16 | // We expect to consume tokens from our Lexer, but we use a layer 17 | // of indirection by constructing our parser with an interface 18 | // instead. 19 | // 20 | // This allows us to create a `FakeLexer` which satisfies the 21 | // interface for testing-purposes. 22 | // 23 | type tokenizer interface { 24 | 25 | // Our tokenizer interface requires anything we 26 | // use to implement the NextToken() method - which 27 | // should return the next token in the stream. 28 | NextToken() token.Token 29 | } 30 | 31 | // Parser holds our internal state. 32 | type Parser struct { 33 | // Our tokenizer. 34 | Tokenizer tokenizer 35 | } 36 | 37 | // New returns a new Parser object, consuming tokens from the specified 38 | // tokenizer-interface. 39 | func New(tk tokenizer) *Parser { 40 | l := &Parser{Tokenizer: tk} 41 | return l 42 | } 43 | 44 | // Parse the given program, catching errors. 45 | func (p *Parser) Parse() ([]statement.Statement, error) { 46 | var result []statement.Statement 47 | 48 | // 49 | // Does the next command use Sudo? 50 | // 51 | sudo := false 52 | 53 | // 54 | // We have a lexer, so we process each token in-turn until we 55 | // hit the end-of-file. 56 | // 57 | run := true 58 | for run { 59 | 60 | // 61 | // Get the next token. 62 | // 63 | tok := p.Tokenizer.NextToken() 64 | 65 | // 66 | // Process each token-type appropriately. 67 | // 68 | // Basically we're performing validation here that there 69 | // are arguments of the appropriate type. 70 | // 71 | switch tok.Type { 72 | 73 | case "ILLEGAL": 74 | // 75 | // If we encounter an illegal-token that means 76 | // the lexer itself found something invalid. 77 | // 78 | // That might be a bogus number (if we supported numbers), 79 | // or an unterminated string. 80 | // 81 | return result, fmt.Errorf("error received from the lexer - %s", tok.Literal) 82 | case "IDENT": 83 | // 84 | // If we find a bare-ident which is not an argument 85 | // then we're either out of sync with reality or 86 | // the user has tried to run a bogus-program: 87 | // 88 | // /usr/bin/id 89 | // Run "/usr/bin/id" 90 | // 91 | // Either way this is an error. 92 | // 93 | return result, fmt.Errorf("found unexpected identifier '%s'", tok.Literal) 94 | case "STRING": 95 | // 96 | // If we find a bare-string which is not an argument 97 | // then we're either out of sync with reality or 98 | // the user has tried to run a bogus-program: 99 | // 100 | // "Test" 101 | // Run "/usr/bin/id" 102 | // 103 | // Either way this is an error. 104 | // 105 | return result, fmt.Errorf("found unexpected string '%s'", tok.Literal) 106 | case "CopyTemplate": 107 | // 108 | // We should have two arguments to CopyTemplate: 109 | // 110 | // 1. IDENT 111 | // 2. IDENT 112 | // 113 | // (Here IDENT means "path".) 114 | // 115 | expected := []token.Token{ 116 | {Type: "IDENT"}, 117 | {Type: "IDENT"}, 118 | } 119 | 120 | // 121 | // Get the arguments, validating types. 122 | // 123 | args, err := p.GetArguments(expected) 124 | 125 | // 126 | // Error? 127 | // 128 | if err != nil { 129 | return result, err 130 | } 131 | 132 | // 133 | // Otherwise we can store this statement. 134 | // 135 | s := statement.Statement{Token: tok} 136 | s.Arguments = args 137 | result = append(result, s) 138 | 139 | case "CopyFile": 140 | 141 | // 142 | // We should have two arguments to CopyFile: 143 | // 144 | // 1. IDENT 145 | // 2. IDENT 146 | // 147 | // (Here IDENT means "path".) 148 | // 149 | expected := []token.Token{ 150 | {Type: "IDENT"}, 151 | {Type: "IDENT"}, 152 | } 153 | 154 | // 155 | // Get the arguments, validating types. 156 | // 157 | args, err := p.GetArguments(expected) 158 | 159 | // 160 | // Error? 161 | // 162 | if err != nil { 163 | return result, err 164 | } 165 | 166 | // 167 | // Otherwise we can store this statement. 168 | // 169 | s := statement.Statement{Token: tok} 170 | s.Arguments = args 171 | result = append(result, s) 172 | 173 | case "DeployTo": 174 | // 175 | // We should have one arguments to DeployTo: 176 | // 177 | // 1. IDENT 178 | // 179 | expected := []token.Token{ 180 | {Type: "IDENT"}, 181 | } 182 | 183 | // 184 | // Get the arguments, validating types. 185 | // 186 | args, err := p.GetArguments(expected) 187 | 188 | // 189 | // Error? 190 | // 191 | if err != nil { 192 | return result, err 193 | } 194 | 195 | // 196 | // Otherwise we can store this statement. 197 | // 198 | s := statement.Statement{Token: tok} 199 | s.Arguments = args 200 | result = append(result, s) 201 | 202 | case "IfChanged": 203 | 204 | // 205 | // We should have one arguments to IfChanged: 206 | // 207 | // 1. String 208 | // 209 | expected := []token.Token{ 210 | {Type: "STRING"}, 211 | } 212 | 213 | // 214 | // Get the arguments, validating types. 215 | // 216 | args, err := p.GetArguments(expected) 217 | 218 | // 219 | // Error? 220 | // 221 | if err != nil { 222 | return result, err 223 | } 224 | 225 | // 226 | // Otherwise we can store this statement. 227 | // 228 | s := statement.Statement{Token: tok} 229 | s.Arguments = args 230 | 231 | // 232 | // Preserve the SUDO state 233 | // 234 | s.Sudo = sudo 235 | sudo = false 236 | 237 | result = append(result, s) 238 | 239 | case "Run": 240 | 241 | // 242 | // We should have one arguments to Run: 243 | // 244 | // 1. String 245 | // 246 | expected := []token.Token{ 247 | {Type: "STRING"}, 248 | } 249 | 250 | // 251 | // Get the arguments, validating types. 252 | // 253 | args, err := p.GetArguments(expected) 254 | 255 | // 256 | // Error? 257 | // 258 | if err != nil { 259 | return result, err 260 | } 261 | 262 | // 263 | // Otherwise we can store this statement. 264 | // 265 | s := statement.Statement{Token: tok} 266 | s.Arguments = args 267 | 268 | // 269 | // Preserve the SUDO state 270 | // 271 | s.Sudo = sudo 272 | sudo = false 273 | 274 | result = append(result, s) 275 | 276 | case "Set": 277 | 278 | // 279 | // We should have two arguments to set: 280 | // 281 | // 1. Ident. 282 | // 2. String 283 | // 284 | expected := []token.Token{ 285 | {Type: "IDENT"}, 286 | {Type: "STRING"}, 287 | } 288 | 289 | // 290 | // Get the arguments, validating types. 291 | // 292 | args, err := p.GetArguments(expected) 293 | 294 | // 295 | // Error? 296 | // 297 | if err != nil { 298 | return result, err 299 | } 300 | 301 | // 302 | // Otherwise we can store this statement. 303 | // 304 | s := statement.Statement{Token: tok} 305 | s.Arguments = args 306 | result = append(result, s) 307 | 308 | case "Sudo": 309 | sudo = true 310 | 311 | case "EOF": 312 | 313 | // 314 | // This causes our parsing-loop to terminate. 315 | // 316 | run = false 317 | default: 318 | 319 | // 320 | // If we hit this point there is a token-type we 321 | // did not handle. 322 | // 323 | return nil, fmt.Errorf("unhandled statement - %v", tok) 324 | 325 | } 326 | } 327 | return result, nil 328 | } 329 | 330 | // GetArguments fetches arguments from the lexer, ensuring they're 331 | // the expected types. 332 | func (p *Parser) GetArguments(expected []token.Token) ([]token.Token, error) { 333 | var ret []token.Token 334 | 335 | for i, arg := range expected { 336 | 337 | next := p.Tokenizer.NextToken() 338 | if next.Type != arg.Type { 339 | return nil, fmt.Errorf("expected %v as argument %d - Got %v", arg.Type, i+1, next.Type) 340 | } 341 | 342 | ret = append(ret, next) 343 | 344 | } 345 | return ret, nil 346 | } 347 | -------------------------------------------------------------------------------- /parser/parser_test.go: -------------------------------------------------------------------------------- 1 | // 2 | // Test-cases for our parser. 3 | // 4 | // The parser is designed to consume tokens from our lexer so we have to 5 | // fake-feed them in. We do this via the `FakeLexer` helper. 6 | // 7 | 8 | package parser 9 | 10 | import ( 11 | "strings" 12 | "testing" 13 | 14 | "github.com/skx/deployr/token" 15 | ) 16 | 17 | // 18 | // FakeLexer is a fake Lexer. D'oh. 19 | // 20 | type FakeLexer struct { 21 | Offset int 22 | Tokens []token.Token 23 | } 24 | 25 | // 26 | // NewFakeLexer creates a fake lexer which will output the given tokens, in turn. 27 | func NewFakeLexer(t []token.Token) *FakeLexer { 28 | l := &FakeLexer{Tokens: t, Offset: 0} 29 | return l 30 | } 31 | 32 | // 33 | // Retrieve and return the next token from our list. 34 | // 35 | func (f *FakeLexer) NextToken() token.Token { 36 | t := f.Tokens[f.Offset] 37 | f.Offset++ 38 | return t 39 | } 40 | 41 | // TestEOF just runs a basic sanity-check 42 | func TestEOF(t *testing.T) { 43 | 44 | // 45 | // Create a fake-lexer holding a "NOP" program 46 | // 47 | toks := []token.Token{ 48 | {Type: "EOF", Literal: "EOF"}, 49 | } 50 | fl := NewFakeLexer(toks) 51 | 52 | // 53 | // Now parse into statements. 54 | // 55 | p := New(fl) 56 | 57 | program, err := p.Parse() 58 | if err != nil { 59 | t.Fatalf("Found unexpected error parsing: %s\n", err.Error()) 60 | } 61 | 62 | if len(program) != 0 { 63 | t.Fatalf("Unexpected length\n") 64 | } 65 | } 66 | 67 | // 68 | // testSingleArgument is a utility function which is designed to test 69 | // that the given function handles both valid and invalid arguments 70 | // correctly. 71 | // 72 | // For example "Run" expects a string, so we can test it like so: 73 | // 74 | // testSingleArgument( "Run", "STRING", "IDENT" ) 75 | // 76 | // "STRING" is valid, "IDENT" is bogus. 77 | // 78 | func testSingleArgument(t *testing.T, tokenName token.Type, validType token.Type, bogusType token.Type) { 79 | 80 | // 81 | // The fake-program which should be valid 82 | // 83 | valid := []token.Token{ 84 | {Type: tokenName, Literal: string(tokenName)}, 85 | {Type: validType, Literal: "My argument here"}, 86 | {Type: "EOF", Literal: "EOF"}, 87 | } 88 | 89 | // 90 | // The fake-program which should be invalid 91 | // 92 | invalid := []token.Token{ 93 | {Type: tokenName, Literal: string(tokenName)}, 94 | {Type: bogusType, Literal: "My argument here"}, 95 | {Type: "EOF", Literal: "EOF"}, 96 | } 97 | 98 | // Parse the valid program 99 | flv := NewFakeLexer(valid) 100 | pv := New(flv) 101 | program, err := pv.Parse() 102 | 103 | // We expect to receive no error. 104 | if err != nil { 105 | t.Fatalf("Received error parsing: %s\n", err.Error()) 106 | } 107 | 108 | // 109 | // We expect our statement to be "DeployTo" with the argument 110 | // pointing to example.com 111 | if program[0].Token.Type != tokenName { 112 | t.Fatalf("Unexpected statement-type : %s\n", program[0].Token.Type) 113 | } 114 | if len(program[0].Arguments) != 1 { 115 | t.Fatalf("Unexpected argument length - got %d\n", len(program[0].Arguments)) 116 | } 117 | if program[0].Arguments[0].Literal != "My argument here" { 118 | t.Fatalf("Unexpected argument: %s\n", program[0].Arguments[0].Literal) 119 | } 120 | 121 | // Parse the invalid program 122 | fli := NewFakeLexer(invalid) 123 | pi := New(fli) 124 | _, err = pi.Parse() 125 | 126 | // We expect to receive an error. 127 | if err == nil { 128 | t.Fatalf("Expected to receive an error got none\n") 129 | } 130 | if !strings.Contains(err.Error(), "expected "+string(validType)) { 131 | t.Fatalf("We received an error, but not the correct one: %s\n", err.Error()) 132 | } 133 | 134 | } 135 | 136 | // TestRun tests "Run" handling. 137 | func TestRun(t *testing.T) { 138 | testSingleArgument(t, "Run", "STRING", "IDENT") 139 | } 140 | 141 | // TestDeployTo tests "DeployTo" handling. 142 | func TestDeployTo(t *testing.T) { 143 | testSingleArgument(t, "DeployTo", "IDENT", "STRING") 144 | } 145 | 146 | // TestIfChanged tests "IfChanged" handling. 147 | func TestIfChanged(t *testing.T) { 148 | testSingleArgument(t, "IfChanged", "STRING", "IDENT") 149 | } 150 | 151 | // TestCopy tests our two copy operations. 152 | // 153 | // We call first of all with two IDENTS, which is valid. Then try two 154 | // bogus versions calling with: 155 | // STRING IDENT 156 | // IDENT STRING 157 | // This should ensure that the argument testing is exercised. 158 | func TestCopy(t *testing.T) { 159 | 160 | // 161 | // We'll repeat our tests with both "CopyFile" and 162 | // "CopyTemplate" 163 | // 164 | terms := []token.Type{"CopyFile", "CopyTemplate"} 165 | 166 | for _, term := range terms { 167 | 168 | // 169 | // A program which is valid. 170 | // 171 | valid := []token.Token{ 172 | {Type: term, Literal: string(term)}, 173 | {Type: "IDENT", Literal: "/path/to/src"}, 174 | {Type: "IDENT", Literal: "/path/to/dst"}, 175 | {Type: "EOF", Literal: "EOF"}, 176 | } 177 | 178 | // 179 | // Parse the program, we expect no errors 180 | // 181 | flv := NewFakeLexer(valid) 182 | pv := New(flv) 183 | program, err := pv.Parse() 184 | 185 | if err != nil { 186 | t.Fatalf("Received unexpected error parsing: %s\n", err.Error()) 187 | } 188 | if len(program) != 1 { 189 | t.Fatalf("Our program should have one statement - found %d\n", len(program)) 190 | } 191 | if len(program[0].Arguments) != 2 { 192 | t.Fatalf("Our statement should have two arguments - found %d\n", len(program[0].Arguments)) 193 | } 194 | 195 | // 196 | // Now test an invalid program. 197 | // 198 | bogus1 := []token.Token{ 199 | {Type: term, Literal: string(term)}, 200 | {Type: "STRING", Literal: "/path/to/src"}, 201 | {Type: "IDENT", Literal: "/path/to/dst"}, 202 | {Type: "EOF", Literal: "EOF"}, 203 | } 204 | 205 | // 206 | // Parse the program, we expect no errors 207 | // 208 | flb1 := NewFakeLexer(bogus1) 209 | pb1 := New(flb1) 210 | _, err = pb1.Parse() 211 | 212 | if err == nil { 213 | t.Fatalf("Expected to receive an error, got none") 214 | } 215 | 216 | if !strings.Contains(err.Error(), "as argument 1") { 217 | t.Fatalf("Our error was misleading: %s", err.Error()) 218 | } 219 | 220 | // 221 | // Test another invalid program. 222 | // 223 | bogus2 := []token.Token{ 224 | {Type: term, Literal: string(term)}, 225 | {Type: "IDENT", Literal: "/path/to/src"}, 226 | {Type: "STRING", Literal: "/path/to/dst"}, 227 | {Type: "EOF", Literal: "EOF"}, 228 | } 229 | 230 | // 231 | // Parse the program, we expect no errors 232 | // 233 | flb2 := NewFakeLexer(bogus2) 234 | pb2 := New(flb2) 235 | _, err = pb2.Parse() 236 | 237 | if err == nil { 238 | t.Fatalf("Expected to receive an error, got none") 239 | } 240 | 241 | if !strings.Contains(err.Error(), "as argument 2") { 242 | t.Fatalf("Our error was misleading %s", err.Error()) 243 | } 244 | 245 | } 246 | } 247 | 248 | // TestBareString tests our error-handling. 249 | func TestBareString(t *testing.T) { 250 | 251 | // 252 | // The stream of tokens we'll parse. 253 | // 254 | toks := []token.Token{ 255 | {Type: "STRING", Literal: "/bin/ls"}, 256 | {Type: "EOF", Literal: "EOF"}, 257 | } 258 | 259 | // 260 | // Now parse into statements. 261 | // 262 | fl := NewFakeLexer(toks) 263 | p := New(fl) 264 | program, err := p.Parse() 265 | 266 | // 267 | // We expect to receive an error & empty-program 268 | // 269 | if err == nil { 270 | t.Fatalf("We expected an error, but saw none!") 271 | } 272 | if len(program) != 0 { 273 | t.Fatalf("Unexpected length, wanted 0 got %d\n", len(program)) 274 | } 275 | } 276 | 277 | // TestBareIdentifier tests our error-handling. 278 | func TestBareIdentifier(t *testing.T) { 279 | 280 | // 281 | // The stream of tokens we'll parse. 282 | // 283 | toks := []token.Token{ 284 | {Type: "IDENT", Literal: "/bin/ls"}, 285 | {Type: "EOF", Literal: "EOF"}, 286 | } 287 | 288 | // 289 | // Now parse into statements. 290 | // 291 | fl := NewFakeLexer(toks) 292 | p := New(fl) 293 | program, err := p.Parse() 294 | 295 | // 296 | // We expect to receive an error & empty-program 297 | // 298 | if err == nil { 299 | t.Fatalf("We expected an error, but saw none!") 300 | } 301 | if len(program) != 0 { 302 | t.Fatalf("Unexpected length, wanted 0 got %d\n", len(program)) 303 | } 304 | } 305 | 306 | // TestDefault tests our unhandled-token setting. 307 | func TestDefault(t *testing.T) { 308 | 309 | // 310 | // The stream of tokens we'll parse. 311 | // 312 | toks := []token.Token{ 313 | {Type: "MOI", Literal: "KISSA"}, 314 | {Type: "EOF", Literal: "EOF"}, 315 | } 316 | 317 | // 318 | // Now parse into statements. 319 | // 320 | fl := NewFakeLexer(toks) 321 | p := New(fl) 322 | _, err := p.Parse() 323 | 324 | // 325 | // We expect one statement, with zero errors. 326 | // 327 | if err == nil { 328 | t.Fatalf("We expected an error, but saw none!") 329 | } 330 | if !strings.Contains(err.Error(), "unhandled") { 331 | t.Fatalf("We received an error, but got the wrong one: %s\n", err.Error()) 332 | } 333 | } 334 | 335 | // TestIllegal tests our error-handling. 336 | func TestIllegal(t *testing.T) { 337 | 338 | // 339 | // The stream of tokens we'll parse. 340 | // 341 | toks := []token.Token{ 342 | {Type: "ILLEGAL", Literal: "I like cake"}, 343 | {Type: "EOF", Literal: "EOF"}, 344 | } 345 | 346 | // 347 | // Now parse into statements. 348 | // 349 | fl := NewFakeLexer(toks) 350 | p := New(fl) 351 | program, err := p.Parse() 352 | 353 | // 354 | // We expect one statement, with zero errors. 355 | // 356 | if err == nil { 357 | t.Fatalf("We expected an error, but saw none!") 358 | } 359 | if len(program) != 0 { 360 | t.Fatalf("Unexpected length, wanted 0 got %d\n", len(program)) 361 | } 362 | if !strings.Contains(err.Error(), "I like cake") { 363 | t.Fatalf("Our error didn't contain the message we set: %s\n", err.Error()) 364 | } 365 | } 366 | 367 | // TestSet tests our variable-setting primitive. 368 | // 369 | // We call first of all with IDENT + "String", which is valid. Then try two 370 | // bogus versions calling with: 371 | // IDENT IDENT 372 | // STRING STRING 373 | // This should ensure that the argument testing is exercised. 374 | func TestSet(t *testing.T) { 375 | 376 | // 377 | // A program which is valid. 378 | // 379 | valid := []token.Token{ 380 | {Type: "Set", Literal: "Set"}, 381 | {Type: "IDENT", Literal: "RELESE"}, 382 | {Type: "STRING", Literal: "1.2"}, 383 | {Type: "EOF", Literal: "EOF"}, 384 | } 385 | 386 | // 387 | // Parse the program, we expect no errors 388 | // 389 | flv := NewFakeLexer(valid) 390 | pv := New(flv) 391 | program, err := pv.Parse() 392 | 393 | if err != nil { 394 | t.Fatalf("Received unexpected error parsing: %s\n", err.Error()) 395 | } 396 | if len(program) != 1 { 397 | t.Fatalf("Our program should have one statement - found %d\n", len(program)) 398 | } 399 | if len(program[0].Arguments) != 2 { 400 | t.Fatalf("Our statement should have two arguments - found %d\n", len(program[0].Arguments)) 401 | } 402 | 403 | // 404 | // Now test an invalid program. 405 | // 406 | bogus1 := []token.Token{ 407 | {Type: "Set", Literal: "Set"}, 408 | {Type: "STRING", Literal: "RELEASE"}, 409 | {Type: "STRING", Literal: "1.2"}, 410 | {Type: "EOF", Literal: "EOF"}, 411 | } 412 | 413 | // 414 | // Parse the program, we expect no errors 415 | // 416 | flb1 := NewFakeLexer(bogus1) 417 | pb1 := New(flb1) 418 | _, err = pb1.Parse() 419 | 420 | if err == nil { 421 | t.Fatalf("Expected to receive an error, got none") 422 | } 423 | 424 | if !strings.Contains(err.Error(), "as argument 1") { 425 | t.Fatalf("Our error was misleading:%s", err.Error()) 426 | } 427 | 428 | // 429 | // Test another invalid program. 430 | // 431 | bogus2 := []token.Token{ 432 | {Type: "Set", Literal: "Set"}, 433 | {Type: "IDENT", Literal: "RELEASE"}, 434 | {Type: "IDENT", Literal: "3.14"}, 435 | {Type: "EOF", Literal: "EOF"}, 436 | } 437 | 438 | // 439 | // Parse the program, we expect no errors 440 | // 441 | flb2 := NewFakeLexer(bogus2) 442 | pb2 := New(flb2) 443 | _, err = pb2.Parse() 444 | 445 | if err == nil { 446 | t.Fatalf("Expected to receive an error, got none") 447 | } 448 | 449 | if !strings.Contains(err.Error(), "as argument 2") { 450 | t.Fatalf("Our error was misleading: %s", err.Error()) 451 | } 452 | } 453 | 454 | // TestSudoHandling tests that we have sudo-handing correct. 455 | func TestSudoHandling(t *testing.T) { 456 | 457 | // 458 | // The stream of tokens we'll parse. 459 | // 460 | toks := []token.Token{ 461 | {Type: "Sudo", Literal: "Sudo"}, 462 | {Type: "EOF", Literal: "EOF"}, 463 | } 464 | 465 | // 466 | // Now parse into statements. 467 | // 468 | fl := NewFakeLexer(toks) 469 | p := New(fl) 470 | program, err := p.Parse() 471 | 472 | // 473 | // We expect one statement, with zero errors. 474 | // 475 | if err != nil { 476 | t.Fatalf("Received an unexpected error!") 477 | } 478 | if len(program) != 0 { 479 | t.Fatalf("Unexpected length, wanted 0 got %d\n", len(program)) 480 | } 481 | } 482 | 483 | // TestSudoFlag tests that we actually set the flag for a sudo-using 484 | // command. 485 | func TestSudoFlag(t *testing.T) { 486 | 487 | // 488 | // The stream of tokens we'll expecting a sudo-flag to be set. 489 | // 490 | set := []token.Token{ 491 | {Type: "Sudo", Literal: "Sudo"}, 492 | {Type: "Run", Literal: "Run"}, 493 | {Type: "STRING", Literal: "/bin/ls"}, 494 | {Type: "EOF", Literal: "EOF"}, 495 | } 496 | 497 | // 498 | // The stream of tokens we'll parse expecting no sudo-flag to be 499 | // set. 500 | // 501 | unset := []token.Token{ 502 | {Type: "Run", Literal: "Run"}, 503 | {Type: "STRING", Literal: "/bin/ls"}, 504 | {Type: "EOF", Literal: "EOF"}, 505 | } 506 | 507 | // 508 | // Now parse into statements. 509 | // 510 | fl := NewFakeLexer(set) 511 | p := New(fl) 512 | program, err := p.Parse() 513 | 514 | // 515 | // We expect one statement, with zero errors. 516 | // 517 | if err != nil { 518 | t.Fatalf("Received an unexpected error!") 519 | } 520 | if len(program) != 1 { 521 | t.Fatalf("Unexpected length, wanted 1 got %d\n", len(program)) 522 | } 523 | 524 | // 525 | // The statement will use sudo 526 | // 527 | 528 | if program[0].Sudo != true { 529 | t.Fatalf("We expected our Run command to use sudo %v", program[0]) 530 | } 531 | 532 | // 533 | // Now parse into statements. 534 | // 535 | fl = NewFakeLexer(unset) 536 | p = New(fl) 537 | program, err = p.Parse() 538 | 539 | // 540 | // We expect one statement, with zero errors. 541 | // 542 | if err != nil { 543 | t.Fatalf("Received an unexpected error!") 544 | } 545 | if len(program) != 1 { 546 | t.Fatalf("Unexpected length, wanted 1 got %d\n", len(program)) 547 | } 548 | 549 | // 550 | // The statement will not use sudo 551 | // 552 | if program[0].Sudo != false { 553 | t.Fatalf("We didn't expect our Run command to use sudo %v", program[0]) 554 | } 555 | } 556 | -------------------------------------------------------------------------------- /statement/statement.go: -------------------------------------------------------------------------------- 1 | // Package statement contains our statements. 2 | // 3 | // A statement is a parsed command from the recipe-file. 4 | // 5 | // A statement will be one of the fixed token-types we 6 | // have defined and an array of "arguments". 7 | // 8 | // For example the "Run "blah"" would become a statement 9 | // with token "Run" and argument "blah". 10 | // 11 | // We setup an array here, but the most arguments supported 12 | // is two, for the CopyFile & CopyTemplate commands. 13 | package statement 14 | 15 | import ( 16 | "github.com/skx/deployr/token" 17 | ) 18 | 19 | // Statement holds a single statement to be executed. 20 | type Statement struct { 21 | // Token is the main action "Set", "Run", etc. 22 | Token token.Token 23 | 24 | // When running a command `Run`, `IfChanged` should we use 25 | // sudo? 26 | Sudo bool 27 | 28 | // Arguments contains the arguments to the operation. 29 | Arguments []token.Token 30 | } 31 | -------------------------------------------------------------------------------- /token/token.go: -------------------------------------------------------------------------------- 1 | // Package token contains the token-types which our lexer produces, 2 | // and which our parser understands. 3 | package token 4 | 5 | // Type is a string 6 | type Type string 7 | 8 | // Token struct represent the lexer token 9 | type Token struct { 10 | Type Type 11 | Literal string 12 | } 13 | 14 | // pre-defined TokenTypes 15 | const ( 16 | EOF = "EOF" 17 | IDENT = "IDENT" 18 | ILLEGAL = "ILLEGAL" 19 | STRING = "STRING" 20 | 21 | // Our keywords. 22 | COPYFILE = "CopyFile" 23 | COPYTEMPLATE = "CopyTemplate" 24 | DEPLOYTO = "DeployTo" 25 | IFCHANGED = "IfChanged" 26 | RUN = "Run" 27 | SET = "Set" 28 | SUDO = "Sudo" 29 | ) 30 | 31 | // keywords holds our reversed keywords 32 | var keywords = map[string]Type{ 33 | "CopyFile": COPYFILE, 34 | "CopyTemplate": COPYTEMPLATE, 35 | "DeployTo": DEPLOYTO, 36 | "IfChanged": IFCHANGED, 37 | "Run": RUN, 38 | "Set": SET, 39 | "Sudo": SUDO, 40 | } 41 | 42 | // LookupIdentifier used to determinate whether identifier is keyword nor not 43 | func LookupIdentifier(identifier string) Type { 44 | if tok, ok := keywords[identifier]; ok { 45 | return tok 46 | } 47 | return IDENT 48 | } 49 | -------------------------------------------------------------------------------- /token/token_test.go: -------------------------------------------------------------------------------- 1 | package token 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | ) 7 | 8 | // Test looking up values succeeds, then fails 9 | func TestLookup(t *testing.T) { 10 | 11 | for key, val := range keywords { 12 | 13 | // Obviously this will pass. 14 | if LookupIdentifier(key) != val { 15 | t.Errorf("Lookup of %s failed", key) 16 | } 17 | 18 | // Once the keywords are uppercase they'll no longer 19 | // match - so we find them as identifiers. 20 | if LookupIdentifier(strings.ToUpper(key)) != IDENT { 21 | t.Errorf("Lookup of %s failed", key) 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /util/util.go: -------------------------------------------------------------------------------- 1 | // Package util contains a couple of utility methods. 2 | package util 3 | 4 | import ( 5 | "crypto/sha1" 6 | "encoding/hex" 7 | "io" 8 | "os" 9 | ) 10 | 11 | // FileExists reports whether the named file or directory exists. 12 | func FileExists(name string) bool { 13 | if _, err := os.Stat(name); err != nil { 14 | if os.IsNotExist(err) { 15 | return false 16 | } 17 | } 18 | return true 19 | } 20 | 21 | // HashFile returns the SHA1-hash of the contents of the specified file. 22 | func HashFile(filePath string) (string, error) { 23 | var returnSHA1String string 24 | 25 | file, err := os.Open(filePath) 26 | if err != nil { 27 | return returnSHA1String, err 28 | } 29 | 30 | defer file.Close() 31 | 32 | hash := sha1.New() 33 | 34 | if _, err := io.Copy(hash, file); err != nil { 35 | return returnSHA1String, err 36 | } 37 | 38 | hashInBytes := hash.Sum(nil)[:20] 39 | returnSHA1String = hex.EncodeToString(hashInBytes) 40 | 41 | return returnSHA1String, nil 42 | } 43 | 44 | // HasSSHAgent reports whether the SSH agent is available 45 | func HasSSHAgent() bool { 46 | if isPageantAvailable() { 47 | return true 48 | } 49 | 50 | authsock, ok := os.LookupEnv("SSH_AUTH_SOCK") 51 | if !ok { 52 | return false 53 | } 54 | if dirent, err := os.Stat(authsock); err != nil { 55 | if os.IsNotExist(err) { 56 | return false 57 | } 58 | if dirent.Mode()&os.ModeSocket == 0 { 59 | return false 60 | } 61 | } 62 | return true 63 | } 64 | -------------------------------------------------------------------------------- /util/util_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "io/ioutil" 5 | "log" 6 | "os" 7 | "testing" 8 | ) 9 | 10 | // TestHash tests the hash of known-contents are correct. 11 | func TestHash(t *testing.T) { 12 | 13 | // 14 | // The string we'll hash 15 | // 16 | input := []byte("This is a test string\n") 17 | 18 | // 19 | // Generate a temporary file 20 | // 21 | tmpfile, err := ioutil.TempFile("", "example") 22 | if err != nil { 23 | log.Fatal(err) 24 | } 25 | 26 | // 27 | // Write out the data to the file. 28 | // 29 | ioutil.WriteFile(tmpfile.Name(), input, 0644) 30 | 31 | // 32 | // Cleanup when we're done. 33 | // 34 | defer os.Remove(tmpfile.Name()) // clean up 35 | 36 | // 37 | // Now hash the contents. 38 | // 39 | content, err := HashFile(tmpfile.Name()) 40 | 41 | // 42 | // We shouldn't see an error. 43 | // 44 | if err != nil { 45 | t.Errorf("We received an unexpected error: %s\n", err.Error()) 46 | } 47 | 48 | // 49 | // Did we get what we expect? 50 | // 51 | expected := "c4af1fb1a2c5a9b67305424eda71bcd91e183f2c" 52 | if content != expected { 53 | t.Errorf("Hash failed - expected:%s received:%s", 54 | expected, content) 55 | } 56 | } 57 | 58 | // TestHashMissing tests that hashing a missing file fails appropriately. 59 | func TestHashMissing(t *testing.T) { 60 | 61 | // 62 | // Hash the contents of a missing-file 63 | // 64 | _, err := HashFile("/not/present/file.CON$!") 65 | 66 | // 67 | // We shouldn't see an error. 68 | // 69 | if err == nil { 70 | t.Errorf("We expected an error, but received none.\n") 71 | } 72 | } 73 | 74 | // TestFileExists tests our file-testing function. 75 | func TestFileExists(t *testing.T) { 76 | 77 | // 78 | // Generate a temporary file 79 | // 80 | tmpfile, err := ioutil.TempFile("", "example") 81 | if err != nil { 82 | log.Fatal(err) 83 | } 84 | 85 | // 86 | // Ensure it exists. 87 | // 88 | if !FileExists(tmpfile.Name()) { 89 | t.Errorf("Testing a present-file failed") 90 | } 91 | 92 | // 93 | // Now remove it and test it is gone. 94 | // 95 | os.Remove(tmpfile.Name()) 96 | 97 | if FileExists(tmpfile.Name()) { 98 | t.Errorf("Missing file is still present?") 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /util/util_unix.go: -------------------------------------------------------------------------------- 1 | //go:build !windows 2 | // +build !windows 3 | 4 | package util 5 | 6 | func isPageantAvailable() bool { 7 | return false 8 | } 9 | -------------------------------------------------------------------------------- /util/util_windows.go: -------------------------------------------------------------------------------- 1 | //go:build windows 2 | // +build windows 3 | 4 | package util 5 | 6 | import "github.com/davidmz/go-pageant" 7 | 8 | func isPageantAvailable() bool { 9 | return pageant.Available() 10 | } 11 | --------------------------------------------------------------------------------