diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5e89e72..ee451b4 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -8,3 +8,8 @@ updates: directory: "/" schedule: interval: "monthly" + + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "monthly" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 86e7830..bad35dd 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -17,6 +17,9 @@ jobs: - name: install bats run: | apt-get update && apt-get install -y bats jq zstd git util-linux make + - name: build + run: | + make penrun - name: run bats run: | make test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..02a1c02 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Stefan Tatschner +# +# SPDX-License-Identifier: CC0-1.0 + +/penrun +/penrun-artifacts diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 1a4a764..0000000 --- a/Dockerfile +++ /dev/null @@ -1,6 +0,0 @@ -FROM debian:latest - -RUN apt-get update && apt-get install -y bats jq zstd git shellcheck shfmt reuse make - -WORKDIR /code -ENTRYPOINT ["bash"] diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt deleted file mode 100644 index 137069b..0000000 --- a/LICENSES/Apache-2.0.txt +++ /dev/null @@ -1,73 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - - (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. - - You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - -To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000..2071b23 --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile index 9bdfeb0..d6bea7e 100644 --- a/Makefile +++ b/Makefile @@ -2,14 +2,20 @@ # # SPDX-License-Identifier: CC0-1.0 +GO ?= go + +.PHONY: penrun +penrun: + $(GO) build $(GOFLAGS) -o $@ . + .PHONY: lint lint: - find . \( -iname "penrun" -or -iname "*.sh" -or -iname "*.bats" \) | xargs shellcheck - find . \( -iname "penrun" -or -iname "*.sh" -or -iname "*.bats" \) | xargs shfmt -d + find . \( -iname "*.sh" -or -iname "*.bats" \) | xargs shellcheck + find . \( -iname "*.sh" -or -iname "*.bats" \) | xargs shfmt -d .PHONY: fmt fmt: - find . \( -iname "penrun" -or -iname "*.sh" -or -iname "*.bats" \) | xargs shfmt -w + find . \( -iname "*.sh" -or -iname "*.bats" \) | xargs shfmt -w .PHONY: test test: diff --git a/config.sh b/config.sh deleted file mode 100644 index 9b5efaf..0000000 --- a/config.sh +++ /dev/null @@ -1,52 +0,0 @@ -# SPDX-FileCopyrightText: AISEC Pentesting Team -# -# SPDX-License-Identifier: Apache-2.0 - -################################################################################ -# Penrun config -# NOTE: These variables are sourced by the shell. -# They are not required to be exported, but could be. -# Please note that bash arrays cannot be exported! - -# If this variable is set then penrun creates the artifacts folder hierarchy -# at this location instead of $PWD. -# -# PENRUN_ARTIFACTS_BASE="$HOME/penrun-artifacts" - -# This variable specifies the compression tool where the output is piped -# to. Since zstd provides multithreading capabilities, it is the fastest -# in all out-of-the-box scenarios. Argument must be a bash array. -# -# PENRUN_COMPRESSION_COMMAND=("gzip" "--stdout") -# PENRUN_COMPRESSION_COMMAND=("zstd" "-T0") - -# Specify the extension that is added to the OUTPUT file. -# shellcheck disable=SC2034 -# PENRUN_OUTPUT_EXTENSION=".zst" - -# Pipe penrun output to an external program. -# Argument must be a bash array. -# PENRUN_PIPE_COMMAND=() - -# Add Default arguments which be appended to each penrun run. -# Argument must be a bash array. -# PENRUN_DEFAULT_ARGS=() - -# Lock on a specifc file. -# Useful to make sure, that only one instance of penrun -# can access a particular resource. -# PENRUN_LOCK="/path/to/lock" - -################################################################################ -# Miscellaneous config - -# Perform this function prior to each penrun run. -# Can be used e.g. for power cycles or sending triggers -# pre_run() { -# echo "I am a pre_run hook!" -# } - -# Perform this function after to each penrun run. -# post_run() { -# echo "I am a post_run hook!" -# } diff --git a/flake.nix b/flake.nix index a5156a7..cd753b2 100644 --- a/flake.nix +++ b/flake.nix @@ -12,14 +12,27 @@ let pkgs = nixpkgs.legacyPackages.x86_64-linux; in { devShell.x86_64-linux = pkgs.mkShell { - buildInputs = with pkgs; [ + buildInputs = with pkgs; [ + go + gopls bats + reuse + shellcheck + shfmt nodePackages_latest.bash-language-server ]; shellHook = '' LD_LIBRARY_PATH=${pkgs.lib.makeLibraryPath [stdenv.cc.cc]} ''; }; + packages.x86_64-linux.default = + pkgs.buildGoModule { + pname = "penrun"; + src = self; + version = self.lastModifiedDate; + buildInputs = [ pkgs.go ]; + vendorHash = "sha256-rUQ/iXG/lnvi01NXBOsu3CoG3YrYUFwPZDadTFThH3g="; + }; formatter.x86_64-linux = pkgs.nixpkgs-fmt; }; } diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..22004e5 --- /dev/null +++ b/go.mod @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: Stefan Tatschner +// +// SPDX-License-Identifier: MIT + +module github.com/rumpelsepp/penrun + +go 1.21.5 + +require github.com/pelletier/go-toml/v2 v2.1.1 + +require ( + github.com/alecthomas/kong v0.8.1 + github.com/alecthomas/kong-toml v0.1.0 + github.com/klauspost/compress v1.17.4 +) + +require github.com/pelletier/go-toml v1.9.5 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..2ff273f --- /dev/null +++ b/go.sum @@ -0,0 +1,32 @@ +github.com/alecthomas/assert/v2 v2.1.0 h1:tbredtNcQnoSd3QBhQWI7QZ3XHOVkw1Moklp2ojoH/0= +github.com/alecthomas/assert/v2 v2.1.0/go.mod h1:b/+1DI2Q6NckYi+3mXyH3wFb8qG37K/DuK80n7WefXA= +github.com/alecthomas/kong v0.8.1 h1:acZdn3m4lLRobeh3Zi2S2EpnXTd1mOL6U7xVml+vfkY= +github.com/alecthomas/kong v0.8.1/go.mod h1:n1iCIO2xS46oE8ZfYCNDqdR0b0wZNrXAIAqro/2132U= +github.com/alecthomas/kong-toml v0.1.0 h1:jKrdGj/G0mkHGbOV5a+Cok3cTDZ+Qxa5CBq177gPKUA= +github.com/alecthomas/kong-toml v0.1.0/go.mod h1:aDIxp+T6kJZY9zLThZX6qI9xxUlQgYlvqmw7PI//7/Y= +github.com/alecthomas/repr v0.1.0 h1:ENn2e1+J3k09gyj2shc0dHr/yjaWSHRlrJ4DPMevDqE= +github.com/alecthomas/repr v0.1.0/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4= +github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= +github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= +github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= +github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/go.sum.license b/go.sum.license new file mode 100644 index 0000000..cd213ca --- /dev/null +++ b/go.sum.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: Stefan Tatschner + +SPDX-License-Identifier: CC0-1.0 diff --git a/internal/config.go b/internal/config.go new file mode 100644 index 0000000..d9c775a --- /dev/null +++ b/internal/config.go @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: Stefan Tatschner +// +// SPDX-License-Identifier: MIT + +package penrun + +import ( + "errors" + "os" + "path/filepath" + + "github.com/pelletier/go-toml/v2" +) + +type Config struct { + CLI []string `kong:"arg,passthrough,help='Command to invoke'"` + ArtifactsDir string `kong:"short='d',help='Set artifacts_dir to this directory'"` + ArtifactsBase string `kong:"short='b',help='Set artifacts_base where the artifacts hierarchy (including LATEST) will be created'"` + Batched bool `kong:"short='B',help='Run several commands in parallel'"` + PreHook string `kong:"help='Shell script that runs before the command'"` + PostHook string `kong:"help='Shell script that runs after the command'"` +} + +const ConfigFileName = "penrun.toml" + +func fileExists(path string) (bool, error) { + if _, err := os.Stat(path); err == nil { + return true, nil + } else if errors.Is(err, os.ErrNotExist) { + return false, nil + } else { + return false, err + } +} + +func FindConfigFile(path string) (string, error) { + if p := os.Getenv("PENRUN_CONFIG"); p != "" { + return p, nil + } + + confPath := filepath.Join(path, ConfigFileName) + exists, err := fileExists(confPath) + if err != nil { + return "", err + } + if exists { + return confPath, nil + } + + if gitRoot, err := detectGitRoot(path); err != nil { + confPath := filepath.Join(gitRoot, ConfigFileName) + exists, err := fileExists(confPath) + if err != nil { + return "", err + } + if exists { + return confPath, nil + } + } + + confDir, err := os.UserConfigDir() + if err == nil { + confPath := filepath.Join(confDir, "penrun", ConfigFileName) + exists, err := fileExists(confPath) + if err != nil { + return "", err + } + if exists { + return confPath, nil + } + } + + confPath = filepath.Join("/etc/penrun", "penrun.toml") + exists, err = fileExists(confPath) + if err != nil { + return "", err + } + if exists { + return confPath, nil + } + + return "", os.ErrNotExist +} + +func ParseConfigFile(path string) (*Config, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + var config Config + err = toml.Unmarshal(data, &config) + if err != nil { + return nil, err + } + return &config, nil +} diff --git a/internal/exitcodes.go b/internal/exitcodes.go new file mode 100644 index 0000000..c00c18e --- /dev/null +++ b/internal/exitcodes.go @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: Stefan Tatschner +// +// SPDX-License-Identifier: MIT + +// Preferred system exit codes as defined by sysexits.h +// +// Exit code constants intended to be passed to `sys.exit()`; +// inspired by https://docs.rs/exitcode. + +package penrun + +const ( + // Successful exit + ExitOK = 0 + + // The command was used incorrectly, e.g., with the + // wrong number of arguments, a bad flag, a bad syntax + // in a parameter, etc. + ExitUsage = 64 + + // The input data was incorrect in some way. This + // should only be used for user's data and not system + // files. + ExitDataErr = 65 + + // An input file (not a system file) did not exist or + // was not readable. This could also include errors + // like "No message" to a mailer (if it cared to + // catch it). + ExitNoInput = 66 + + // The user specified did not exist. This might be + // used for mail addresses or remote logins. + ExitNoUser = 67 + + // The host specified did not exist. This is used in + // mail addresses or network requests. + ExitNoHost = 68 + + // A service is unavailable. This can occur if a + // support program or file does not exist. This can also + // be used as a catchall message when something you + // wanted to do doesn't work, but you don't know why. + ExitUnavailable = 69 + + // An internal software error has been detected. This + // should be limited to non-operating system related + // errors as possible. + ExitSoftware = 70 + + // An operating system error has been detected. This + // is intended to be used for such things as "cannot + // fork", "cannot create pipe", or the like. It + // includes things like getuid returning a user that + // does not exist in the passwd file. + ExitOSErr = 71 + + // Some system file (e.g., /etc/passwd, /var/run/utmp, + // etc.) does not exist, cannot be opened, or has some + // sort of error (e.g., syntax error). + ExitOSFile = 72 + + // A (user specified) output file cannot be created. + ExitCantCreat = 73 + + // An error occurred while doing I/O on some file. + ExitIOErr = 74 + + // Temporary failure, indicating something that is not + // really an error. In sendmail, this means that a + // mailer (e.g.) could not create a connection, and + // the request should be reattempted later. + ExitTempfail = 75 + + // The remote system returned something that was + // "not possible" during a protocol exchange. + ExitProtocol = 76 + + // You did not have sufficient permission to perform + // the operation. This is not intended for file system + // problems, which should use `NOINPUT` or `CANTCREAT`, + // but rather for higher level permissions. + ExitNoPerm = 77 + + // Something was found in an unconfigured or misconfigured state. + ExitConfig = 78 +) diff --git a/internal/git.go b/internal/git.go new file mode 100644 index 0000000..4b8e63a --- /dev/null +++ b/internal/git.go @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: Stefan Tatschner +// +// SPDX-License-Identifier: MIT + +package penrun + +import ( + "errors" + "fmt" + "os" + "path/filepath" +) + +// Extracted from: https://github.com/go-git/go-git/issues/74 + +func isGitDir(path string) (bool, error) { + markers := []string{"HEAD", "objects", "refs"} + + for _, marker := range markers { + _, err := os.Stat(filepath.Join(path, marker)) + if err == nil { + continue + } + if !errors.Is(err, os.ErrNotExist) { + // unknown error + return false, err + } else { + return false, nil + } + } + + return true, nil +} + +func detectGitPath(path string) (string, error) { + // normalize the path + path, err := filepath.Abs(path) + if err != nil { + return "", err + } + + for { + fi, err := os.Stat(filepath.Join(path, ".git")) + if err == nil { + if !fi.IsDir() { + return "", fmt.Errorf(".git exist but is not a directory") + } + return filepath.Join(path, ".git"), nil + } + if !os.IsNotExist(err) { + // unknown error + return "", err + } + + // detect bare repo + ok, err := isGitDir(path) + if err != nil { + return "", err + } + if ok { + return path, nil + } + + if parent := filepath.Dir(path); parent == path { + return "", fmt.Errorf(".git not found") + } else { + path = parent + } + } +} + +func detectGitRoot(path string) (string, error) { + p, err := detectGitPath(".") + if err != nil { + return "", err + } + return filepath.Dir(p), nil +} diff --git a/internal/testrun.go b/internal/testrun.go new file mode 100644 index 0000000..e17bfef --- /dev/null +++ b/internal/testrun.go @@ -0,0 +1,309 @@ +// SPDX-FileCopyrightText: Stefan Tatschner +// +// SPDX-License-Identifier: MIT + +package penrun + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "os" + "os/exec" + "os/signal" + "path/filepath" + "runtime/debug" + "strings" + "syscall" + "time" + + "github.com/klauspost/compress/zstd" +) + +type TestRun struct { + *Config + + artifactsDirNormalized string + createLatestLink bool +} + +func NewTestRun(config *Config) *TestRun { + return &TestRun{Config: config} +} + +func (tr *TestRun) createEnvironment() []string { + // TODO: sudo cleans env variables; reuse this filer maybe? + env := os.Environ() + env = append(env, fmt.Sprintf("PENRUN_CLI_STRING=%s", strings.Join(tr.CLI, " "))) + env = append(env, fmt.Sprintf("PENRUN_ARTIFACTS_DIR=%s", tr.artifactsDirNormalized)) + env = append(env, fmt.Sprintf("PENRUN_INVOCATION=%s", strings.Join(os.Args, " "))) + return env +} + +func (tr *TestRun) prepareRun() error { + artifactsDir := "" + if tr.ArtifactsDir != "" { + artifactsDir = tr.ArtifactsDir + tr.createLatestLink = false + } else { + if tr.ArtifactsBase != "" { + artifactsDir = tr.ArtifactsBase + } else { + artifactsDir = "penrun-artifacts" + } + + artifactsDir = filepath.Join(artifactsDir, tr.CLI[0], fmt.Sprintf("run-%s", time.Now().Format(time.RFC3339Nano))) + tr.createLatestLink = true + } + + var err error + artifactsDir, err = filepath.Abs(artifactsDir) + if err != nil { + return err + } + + if err := os.MkdirAll(artifactsDir, 0755); err != nil { + return err + } + tr.artifactsDirNormalized = artifactsDir + + return nil +} + +func (tr *TestRun) runHook(cli string) error { + cmd := exec.Command("/bin/sh", "-c", cli) + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr + cmd.Stdout = os.Stdout + return cmd.Run() +} + +func (tr *TestRun) runPreHook() error { + if tr.PreHook != "" { + return tr.runHook(tr.PreHook) + } + return nil +} + +func (tr *TestRun) runPostHook() error { + if tr.PostHook != "" { + return tr.runHook(tr.PostHook) + } + return nil +} + +func (tr *TestRun) run() (*exec.Cmd, error) { + cmd := exec.Command(tr.CLI[0], tr.CLI[1:]...) + + outfile, err := os.Create(filepath.Join(tr.artifactsDirNormalized, "OUTPUT.zst")) + if err != nil { + return nil, err + } + + zstdEncoder, err := zstd.NewWriter(outfile) + if err != nil { + return nil, err + } + + cmd.Env = tr.createEnvironment() + + rp, wp := io.Pipe() + cmd.Stderr = wp + cmd.Stdout = wp + cmd.Stdin = os.Stdin + + teeReader := io.TeeReader(rp, zstdEncoder) + + if err := cmd.Start(); err != nil { + return nil, err + } + + // Copy stdout/stderr into the teeReader, aka. the terminal and OUTPUT.zst. + errCh := make(chan error) + go func() { + _, err := io.Copy(os.Stderr, teeReader) + errCh <- err + }() + + // Signal Handling + go func() { + sigCh := make(chan os.Signal) + signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT) + recvSig := <-sigCh + + // Forward the catched signal to the child process. + cmd.Process.Signal(recvSig) + }() + + // Ignore errors here, since failed runs need to be + // tracked as well. + // TODO: are there errors that need to be handled? + cmd.Wait() + + if err := wp.Close(); err != nil { + return nil, err + } + + err = <-errCh + if err != nil { + return nil, err + } + + if err := zstdEncoder.Close(); err != nil { + return nil, err + } + if err := outfile.Close(); err != nil { + return nil, err + } + + return cmd, nil +} + +func (tr *TestRun) getFinishedRun(cmd *exec.Cmd, startTime time.Time) *FinishedRun { + buildInfoStr := "unknown" + buildInfo, ok := debug.ReadBuildInfo() + if ok { + buildInfoStr = buildInfo.String() + } + hostname, err := os.Hostname() + if err != nil { + hostname = "unknown" + } + cwd, err := os.Getwd() + if err != nil { + cwd = "unknown" + } + + endTime := time.Now() + + exitCode := cmd.ProcessState.ExitCode() + + // If the process was terminated by a signal, then extract the real exit code. + // Typically it is 128 + SIGNAL_NUMBER. + if exitCode == -1 { + waitStatus := cmd.ProcessState.Sys().(syscall.WaitStatus) + exitCode = int(128 + waitStatus.Signal()) + } + + return &FinishedRun{ + CLI: tr.CLI, + CLIString: strings.Join(tr.CLI, " "), + ArtifactsDir: tr.artifactsDirNormalized, + ExitCode: exitCode, + StartTime: startTime, + EndTime: endTime, + Duration: endTime.Sub(startTime), + Environ: tr.createEnvironment(), + Hostname: hostname, + CWD: cwd, + PenrunVersion: buildInfoStr, + } +} + +func (tr *TestRun) Run() (*FinishedRun, error) { + if err := tr.prepareRun(); err != nil { + return nil, err + } + + if tr.PreHook != "" { + if err := tr.runPreHook(); err != nil { + slog.Warn(fmt.Sprintf("pre hook failed: %s", err)) + } + } + + startTime := time.Now() + + cmd, err := tr.run() + if err != nil { + return nil, err + } + + signal.Reset() + + if tr.PostHook != "" { + if err := tr.runPostHook(); err != nil { + slog.Warn(fmt.Sprintf("post hook failed: %s", err)) + } + } + + return tr.getFinishedRun(cmd, startTime), nil +} + +type FinishedRun struct { + ArtifactsDir string `json:"artifacts_dir"` + CLI []string `json:"cli"` + CLIString string `json:"cli_string"` + CWD string `json:"cwd"` + ExitCode int `json:"exit_code"` + StartTime time.Time `json:"start_time"` + EndTime time.Time `json:"end_time"` + Duration time.Duration `json:"duration"` + Environ []string `json:"environ"` + Hostname string `json:"hostname"` + PenrunVersion string `json:"penrun_version"` +} + +func RunCommand(config *Config) (*FinishedRun, error) { + tr := NewTestRun(config) + fr, err := tr.Run() + if err != nil { + return nil, err + } + + if err := fr.createArtifacts(); err != nil { + return nil, err + } + + return fr, nil +} + +func (fr *FinishedRun) createMetaFile() error { + data, err := json.Marshal(fr) + if err != nil { + return err + } + + var ( + metaPath = filepath.Join(fr.ArtifactsDir, "META.json.zst") + encoder, _ = zstd.NewWriter(nil) + outData = make([]byte, 0, len(data)) + ) + outData = encoder.EncodeAll(append(data, '\n'), outData) + + if err := os.WriteFile(metaPath, outData, 0644); err != nil { + return nil + } + return nil +} + +func (fr *FinishedRun) createLatestSymlink() error { + latestLinkPath := filepath.Join(filepath.Dir(fr.ArtifactsDir), "LATEST") + if _, err := os.Stat(latestLinkPath); !errors.Is(err, os.ErrNotExist) { + if err := os.Remove(latestLinkPath); err != nil { + return err + } + } + + // The LATEST symlink must have a relative target, such that the + // directory hierarchy can be moved around without breaking the link. + if err := os.Symlink(filepath.Base(fr.ArtifactsDir), latestLinkPath); err != nil { + return err + } + return nil +} + +func (fr *FinishedRun) createArtifacts() error { + if err := fr.createMetaFile(); err != nil { + return err + } + if err := fr.createLatestSymlink(); err != nil { + return err + } + return nil +} + +func (fr *FinishedRun) Success() bool { + return fr.ExitCode == 0 +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..f2c21bf --- /dev/null +++ b/main.go @@ -0,0 +1,53 @@ +// SPDX-FileCopyrightText: Stefan Tatschner +// +// SPDX-License-Identifier: MIT + +package main + +import ( + "errors" + "fmt" + "os" + + "github.com/alecthomas/kong" + "github.com/alecthomas/kong-toml" + "github.com/rumpelsepp/penrun/internal" +) + +func main() { + var ( + config penrun.Config + ctx *kong.Context + ) + + cwd, err := os.Getwd() + if err != nil { + fmt.Fprintln(os.Stderr, err) + // TODO: Use exit codes from FreeBSD + os.Exit(1) + } + + configPath, err := penrun.FindConfigFile(cwd) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + fmt.Fprintln(os.Stderr, err) + // TODO: Use exit codes from FreeBSD + os.Exit(1) + } + } + + if configPath != "" { + ctx = kong.Parse(&config, kong.Configuration(kongtoml.Loader, configPath)) + } else { + ctx = kong.Parse(&config) + } + + fr, err := penrun.RunCommand(&config) + if err != nil { + fmt.Fprintln(os.Stderr, err) + // TODO: Use exit codes from FreeBSD + ctx.Exit(1) + } + + os.Exit(fr.ExitCode) +} diff --git a/penrun b/penrun deleted file mode 100755 index 6fc7940..0000000 --- a/penrun +++ /dev/null @@ -1,461 +0,0 @@ -#!/usr/bin/env bash - -# SPDX-FileCopyrightText: AISEC Pentesting Team -# -# SPDX-License-Identifier: Apache-2.0 - -set -u -set -o pipefail - -PENRUN_DEFAULT_ARGS=() -PENRUN_PIPE_COMMAND=() -PENRUN_COMPRESSION_COMMAND=("zstd" "-T0") -PENRUN_OUTPUT_EXTENSION=".zst" - -EXIT_CODE_JOB_FAILED=1 -EXIT_CODE_FAILED_FIRST=2 - -# https://www.freebsd.org/cgi/man.cgi?query=sysexits -EXIT_CODE_EX_USAGE=64 -EXIT_CODE_EX_SOFTWARE=70 - -log() { - printf "%s\n" "$*" >&2 -} - -die() { - log "error: $*" - exit "$EXIT_CODE_EX_SOFTWARE" -} - -search_configs() { - local global_conf="/etc/penrun/config.sh" - if [[ -f "$global_conf" ]]; then - export PENRUN_GLOBAL_CONF="$global_conf" - fi - - local user_conf="$HOME/.config/penrun/config.sh" - if [[ -f "$user_conf" ]]; then - export PENRUN_USER_CONF="$user_conf" - fi - - local git_root - if git_root="$(git rev-parse --show-toplevel 2>/dev/null)"; then - local git_root_conf="$git_root/.penrun.sh" - if [[ -f "$git_root_conf" ]]; then - export PENRUN_GIT_ROOT_CONF="$git_root_conf" - fi - fi - - local pwd_conf="$PWD/.penrun.sh" - if [[ -f "$pwd_conf" ]]; then - export PENRUN_PWD_CONF="$pwd_conf" - fi -} - -search_and_source_config() { - search_configs - - if [[ -n "${PENRUN_PWD_CONF-}" ]]; then - # shellcheck source=/dev/null - source "$PENRUN_PWD_CONF" - return 0 - fi - if [[ -n "${PENRUN_GIT_ROOT_CONF-}" ]]; then - # shellcheck source=/dev/null - source "$PENRUN_GIT_ROOT_CONF" - return 0 - fi - if [[ -n "${PENRUN_USER_CONF-}" ]]; then - # shellcheck source=/dev/null - source "$PENRUN_USER_CONF" - return 0 - fi - if [[ -n "${PENRUN_GLOBAL_CONF-}" ]]; then - # shellcheck source=/dev/null - source "$PENRUN_GLOBAL_CONF" - return 0 - fi -} - -lock_or_wait() { - if [[ -n "${PENRUN_LOCK-}" ]]; then - mkdir -p "$(dirname "${PENRUN_LOCK}")" && touch "${PENRUN_LOCK}" 2>/dev/null - exec 87<"${PENRUN_LOCK}" - - if ! flock -n 87; then - log "Could not aquire lock ${PENRUN_LOCK}" - log "Waiting for lock…" - flock 87 || die "Lock cannot be aquired" - log "… aquired lock." - fi - fi -} - -# $1: path -mkdir_if_not_exists() { - if [[ ! -d "$1" ]]; then - mkdir -p "$1" - fi -} - -# $1: name -isfunction() { - if [[ "$(type -t "$1")" == "function" ]]; then - return 0 - fi - return 1 -} - -# $1: path -isabsolute() { - if [[ "${1:0:1}" == "/" ]]; then - return 0 - fi - return 1 -} - -# Create META file in passed directory. -# $1 : artifacts dir -# $2 : exit_code -# $3 : start time -# $4…n: command -meta_create() { - local filepath="$1/META.json" - local exit_code="$2" - local start_time="$3" - local cmd - local end_time - shift 3 - - cmd="$(printf ', \"%s\"' "$@")" - cmd="[${cmd:2}]" - end_time="$(date --iso-8601=seconds)" - - jq -n --argjson cmd "$cmd" \ - --argjson exit_code "$exit_code" \ - --arg start_time "$start_time" \ - --arg end_time "$end_time" \ - '{command: $cmd, start_time: $start_time, end_time: $end_time, exit_code: $exit_code}' \ - >"$filepath" -} - -# $1 : artifacts dir -# $2…$n: command -run_hook() { - local artifactsdir="$1" - local raw_out - shift 1 - - if [[ "$1" == "pre_run" ]]; then - raw_out="$artifactsdir/PRERUN_OUTPUT" - elif [[ "$1" == "post_run" ]]; then - raw_out="$artifactsdir/POSTRUN_OUTPUT" - else - die "BUG: invalid hook" - fi - - "$@" | tee "$raw_out" -} - -# $1 : skip_hooks -# $2 : use_default_args -# $3 : artifactsdir -# $4 : tag -# $5 : command fragment from stdin -# $6…$n: cmd -prepare_and_run_cmd() { - local skip_hooks="$1" - local use_default_args="$2" - local artifactsdir="$3" - local tag="$4" - local fragment="$5" - local artifacts_base_default="$PWD/penrun-artifacts" - shift 5 - - local scriptname - scriptname="$(basename "$1")" - # Strip the fileending here, otherwise a - # tag might be stripped as well. - scriptname="${scriptname%.*}" - - local cmd_escaped - cmd_escaped="$(printf "%q " "$@")" - - if [[ -n "$tag" ]]; then - scriptname="$scriptname-$tag" - fi - if [[ -z "${artifactsdir-}" ]]; then - artifactsdir="${PENRUN_ARTIFACTS_BASE:-$artifacts_base_default}/${scriptname}/run-$(date +%Y%m%d-%H%M%S.%N)" - fi - if isfunction "cmd_to_artifactsdir"; then - if ! artifactsdir="$(cmd_to_artifactsdir "$artifactsdir" "$fragment" "$tag" "$cmd_escaped")"; then - die "artifactsdir could not be built" - fi - fi - if ! isabsolute "$artifactsdir"; then - artifactsdir="$PWD/$artifactsdir" - fi - - mkdir_if_not_exists "$artifactsdir" - - if ((!use_default_args)); then - PENRUN_DEFAULT_ARGS=() - fi - - # Environment variables PENRUN_COMMAND and PENRUN_ARTIFACTS - # are scoped to the relevant run. Otherwise they would overwrite - # themselves when batched mode with parallel jobs is used. - if ((!skip_hooks)) && isfunction "pre_run"; then - if ! PENRUN_COMMAND="$cmd_escaped" PENRUN_ARTIFACTS="$artifactsdir" \ - run_hook "$artifactsdir" "pre_run"; then - die "pre_run hook failed" - fi - fi - - local ret - PENRUN_COMMAND="$cmd_escaped" PENRUN_ARTIFACTS="$artifactsdir" run_cmd \ - "$artifactsdir" \ - "$@" - ret="$?" - - if ((!skip_hooks)) && isfunction "post_run"; then - if ! PENRUN_COMMAND="$cmd_escaped" PENRUN_ARTIFACTS="$artifactsdir" \ - run_hook "$artifactsdir" "post_run"; then - die "post_run hook failed" - fi - fi - - return "$ret" -} - -# Run a command in a subshell with SIGINT ignored. -# $1…$n: command -mask_sigint() { - ( - trap '' SIGINT - "$@" - ) -} - -# $1 : artifacts dir -# $2…$n: command -run_cmd() { - local cmd - local latest - local start - local artifactsdir="$1" - local raw_out="$artifactsdir/OUTPUT${PENRUN_OUTPUT_EXTENSION}" - local envfile="$artifactsdir/ENV" - latest="$(dirname "$artifactsdir")/LATEST" - shift 1 - - mkdir_if_not_exists "$artifactsdir" - - printenv >"$envfile" - ln -sfnr "$artifactsdir" "$latest" - - start="$(date --iso-8601=seconds)" - - trap 'meta_create "$artifactsdir" "$?" "$start" "$@" "${PENRUN_DEFAULT_ARGS[@]}"; trap - RETURN' RETURN - - if (("${#PENRUN_PIPE_COMMAND[@]}" > 0)); then - "$@" "${PENRUN_DEFAULT_ARGS[@]}" 2>&1 | - mask_sigint tee -p >(mask_sigint "${PENRUN_COMPRESSION_COMMAND[@]}" >"$raw_out") | - mask_sigint "${PENRUN_PIPE_COMMAND[@]}" - else - "$@" "${PENRUN_DEFAULT_ARGS[@]}" 2>&1 | - mask_sigint tee -p >(mask_sigint "${PENRUN_COMPRESSION_COMMAND[@]}" >"$raw_out") - fi -} - -usage() { - echo "penrun [-bnsuh] [-C CMD] [-S SEC] [-T TPL] [-c FILE]" - echo " [-d DIR] [-e EXT] [-j JOBS] [-p CMD] [-t TAG] COMMAND" - echo "" - echo "options:" - echo " -C CMD Compression command for OUTPUT" - echo " -S SEC Sleep this time beetween jobs" - echo " -T TPL A command template for batch processing" - echo " -b Use batched mode for parallel processing. Commands are read from stdin." - echo " -c FILE Use this config file exclusively" - echo " -d DIR Use artifactsdir DIR" - echo " -e EXT File extension for OUTPUT" - echo " -j JOBS In batch mode process these number of jobs at a time" - echo " -n Do not use DEFAULT_ARGS from config" - echo " -p CMD Pipe output through CMD" - echo " -s Skip hooks" - echo " -t TAG Add a tag to this run" - echo " -u Run until the first error occurs and exit" - echo " -h Show this page and exit." -} - -dienocmd() { - log "error: no command specified" - exit "$EXIT_CODE_EX_USAGE" -} - -main() { - local artifactsdir="" - local batch_mode="" - local forced_config="" - local jobs="1" - local run_until="0" - local skip_hooks="0" - local sleep_time="0" - local tag="" - local template="" - local use_default_args="1" - - while getopts "C:S:T:bc:d:e:j:np:st:uh" arg; do - case "$arg" in - C) read -r -a PENRUN_COMPRESSION_COMMAND <<<"$OPTARG" ;; - S) sleep_time="$OPTARG" ;; - T) template="$OPTARG" ;; - b) batch_mode=1 ;; - c) forced_config="$OPTARG" ;; - d) artifactsdir="$OPTARG" ;; - e) PENRUN_OUTPUT_EXTENSION="$OPTARG" ;; - j) jobs="$OPTARG" ;; - n) use_default_args=0 ;; - p) read -r -a PENRUN_PIPE_COMMAND <<<"$OPTARG" ;; - s) skip_hooks=1 ;; - t) tag="$OPTARG" ;; - u) run_until=1 ;; - - h) usage && exit 0 ;; - *) usage && exit 1 ;; - esac - done - shift $((OPTIND - 1)) - - if [[ -n "$template" ]]; then - if [[ "$template" =~ .*\" || "$template" =~ .*\' ]]; then - die "-T must not contain any quotes!" - fi - fi - - local cmds - if ((batch_mode)); then - mapfile -t cmds 1)); then - log "Scheduling job '$cmd'." - - # Hooks are disabled for jobcontrol. - # Enabled hooks might cause scary race conditions. - # Further, with enabled job control the terminal output - # is undesired. - PENRUN_PIPE_COMMAND=() - prepare_and_run_cmd \ - "1" \ - "$use_default_args" \ - "$artifactsdir" \ - "$tag" \ - "$fragment" \ - "${cmd_arr[@]}" >/dev/null & - - # Spawn jobs until the configured limit via -j - # is reached. Then await them one at a time. - cur_jobs="$((cur_jobs + 1))" - if ((cur_jobs < jobs)); then - continue - fi - - wait -n - cur_jobs="$((cur_jobs - 1))" - log "Job terminated. Currently active jobs: $cur_jobs." - else - if [[ -n "${PENRUN_BATCH_MODE-}" ]]; then - log "Starting command '$cmd'." - fi - - prepare_and_run_cmd \ - "$skip_hooks" \ - "$use_default_args" \ - "$artifactsdir" \ - "$tag" \ - "$fragment" \ - "${cmd_arr[@]}" - fi - - ret="$?" - - if [[ -n "${PENRUN_BATCH_MODE-}" ]]; then - if ((run_until)) && ((ret != 0)); then - return "$((-EXIT_CODE_FAILED_FIRST))" - elif ((ret != 0)); then - r="$((-EXIT_CODE_JOB_FAILED))" - fi - fi - - sleep "$sleep_time" - done - - # Cleanup leftover jobs. - while ((cur_jobs > 0)); do - wait -n - cur_jobs="$((cur_jobs - 1))" - log "Job terminated. Currently active jobs: $cur_jobs." - if ((run_until)) && ((ret != 0)); then - return "$((-EXIT_CODE_FAILED_FIRST))" - elif ((ret != 0)); then - r="$((-EXIT_CODE_JOB_FAILED))" - fi - done - - if ((r != 0)); then - ret="$r" - fi - - return "$ret" -} - -main "$@" diff --git a/penrun.1.rst b/penrun.1.rst deleted file mode 100644 index fe75af7..0000000 --- a/penrun.1.rst +++ /dev/null @@ -1,247 +0,0 @@ -.. SPDX-FileCopyrightText: AISEC Pentesting Team -.. -.. SPDX-License-Identifier: CC0-1.0 - -penrun -====== - -Synopsis --------- - -:: - - penrun [ARGS] COMMAND… - -Description ------------ - -penrun(1) is a runner intended for invoking tests; any shellcommand can be started. -A well defined directory structure is created for the so called "artifacts". -COMMAND is run within this directory which is there for any results (e.g. pcap files, penlog artifacts, …). -For more information about the artifacts directory, see the ARTIFACTS section. - -An experimental batched mode is supported. -``penrun`` can read a list of commands or command fragments (see ``-T``) and process them sequentially or in parallel. - -Arguments ---------- - -The following arguments are understood by penrun. - -.. cmdoption:: -C CMD - - The output of ``COMMAND`` is piped through the command, specified as ``CMD``. - The program specified with ``CMD`` must read from stdin and write to stdout. - Example: ``zstd -T0``. See also: ``-e``. - -.. cmdoption:: -S SEC - - Sleep this amount of time (same format as ``sleep(1)`` accepts) between commands. - Only evaluated in batched mode. - -.. cmdoption:: -T TPL - - A template string for command artifacts used by penrun's batched mode. - The string ``%s`` is expanded to the current line on penrun's stdin. - Example: If TPL is ``curl -LO %s`` and a list of URLs is piped to penrun, then penrun expands ``%s`` to the current URL and invoces ``curl`` with ``curl -LO URL``. - -.. cmdoption:: -c FILE - - Source the config file ``FILE`` instead searching in the known paths. - -.. cmdoption:: -d DIR - - Use ``DIR`` for all artifacts instead of creating a new one. - -.. cmdoption:: -e EXT - - Use ``EXT`` as a file extension to the OUTPUT file in the artifactsdir. - -.. cmdoption:: -j JOBS - - Run ``JOBS`` in parallel when operating in batched mode. - -.. cmdoption:: -n - - Ignore the ``PENRUN_DEFAULT_ARGS`` from the config. - -.. cmdoption:: -p CMD - - Pipe the output of ``COMMAND`` through the ``CMD`` specified with ``-p``. - -.. cmdoption:: -s - - Do not run any hooks this time. - -.. cmdoption:: -t TAG - - Adds a suffix to the artifactsdir. - If the COMMAND is ``ls`` and tag is ``foo`` then the artifactsdir might be ``ls-foo/run-20200806-113712``. - -.. cmdoption:: -u - - In batched mode, abort when the first error occurs. - -.. cmdoption:: -h - - Show the usage help page and exit - - -Config Files ------------- - -Customization is possible with config files, which are plain boring bash files. -The following locations are searched in this order. -The filepath of each config is exported as an environment variable. - -* ``PENRUN_PWD_CONF``: ``$PWD/.penrun.sh`` -* ``PENRUN_GIT_ROOT_CONF``: ``$GITROOT/.penrun.sh`` (``$GITROOT`` is obtained via ``git rev-parse --show-toplevel``) -* ``PENRUN_USER_CONF``: ``$HOME/.config/penrun/config.sh`` -* ``PENRUN_GLOBAL_CONF``: ``/etc/penrun/config.sh`` - -If **one** of these files is found, automatic sourcing of config files stops. -This choice was made in order to avoid confusing about old and forgotten config files. -Config loading has to be explicit. -If a config hierarchy is required a snippet like the following could be placed in the configuration: - -:: - - # stuff … - - if [[ -n "${PENRUN_GLOBAL_CONF-}" ]]; then - source "$PENRUN_GLOBAL_CONF" - fi - -If one of these variables (``PENRUN_PWD_CONF``, …) is not defined, then the config file does not exist. - -Config Variables ----------------- - -The following variables have special meaning in a penrun(1) config script. - -PENRUN_DEFAULT_ARGS (array) - These arguments are prepended to the arguments of COMMAND. - If COMMAND is ``ls -lah`` and DEFAULT_ARGS is ``(--foo --bar)``, then the following command is invoked: ``ls --foo --bar -lah``. - -PENRUN_ARTIFACTS_BASE - If this variable is set then penrun creates the artifacts folder hierarchy at this location instead of $PWD. - -PENRUN_PIPE_COMMAND - A command (as an bash array) which reads from stdin where the output of ``COMMAND`` is piped into. - Example: ``PENRUN_PIPE_COMMAND=("hr" "-p" "info")``. - -PENRUN_COMPRESSION_COMMAND - The same as ``-C`` but as a bash array. - -PENRUN_OUTPUT_EXTENSION - The same as ``-e``. - -Hooks ------ - -Hook functions can be defined as ordinary shell functions. -Hooks must finish with exit code 0. -Any other code is considered an error by penrun causing penrun to exit. -The following hooks are available: - -``pre_run`` - This function is run **before** COMMAND. - -``post_run`` - This function is run **after** COMMAND. - -Functions ---------- - -cmd_to_artifactsdir - If this function is defined in the config, then it is called with the following arguments: - ``artifactsdir``, ``fragment``, ``command``. - The output of this function will be used by ``penrun`` as the actual artifactsdir. - The usecase might be, when there is a tool which has a single entrypoint, such as ``git``, then the artifactsdir can be rewritten to use the subcommand as a directory name instead. - -Artifacts ---------- - -On each invocation a new directory is created at the following location ``$PWD/$COMMAND/run-$(date +%Y%m%d-%H%M%S)``, called ``artifactsdir``. -Before COMMAND is invoked, the current directory is changed to ``artifactsdir``. -Artifacts, such as pcap or penlog files, can easily be placed in the current working directory of COMMAND. -The output of stderr and stdout is stored in a file ``OUTPUT`` in the ``artifactsdir``. -Metainformation, such as the exit code, are placed in a file ``META`` in the ``artifactsdir``. -The environment is stored in a file ``ENV`` in the ``artifactsdir``. -In order to locate the last run, the last run's ``artifactsdir`` is always symlinked with ``LATEST``. - -META ----- - -META files contain metainformation about the respective testrun for reproducability reasons. -The file format is a simple linebased key value format. -Keys are separated from values with a colon ``:``; whitespace has no semantic meaning. -META files contain the following key value pairs: - -COMMAND (string):: - The full invocation string; in this manpage referred to as COMMAND. - -EXIT (integer):: - The exit code of the issued COMMAND. - -START (string):: - The exact start date of COMMAND in ISO8601 format. - -END (string):: - The exact end date of COMMAND in ISO8601 format. - -ENV ---- - -All environment variables are stored in this file. -The format is the same as produced by the ``printenv`` tool. - -OUTPUT ------- - -OUTPUT files contain the unfiltered stderr and stdout of COMMAND. -It may be compressed which is then indicated with a ``.gz`` or ``.zst`` file extension. - -If hooks are run, their output is stored in PRERUN_OUTPUT and POSTRUN_OUTPUT. - -Examples --------- - -:: - - $ penrun ls -lah > /dev/null - $ penrun ls -lah > /dev/null - $ tree ls - ls - ├── LATEST -> run-20200710-101415 - ├── run-20200710-101334 - │ ├── ENV - │ ├── META - │ └── OUTPUT - └── run-20200710-101415 - ├── ENV - ├── META - └── OUTPUT - -Environment Variables ---------------------- - -The following variables are set by penrun and can be evaluated by programs orchestrated by penrun. - -PENRUN_ARTIFACTS - This variable is set by penrun to the current artifactsdir. - Spawned programs can use this variable to locate the current artifactsdir to store further artifacts on their own. - -PENRUN_BATCH_MODE - This variable is set, when penrun processes commands in batch mode. - -PENRUN_COMMAND - This variable includes the full command provided to penrun; excluding DEFAULT_ARGS. - -PENRUN_PWD_CONF, PENRUN_GIT_ROOT_CONF, PENRUN_USER_CONF, PENRUN_GLOBAL_CONF - These variables are set if the appropriate config exists (see CUSTOMIZATION). - -See Also --------- - -:manpage:`hr(1)`, :manpage:`penlog(7)` diff --git a/penrun.fish b/penrun.fish deleted file mode 100644 index 8f81b4e..0000000 --- a/penrun.fish +++ /dev/null @@ -1,32 +0,0 @@ -# SPDX-FileCopyrightText: AISEC Pentesting Team -# -# SPDX-License-Identifier: Apache-2.0 - -# stolen from sudo.fish - -function __fish_penrun_no_subcommand - if test -n "$argv" - and not string match -qr '^-' $argv[1] - return 1 - else - return 0 - end -end - -complete -c penrun -n __fish_penrun_no_subcommand -s C -r -d "Compression command for OUTPUT" -complete -c penrun -n __fish_penrun_no_subcommand -s S -r -d "Sleep this time beetween jobs" -complete -c penrun -n __fish_penrun_no_subcommand -s T -r -d "A command template for batch processing" -complete -c penrun -n __fish_penrun_no_subcommand -s c -r -d "Use this config file exclusively" -complete -c penrun -n __fish_penrun_no_subcommand -s d -r -d "Use artifactsdir DIR" -complete -c penrun -n __fish_penrun_no_subcommand -s e -r -d "File extension for OUTPUT" -complete -c penrun -n __fish_penrun_no_subcommand -s j -r -d "In batch mode process these number of jobs at a time" -complete -c penrun -n __fish_penrun_no_subcommand -s n -d "Do not use DEFAULT_ARGS from config" -complete -c penrun -n __fish_penrun_no_subcommand -s p -r -d "Pipe output through CMD" - -complete -c penrun -n __fish_penrun_no_subcommand -s s -d "Skip hooks" -complete -c penrun -n __fish_penrun_no_subcommand -s t -r -d "Add a tag to this run" -complete -c penrun -n __fish_penrun_no_subcommand -s u -d "Run until the first error occurs and exit" -complete -c penrun -n __fish_penrun_no_subcommand -s h -d "Show this page and exit" - -# Complete the command we are executed under penrun -complete -c penrun -x -n 'not __fish_seen_argument -s e' -a "(__fish_complete_subcommand)" diff --git a/tests/0001-invocation.bats b/tests/0001-invocation.bats index 1d7a341..c3ac950 100644 --- a/tests/0001-invocation.bats +++ b/tests/0001-invocation.bats @@ -1,10 +1,10 @@ #!/usr/bin/env bats -# SPDX-FileCopyrightText: AISEC Pentesting Team +# SPDX-FileCopyrightText: Stefan Tatschner # -# SPDX-License-Identifier: Apache-2.0 +# SPDX-License-Identifier: MIT -load setup.sh +load setup.bash @test "invoke penrun without parameters" { mkdir foo @@ -12,4 +12,37 @@ load setup.sh penrun ls -lah [[ -d "penrun-artifacts" ]] + [[ -r "penrun-artifacts/ls/LATEST/META.json.zst" ]] + [[ -r "penrun-artifacts/ls/LATEST/OUTPUT.zst" ]] +} + +@test "invoke penrun with set artifacts basedir" { + mkdir artifacts + + penrun -d artifacts true + + [[ -r "artifacts/META.json.zst" ]] + [[ -r "artifacts/OUTPUT.zst" ]] +} + +@test "invoke penrun with set artifacts dir from config" { + echo 'artifacts-dir = "artifacts"' >penrun.toml + + mkdir artifacts + + penrun true + + [[ -r "artifacts/META.json.zst" ]] + [[ -r "artifacts/OUTPUT.zst" ]] +} + +@test "invoke penrun with set artifacts basedir from config" { + echo 'artifacts-base = "artifacts"' >penrun.toml + + mkdir artifacts + + penrun true + + [[ -r "artifacts/true/LATEST/META.json.zst" ]] + [[ -r "artifacts/true/LATEST/OUTPUT.zst" ]] } diff --git a/tests/0002-artifacts.bats b/tests/0002-artifacts.bats index 8ad5ab7..2d4d1f2 100644 --- a/tests/0002-artifacts.bats +++ b/tests/0002-artifacts.bats @@ -1,33 +1,33 @@ #!/usr/bin/env bats -# SPDX-FileCopyrightText: AISEC Pentesting Team +# SPDX-FileCopyrightText: Stefan Tatschner # -# SPDX-License-Identifier: Apache-2.0 +# SPDX-License-Identifier: MIT -load setup.sh +load setup.bash +load lib.bash -@test "check penrun environment variables" { - penrun true +@test "check META.json" { + penrun ls -lah - local command - command="$(trim_string "$(grep PENRUN_COMMAND