From c45cdf2e550b2dd8565c04e8bcc35a2cce76241b Mon Sep 17 00:00:00 2001 From: Karl Sassenberg Date: Wed, 22 Mar 2023 13:27:35 +0000 Subject: [PATCH] feat: rebase after resync of fork --- go.mod | 21 +- go.sum | 54 +- go.work.sum | 4 + sdk/proto/events/event.pb.go | 208 --- test/integration/go.mod | 7 +- test/integration/go.sum | 18 +- .../github.com/imdario/mergo/CONTRIBUTING.md | 112 ++ .../vendor/github.com/imdario/mergo/README.md | 5 +- .../github.com/imdario/mergo/SECURITY.md | 14 + .../vendor/github.com/imdario/mergo/map.go | 2 +- .../vendor/github.com/imdario/mergo/merge.go | 14 +- .../vendor/github.com/imdario/mergo/mergo.go | 2 +- .../github.com/klauspost/compress/README.md | 15 + .../klauspost/compress/fse/decompress.go | 4 +- .../klauspost/compress/huff0/bitwriter.go | 16 + .../klauspost/compress/huff0/compress.go | 3 +- .../klauspost/compress/zstd/blockdec.go | 4 + .../klauspost/compress/zstd/bytebuf.go | 2 +- .../klauspost/compress/zstd/enc_best.go | 65 +- .../klauspost/compress/zstd/seqdec.go | 6 +- .../klauspost/compress/zstd/seqdec_amd64.go | 1 - .../vendor/github.com/shirou/gopsutil/LICENSE | 61 - .../github.com/shirou/gopsutil/cpu/cpu.go | 185 --- .../shirou/gopsutil/cpu/cpu_darwin.go | 112 -- .../shirou/gopsutil/cpu/cpu_darwin_cgo.go | 112 -- .../shirou/gopsutil/cpu/cpu_darwin_nocgo.go | 14 - .../shirou/gopsutil/cpu/cpu_dragonfly.go | 154 --- .../gopsutil/cpu/cpu_dragonfly_amd64.go | 9 - .../shirou/gopsutil/cpu/cpu_fallback.go | 30 - .../shirou/gopsutil/cpu/cpu_freebsd.go | 166 --- .../shirou/gopsutil/cpu/cpu_freebsd_386.go | 9 - .../shirou/gopsutil/cpu/cpu_freebsd_amd64.go | 9 - .../shirou/gopsutil/cpu/cpu_freebsd_arm.go | 9 - .../shirou/gopsutil/cpu/cpu_freebsd_arm64.go | 9 - .../shirou/gopsutil/cpu/cpu_linux.go | 406 ------ .../shirou/gopsutil/cpu/cpu_openbsd.go | 178 --- .../shirou/gopsutil/cpu/cpu_solaris.go | 281 ---- .../shirou/gopsutil/cpu/cpu_windows.go | 265 ---- .../shirou/gopsutil/internal/common/binary.go | 634 --------- .../shirou/gopsutil/internal/common/common.go | 379 ------ .../gopsutil/internal/common/common_darwin.go | 69 - .../internal/common/common_freebsd.go | 85 -- .../gopsutil/internal/common/common_linux.go | 291 ---- .../internal/common/common_openbsd.go | 69 - .../gopsutil/internal/common/common_unix.go | 66 - .../internal/common/common_windows.go | 300 ----- .../shirou/gopsutil/internal/common/sleep.go | 18 - .../github.com/shirou/gopsutil/mem/mem.go | 116 -- .../github.com/shirou/gopsutil/mem/mem_bsd.go | 91 -- .../shirou/gopsutil/mem/mem_darwin.go | 70 - .../shirou/gopsutil/mem/mem_darwin_cgo.go | 58 - .../shirou/gopsutil/mem/mem_darwin_nocgo.go | 93 -- .../shirou/gopsutil/mem/mem_fallback.go | 33 - .../shirou/gopsutil/mem/mem_freebsd.go | 167 --- .../shirou/gopsutil/mem/mem_linux.go | 514 ------- .../shirou/gopsutil/mem/mem_openbsd.go | 105 -- .../shirou/gopsutil/mem/mem_openbsd_386.go | 37 - .../shirou/gopsutil/mem/mem_openbsd_amd64.go | 32 - .../shirou/gopsutil/mem/mem_openbsd_arm64.go | 37 - .../shirou/gopsutil/mem/mem_solaris.go | 204 --- .../shirou/gopsutil/mem/mem_windows.go | 165 --- .../github.com/shirou/gopsutil/net/net.go | 263 ---- .../github.com/shirou/gopsutil/net/net_aix.go | 425 ------ .../shirou/gopsutil/net/net_darwin.go | 293 ---- .../shirou/gopsutil/net/net_fallback.go | 92 -- .../shirou/gopsutil/net/net_freebsd.go | 132 -- .../shirou/gopsutil/net/net_linux.go | 884 ------------ .../shirou/gopsutil/net/net_openbsd.go | 319 ----- .../shirou/gopsutil/net/net_unix.go | 224 --- .../shirou/gopsutil/net/net_windows.go | 773 ----------- .../shirou/gopsutil/process/process.go | 549 -------- .../shirou/gopsutil/process/process_bsd.go | 84 -- .../shirou/gopsutil/process/process_darwin.go | 485 ------- .../gopsutil/process/process_darwin_386.go | 234 ---- .../gopsutil/process/process_darwin_amd64.go | 234 ---- .../gopsutil/process/process_darwin_arm64.go | 212 --- .../gopsutil/process/process_darwin_cgo.go | 30 - .../gopsutil/process/process_darwin_nocgo.go | 34 - .../gopsutil/process/process_fallback.go | 209 --- .../gopsutil/process/process_freebsd.go | 338 ----- .../gopsutil/process/process_freebsd_386.go | 192 --- .../gopsutil/process/process_freebsd_amd64.go | 192 --- .../gopsutil/process/process_freebsd_arm.go | 192 --- .../gopsutil/process/process_freebsd_arm64.go | 201 --- .../shirou/gopsutil/process/process_linux.go | 1195 ----------------- .../gopsutil/process/process_openbsd.go | 395 ------ .../gopsutil/process/process_openbsd_386.go | 201 --- .../gopsutil/process/process_openbsd_amd64.go | 200 --- .../gopsutil/process/process_openbsd_arm64.go | 202 --- .../shirou/gopsutil/process/process_posix.go | 180 --- .../gopsutil/process/process_solaris.go | 313 ----- .../gopsutil/process/process_windows.go | 1194 ---------------- .../gopsutil/process/process_windows_386.go | 107 -- .../gopsutil/process/process_windows_amd64.go | 78 -- .../gopsutil/process/process_windows_arm64.go | 104 -- .../vendor/github.com/spf13/afero/afero.go | 2 +- .../vendor/github.com/spf13/afero/basepath.go | 1 - .../github.com/spf13/afero/copyOnWriteFs.go | 9 +- .../vendor/github.com/spf13/afero/ioutil.go | 11 +- .../vendor/github.com/spf13/afero/mem/file.go | 7 +- .../vendor/github.com/spf13/afero/memmap.go | 21 +- .../vendor/github.com/spf13/afero/regexpfs.go | 1 - .../vendor/github.com/spf13/afero/symlink.go | 6 +- .../github.com/spf13/afero/unionFile.go | 7 +- .../vendor/github.com/spf13/afero/util.go | 7 +- test/integration/vendor/modules.txt | 13 +- test/performance/go.mod | 4 +- test/performance/go.sum | 11 +- .../klauspost/compress/s2/encode_go.go | 8 + .../compress/s2/encodeblock_amd64.go | 12 +- .../klauspost/compress/s2/encodeblock_amd64.s | 753 +++++++++++ .../klauspost/compress/s2/lz4sconvert.go | 467 +++++++ .../agent/sdk/v2/proto/events/event.pb.go | 208 --- .../vendor/github.com/spf13/afero/afero.go | 2 +- .../vendor/github.com/spf13/afero/basepath.go | 1 - .../github.com/spf13/afero/copyOnWriteFs.go | 9 +- .../vendor/github.com/spf13/afero/ioutil.go | 11 +- .../vendor/github.com/spf13/afero/mem/file.go | 7 +- .../vendor/github.com/spf13/afero/memmap.go | 21 +- .../vendor/github.com/spf13/afero/regexpfs.go | 1 - .../vendor/github.com/spf13/afero/symlink.go | 6 +- .../github.com/spf13/afero/unionFile.go | 7 +- .../vendor/github.com/spf13/afero/util.go | 7 +- test/performance/vendor/modules.txt | 4 +- .../aymanbagabas/go-osc52/v2/LICENSE | 21 + .../aymanbagabas/go-osc52/v2/README.md | 83 ++ .../aymanbagabas/go-osc52/v2/osc52.go | 305 +++++ .../github.com/briandowns/spinner/spinner.go | 29 +- .../charmbracelet/lipgloss/.gitignore | 1 + .../charmbracelet/lipgloss/README.md | 85 +- .../charmbracelet/lipgloss/borders.go | 64 +- .../charmbracelet/lipgloss/color.go | 253 +--- .../github.com/charmbracelet/lipgloss/get.go | 35 +- .../charmbracelet/lipgloss/position.go | 36 +- .../charmbracelet/lipgloss/renderer.go | 143 ++ .../charmbracelet/lipgloss/runes.go | 2 +- .../github.com/charmbracelet/lipgloss/set.go | 34 +- .../charmbracelet/lipgloss/style.go | 65 +- .../charmbracelet/lipgloss/unset.go | 2 +- .../charmbracelet/lipgloss/whitespace.go | 19 +- .../evilmartians/lefthook/CHANGELOG.md | 15 +- .../github.com/evilmartians/lefthook/Makefile | 8 + .../internal/config/available_hooks.go | 4 + .../lefthook/internal/config/load.go | 15 + .../lefthook/internal/config/skip.go | 14 +- .../lefthook/internal/lefthook/run.go | 6 + .../lefthook/runner/prepare_command.go | 34 +- .../internal/lefthook/runner/runner.go | 22 +- .../lefthook/internal/version/version.go | 2 +- .../goreleaser/chglog/.goreleaser.yml | 13 +- .../goreleaser/nfpm/v2/.golangci.yml | 25 + .../goreleaser/nfpm/v2/.goreleaser.yml | 10 +- .../github.com/goreleaser/nfpm/v2/apk/apk.go | 146 +- .../goreleaser/nfpm/v2/arch/arch.go | 257 +--- .../github.com/goreleaser/nfpm/v2/deb/deb.go | 211 +-- .../goreleaser/nfpm/v2/files/files.go | 409 +++++- .../goreleaser/nfpm/v2/internal/cmd/root.go | 8 +- .../nfpm/v2/internal/rpmpack/header.go | 4 +- .../nfpm/v2/internal/rpmpack/rpm.go | 48 +- .../goreleaser/nfpm/v2/internal/sign/pgp.go | 30 +- vendor/github.com/goreleaser/nfpm/v2/nfpm.go | 35 +- .../github.com/goreleaser/nfpm/v2/rpm/rpm.go | 35 +- .../github.com/imdario/mergo/CONTRIBUTING.md | 112 ++ vendor/github.com/imdario/mergo/README.md | 5 +- vendor/github.com/imdario/mergo/SECURITY.md | 14 + vendor/github.com/imdario/mergo/map.go | 2 +- vendor/github.com/imdario/mergo/merge.go | 14 +- vendor/github.com/imdario/mergo/mergo.go | 2 +- .../github.com/klauspost/compress/README.md | 15 + .../klauspost/compress/fse/decompress.go | 4 +- .../klauspost/compress/huff0/bitwriter.go | 16 + .../klauspost/compress/huff0/compress.go | 3 +- .../klauspost/compress/zstd/blockdec.go | 4 + .../klauspost/compress/zstd/bytebuf.go | 2 +- .../klauspost/compress/zstd/enc_best.go | 65 +- .../klauspost/compress/zstd/seqdec.go | 6 +- .../klauspost/compress/zstd/seqdec_amd64.go | 1 - .../muesli/reflow/truncate/truncate.go | 7 +- vendor/github.com/muesli/termenv/README.md | 248 ++-- .../github.com/muesli/termenv/ansi_compat.md | 17 + vendor/github.com/muesli/termenv/color.go | 80 +- vendor/github.com/muesli/termenv/copy.go | 37 + vendor/github.com/muesli/termenv/hyperlink.go | 11 + .../github.com/muesli/termenv/notification.go | 11 + vendor/github.com/muesli/termenv/output.go | 197 +++ vendor/github.com/muesli/termenv/profile.go | 97 ++ vendor/github.com/muesli/termenv/screen.go | 442 +++++- vendor/github.com/muesli/termenv/style.go | 7 +- .../muesli/termenv/templatehelper.go | 57 +- vendor/github.com/muesli/termenv/termenv.go | 89 +- .../github.com/muesli/termenv/termenv_js.go | 18 - .../muesli/termenv/termenv_other.go | 30 + .../muesli/termenv/termenv_posix.go | 17 + .../muesli/termenv/termenv_solaris.go | 22 + .../github.com/muesli/termenv/termenv_unix.go | 127 +- .../muesli/termenv/termenv_windows.go | 66 +- .../agent/sdk/v2/proto/events/event.pb.go | 208 --- vendor/github.com/spf13/afero/afero.go | 2 +- vendor/github.com/spf13/afero/basepath.go | 1 - .../github.com/spf13/afero/copyOnWriteFs.go | 9 +- vendor/github.com/spf13/afero/ioutil.go | 11 +- vendor/github.com/spf13/afero/mem/file.go | 7 +- vendor/github.com/spf13/afero/memmap.go | 21 +- vendor/github.com/spf13/afero/regexpfs.go | 1 - vendor/github.com/spf13/afero/symlink.go | 6 +- vendor/github.com/spf13/afero/unionFile.go | 7 +- vendor/github.com/spf13/afero/util.go | 7 +- vendor/modules.txt | 31 +- 208 files changed, 4736 insertions(+), 18551 deletions(-) create mode 100644 test/integration/vendor/github.com/imdario/mergo/CONTRIBUTING.md create mode 100644 test/integration/vendor/github.com/imdario/mergo/SECURITY.md delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/LICENSE delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_cgo.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_nocgo.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly_amd64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_fallback.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_386.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_amd64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_linux.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_openbsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_solaris.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_windows.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/internal/common/binary.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/internal/common/common.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_darwin.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_freebsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_linux.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_openbsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_unix.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_windows.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/internal/common/sleep.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_bsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin_cgo.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin_nocgo.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_fallback.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_freebsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_linux.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_386.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_amd64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_arm64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_solaris.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/mem/mem_windows.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/net/net.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/net/net_aix.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/net/net_darwin.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/net/net_fallback.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/net/net_freebsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/net/net_linux.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/net/net_openbsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/net/net_unix.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/net/net_windows.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_bsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_386.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_amd64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_arm64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_cgo.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_nocgo.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_fallback.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_386.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_amd64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_linux.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_386.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_amd64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_arm64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_posix.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_solaris.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_windows.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_386.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_amd64.go delete mode 100644 test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_arm64.go create mode 100644 test/performance/vendor/github.com/klauspost/compress/s2/lz4sconvert.go create mode 100644 vendor/github.com/aymanbagabas/go-osc52/v2/LICENSE create mode 100644 vendor/github.com/aymanbagabas/go-osc52/v2/README.md create mode 100644 vendor/github.com/aymanbagabas/go-osc52/v2/osc52.go create mode 100644 vendor/github.com/charmbracelet/lipgloss/.gitignore create mode 100644 vendor/github.com/charmbracelet/lipgloss/renderer.go create mode 100644 vendor/github.com/imdario/mergo/CONTRIBUTING.md create mode 100644 vendor/github.com/imdario/mergo/SECURITY.md create mode 100644 vendor/github.com/muesli/termenv/copy.go create mode 100644 vendor/github.com/muesli/termenv/hyperlink.go create mode 100644 vendor/github.com/muesli/termenv/notification.go create mode 100644 vendor/github.com/muesli/termenv/output.go create mode 100644 vendor/github.com/muesli/termenv/profile.go delete mode 100644 vendor/github.com/muesli/termenv/termenv_js.go create mode 100644 vendor/github.com/muesli/termenv/termenv_other.go create mode 100644 vendor/github.com/muesli/termenv/termenv_posix.go create mode 100644 vendor/github.com/muesli/termenv/termenv_solaris.go diff --git a/go.mod b/go.mod index b4c601acb..23b3629dd 100644 --- a/go.mod +++ b/go.mod @@ -39,10 +39,10 @@ require ( require ( github.com/bufbuild/buf v1.15.1 - github.com/evilmartians/lefthook v1.3.5 + github.com/evilmartians/lefthook v1.3.7 github.com/go-resty/resty/v2 v2.7.0 github.com/go-swagger/go-swagger v0.30.4 - github.com/goreleaser/nfpm/v2 v2.26.0 + github.com/goreleaser/nfpm/v2 v2.27.1 github.com/nginx/agent/sdk/v2 v2.0.0-00010101000000-000000000000 github.com/prometheus/client_golang v1.13.0 github.com/pseudomuto/protoc-gen-doc v1.5.1 @@ -63,14 +63,15 @@ require ( github.com/Microsoft/go-winio v0.6.0 // indirect github.com/ProtonMail/go-crypto v0.0.0-20210512092938-c05353c2d58c // indirect github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb // indirect - github.com/briandowns/spinner v1.21.0 // indirect + github.com/briandowns/spinner v1.23.0 // indirect github.com/bufbuild/connect-go v1.5.2 // indirect github.com/bufbuild/protocompile v0.5.1 // indirect github.com/cavaliergopher/cpio v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.1.2 // indirect - github.com/charmbracelet/lipgloss v0.6.0 // indirect + github.com/charmbracelet/lipgloss v0.7.1 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/creack/pty v1.1.18 // indirect github.com/davecgh/go-spew v1.1.1 // indirect @@ -108,14 +109,14 @@ require ( github.com/gofrs/uuid/v5 v5.0.0 // indirect github.com/google/go-containerregistry v0.13.0 // indirect github.com/google/pprof v0.0.0-20230228050547-1710fef4ab10 // indirect - github.com/goreleaser/chglog v0.4.1 // indirect + github.com/goreleaser/chglog v0.4.2 // indirect github.com/goreleaser/fileglob v1.3.0 // indirect github.com/gorilla/handlers v1.5.1 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/huandu/xstrings v1.3.3 // indirect github.com/iancoleman/orderedmap v0.0.0-20190318233801-ac98e3ecb4b0 // indirect - github.com/imdario/mergo v0.3.13 // indirect + github.com/imdario/mergo v0.3.14 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/invopop/jsonschema v0.7.0 // indirect github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect @@ -123,7 +124,7 @@ require ( github.com/jessevdk/go-flags v1.5.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/kevinburke/ssh_config v1.1.0 // indirect - github.com/klauspost/compress v1.16.0 // indirect + github.com/klauspost/compress v1.16.3 // indirect github.com/klauspost/pgzip v1.2.5 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect @@ -143,9 +144,9 @@ require ( github.com/muesli/mango v0.1.0 // indirect github.com/muesli/mango-cobra v1.2.0 // indirect github.com/muesli/mango-pflag v0.1.0 // indirect - github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68 // indirect + github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/roff v0.1.0 // indirect - github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0 // indirect + github.com/muesli/termenv v0.15.1 // indirect github.com/nginxinc/nginx-go-crossplane v0.4.1 // indirect github.com/oklog/ulid v1.3.1 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect @@ -166,7 +167,7 @@ require ( github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sergi/go-diff v1.2.0 // indirect github.com/shopspring/decimal v1.2.0 // indirect - github.com/spf13/afero v1.9.3 // indirect + github.com/spf13/afero v1.9.5 // indirect github.com/spf13/cast v1.5.0 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/stretchr/objx v0.5.0 // indirect diff --git a/go.sum b/go.sum index 1778b4093..2456fccc7 100644 --- a/go.sum +++ b/go.sum @@ -81,6 +81,8 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkY github.com/asaskevich/govalidator v0.0.0-20200907205600-7a23bdc65eef/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d h1:Byv0BzEl3/e6D5CLfI0j/7hiIEtvGVFPCZ7Ei2oq8iQ= github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= @@ -88,8 +90,8 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb h1:m935MPodAbYS46DG4pJSv7WO+VECIWUQ7OJYSoTrMh4= github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb/go.mod h1:PkYb9DJNAwrSvRx5DYA+gUcOIgTGVMNkfSCbZM8cWpI= -github.com/briandowns/spinner v1.21.0 h1:2lVBzf3iZ3cT/ulVXljc4BzlL3yTWZDzsGsamI7si+A= -github.com/briandowns/spinner v1.21.0/go.mod h1:TcwZHb7Wb6vn/+bcVv1UXEzaA4pLS7yznHlkY/HzH44= +github.com/briandowns/spinner v1.23.0 h1:alDF2guRWqa/FOZZYWjlMIx2L6H0wyewPxo/CH4Pt2A= +github.com/briandowns/spinner v1.23.0/go.mod h1:rPG4gmXeN3wQV/TsAY4w8lPdIM6RX3yqeBQJSrbXjuE= github.com/bufbuild/buf v1.15.1 h1:v7sK2uMEsGX4Z2hvu+xiMheH3C3AKBGfxPBgdUZYDQ8= github.com/bufbuild/buf v1.15.1/go.mod h1:TQeGKam1QMfHy/xsSnnMpxN3JK5HBb6aNvZj4m52gkE= github.com/bufbuild/connect-go v1.5.2 h1:G4EZd5gF1U1ZhhbVJXplbuUnfKpBZ5j5izqIwu2g2W8= @@ -107,8 +109,8 @@ github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/charmbracelet/lipgloss v0.6.0 h1:1StyZB9vBSOyuZxQUcUwGr17JmojPNm87inij9N3wJY= -github.com/charmbracelet/lipgloss v0.6.0/go.mod h1:tHh2wr34xcHjC2HCXIlGSG1jaDF0S0atAUvBMP6Ppuk= +github.com/charmbracelet/lipgloss v0.7.1 h1:17WMwi7N1b1rVWOjMT+rCh7sQkvDU75B2hbZpc5Kc1E= +github.com/charmbracelet/lipgloss v0.7.1/go.mod h1:yG0k3giv8Qj8edTCbbg6AlQ5e8KNWpFujkNawKNhE2c= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= @@ -147,9 +149,8 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.m github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.3.0-java h1:bV5JGEB1ouEzZa0hgVDFFiClrUEuGWRaAc/3mxR2QK0= github.com/envoyproxy/protoc-gen-validate v0.3.0-java/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/evilmartians/lefthook v1.3.5 h1:K+wkFYtf1+oNe/gguNEGly1jXlUmfYIMYaZ7A43QZjQ= -github.com/evilmartians/lefthook v1.3.5/go.mod h1:X4o0AX2Jh9SVFyxyDMoJb6p8LmzzqGGfNkrcg1FiDt8= -github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/evilmartians/lefthook v1.3.7 h1:h2lvNl5OSlnAZdV3bdA283itH6pHKaTnzk837dQqrCk= +github.com/evilmartians/lefthook v1.3.7/go.mod h1:FTw9v/+5Tg5AlrLPxS2kJeqHhQNqhUA+6/WdGeaf41s= github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w= github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg= github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= @@ -348,12 +349,12 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= -github.com/goreleaser/chglog v0.4.1 h1:6IAduyHpR58u3OFBdTrg8I/qAaBAmYYZ4Wq1Fz30QUY= -github.com/goreleaser/chglog v0.4.1/go.mod h1:85xT/GTwDCzLdjysP9aj+x6hQ+IxAv8SXx9MTrgcY2Y= +github.com/goreleaser/chglog v0.4.2 h1:afmbT1d7lX/q+GF8wv3a1Dofs2j/Y9YkiCpGemWR6mI= +github.com/goreleaser/chglog v0.4.2/go.mod h1:u/F03un4hMCQrp65qSWCkkC6T+G7YLKZ+AM2mITE47s= github.com/goreleaser/fileglob v1.3.0 h1:/X6J7U8lbDpQtBvGcwwPS6OpzkNVlVEsFUVRx9+k+7I= github.com/goreleaser/fileglob v1.3.0/go.mod h1:Jx6BoXv3mbYkEzwm9THo7xbr5egkAraxkGorbJb4RxU= -github.com/goreleaser/nfpm/v2 v2.26.0 h1:nL7sXwsMLsc+NWE4Eddev+ZZomRaucT0WSnWkLwuxBM= -github.com/goreleaser/nfpm/v2 v2.26.0/go.mod h1:AQAOZ89rL4rHbv6ZdwyCWkjMam3LrHi9QIq56TnjUQk= +github.com/goreleaser/nfpm/v2 v2.27.1 h1:+q7/aY+SCQjB5OKiqzdBVoFIhG1XnxRBU2Pxqt8qm3U= +github.com/goreleaser/nfpm/v2 v2.27.1/go.mod h1:o5coBBYYdw+tifbB6DJLL/rR42bUmI5mWCKGumJmEt8= github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw= @@ -372,8 +373,8 @@ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1: github.com/ianlancetaylor/demangle v0.0.0-20210905161508-09a460cdf81d/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w= github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= -github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= -github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= +github.com/imdario/mergo v0.3.14 h1:fOqeC1+nCuuk6PKQdg9YmosXX7Y7mHX6R/0ZldI9iHo= +github.com/imdario/mergo v0.3.14/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= @@ -411,8 +412,8 @@ github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQL github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw1HU4= -github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= +github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid/v2 v2.1.0 h1:eyi1Ad2aNJMW95zcSbmGg7Cg6cq3ADwLpMAP96d8rF0= github.com/klauspost/cpuid/v2 v2.1.0/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= @@ -446,16 +447,12 @@ github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsI github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0= github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE= github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= -github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= -github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= @@ -492,12 +489,12 @@ github.com/muesli/mango-cobra v1.2.0 h1:DQvjzAM0PMZr85Iv9LIMaYISpTOliMEg+uMFtNbY github.com/muesli/mango-cobra v1.2.0/go.mod h1:vMJL54QytZAJhCT13LPVDfkvCUJ5/4jNUKF/8NC2UjA= github.com/muesli/mango-pflag v0.1.0 h1:UADqbYgpUyRoBja3g6LUL+3LErjpsOwaC9ywvBWe7Sg= github.com/muesli/mango-pflag v0.1.0/go.mod h1:YEQomTxaCUp8PrbhFh10UfbhbQrM/xJ4i2PB8VTLLW0= -github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68 h1:y1p/ycavWjGT9FnmSjdbWUlLGvcxrY0Rw3ATltrxOhk= -github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68/go.mod h1:Xk+z4oIWdQqJzsxyjgl3P22oYZnHdZ8FFTHAQQt5BMQ= +github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= +github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= github.com/muesli/roff v0.1.0 h1:YD0lalCotmYuF5HhZliKWlIx7IEhiXeSfq7hNjFqGF8= github.com/muesli/roff v0.1.0/go.mod h1:pjAHQM9hdUUwm/krAfrLGgJkXJ+YuhtsfZ42kieB2Ig= -github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0 h1:STjmj0uFfRryL9fzRA/OupNppeAID6QJYPMavTL7jtY= -github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs= +github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxs= +github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-proto-validators v0.3.2 h1:qRlmpTzm2pstMKKzTdvwPCF5QfBNURSlAgN/R+qbKos= @@ -613,8 +610,8 @@ github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0 github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hgR6gDIPg= -github.com/spf13/afero v1.9.3 h1:41FoI0fD7OR7mGcKE/aOiLkGreyf8ifIOQmJANWogMk= -github.com/spf13/afero v1.9.3/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y= +github.com/spf13/afero v1.9.5 h1:stMpOSZFs//0Lv29HduCmli3GUfpFoF3Y1Q/aXj/wVM= +github.com/spf13/afero v1.9.5/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= @@ -727,8 +724,8 @@ golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= @@ -850,7 +847,6 @@ golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190221075227-b4e8571b14e0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -925,7 +921,6 @@ golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= @@ -1142,7 +1137,6 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200605160147-a5ece683394c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0/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= gotest.tools/v3 v3.4.0 h1:ZazjZUfuVeZGLAmlKKuyv3IKP5orXcwtOwDQH6YVr6o= diff --git a/go.work.sum b/go.work.sum index 45b7cfe86..5a3355986 100644 --- a/go.work.sum +++ b/go.work.sum @@ -731,6 +731,7 @@ golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028 h1:4+4C/Iv2U4fMZBiMCc98MG1In4gJY5YRhtpDNeDeHWs= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -749,6 +750,7 @@ golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.0.0-20221014081412-f15817d10f9b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= @@ -792,6 +794,7 @@ golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= @@ -800,6 +803,7 @@ golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= diff --git a/sdk/proto/events/event.pb.go b/sdk/proto/events/event.pb.go index 17f1ab782..a6bba3fd8 100644 --- a/sdk/proto/events/event.pb.go +++ b/sdk/proto/events/event.pb.go @@ -1291,208 +1291,9 @@ func (m *SecurityViolationEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) _ = i var l int _ = l -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -======= ->>>>>>> Create dedicated cache and upstream metrics reports -======= ->>>>>>> Create dedicated cache and upstream metrics reports -======= ->>>>>>> Create dedicated cache and upstream metrics reports - if len(m.PolicyName) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.PolicyName))) - i += copy(dAtA[i:], m.PolicyName) -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } -<<<<<<< HEAD - if len(m.DisplayName) > 0 { - i -= len(m.DisplayName) - copy(dAtA[i:], m.DisplayName) - i = encodeVarintEvent(dAtA, i, uint64(len(m.DisplayName))) - i-- - dAtA[i] = 0x2 - i-- - dAtA[i] = 0xb2 -======= - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= if m.XXX_unrecognized != nil { i -= len(m.XXX_unrecognized) copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf -======= ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= - if m.XXX_unrecognized != nil { - i -= len(m.XXX_unrecognized) - copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf -======= ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= - if m.XXX_unrecognized != nil { - i -= len(m.XXX_unrecognized) - copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf -======= ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= - if m.XXX_unrecognized != nil { - i -= len(m.XXX_unrecognized) - copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf } if len(m.ParentHostname) > 0 { i -= len(m.ParentHostname) @@ -1503,15 +1304,6 @@ func (m *SecurityViolationEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) i-- dAtA[i] = 0xc2 } - if len(m.NginxID) > 0 { - i -= len(m.NginxID) - copy(dAtA[i:], m.NginxID) - i = encodeVarintEvent(dAtA, i, uint64(len(m.NginxID))) - i-- - dAtA[i] = 0x2 - i-- - dAtA[i] = 0xba - } if len(m.DisplayName) > 0 { i -= len(m.DisplayName) copy(dAtA[i:], m.DisplayName) diff --git a/test/integration/go.mod b/test/integration/go.mod index a083a233a..c45092e5f 100644 --- a/test/integration/go.mod +++ b/test/integration/go.mod @@ -6,7 +6,6 @@ require ( github.com/go-resty/resty/v2 v2.7.0 github.com/nginx/agent/sdk/v2 v2.0.0-00010101000000-000000000000 github.com/nginx/agent/v2 v2.22.0 - github.com/shirou/gopsutil v3.21.11+incompatible github.com/sirupsen/logrus v1.9.0 github.com/stretchr/testify v1.8.2 github.com/testcontainers/testcontainers-go v0.17.0 @@ -64,12 +63,12 @@ require ( github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-version v1.6.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect - github.com/imdario/mergo v0.3.13 // indirect + github.com/imdario/mergo v0.3.14 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect - github.com/klauspost/compress v1.16.0 // indirect + github.com/klauspost/compress v1.16.3 // indirect github.com/klauspost/cpuid/v2 v2.1.0 // indirect github.com/lufia/plan9stats v0.0.0-20220517141722-cf486979b281 // indirect github.com/magiconair/properties v1.8.7 // indirect @@ -111,7 +110,7 @@ require ( github.com/rogpeppe/go-internal v1.9.0 // indirect github.com/serialx/hashring v0.0.0-20190422032157-8b2912629002 // indirect github.com/shirou/gopsutil/v3 v3.22.7 // indirect - github.com/spf13/afero v1.9.3 // indirect + github.com/spf13/afero v1.9.5 // indirect github.com/spf13/cast v1.5.0 // indirect github.com/spf13/cobra v1.6.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect diff --git a/test/integration/go.sum b/test/integration/go.sum index 9173c81c4..b25d974f3 100644 --- a/test/integration/go.sum +++ b/test/integration/go.sum @@ -341,8 +341,8 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= -github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= +github.com/imdario/mergo v0.3.14 h1:fOqeC1+nCuuk6PKQdg9YmosXX7Y7mHX6R/0ZldI9iHo= +github.com/imdario/mergo v0.3.14/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= @@ -371,8 +371,8 @@ github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNU github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw1HU4= -github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= +github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid/v2 v2.1.0 h1:eyi1Ad2aNJMW95zcSbmGg7Cg6cq3ADwLpMAP96d8rF0= github.com/klauspost/cpuid/v2 v2.1.0/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -550,8 +550,6 @@ github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4Qn github.com/seccomp/libseccomp-golang v0.9.2-0.20220502022130-f33da4d89646/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= github.com/serialx/hashring v0.0.0-20190422032157-8b2912629002 h1:ka9QPuQg2u4LGipiZGsgkg3rJCo4iIUCy75FddM0GRQ= github.com/serialx/hashring v0.0.0-20190422032157-8b2912629002/go.mod h1:/yeG0My1xr/u+HZrFQ1tOQQQQrOawfyMUH13ai5brBc= -github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= -github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shirou/gopsutil/v3 v3.22.7 h1:flKnuCMfUUrO+oAvwAd6GKZgnPzr098VA/UJ14nhJd4= github.com/shirou/gopsutil/v3 v3.22.7/go.mod h1:s648gW4IywYzUfE/KjXxUsqrqx/T2xO5VqOXxONeRfI= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= @@ -564,8 +562,8 @@ github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= -github.com/spf13/afero v1.9.3 h1:41FoI0fD7OR7mGcKE/aOiLkGreyf8ifIOQmJANWogMk= -github.com/spf13/afero v1.9.3/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y= +github.com/spf13/afero v1.9.5 h1:stMpOSZFs//0Lv29HduCmli3GUfpFoF3Y1Q/aXj/wVM= +github.com/spf13/afero v1.9.5/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ= github.com/spf13/cast v0.0.0-20150508191742-4d07383ffe94/go.mod h1:r2rcYCSwa1IExKTDiTfzaxqT2FNHs8hODu4LnUfgKEg= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= @@ -698,7 +696,7 @@ golang.org/x/crypto v0.0.0-20201117144127-c1f2f97bffc9/go.mod h1:jdWPYTVW3xRLrWP golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -780,6 +778,7 @@ golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= @@ -1107,7 +1106,6 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0/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= gotest.tools/v3 v3.4.0 h1:ZazjZUfuVeZGLAmlKKuyv3IKP5orXcwtOwDQH6YVr6o= diff --git a/test/integration/vendor/github.com/imdario/mergo/CONTRIBUTING.md b/test/integration/vendor/github.com/imdario/mergo/CONTRIBUTING.md new file mode 100644 index 000000000..0a1ff9f94 --- /dev/null +++ b/test/integration/vendor/github.com/imdario/mergo/CONTRIBUTING.md @@ -0,0 +1,112 @@ + +# Contributing to mergo + +First off, thanks for taking the time to contribute! ❤️ + +All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 + +> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: +> - Star the project +> - Tweet about it +> - Refer this project in your project's readme +> - Mention the project at local meetups and tell your friends/colleagues + + +## Table of Contents + +- [Code of Conduct](#code-of-conduct) +- [I Have a Question](#i-have-a-question) +- [I Want To Contribute](#i-want-to-contribute) +- [Reporting Bugs](#reporting-bugs) +- [Suggesting Enhancements](#suggesting-enhancements) + +## Code of Conduct + +This project and everyone participating in it is governed by the +[mergo Code of Conduct](https://github.com/imdario/mergoblob/master/CODE_OF_CONDUCT.md). +By participating, you are expected to uphold this code. Please report unacceptable behavior +to <>. + + +## I Have a Question + +> If you want to ask a question, we assume that you have read the available [Documentation](https://pkg.go.dev/github.com/imdario/mergo). + +Before you ask a question, it is best to search for existing [Issues](https://github.com/imdario/mergo/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. + +If you then still feel the need to ask a question and need clarification, we recommend the following: + +- Open an [Issue](https://github.com/imdario/mergo/issues/new). +- Provide as much context as you can about what you're running into. +- Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. + +We will then take care of the issue as soon as possible. + +## I Want To Contribute + +> ### Legal Notice +> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. + +### Reporting Bugs + + +#### Before Submitting a Bug Report + +A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. + +- Make sure that you are using the latest version. +- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](). If you are looking for support, you might want to check [this section](#i-have-a-question)). +- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/imdario/mergoissues?q=label%3Abug). +- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. +- Collect information about the bug: +- Stack trace (Traceback) +- OS, Platform and Version (Windows, Linux, macOS, x86, ARM) +- Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. +- Possibly your input and the output +- Can you reliably reproduce the issue? And can you also reproduce it with older versions? + + +#### How Do I Submit a Good Bug Report? + +> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to . + + +We use GitHub issues to track bugs and errors. If you run into an issue with the project: + +- Open an [Issue](https://github.com/imdario/mergo/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) +- Explain the behavior you would expect and the actual behavior. +- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. +- Provide the information you collected in the previous section. + +Once it's filed: + +- The project team will label the issue accordingly. +- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. +- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be implemented by someone. + +### Suggesting Enhancements + +This section guides you through submitting an enhancement suggestion for mergo, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. + + +#### Before Submitting an Enhancement + +- Make sure that you are using the latest version. +- Read the [documentation]() carefully and find out if the functionality is already covered, maybe by an individual configuration. +- Perform a [search](https://github.com/imdario/mergo/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. +- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. + + +#### How Do I Submit a Good Enhancement Suggestion? + +Enhancement suggestions are tracked as [GitHub issues](https://github.com/imdario/mergo/issues). + +- Use a **clear and descriptive title** for the issue to identify the suggestion. +- Provide a **step-by-step description of the suggested enhancement** in as many details as possible. +- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. +- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. +- **Explain why this enhancement would be useful** to most mergo users. You may also want to point out the other projects that solved it better and which could serve as inspiration. + + +## Attribution +This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)! diff --git a/test/integration/vendor/github.com/imdario/mergo/README.md b/test/integration/vendor/github.com/imdario/mergo/README.md index 7e6f7aeee..4f0287498 100644 --- a/test/integration/vendor/github.com/imdario/mergo/README.md +++ b/test/integration/vendor/github.com/imdario/mergo/README.md @@ -1,6 +1,5 @@ # Mergo - [![GoDoc][3]][4] [![GitHub release][5]][6] [![GoCard][7]][8] @@ -9,6 +8,7 @@ [![Sourcegraph][11]][12] [![FOSSA Status][13]][14] [![Become my sponsor][15]][16] +[![Tidelift][17]][18] [1]: https://travis-ci.org/imdario/mergo.png [2]: https://travis-ci.org/imdario/mergo @@ -26,6 +26,8 @@ [14]: https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_shield [15]: https://img.shields.io/github/sponsors/imdario [16]: https://github.com/sponsors/imdario +[17]: https://tidelift.com/badges/package/go/github.com%2Fimdario%2Fmergo +[18]: https://tidelift.com/subscription/pkg/go-github.com-imdario-mergo A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. @@ -55,7 +57,6 @@ If Mergo is useful to you, consider buying me a coffee, a beer, or making a mont ### Mergo in the wild -- [cli/cli](https://github.com/cli/cli) - [moby/moby](https://github.com/moby/moby) - [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes) - [vmware/dispatch](https://github.com/vmware/dispatch) diff --git a/test/integration/vendor/github.com/imdario/mergo/SECURITY.md b/test/integration/vendor/github.com/imdario/mergo/SECURITY.md new file mode 100644 index 000000000..a5de61f77 --- /dev/null +++ b/test/integration/vendor/github.com/imdario/mergo/SECURITY.md @@ -0,0 +1,14 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.3.x | :white_check_mark: | +| < 0.3 | :x: | + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/test/integration/vendor/github.com/imdario/mergo/map.go b/test/integration/vendor/github.com/imdario/mergo/map.go index a13a7ee46..f739255af 100644 --- a/test/integration/vendor/github.com/imdario/mergo/map.go +++ b/test/integration/vendor/github.com/imdario/mergo/map.go @@ -44,7 +44,7 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf } } // Remember, remember... - visited[h] = &visit{addr, typ, seen} + visited[h] = &visit{typ, seen, addr} } zeroValue := reflect.Value{} switch dst.Kind() { diff --git a/test/integration/vendor/github.com/imdario/mergo/merge.go b/test/integration/vendor/github.com/imdario/mergo/merge.go index 8b4e2f47a..1bf26cfe5 100644 --- a/test/integration/vendor/github.com/imdario/mergo/merge.go +++ b/test/integration/vendor/github.com/imdario/mergo/merge.go @@ -38,10 +38,10 @@ func isExportedComponent(field *reflect.StructField) bool { } type Config struct { + Transformers Transformers Overwrite bool AppendSlice bool TypeCheck bool - Transformers Transformers overwriteWithEmptyValue bool overwriteSliceWithEmptyValue bool sliceDeepCopy bool @@ -76,7 +76,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } } // Remember, remember... - visited[h] = &visit{addr, typ, seen} + visited[h] = &visit{typ, seen, addr} } if config.Transformers != nil && !isReflectNil(dst) && dst.IsValid() { @@ -205,6 +205,16 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co dst.SetMapIndex(key, srcElement) } } + + // Ensure that all keys in dst are deleted if they are not in src. + if overwriteWithEmptySrc { + for _, key := range dst.MapKeys() { + srcElement := src.MapIndex(key) + if !srcElement.IsValid() { + dst.SetMapIndex(key, reflect.Value{}) + } + } + } case reflect.Slice: if !dst.CanSet() { break diff --git a/test/integration/vendor/github.com/imdario/mergo/mergo.go b/test/integration/vendor/github.com/imdario/mergo/mergo.go index 9fe362d47..d2af2a95f 100644 --- a/test/integration/vendor/github.com/imdario/mergo/mergo.go +++ b/test/integration/vendor/github.com/imdario/mergo/mergo.go @@ -28,9 +28,9 @@ var ( // checks in progress are true when it reencounters them. // Visited are stored in a map indexed by 17 * a1 + a2; type visit struct { - ptr uintptr typ reflect.Type next *visit + ptr uintptr } // From src/pkg/encoding/json/encode.go. diff --git a/test/integration/vendor/github.com/klauspost/compress/README.md b/test/integration/vendor/github.com/klauspost/compress/README.md index 958666ed8..c2c7252fe 100644 --- a/test/integration/vendor/github.com/klauspost/compress/README.md +++ b/test/integration/vendor/github.com/klauspost/compress/README.md @@ -16,6 +16,21 @@ This package provides various compression algorithms. # changelog +* Mar 13, 2023 - [v1.16.1](https://github.com/klauspost/compress/releases/tag/v1.16.1) + * zstd: Speed up + improve best encoder by @greatroar in https://github.com/klauspost/compress/pull/776 + * gzhttp: Add optional [BREACH mitigation](https://github.com/klauspost/compress/tree/master/gzhttp#breach-mitigation). https://github.com/klauspost/compress/pull/762 https://github.com/klauspost/compress/pull/768 https://github.com/klauspost/compress/pull/769 https://github.com/klauspost/compress/pull/770 https://github.com/klauspost/compress/pull/767 + * s2: Add Intel LZ4s converter https://github.com/klauspost/compress/pull/766 + * zstd: Minor bug fixes https://github.com/klauspost/compress/pull/771 https://github.com/klauspost/compress/pull/772 https://github.com/klauspost/compress/pull/773 + * huff0: Speed up compress1xDo by @greatroar in https://github.com/klauspost/compress/pull/774 + +* Feb 26, 2023 - [v1.16.0](https://github.com/klauspost/compress/releases/tag/v1.16.0) + * s2: Add [Dictionary](https://github.com/klauspost/compress/tree/master/s2#dictionaries) support. https://github.com/klauspost/compress/pull/685 + * s2: Add Compression Size Estimate. https://github.com/klauspost/compress/pull/752 + * s2: Add support for custom stream encoder. https://github.com/klauspost/compress/pull/755 + * s2: Add LZ4 block converter. https://github.com/klauspost/compress/pull/748 + * s2: Support io.ReaderAt in ReadSeeker. https://github.com/klauspost/compress/pull/747 + * s2c/s2sx: Use concurrent decoding. https://github.com/klauspost/compress/pull/746 + * Jan 21st, 2023 (v1.15.15) * deflate: Improve level 7-9 by @klauspost in https://github.com/klauspost/compress/pull/739 * zstd: Add delta encoding support by @greatroar in https://github.com/klauspost/compress/pull/728 diff --git a/test/integration/vendor/github.com/klauspost/compress/fse/decompress.go b/test/integration/vendor/github.com/klauspost/compress/fse/decompress.go index 926f5f153..cc05d0f7e 100644 --- a/test/integration/vendor/github.com/klauspost/compress/fse/decompress.go +++ b/test/integration/vendor/github.com/klauspost/compress/fse/decompress.go @@ -260,7 +260,9 @@ func (s *Scratch) buildDtable() error { // If the buffer is over-read an error is returned. func (s *Scratch) decompress() error { br := &s.bits - br.init(s.br.unread()) + if err := br.init(s.br.unread()); err != nil { + return err + } var s1, s2 decoder // Initialize and decode first state and symbol. diff --git a/test/integration/vendor/github.com/klauspost/compress/huff0/bitwriter.go b/test/integration/vendor/github.com/klauspost/compress/huff0/bitwriter.go index ec71f7a34..aed2347ce 100644 --- a/test/integration/vendor/github.com/klauspost/compress/huff0/bitwriter.go +++ b/test/integration/vendor/github.com/klauspost/compress/huff0/bitwriter.go @@ -60,6 +60,22 @@ func (b *bitWriter) encTwoSymbols(ct cTable, av, bv byte) { b.nBits += encA.nBits + encB.nBits } +// encFourSymbols adds up to 32 bits from four symbols. +// It will not check if there is space for them, +// so the caller must ensure that b has been flushed recently. +func (b *bitWriter) encFourSymbols(encA, encB, encC, encD cTableEntry) { + bitsA := encA.nBits + bitsB := bitsA + encB.nBits + bitsC := bitsB + encC.nBits + bitsD := bitsC + encD.nBits + combined := uint64(encA.val) | + (uint64(encB.val) << (bitsA & 63)) | + (uint64(encC.val) << (bitsB & 63)) | + (uint64(encD.val) << (bitsC & 63)) + b.bitContainer |= combined << (b.nBits & 63) + b.nBits += bitsD +} + // flush32 will flush out, so there are at least 32 bits available for writing. func (b *bitWriter) flush32() { if b.nBits < 32 { diff --git a/test/integration/vendor/github.com/klauspost/compress/huff0/compress.go b/test/integration/vendor/github.com/klauspost/compress/huff0/compress.go index cdc94856f..4ee4fa18d 100644 --- a/test/integration/vendor/github.com/klauspost/compress/huff0/compress.go +++ b/test/integration/vendor/github.com/klauspost/compress/huff0/compress.go @@ -248,8 +248,7 @@ func (s *Scratch) compress1xDo(dst, src []byte) ([]byte, error) { tmp := src[n : n+4] // tmp should be len 4 bw.flush32() - bw.encTwoSymbols(cTable, tmp[3], tmp[2]) - bw.encTwoSymbols(cTable, tmp[1], tmp[0]) + bw.encFourSymbols(cTable[tmp[3]], cTable[tmp[2]], cTable[tmp[1]], cTable[tmp[0]]) } } else { for ; n >= 0; n -= 4 { diff --git a/test/integration/vendor/github.com/klauspost/compress/zstd/blockdec.go b/test/integration/vendor/github.com/klauspost/compress/zstd/blockdec.go index 2445bb4fe..5f272d87f 100644 --- a/test/integration/vendor/github.com/klauspost/compress/zstd/blockdec.go +++ b/test/integration/vendor/github.com/klauspost/compress/zstd/blockdec.go @@ -9,6 +9,7 @@ import ( "encoding/binary" "errors" "fmt" + "hash/crc32" "io" "os" "path/filepath" @@ -442,6 +443,9 @@ func (b *blockDec) decodeLiterals(in []byte, hist *history) (remain []byte, err } } var err error + if debugDecoder { + println("huff table input:", len(literals), "CRC:", crc32.ChecksumIEEE(literals)) + } huff, literals, err = huff0.ReadTable(literals, huff) if err != nil { println("reading huffman table:", err) diff --git a/test/integration/vendor/github.com/klauspost/compress/zstd/bytebuf.go b/test/integration/vendor/github.com/klauspost/compress/zstd/bytebuf.go index 176788f25..512ffe5b9 100644 --- a/test/integration/vendor/github.com/klauspost/compress/zstd/bytebuf.go +++ b/test/integration/vendor/github.com/klauspost/compress/zstd/bytebuf.go @@ -54,7 +54,7 @@ func (b *byteBuf) readBig(n int, dst []byte) ([]byte, error) { func (b *byteBuf) readByte() (byte, error) { bb := *b if len(bb) < 1 { - return 0, nil + return 0, io.ErrUnexpectedEOF } r := bb[0] *b = bb[1:] diff --git a/test/integration/vendor/github.com/klauspost/compress/zstd/enc_best.go b/test/integration/vendor/github.com/klauspost/compress/zstd/enc_best.go index 830f5ba74..07f657d36 100644 --- a/test/integration/vendor/github.com/klauspost/compress/zstd/enc_best.go +++ b/test/integration/vendor/github.com/klauspost/compress/zstd/enc_best.go @@ -32,7 +32,6 @@ type match struct { length int32 rep int32 est int32 - _ [12]byte // Aligned size to cache line: 4+4+4+4+4 bytes + 12 bytes padding = 32 bytes } const highScore = 25000 @@ -189,12 +188,6 @@ encodeLoop: panic("offset0 was 0") } - bestOf := func(a, b *match) *match { - if a.est-b.est+(a.s-b.s)*bitsPerByte>>10 < 0 { - return a - } - return b - } const goodEnough = 100 nextHashL := hashLen(cv, bestLongTableBits, bestLongLen) @@ -202,40 +195,41 @@ encodeLoop: candidateL := e.longTable[nextHashL] candidateS := e.table[nextHashS] - matchAt := func(offset int32, s int32, first uint32, rep int32) match { + // Set m to a match at offset if it looks like that will improve compression. + improve := func(m *match, offset int32, s int32, first uint32, rep int32) { if s-offset >= e.maxMatchOff || load3232(src, offset) != first { - return match{s: s, est: highScore} + return } if debugAsserts { if !bytes.Equal(src[s:s+4], src[offset:offset+4]) { panic(fmt.Sprintf("first match mismatch: %v != %v, first: %08x", src[s:s+4], src[offset:offset+4], first)) } } - m := match{offset: offset, s: s, length: 4 + e.matchlen(s+4, offset+4, src), rep: rep} - m.estBits(bitsPerByte) - return m + cand := match{offset: offset, s: s, length: 4 + e.matchlen(s+4, offset+4, src), rep: rep} + cand.estBits(bitsPerByte) + if m.est >= highScore || cand.est-m.est+(cand.s-m.s)*bitsPerByte>>10 < 0 { + *m = cand + } } - m1 := matchAt(candidateL.offset-e.cur, s, uint32(cv), -1) - m2 := matchAt(candidateL.prev-e.cur, s, uint32(cv), -1) - m3 := matchAt(candidateS.offset-e.cur, s, uint32(cv), -1) - m4 := matchAt(candidateS.prev-e.cur, s, uint32(cv), -1) - best := bestOf(bestOf(&m1, &m2), bestOf(&m3, &m4)) + best := match{s: s, est: highScore} + improve(&best, candidateL.offset-e.cur, s, uint32(cv), -1) + improve(&best, candidateL.prev-e.cur, s, uint32(cv), -1) + improve(&best, candidateS.offset-e.cur, s, uint32(cv), -1) + improve(&best, candidateS.prev-e.cur, s, uint32(cv), -1) if canRepeat && best.length < goodEnough { cv32 := uint32(cv >> 8) spp := s + 1 - m1 := matchAt(spp-offset1, spp, cv32, 1) - m2 := matchAt(spp-offset2, spp, cv32, 2) - m3 := matchAt(spp-offset3, spp, cv32, 3) - best = bestOf(bestOf(best, &m1), bestOf(&m2, &m3)) + improve(&best, spp-offset1, spp, cv32, 1) + improve(&best, spp-offset2, spp, cv32, 2) + improve(&best, spp-offset3, spp, cv32, 3) if best.length > 0 { cv32 = uint32(cv >> 24) spp += 2 - m1 := matchAt(spp-offset1, spp, cv32, 1) - m2 := matchAt(spp-offset2, spp, cv32, 2) - m3 := matchAt(spp-offset3, spp, cv32, 3) - best = bestOf(bestOf(best, &m1), bestOf(&m2, &m3)) + improve(&best, spp-offset1, spp, cv32, 1) + improve(&best, spp-offset2, spp, cv32, 2) + improve(&best, spp-offset3, spp, cv32, 3) } } // Load next and check... @@ -262,18 +256,16 @@ encodeLoop: candidateL2 := e.longTable[hashLen(cv2, bestLongTableBits, bestLongLen)] // Short at s+1 - m1 := matchAt(candidateS.offset-e.cur, s, uint32(cv), -1) + improve(&best, candidateS.offset-e.cur, s, uint32(cv), -1) // Long at s+1, s+2 - m2 := matchAt(candidateL.offset-e.cur, s, uint32(cv), -1) - m3 := matchAt(candidateL.prev-e.cur, s, uint32(cv), -1) - m4 := matchAt(candidateL2.offset-e.cur, s+1, uint32(cv2), -1) - m5 := matchAt(candidateL2.prev-e.cur, s+1, uint32(cv2), -1) - best = bestOf(bestOf(bestOf(best, &m1), &m2), bestOf(bestOf(&m3, &m4), &m5)) + improve(&best, candidateL.offset-e.cur, s, uint32(cv), -1) + improve(&best, candidateL.prev-e.cur, s, uint32(cv), -1) + improve(&best, candidateL2.offset-e.cur, s+1, uint32(cv2), -1) + improve(&best, candidateL2.prev-e.cur, s+1, uint32(cv2), -1) if false { // Short at s+3. // Too often worse... - m := matchAt(e.table[hashLen(cv2>>8, bestShortTableBits, bestShortLen)].offset-e.cur, s+2, uint32(cv2>>8), -1) - best = bestOf(best, &m) + improve(&best, e.table[hashLen(cv2>>8, bestShortTableBits, bestShortLen)].offset-e.cur, s+2, uint32(cv2>>8), -1) } // See if we can find a better match by checking where the current best ends. // Use that offset to see if we can find a better full match. @@ -284,13 +276,10 @@ encodeLoop: // For this compression level 2 yields the best results. const skipBeginning = 2 if pos := candidateEnd.offset - e.cur - best.length + skipBeginning; pos >= 0 { - m := matchAt(pos, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) - bestEnd := bestOf(best, &m) + improve(&best, pos, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) if pos := candidateEnd.prev - e.cur - best.length + skipBeginning; pos >= 0 { - m := matchAt(pos, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) - bestEnd = bestOf(bestEnd, &m) + improve(&best, pos, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) } - best = bestEnd } } } diff --git a/test/integration/vendor/github.com/klauspost/compress/zstd/seqdec.go b/test/integration/vendor/github.com/klauspost/compress/zstd/seqdec.go index f833d1541..27fdf90fb 100644 --- a/test/integration/vendor/github.com/klauspost/compress/zstd/seqdec.go +++ b/test/integration/vendor/github.com/klauspost/compress/zstd/seqdec.go @@ -314,9 +314,6 @@ func (s *sequenceDecs) decodeSync(hist []byte) error { } size := ll + ml + len(out) if size-startSize > maxBlockSize { - if size-startSize == 424242 { - panic("here") - } return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) } if size > cap(out) { @@ -427,8 +424,7 @@ func (s *sequenceDecs) decodeSync(hist []byte) error { } } - // Check if space for literals - if size := len(s.literals) + len(s.out) - startSize; size > maxBlockSize { + if size := len(s.literals) + len(out) - startSize; size > maxBlockSize { return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) } diff --git a/test/integration/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go b/test/integration/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go index 191384adf..387a30e99 100644 --- a/test/integration/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go +++ b/test/integration/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go @@ -148,7 +148,6 @@ func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { s.seqSize += ctx.litRemain if s.seqSize > maxBlockSize { return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } err := br.close() if err != nil { diff --git a/test/integration/vendor/github.com/shirou/gopsutil/LICENSE b/test/integration/vendor/github.com/shirou/gopsutil/LICENSE deleted file mode 100644 index da71a5e72..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/LICENSE +++ /dev/null @@ -1,61 +0,0 @@ -gopsutil is distributed under BSD license reproduced below. - -Copyright (c) 2014, WAKAYAMA Shirou -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the gopsutil authors nor the names of its contributors - may be used to endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -------- -internal/common/binary.go in the gopsutil is copied and modifid from golang/encoding/binary.go. - - - -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu.go deleted file mode 100644 index 24a81167d..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu.go +++ /dev/null @@ -1,185 +0,0 @@ -package cpu - -import ( - "context" - "encoding/json" - "fmt" - "math" - "strconv" - "strings" - "sync" - "time" - - "github.com/shirou/gopsutil/internal/common" -) - -// TimesStat contains the amounts of time the CPU has spent performing different -// kinds of work. Time units are in seconds. It is based on linux /proc/stat file. -type TimesStat struct { - CPU string `json:"cpu"` - User float64 `json:"user"` - System float64 `json:"system"` - Idle float64 `json:"idle"` - Nice float64 `json:"nice"` - Iowait float64 `json:"iowait"` - Irq float64 `json:"irq"` - Softirq float64 `json:"softirq"` - Steal float64 `json:"steal"` - Guest float64 `json:"guest"` - GuestNice float64 `json:"guestNice"` -} - -type InfoStat struct { - CPU int32 `json:"cpu"` - VendorID string `json:"vendorId"` - Family string `json:"family"` - Model string `json:"model"` - Stepping int32 `json:"stepping"` - PhysicalID string `json:"physicalId"` - CoreID string `json:"coreId"` - Cores int32 `json:"cores"` - ModelName string `json:"modelName"` - Mhz float64 `json:"mhz"` - CacheSize int32 `json:"cacheSize"` - Flags []string `json:"flags"` - Microcode string `json:"microcode"` -} - -type lastPercent struct { - sync.Mutex - lastCPUTimes []TimesStat - lastPerCPUTimes []TimesStat -} - -var lastCPUPercent lastPercent -var invoke common.Invoker = common.Invoke{} - -func init() { - lastCPUPercent.Lock() - lastCPUPercent.lastCPUTimes, _ = Times(false) - lastCPUPercent.lastPerCPUTimes, _ = Times(true) - lastCPUPercent.Unlock() -} - -// Counts returns the number of physical or logical cores in the system -func Counts(logical bool) (int, error) { - return CountsWithContext(context.Background(), logical) -} - -func (c TimesStat) String() string { - v := []string{ - `"cpu":"` + c.CPU + `"`, - `"user":` + strconv.FormatFloat(c.User, 'f', 1, 64), - `"system":` + strconv.FormatFloat(c.System, 'f', 1, 64), - `"idle":` + strconv.FormatFloat(c.Idle, 'f', 1, 64), - `"nice":` + strconv.FormatFloat(c.Nice, 'f', 1, 64), - `"iowait":` + strconv.FormatFloat(c.Iowait, 'f', 1, 64), - `"irq":` + strconv.FormatFloat(c.Irq, 'f', 1, 64), - `"softirq":` + strconv.FormatFloat(c.Softirq, 'f', 1, 64), - `"steal":` + strconv.FormatFloat(c.Steal, 'f', 1, 64), - `"guest":` + strconv.FormatFloat(c.Guest, 'f', 1, 64), - `"guestNice":` + strconv.FormatFloat(c.GuestNice, 'f', 1, 64), - } - - return `{` + strings.Join(v, ",") + `}` -} - -// Total returns the total number of seconds in a CPUTimesStat -func (c TimesStat) Total() float64 { - total := c.User + c.System + c.Nice + c.Iowait + c.Irq + c.Softirq + - c.Steal + c.Idle - return total -} - -func (c InfoStat) String() string { - s, _ := json.Marshal(c) - return string(s) -} - -func getAllBusy(t TimesStat) (float64, float64) { - busy := t.User + t.System + t.Nice + t.Iowait + t.Irq + - t.Softirq + t.Steal - return busy + t.Idle, busy -} - -func calculateBusy(t1, t2 TimesStat) float64 { - t1All, t1Busy := getAllBusy(t1) - t2All, t2Busy := getAllBusy(t2) - - if t2Busy <= t1Busy { - return 0 - } - if t2All <= t1All { - return 100 - } - return math.Min(100, math.Max(0, (t2Busy-t1Busy)/(t2All-t1All)*100)) -} - -func calculateAllBusy(t1, t2 []TimesStat) ([]float64, error) { - // Make sure the CPU measurements have the same length. - if len(t1) != len(t2) { - return nil, fmt.Errorf( - "received two CPU counts: %d != %d", - len(t1), len(t2), - ) - } - - ret := make([]float64, len(t1)) - for i, t := range t2 { - ret[i] = calculateBusy(t1[i], t) - } - return ret, nil -} - -// Percent calculates the percentage of cpu used either per CPU or combined. -// If an interval of 0 is given it will compare the current cpu times against the last call. -// Returns one value per cpu, or a single value if percpu is set to false. -func Percent(interval time.Duration, percpu bool) ([]float64, error) { - return PercentWithContext(context.Background(), interval, percpu) -} - -func PercentWithContext(ctx context.Context, interval time.Duration, percpu bool) ([]float64, error) { - if interval <= 0 { - return percentUsedFromLastCall(percpu) - } - - // Get CPU usage at the start of the interval. - cpuTimes1, err := Times(percpu) - if err != nil { - return nil, err - } - - if err := common.Sleep(ctx, interval); err != nil { - return nil, err - } - - // And at the end of the interval. - cpuTimes2, err := Times(percpu) - if err != nil { - return nil, err - } - - return calculateAllBusy(cpuTimes1, cpuTimes2) -} - -func percentUsedFromLastCall(percpu bool) ([]float64, error) { - cpuTimes, err := Times(percpu) - if err != nil { - return nil, err - } - lastCPUPercent.Lock() - defer lastCPUPercent.Unlock() - var lastTimes []TimesStat - if percpu { - lastTimes = lastCPUPercent.lastPerCPUTimes - lastCPUPercent.lastPerCPUTimes = cpuTimes - } else { - lastTimes = lastCPUPercent.lastCPUTimes - lastCPUPercent.lastCPUTimes = cpuTimes - } - - if lastTimes == nil { - return nil, fmt.Errorf("error getting times for cpu percent. lastTimes was nil") - } - return calculateAllBusy(lastTimes, cpuTimes) -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin.go deleted file mode 100644 index 421f1e16b..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin.go +++ /dev/null @@ -1,112 +0,0 @@ -// +build darwin - -package cpu - -import ( - "context" - "strconv" - "strings" - - "github.com/tklauser/go-sysconf" - "golang.org/x/sys/unix" -) - -// sys/resource.h -const ( - CPUser = 0 - CPNice = 1 - CPSys = 2 - CPIntr = 3 - CPIdle = 4 - CPUStates = 5 -) - -// default value. from time.h -var ClocksPerSec = float64(128) - -func init() { - clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) - // ignore errors - if err == nil { - ClocksPerSec = float64(clkTck) - } -} - -func Times(percpu bool) ([]TimesStat, error) { - return TimesWithContext(context.Background(), percpu) -} - -func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - if percpu { - return perCPUTimes() - } - - return allCPUTimes() -} - -// Returns only one CPUInfoStat on FreeBSD -func Info() ([]InfoStat, error) { - return InfoWithContext(context.Background()) -} - -func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - var ret []InfoStat - - c := InfoStat{} - c.ModelName, _ = unix.Sysctl("machdep.cpu.brand_string") - family, _ := unix.SysctlUint32("machdep.cpu.family") - c.Family = strconv.FormatUint(uint64(family), 10) - model, _ := unix.SysctlUint32("machdep.cpu.model") - c.Model = strconv.FormatUint(uint64(model), 10) - stepping, _ := unix.SysctlUint32("machdep.cpu.stepping") - c.Stepping = int32(stepping) - features, err := unix.Sysctl("machdep.cpu.features") - if err == nil { - for _, v := range strings.Fields(features) { - c.Flags = append(c.Flags, strings.ToLower(v)) - } - } - leaf7Features, err := unix.Sysctl("machdep.cpu.leaf7_features") - if err == nil { - for _, v := range strings.Fields(leaf7Features) { - c.Flags = append(c.Flags, strings.ToLower(v)) - } - } - extfeatures, err := unix.Sysctl("machdep.cpu.extfeatures") - if err == nil { - for _, v := range strings.Fields(extfeatures) { - c.Flags = append(c.Flags, strings.ToLower(v)) - } - } - cores, _ := unix.SysctlUint32("machdep.cpu.core_count") - c.Cores = int32(cores) - cacheSize, _ := unix.SysctlUint32("machdep.cpu.cache.size") - c.CacheSize = int32(cacheSize) - c.VendorID, _ = unix.Sysctl("machdep.cpu.vendor") - - // Use the rated frequency of the CPU. This is a static value and does not - // account for low power or Turbo Boost modes. - cpuFrequency, err := unix.SysctlUint64("hw.cpufrequency") - if err != nil { - return ret, err - } - c.Mhz = float64(cpuFrequency) / 1000000.0 - - return append(ret, c), nil -} - -func CountsWithContext(ctx context.Context, logical bool) (int, error) { - var cpuArgument string - if logical { - cpuArgument = "hw.logicalcpu" - } else { - cpuArgument = "hw.physicalcpu" - } - - count, err := unix.SysctlUint32(cpuArgument) - if err != nil { - return 0, err - } - - return int(count), nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_cgo.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_cgo.go deleted file mode 100644 index 2a7d4a115..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_cgo.go +++ /dev/null @@ -1,112 +0,0 @@ -// +build darwin -// +build cgo - -package cpu - -/* -#include -#include -#include -#include -#include -#include -#include -#if TARGET_OS_MAC -#include -#endif -#include -#include -*/ -import "C" - -import ( - "bytes" - "encoding/binary" - "fmt" - "unsafe" -) - -// these CPU times for darwin is borrowed from influxdb/telegraf. - -func perCPUTimes() ([]TimesStat, error) { - var ( - count C.mach_msg_type_number_t - cpuload *C.processor_cpu_load_info_data_t - ncpu C.natural_t - ) - - status := C.host_processor_info(C.host_t(C.mach_host_self()), - C.PROCESSOR_CPU_LOAD_INFO, - &ncpu, - (*C.processor_info_array_t)(unsafe.Pointer(&cpuload)), - &count) - - if status != C.KERN_SUCCESS { - return nil, fmt.Errorf("host_processor_info error=%d", status) - } - - // jump through some cgo casting hoops and ensure we properly free - // the memory that cpuload points to - target := C.vm_map_t(C.mach_task_self_) - address := C.vm_address_t(uintptr(unsafe.Pointer(cpuload))) - defer C.vm_deallocate(target, address, C.vm_size_t(ncpu)) - - // the body of struct processor_cpu_load_info - // aka processor_cpu_load_info_data_t - var cpu_ticks [C.CPU_STATE_MAX]uint32 - - // copy the cpuload array to a []byte buffer - // where we can binary.Read the data - size := int(ncpu) * binary.Size(cpu_ticks) - buf := (*[1 << 30]byte)(unsafe.Pointer(cpuload))[:size:size] - - bbuf := bytes.NewBuffer(buf) - - var ret []TimesStat - - for i := 0; i < int(ncpu); i++ { - err := binary.Read(bbuf, binary.LittleEndian, &cpu_ticks) - if err != nil { - return nil, err - } - - c := TimesStat{ - CPU: fmt.Sprintf("cpu%d", i), - User: float64(cpu_ticks[C.CPU_STATE_USER]) / ClocksPerSec, - System: float64(cpu_ticks[C.CPU_STATE_SYSTEM]) / ClocksPerSec, - Nice: float64(cpu_ticks[C.CPU_STATE_NICE]) / ClocksPerSec, - Idle: float64(cpu_ticks[C.CPU_STATE_IDLE]) / ClocksPerSec, - } - - ret = append(ret, c) - } - - return ret, nil -} - -func allCPUTimes() ([]TimesStat, error) { - var count C.mach_msg_type_number_t - var cpuload C.host_cpu_load_info_data_t - - count = C.HOST_CPU_LOAD_INFO_COUNT - - status := C.host_statistics(C.host_t(C.mach_host_self()), - C.HOST_CPU_LOAD_INFO, - C.host_info_t(unsafe.Pointer(&cpuload)), - &count) - - if status != C.KERN_SUCCESS { - return nil, fmt.Errorf("host_statistics error=%d", status) - } - - c := TimesStat{ - CPU: "cpu-total", - User: float64(cpuload.cpu_ticks[C.CPU_STATE_USER]) / ClocksPerSec, - System: float64(cpuload.cpu_ticks[C.CPU_STATE_SYSTEM]) / ClocksPerSec, - Nice: float64(cpuload.cpu_ticks[C.CPU_STATE_NICE]) / ClocksPerSec, - Idle: float64(cpuload.cpu_ticks[C.CPU_STATE_IDLE]) / ClocksPerSec, - } - - return []TimesStat{c}, nil - -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_nocgo.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_nocgo.go deleted file mode 100644 index 242b4a8e7..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_darwin_nocgo.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build darwin -// +build !cgo - -package cpu - -import "github.com/shirou/gopsutil/internal/common" - -func perCPUTimes() ([]TimesStat, error) { - return []TimesStat{}, common.ErrNotImplementedError -} - -func allCPUTimes() ([]TimesStat, error) { - return []TimesStat{}, common.ErrNotImplementedError -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly.go deleted file mode 100644 index 45094df1d..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly.go +++ /dev/null @@ -1,154 +0,0 @@ -package cpu - -import ( - "context" - "fmt" - "reflect" - "regexp" - "runtime" - "strconv" - "strings" - "unsafe" - - "github.com/shirou/gopsutil/internal/common" - "github.com/tklauser/go-sysconf" - "golang.org/x/sys/unix" -) - -var ClocksPerSec = float64(128) -var cpuMatch = regexp.MustCompile(`^CPU:`) -var originMatch = regexp.MustCompile(`Origin\s*=\s*"(.+)"\s+Id\s*=\s*(.+)\s+Stepping\s*=\s*(.+)`) -var featuresMatch = regexp.MustCompile(`Features=.+<(.+)>`) -var featuresMatch2 = regexp.MustCompile(`Features2=[a-f\dx]+<(.+)>`) -var cpuEnd = regexp.MustCompile(`^Trying to mount root`) -var cpuTimesSize int -var emptyTimes cpuTimes - -func init() { - clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) - // ignore errors - if err == nil { - ClocksPerSec = float64(clkTck) - } -} - -func timeStat(name string, t *cpuTimes) *TimesStat { - return &TimesStat{ - User: float64(t.User) / ClocksPerSec, - Nice: float64(t.Nice) / ClocksPerSec, - System: float64(t.Sys) / ClocksPerSec, - Idle: float64(t.Idle) / ClocksPerSec, - Irq: float64(t.Intr) / ClocksPerSec, - CPU: name, - } -} - -func Times(percpu bool) ([]TimesStat, error) { - return TimesWithContext(context.Background(), percpu) -} - -func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - if percpu { - buf, err := unix.SysctlRaw("kern.cp_times") - if err != nil { - return nil, err - } - - // We can't do this in init due to the conflict with cpu.init() - if cpuTimesSize == 0 { - cpuTimesSize = int(reflect.TypeOf(cpuTimes{}).Size()) - } - - ncpus := len(buf) / cpuTimesSize - ret := make([]TimesStat, 0, ncpus) - for i := 0; i < ncpus; i++ { - times := (*cpuTimes)(unsafe.Pointer(&buf[i*cpuTimesSize])) - if *times == emptyTimes { - // CPU not present - continue - } - ret = append(ret, *timeStat(fmt.Sprintf("cpu%d", len(ret)), times)) - } - return ret, nil - } - - buf, err := unix.SysctlRaw("kern.cp_time") - if err != nil { - return nil, err - } - - times := (*cpuTimes)(unsafe.Pointer(&buf[0])) - return []TimesStat{*timeStat("cpu-total", times)}, nil -} - -// Returns only one InfoStat on DragonflyBSD. The information regarding core -// count, however is accurate and it is assumed that all InfoStat attributes -// are the same across CPUs. -func Info() ([]InfoStat, error) { - return InfoWithContext(context.Background()) -} - -func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - const dmesgBoot = "/var/run/dmesg.boot" - - c, err := parseDmesgBoot(dmesgBoot) - if err != nil { - return nil, err - } - - var u32 uint32 - if u32, err = unix.SysctlUint32("hw.clockrate"); err != nil { - return nil, err - } - c.Mhz = float64(u32) - - var num int - var buf string - if buf, err = unix.Sysctl("hw.cpu_topology.tree"); err != nil { - return nil, err - } - num = strings.Count(buf, "CHIP") - c.Cores = int32(strings.Count(string(buf), "CORE") / num) - - if c.ModelName, err = unix.Sysctl("hw.model"); err != nil { - return nil, err - } - - ret := make([]InfoStat, num) - for i := 0; i < num; i++ { - ret[i] = c - } - - return ret, nil -} - -func parseDmesgBoot(fileName string) (InfoStat, error) { - c := InfoStat{} - lines, _ := common.ReadLines(fileName) - for _, line := range lines { - if matches := cpuEnd.FindStringSubmatch(line); matches != nil { - break - } else if matches := originMatch.FindStringSubmatch(line); matches != nil { - c.VendorID = matches[1] - t, err := strconv.ParseInt(matches[2], 10, 32) - if err != nil { - return c, fmt.Errorf("unable to parse DragonflyBSD CPU stepping information from %q: %v", line, err) - } - c.Stepping = int32(t) - } else if matches := featuresMatch.FindStringSubmatch(line); matches != nil { - for _, v := range strings.Split(matches[1], ",") { - c.Flags = append(c.Flags, strings.ToLower(v)) - } - } else if matches := featuresMatch2.FindStringSubmatch(line); matches != nil { - for _, v := range strings.Split(matches[1], ",") { - c.Flags = append(c.Flags, strings.ToLower(v)) - } - } - } - - return c, nil -} - -func CountsWithContext(ctx context.Context, logical bool) (int, error) { - return runtime.NumCPU(), nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly_amd64.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly_amd64.go deleted file mode 100644 index 57e14528d..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_dragonfly_amd64.go +++ /dev/null @@ -1,9 +0,0 @@ -package cpu - -type cpuTimes struct { - User uint64 - Nice uint64 - Sys uint64 - Intr uint64 - Idle uint64 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_fallback.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_fallback.go deleted file mode 100644 index 5551c49d1..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_fallback.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows,!dragonfly - -package cpu - -import ( - "context" - "runtime" - - "github.com/shirou/gopsutil/internal/common" -) - -func Times(percpu bool) ([]TimesStat, error) { - return TimesWithContext(context.Background(), percpu) -} - -func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - return []TimesStat{}, common.ErrNotImplementedError -} - -func Info() ([]InfoStat, error) { - return InfoWithContext(context.Background()) -} - -func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - return []InfoStat{}, common.ErrNotImplementedError -} - -func CountsWithContext(ctx context.Context, logical bool) (int, error) { - return runtime.NumCPU(), nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd.go deleted file mode 100644 index 24527af20..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd.go +++ /dev/null @@ -1,166 +0,0 @@ -package cpu - -import ( - "context" - "fmt" - "reflect" - "regexp" - "runtime" - "strconv" - "strings" - "unsafe" - - "github.com/shirou/gopsutil/internal/common" - "github.com/tklauser/go-sysconf" - "golang.org/x/sys/unix" -) - -var ClocksPerSec = float64(128) -var cpuMatch = regexp.MustCompile(`^CPU:`) -var originMatch = regexp.MustCompile(`Origin\s*=\s*"(.+)"\s+Id\s*=\s*(.+)\s+Family\s*=\s*(.+)\s+Model\s*=\s*(.+)\s+Stepping\s*=\s*(.+)`) -var featuresMatch = regexp.MustCompile(`Features=.+<(.+)>`) -var featuresMatch2 = regexp.MustCompile(`Features2=[a-f\dx]+<(.+)>`) -var cpuEnd = regexp.MustCompile(`^Trying to mount root`) -var cpuCores = regexp.MustCompile(`FreeBSD/SMP: (\d*) package\(s\) x (\d*) core\(s\)`) -var cpuTimesSize int -var emptyTimes cpuTimes - -func init() { - clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) - // ignore errors - if err == nil { - ClocksPerSec = float64(clkTck) - } -} - -func timeStat(name string, t *cpuTimes) *TimesStat { - return &TimesStat{ - User: float64(t.User) / ClocksPerSec, - Nice: float64(t.Nice) / ClocksPerSec, - System: float64(t.Sys) / ClocksPerSec, - Idle: float64(t.Idle) / ClocksPerSec, - Irq: float64(t.Intr) / ClocksPerSec, - CPU: name, - } -} - -func Times(percpu bool) ([]TimesStat, error) { - return TimesWithContext(context.Background(), percpu) -} - -func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - if percpu { - buf, err := unix.SysctlRaw("kern.cp_times") - if err != nil { - return nil, err - } - - // We can't do this in init due to the conflict with cpu.init() - if cpuTimesSize == 0 { - cpuTimesSize = int(reflect.TypeOf(cpuTimes{}).Size()) - } - - ncpus := len(buf) / cpuTimesSize - ret := make([]TimesStat, 0, ncpus) - for i := 0; i < ncpus; i++ { - times := (*cpuTimes)(unsafe.Pointer(&buf[i*cpuTimesSize])) - if *times == emptyTimes { - // CPU not present - continue - } - ret = append(ret, *timeStat(fmt.Sprintf("cpu%d", len(ret)), times)) - } - return ret, nil - } - - buf, err := unix.SysctlRaw("kern.cp_time") - if err != nil { - return nil, err - } - - times := (*cpuTimes)(unsafe.Pointer(&buf[0])) - return []TimesStat{*timeStat("cpu-total", times)}, nil -} - -// Returns only one InfoStat on FreeBSD. The information regarding core -// count, however is accurate and it is assumed that all InfoStat attributes -// are the same across CPUs. -func Info() ([]InfoStat, error) { - return InfoWithContext(context.Background()) -} - -func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - const dmesgBoot = "/var/run/dmesg.boot" - - c, num, err := parseDmesgBoot(dmesgBoot) - if err != nil { - return nil, err - } - - var u32 uint32 - if u32, err = unix.SysctlUint32("hw.clockrate"); err != nil { - return nil, err - } - c.Mhz = float64(u32) - - if u32, err = unix.SysctlUint32("hw.ncpu"); err != nil { - return nil, err - } - c.Cores = int32(u32) - - if c.ModelName, err = unix.Sysctl("hw.model"); err != nil { - return nil, err - } - - ret := make([]InfoStat, num) - for i := 0; i < num; i++ { - ret[i] = c - } - - return ret, nil -} - -func parseDmesgBoot(fileName string) (InfoStat, int, error) { - c := InfoStat{} - lines, _ := common.ReadLines(fileName) - cpuNum := 1 // default cpu num is 1 - for _, line := range lines { - if matches := cpuEnd.FindStringSubmatch(line); matches != nil { - break - } else if matches := originMatch.FindStringSubmatch(line); matches != nil { - c.VendorID = matches[1] - c.Family = matches[3] - c.Model = matches[4] - t, err := strconv.ParseInt(matches[5], 10, 32) - if err != nil { - return c, 0, fmt.Errorf("unable to parse FreeBSD CPU stepping information from %q: %v", line, err) - } - c.Stepping = int32(t) - } else if matches := featuresMatch.FindStringSubmatch(line); matches != nil { - for _, v := range strings.Split(matches[1], ",") { - c.Flags = append(c.Flags, strings.ToLower(v)) - } - } else if matches := featuresMatch2.FindStringSubmatch(line); matches != nil { - for _, v := range strings.Split(matches[1], ",") { - c.Flags = append(c.Flags, strings.ToLower(v)) - } - } else if matches := cpuCores.FindStringSubmatch(line); matches != nil { - t, err := strconv.ParseInt(matches[1], 10, 32) - if err != nil { - return c, 0, fmt.Errorf("unable to parse FreeBSD CPU Nums from %q: %v", line, err) - } - cpuNum = int(t) - t2, err := strconv.ParseInt(matches[2], 10, 32) - if err != nil { - return c, 0, fmt.Errorf("unable to parse FreeBSD CPU cores from %q: %v", line, err) - } - c.Cores = int32(t2) - } - } - - return c, cpuNum, nil -} - -func CountsWithContext(ctx context.Context, logical bool) (int, error) { - return runtime.NumCPU(), nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_386.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_386.go deleted file mode 100644 index 8b7f4c321..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_386.go +++ /dev/null @@ -1,9 +0,0 @@ -package cpu - -type cpuTimes struct { - User uint32 - Nice uint32 - Sys uint32 - Intr uint32 - Idle uint32 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_amd64.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_amd64.go deleted file mode 100644 index 57e14528d..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_amd64.go +++ /dev/null @@ -1,9 +0,0 @@ -package cpu - -type cpuTimes struct { - User uint64 - Nice uint64 - Sys uint64 - Intr uint64 - Idle uint64 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm.go deleted file mode 100644 index 8b7f4c321..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm.go +++ /dev/null @@ -1,9 +0,0 @@ -package cpu - -type cpuTimes struct { - User uint32 - Nice uint32 - Sys uint32 - Intr uint32 - Idle uint32 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm64.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm64.go deleted file mode 100644 index 57e14528d..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_freebsd_arm64.go +++ /dev/null @@ -1,9 +0,0 @@ -package cpu - -type cpuTimes struct { - User uint64 - Nice uint64 - Sys uint64 - Intr uint64 - Idle uint64 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_linux.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_linux.go deleted file mode 100644 index 21006bc33..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_linux.go +++ /dev/null @@ -1,406 +0,0 @@ -// +build linux - -package cpu - -import ( - "context" - "errors" - "fmt" - "path/filepath" - "strconv" - "strings" - - "github.com/shirou/gopsutil/internal/common" - "github.com/tklauser/go-sysconf" -) - -var ClocksPerSec = float64(100) - -func init() { - clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) - // ignore errors - if err == nil { - ClocksPerSec = float64(clkTck) - } -} - -func Times(percpu bool) ([]TimesStat, error) { - return TimesWithContext(context.Background(), percpu) -} - -func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - filename := common.HostProc("stat") - var lines = []string{} - if percpu { - statlines, err := common.ReadLines(filename) - if err != nil || len(statlines) < 2 { - return []TimesStat{}, nil - } - for _, line := range statlines[1:] { - if !strings.HasPrefix(line, "cpu") { - break - } - lines = append(lines, line) - } - } else { - lines, _ = common.ReadLinesOffsetN(filename, 0, 1) - } - - ret := make([]TimesStat, 0, len(lines)) - - for _, line := range lines { - ct, err := parseStatLine(line) - if err != nil { - continue - } - ret = append(ret, *ct) - - } - return ret, nil -} - -func sysCPUPath(cpu int32, relPath string) string { - return common.HostSys(fmt.Sprintf("devices/system/cpu/cpu%d", cpu), relPath) -} - -func finishCPUInfo(c *InfoStat) error { - var lines []string - var err error - var value float64 - - if len(c.CoreID) == 0 { - lines, err = common.ReadLines(sysCPUPath(c.CPU, "topology/core_id")) - if err == nil { - c.CoreID = lines[0] - } - } - - // override the value of c.Mhz with cpufreq/cpuinfo_max_freq regardless - // of the value from /proc/cpuinfo because we want to report the maximum - // clock-speed of the CPU for c.Mhz, matching the behaviour of Windows - lines, err = common.ReadLines(sysCPUPath(c.CPU, "cpufreq/cpuinfo_max_freq")) - // if we encounter errors below such as there are no cpuinfo_max_freq file, - // we just ignore. so let Mhz is 0. - if err != nil || len(lines) == 0 { - return nil - } - value, err = strconv.ParseFloat(lines[0], 64) - if err != nil { - return nil - } - c.Mhz = value / 1000.0 // value is in kHz - if c.Mhz > 9999 { - c.Mhz = c.Mhz / 1000.0 // value in Hz - } - return nil -} - -// CPUInfo on linux will return 1 item per physical thread. -// -// CPUs have three levels of counting: sockets, cores, threads. -// Cores with HyperThreading count as having 2 threads per core. -// Sockets often come with many physical CPU cores. -// For example a single socket board with two cores each with HT will -// return 4 CPUInfoStat structs on Linux and the "Cores" field set to 1. -func Info() ([]InfoStat, error) { - return InfoWithContext(context.Background()) -} - -func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - filename := common.HostProc("cpuinfo") - lines, _ := common.ReadLines(filename) - - var ret []InfoStat - var processorName string - - c := InfoStat{CPU: -1, Cores: 1} - for _, line := range lines { - fields := strings.Split(line, ":") - if len(fields) < 2 { - continue - } - key := strings.TrimSpace(fields[0]) - value := strings.TrimSpace(fields[1]) - - switch key { - case "Processor": - processorName = value - case "processor": - if c.CPU >= 0 { - err := finishCPUInfo(&c) - if err != nil { - return ret, err - } - ret = append(ret, c) - } - c = InfoStat{Cores: 1, ModelName: processorName} - t, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return ret, err - } - c.CPU = int32(t) - case "vendorId", "vendor_id": - c.VendorID = value - case "CPU implementer": - if v, err := strconv.ParseUint(value, 0, 8); err == nil { - switch v { - case 0x41: - c.VendorID = "ARM" - case 0x42: - c.VendorID = "Broadcom" - case 0x43: - c.VendorID = "Cavium" - case 0x44: - c.VendorID = "DEC" - case 0x46: - c.VendorID = "Fujitsu" - case 0x48: - c.VendorID = "HiSilicon" - case 0x49: - c.VendorID = "Infineon" - case 0x4d: - c.VendorID = "Motorola/Freescale" - case 0x4e: - c.VendorID = "NVIDIA" - case 0x50: - c.VendorID = "APM" - case 0x51: - c.VendorID = "Qualcomm" - case 0x56: - c.VendorID = "Marvell" - case 0x61: - c.VendorID = "Apple" - case 0x69: - c.VendorID = "Intel" - case 0xc0: - c.VendorID = "Ampere" - } - } - case "cpu family": - c.Family = value - case "model", "CPU part": - c.Model = value - case "model name", "cpu": - c.ModelName = value - if strings.Contains(value, "POWER8") || - strings.Contains(value, "POWER7") { - c.Model = strings.Split(value, " ")[0] - c.Family = "POWER" - c.VendorID = "IBM" - } - case "stepping", "revision", "CPU revision": - val := value - - if key == "revision" { - val = strings.Split(value, ".")[0] - } - - t, err := strconv.ParseInt(val, 10, 64) - if err != nil { - return ret, err - } - c.Stepping = int32(t) - case "cpu MHz", "clock": - // treat this as the fallback value, thus we ignore error - if t, err := strconv.ParseFloat(strings.Replace(value, "MHz", "", 1), 64); err == nil { - c.Mhz = t - } - case "cache size": - t, err := strconv.ParseInt(strings.Replace(value, " KB", "", 1), 10, 64) - if err != nil { - return ret, err - } - c.CacheSize = int32(t) - case "physical id": - c.PhysicalID = value - case "core id": - c.CoreID = value - case "flags", "Features": - c.Flags = strings.FieldsFunc(value, func(r rune) bool { - return r == ',' || r == ' ' - }) - case "microcode": - c.Microcode = value - } - } - if c.CPU >= 0 { - err := finishCPUInfo(&c) - if err != nil { - return ret, err - } - ret = append(ret, c) - } - return ret, nil -} - -func parseStatLine(line string) (*TimesStat, error) { - fields := strings.Fields(line) - - if len(fields) == 0 { - return nil, errors.New("stat does not contain cpu info") - } - - if strings.HasPrefix(fields[0], "cpu") == false { - return nil, errors.New("not contain cpu") - } - - cpu := fields[0] - if cpu == "cpu" { - cpu = "cpu-total" - } - user, err := strconv.ParseFloat(fields[1], 64) - if err != nil { - return nil, err - } - nice, err := strconv.ParseFloat(fields[2], 64) - if err != nil { - return nil, err - } - system, err := strconv.ParseFloat(fields[3], 64) - if err != nil { - return nil, err - } - idle, err := strconv.ParseFloat(fields[4], 64) - if err != nil { - return nil, err - } - iowait, err := strconv.ParseFloat(fields[5], 64) - if err != nil { - return nil, err - } - irq, err := strconv.ParseFloat(fields[6], 64) - if err != nil { - return nil, err - } - softirq, err := strconv.ParseFloat(fields[7], 64) - if err != nil { - return nil, err - } - - ct := &TimesStat{ - CPU: cpu, - User: user / ClocksPerSec, - Nice: nice / ClocksPerSec, - System: system / ClocksPerSec, - Idle: idle / ClocksPerSec, - Iowait: iowait / ClocksPerSec, - Irq: irq / ClocksPerSec, - Softirq: softirq / ClocksPerSec, - } - if len(fields) > 8 { // Linux >= 2.6.11 - steal, err := strconv.ParseFloat(fields[8], 64) - if err != nil { - return nil, err - } - ct.Steal = steal / ClocksPerSec - } - if len(fields) > 9 { // Linux >= 2.6.24 - guest, err := strconv.ParseFloat(fields[9], 64) - if err != nil { - return nil, err - } - ct.Guest = guest / ClocksPerSec - } - if len(fields) > 10 { // Linux >= 3.2.0 - guestNice, err := strconv.ParseFloat(fields[10], 64) - if err != nil { - return nil, err - } - ct.GuestNice = guestNice / ClocksPerSec - } - - return ct, nil -} - -func CountsWithContext(ctx context.Context, logical bool) (int, error) { - if logical { - ret := 0 - // https://github.com/giampaolo/psutil/blob/d01a9eaa35a8aadf6c519839e987a49d8be2d891/psutil/_pslinux.py#L599 - procCpuinfo := common.HostProc("cpuinfo") - lines, err := common.ReadLines(procCpuinfo) - if err == nil { - for _, line := range lines { - line = strings.ToLower(line) - if strings.HasPrefix(line, "processor") { - _, err = strconv.Atoi(strings.TrimSpace(line[strings.IndexByte(line, ':')+1:])) - if err == nil { - ret++ - } - } - } - } - if ret == 0 { - procStat := common.HostProc("stat") - lines, err = common.ReadLines(procStat) - if err != nil { - return 0, err - } - for _, line := range lines { - if len(line) >= 4 && strings.HasPrefix(line, "cpu") && '0' <= line[3] && line[3] <= '9' { // `^cpu\d` regexp matching - ret++ - } - } - } - return ret, nil - } - // physical cores - // https://github.com/giampaolo/psutil/blob/8415355c8badc9c94418b19bdf26e622f06f0cce/psutil/_pslinux.py#L615-L628 - var threadSiblingsLists = make(map[string]bool) - // These 2 files are the same but */core_cpus_list is newer while */thread_siblings_list is deprecated and may disappear in the future. - // https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst - // https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964 - // https://lkml.org/lkml/2019/2/26/41 - for _, glob := range []string{"devices/system/cpu/cpu[0-9]*/topology/core_cpus_list", "devices/system/cpu/cpu[0-9]*/topology/thread_siblings_list"} { - if files, err := filepath.Glob(common.HostSys(glob)); err == nil { - for _, file := range files { - lines, err := common.ReadLines(file) - if err != nil || len(lines) != 1 { - continue - } - threadSiblingsLists[lines[0]] = true - } - ret := len(threadSiblingsLists) - if ret != 0 { - return ret, nil - } - } - } - // https://github.com/giampaolo/psutil/blob/122174a10b75c9beebe15f6c07dcf3afbe3b120d/psutil/_pslinux.py#L631-L652 - filename := common.HostProc("cpuinfo") - lines, err := common.ReadLines(filename) - if err != nil { - return 0, err - } - mapping := make(map[int]int) - currentInfo := make(map[string]int) - for _, line := range lines { - line = strings.ToLower(strings.TrimSpace(line)) - if line == "" { - // new section - id, okID := currentInfo["physical id"] - cores, okCores := currentInfo["cpu cores"] - if okID && okCores { - mapping[id] = cores - } - currentInfo = make(map[string]int) - continue - } - fields := strings.Split(line, ":") - if len(fields) < 2 { - continue - } - fields[0] = strings.TrimSpace(fields[0]) - if fields[0] == "physical id" || fields[0] == "cpu cores" { - val, err := strconv.Atoi(strings.TrimSpace(fields[1])) - if err != nil { - continue - } - currentInfo[fields[0]] = val - } - } - ret := 0 - for _, v := range mapping { - ret += v - } - return ret, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_openbsd.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_openbsd.go deleted file mode 100644 index c761aa21d..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_openbsd.go +++ /dev/null @@ -1,178 +0,0 @@ -// +build openbsd - -package cpu - -import ( - "bytes" - "context" - "encoding/binary" - "fmt" - "runtime" - "strconv" - "strings" - "syscall" - - "github.com/shirou/gopsutil/internal/common" - "github.com/tklauser/go-sysconf" - "golang.org/x/sys/unix" -) - -// sys/sched.h -var ( - CPUser = 0 - CPNice = 1 - CPSys = 2 - CPIntr = 3 - CPIdle = 4 - CPUStates = 5 -) - -// sys/sysctl.h -const ( - CTLKern = 1 // "high kernel": proc, limits - CTLHw = 6 // CTL_HW - SMT = 24 // HW_SMT - KernCptime = 40 // KERN_CPTIME - KernCptime2 = 71 // KERN_CPTIME2 -) - -var ClocksPerSec = float64(128) - -func init() { - clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) - // ignore errors - if err == nil { - ClocksPerSec = float64(clkTck) - } - - func() { - v, err := unix.Sysctl("kern.osrelease") // can't reuse host.PlatformInformation because of circular import - if err != nil { - return - } - v = strings.ToLower(v) - version, err := strconv.ParseFloat(v, 64) - if err != nil { - return - } - if version >= 6.4 { - CPIntr = 4 - CPIdle = 5 - CPUStates = 6 - } - }() -} - -func smt() (bool, error) { - mib := []int32{CTLHw, SMT} - buf, _, err := common.CallSyscall(mib) - if err != nil { - return false, err - } - - var ret bool - br := bytes.NewReader(buf) - if err := binary.Read(br, binary.LittleEndian, &ret); err != nil { - return false, err - } - - return ret, nil -} - -func Times(percpu bool) ([]TimesStat, error) { - return TimesWithContext(context.Background(), percpu) -} - -func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - var ret []TimesStat - - var ncpu int - if percpu { - ncpu, _ = Counts(true) - } else { - ncpu = 1 - } - - smt, err := smt() - if err == syscall.EOPNOTSUPP { - // if hw.smt is not applicable for this platform (e.g. i386), - // pretend it's enabled - smt = true - } else if err != nil { - return nil, err - } - - for i := 0; i < ncpu; i++ { - j := i - if !smt { - j *= 2 - } - - var cpuTimes = make([]int32, CPUStates) - var mib []int32 - if percpu { - mib = []int32{CTLKern, KernCptime2, int32(j)} - } else { - mib = []int32{CTLKern, KernCptime} - } - buf, _, err := common.CallSyscall(mib) - if err != nil { - return ret, err - } - - br := bytes.NewReader(buf) - err = binary.Read(br, binary.LittleEndian, &cpuTimes) - if err != nil { - return ret, err - } - c := TimesStat{ - User: float64(cpuTimes[CPUser]) / ClocksPerSec, - Nice: float64(cpuTimes[CPNice]) / ClocksPerSec, - System: float64(cpuTimes[CPSys]) / ClocksPerSec, - Idle: float64(cpuTimes[CPIdle]) / ClocksPerSec, - Irq: float64(cpuTimes[CPIntr]) / ClocksPerSec, - } - if percpu { - c.CPU = fmt.Sprintf("cpu%d", j) - } else { - c.CPU = "cpu-total" - } - ret = append(ret, c) - } - - return ret, nil -} - -// Returns only one (minimal) CPUInfoStat on OpenBSD -func Info() ([]InfoStat, error) { - return InfoWithContext(context.Background()) -} - -func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - var ret []InfoStat - var err error - - c := InfoStat{} - - mhz, err := unix.SysctlUint32("hw.cpuspeed") - if err != nil { - return nil, err - } - c.Mhz = float64(mhz) - - ncpu, err := unix.SysctlUint32("hw.ncpuonline") - if err != nil { - return nil, err - } - c.Cores = int32(ncpu) - - if c.ModelName, err = unix.Sysctl("hw.model"); err != nil { - return nil, err - } - - return append(ret, c), nil -} - -func CountsWithContext(ctx context.Context, logical bool) (int, error) { - return runtime.NumCPU(), nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_solaris.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_solaris.go deleted file mode 100644 index 4e3dea02a..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_solaris.go +++ /dev/null @@ -1,281 +0,0 @@ -package cpu - -import ( - "context" - "errors" - "fmt" - "os/exec" - "regexp" - "runtime" - "sort" - "strconv" - "strings" - - "github.com/tklauser/go-sysconf" -) - -var ClocksPerSec = float64(128) - -func init() { - clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) - // ignore errors - if err == nil { - ClocksPerSec = float64(clkTck) - } -} - -//sum all values in a float64 map with float64 keys -func msum(x map[float64]float64) float64 { - total := 0.0 - for _, y := range x { - total += y - } - return total -} - -func Times(percpu bool) ([]TimesStat, error) { - return TimesWithContext(context.Background(), percpu) -} - -func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - kstatSys, err := exec.LookPath("kstat") - if err != nil { - return nil, fmt.Errorf("cannot find kstat: %s", err) - } - cpu := make(map[float64]float64) - idle := make(map[float64]float64) - user := make(map[float64]float64) - kern := make(map[float64]float64) - iowt := make(map[float64]float64) - //swap := make(map[float64]float64) - kstatSysOut, err := invoke.CommandWithContext(ctx, kstatSys, "-p", "cpu_stat:*:*:/^idle$|^user$|^kernel$|^iowait$|^swap$/") - if err != nil { - return nil, fmt.Errorf("cannot execute kstat: %s", err) - } - re := regexp.MustCompile(`[:\s]+`) - for _, line := range strings.Split(string(kstatSysOut), "\n") { - fields := re.Split(line, -1) - if fields[0] != "cpu_stat" { - continue - } - cpuNumber, err := strconv.ParseFloat(fields[1], 64) - if err != nil { - return nil, fmt.Errorf("cannot parse cpu number: %s", err) - } - cpu[cpuNumber] = cpuNumber - switch fields[3] { - case "idle": - idle[cpuNumber], err = strconv.ParseFloat(fields[4], 64) - if err != nil { - return nil, fmt.Errorf("cannot parse idle: %s", err) - } - case "user": - user[cpuNumber], err = strconv.ParseFloat(fields[4], 64) - if err != nil { - return nil, fmt.Errorf("cannot parse user: %s", err) - } - case "kernel": - kern[cpuNumber], err = strconv.ParseFloat(fields[4], 64) - if err != nil { - return nil, fmt.Errorf("cannot parse kernel: %s", err) - } - case "iowait": - iowt[cpuNumber], err = strconv.ParseFloat(fields[4], 64) - if err != nil { - return nil, fmt.Errorf("cannot parse iowait: %s", err) - } - //not sure how this translates, don't report, add to kernel, something else? - /*case "swap": - swap[cpuNumber], err = strconv.ParseFloat(fields[4], 64) - if err != nil { - return nil, fmt.Errorf("cannot parse swap: %s", err) - } */ - } - } - ret := make([]TimesStat, 0, len(cpu)) - if percpu { - for _, c := range cpu { - ct := &TimesStat{ - CPU: fmt.Sprintf("cpu%d", int(cpu[c])), - Idle: idle[c] / ClocksPerSec, - User: user[c] / ClocksPerSec, - System: kern[c] / ClocksPerSec, - Iowait: iowt[c] / ClocksPerSec, - } - ret = append(ret, *ct) - } - } else { - ct := &TimesStat{ - CPU: "cpu-total", - Idle: msum(idle) / ClocksPerSec, - User: msum(user) / ClocksPerSec, - System: msum(kern) / ClocksPerSec, - Iowait: msum(iowt) / ClocksPerSec, - } - ret = append(ret, *ct) - } - return ret, nil -} - -func Info() ([]InfoStat, error) { - return InfoWithContext(context.Background()) -} - -func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - psrInfo, err := exec.LookPath("psrinfo") - if err != nil { - return nil, fmt.Errorf("cannot find psrinfo: %s", err) - } - psrInfoOut, err := invoke.CommandWithContext(ctx, psrInfo, "-p", "-v") - if err != nil { - return nil, fmt.Errorf("cannot execute psrinfo: %s", err) - } - - isaInfo, err := exec.LookPath("isainfo") - if err != nil { - return nil, fmt.Errorf("cannot find isainfo: %s", err) - } - isaInfoOut, err := invoke.CommandWithContext(ctx, isaInfo, "-b", "-v") - if err != nil { - return nil, fmt.Errorf("cannot execute isainfo: %s", err) - } - - procs, err := parseProcessorInfo(string(psrInfoOut)) - if err != nil { - return nil, fmt.Errorf("error parsing psrinfo output: %s", err) - } - - flags, err := parseISAInfo(string(isaInfoOut)) - if err != nil { - return nil, fmt.Errorf("error parsing isainfo output: %s", err) - } - - result := make([]InfoStat, 0, len(flags)) - for _, proc := range procs { - procWithFlags := proc - procWithFlags.Flags = flags - result = append(result, procWithFlags) - } - - return result, nil -} - -var flagsMatch = regexp.MustCompile(`[\w\.]+`) - -func parseISAInfo(cmdOutput string) ([]string, error) { - words := flagsMatch.FindAllString(cmdOutput, -1) - - // Sanity check the output - if len(words) < 4 || words[1] != "bit" || words[3] != "applications" { - return nil, errors.New("attempted to parse invalid isainfo output") - } - - flags := make([]string, len(words)-4) - for i, val := range words[4:] { - flags[i] = val - } - sort.Strings(flags) - - return flags, nil -} - -var psrInfoMatch = regexp.MustCompile(`The physical processor has (?:([\d]+) virtual processors? \(([\d-]+)\)|([\d]+) cores and ([\d]+) virtual processors[^\n]+)\n(?:\s+ The core has.+\n)*\s+.+ \((\w+) ([\S]+) family (.+) model (.+) step (.+) clock (.+) MHz\)\n[\s]*(.*)`) - -const ( - psrNumCoresOffset = 1 - psrNumCoresHTOffset = 3 - psrNumHTOffset = 4 - psrVendorIDOffset = 5 - psrFamilyOffset = 7 - psrModelOffset = 8 - psrStepOffset = 9 - psrClockOffset = 10 - psrModelNameOffset = 11 -) - -func parseProcessorInfo(cmdOutput string) ([]InfoStat, error) { - matches := psrInfoMatch.FindAllStringSubmatch(cmdOutput, -1) - - var infoStatCount int32 - result := make([]InfoStat, 0, len(matches)) - for physicalIndex, physicalCPU := range matches { - var step int32 - var clock float64 - - if physicalCPU[psrStepOffset] != "" { - stepParsed, err := strconv.ParseInt(physicalCPU[psrStepOffset], 10, 32) - if err != nil { - return nil, fmt.Errorf("cannot parse value %q for step as 32-bit integer: %s", physicalCPU[9], err) - } - step = int32(stepParsed) - } - - if physicalCPU[psrClockOffset] != "" { - clockParsed, err := strconv.ParseInt(physicalCPU[psrClockOffset], 10, 64) - if err != nil { - return nil, fmt.Errorf("cannot parse value %q for clock as 32-bit integer: %s", physicalCPU[10], err) - } - clock = float64(clockParsed) - } - - var err error - var numCores int64 - var numHT int64 - switch { - case physicalCPU[psrNumCoresOffset] != "": - numCores, err = strconv.ParseInt(physicalCPU[psrNumCoresOffset], 10, 32) - if err != nil { - return nil, fmt.Errorf("cannot parse value %q for core count as 32-bit integer: %s", physicalCPU[1], err) - } - - for i := 0; i < int(numCores); i++ { - result = append(result, InfoStat{ - CPU: infoStatCount, - PhysicalID: strconv.Itoa(physicalIndex), - CoreID: strconv.Itoa(i), - Cores: 1, - VendorID: physicalCPU[psrVendorIDOffset], - ModelName: physicalCPU[psrModelNameOffset], - Family: physicalCPU[psrFamilyOffset], - Model: physicalCPU[psrModelOffset], - Stepping: step, - Mhz: clock, - }) - infoStatCount++ - } - case physicalCPU[psrNumCoresHTOffset] != "": - numCores, err = strconv.ParseInt(physicalCPU[psrNumCoresHTOffset], 10, 32) - if err != nil { - return nil, fmt.Errorf("cannot parse value %q for core count as 32-bit integer: %s", physicalCPU[3], err) - } - - numHT, err = strconv.ParseInt(physicalCPU[psrNumHTOffset], 10, 32) - if err != nil { - return nil, fmt.Errorf("cannot parse value %q for hyperthread count as 32-bit integer: %s", physicalCPU[4], err) - } - - for i := 0; i < int(numCores); i++ { - result = append(result, InfoStat{ - CPU: infoStatCount, - PhysicalID: strconv.Itoa(physicalIndex), - CoreID: strconv.Itoa(i), - Cores: int32(numHT) / int32(numCores), - VendorID: physicalCPU[psrVendorIDOffset], - ModelName: physicalCPU[psrModelNameOffset], - Family: physicalCPU[psrFamilyOffset], - Model: physicalCPU[psrModelOffset], - Stepping: step, - Mhz: clock, - }) - infoStatCount++ - } - default: - return nil, errors.New("values for cores with and without hyperthreading are both set") - } - } - return result, nil -} - -func CountsWithContext(ctx context.Context, logical bool) (int, error) { - return runtime.NumCPU(), nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_windows.go b/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_windows.go deleted file mode 100644 index 0176c4775..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/cpu/cpu_windows.go +++ /dev/null @@ -1,265 +0,0 @@ -// +build windows - -package cpu - -import ( - "context" - "fmt" - "strings" - "unsafe" - - "github.com/yusufpapurcu/wmi" - "github.com/shirou/gopsutil/internal/common" - "golang.org/x/sys/windows" -) - -var ( - procGetActiveProcessorCount = common.Modkernel32.NewProc("GetActiveProcessorCount") - procGetNativeSystemInfo = common.Modkernel32.NewProc("GetNativeSystemInfo") -) - -type Win32_Processor struct { - Win32_ProcessorWithoutLoadPct - LoadPercentage *uint16 -} - -// LoadPercentage takes a linearly more time as the number of sockets increases. -// For vSphere by default corespersocket = 1, meaning for a 40 vCPU VM Get Processor Info -// could take more than half a minute. -type Win32_ProcessorWithoutLoadPct struct { - Family uint16 - Manufacturer string - Name string - NumberOfLogicalProcessors uint32 - NumberOfCores uint32 - ProcessorID *string - Stepping *string - MaxClockSpeed uint32 -} - -// SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION -// defined in windows api doc with the following -// https://docs.microsoft.com/en-us/windows/desktop/api/winternl/nf-winternl-ntquerysysteminformation#system_processor_performance_information -// additional fields documented here -// https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/processor_performance.htm -type win32_SystemProcessorPerformanceInformation struct { - IdleTime int64 // idle time in 100ns (this is not a filetime). - KernelTime int64 // kernel time in 100ns. kernel time includes idle time. (this is not a filetime). - UserTime int64 // usertime in 100ns (this is not a filetime). - DpcTime int64 // dpc time in 100ns (this is not a filetime). - InterruptTime int64 // interrupt time in 100ns - InterruptCount uint32 -} - -// Win32_PerfFormattedData_PerfOS_System struct to have count of processes and processor queue length -type Win32_PerfFormattedData_PerfOS_System struct { - Processes uint32 - ProcessorQueueLength uint32 -} - -const ( - ClocksPerSec = 10000000.0 - - // systemProcessorPerformanceInformationClass information class to query with NTQuerySystemInformation - // https://processhacker.sourceforge.io/doc/ntexapi_8h.html#ad5d815b48e8f4da1ef2eb7a2f18a54e0 - win32_SystemProcessorPerformanceInformationClass = 8 - - // size of systemProcessorPerformanceInfoSize in memory - win32_SystemProcessorPerformanceInfoSize = uint32(unsafe.Sizeof(win32_SystemProcessorPerformanceInformation{})) -) - -// Times returns times stat per cpu and combined for all CPUs -func Times(percpu bool) ([]TimesStat, error) { - return TimesWithContext(context.Background(), percpu) -} - -func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { - if percpu { - return perCPUTimes() - } - - var ret []TimesStat - var lpIdleTime common.FILETIME - var lpKernelTime common.FILETIME - var lpUserTime common.FILETIME - r, _, _ := common.ProcGetSystemTimes.Call( - uintptr(unsafe.Pointer(&lpIdleTime)), - uintptr(unsafe.Pointer(&lpKernelTime)), - uintptr(unsafe.Pointer(&lpUserTime))) - if r == 0 { - return ret, windows.GetLastError() - } - - LOT := float64(0.0000001) - HIT := (LOT * 4294967296.0) - idle := ((HIT * float64(lpIdleTime.DwHighDateTime)) + (LOT * float64(lpIdleTime.DwLowDateTime))) - user := ((HIT * float64(lpUserTime.DwHighDateTime)) + (LOT * float64(lpUserTime.DwLowDateTime))) - kernel := ((HIT * float64(lpKernelTime.DwHighDateTime)) + (LOT * float64(lpKernelTime.DwLowDateTime))) - system := (kernel - idle) - - ret = append(ret, TimesStat{ - CPU: "cpu-total", - Idle: float64(idle), - User: float64(user), - System: float64(system), - }) - return ret, nil -} - -func Info() ([]InfoStat, error) { - return InfoWithContext(context.Background()) -} - -func InfoWithContext(ctx context.Context) ([]InfoStat, error) { - var ret []InfoStat - var dst []Win32_ProcessorWithoutLoadPct - q := wmi.CreateQuery(&dst, "") - q = strings.ReplaceAll(q, "Win32_ProcessorWithoutLoadPct", "Win32_Processor") - if err := common.WMIQueryWithContext(ctx, q, &dst); err != nil { - return ret, err - } - - var procID string - for i, l := range dst { - procID = "" - if l.ProcessorID != nil { - procID = *l.ProcessorID - } - - cpu := InfoStat{ - CPU: int32(i), - Family: fmt.Sprintf("%d", l.Family), - VendorID: l.Manufacturer, - ModelName: l.Name, - Cores: int32(l.NumberOfLogicalProcessors), - PhysicalID: procID, - Mhz: float64(l.MaxClockSpeed), - Flags: []string{}, - } - ret = append(ret, cpu) - } - - return ret, nil -} - -// ProcInfo returns processes count and processor queue length in the system. -// There is a single queue for processor even on multiprocessors systems. -func ProcInfo() ([]Win32_PerfFormattedData_PerfOS_System, error) { - return ProcInfoWithContext(context.Background()) -} - -func ProcInfoWithContext(ctx context.Context) ([]Win32_PerfFormattedData_PerfOS_System, error) { - var ret []Win32_PerfFormattedData_PerfOS_System - q := wmi.CreateQuery(&ret, "") - err := common.WMIQueryWithContext(ctx, q, &ret) - if err != nil { - return []Win32_PerfFormattedData_PerfOS_System{}, err - } - return ret, err -} - -// perCPUTimes returns times stat per cpu, per core and overall for all CPUs -func perCPUTimes() ([]TimesStat, error) { - var ret []TimesStat - stats, err := perfInfo() - if err != nil { - return nil, err - } - for core, v := range stats { - c := TimesStat{ - CPU: fmt.Sprintf("cpu%d", core), - User: float64(v.UserTime) / ClocksPerSec, - System: float64(v.KernelTime-v.IdleTime) / ClocksPerSec, - Idle: float64(v.IdleTime) / ClocksPerSec, - Irq: float64(v.InterruptTime) / ClocksPerSec, - } - ret = append(ret, c) - } - return ret, nil -} - -// makes call to Windows API function to retrieve performance information for each core -func perfInfo() ([]win32_SystemProcessorPerformanceInformation, error) { - // Make maxResults large for safety. - // We can't invoke the api call with a results array that's too small. - // If we have more than 2056 cores on a single host, then it's probably the future. - maxBuffer := 2056 - // buffer for results from the windows proc - resultBuffer := make([]win32_SystemProcessorPerformanceInformation, maxBuffer) - // size of the buffer in memory - bufferSize := uintptr(win32_SystemProcessorPerformanceInfoSize) * uintptr(maxBuffer) - // size of the returned response - var retSize uint32 - - // Invoke windows api proc. - // The returned err from the windows dll proc will always be non-nil even when successful. - // See https://godoc.org/golang.org/x/sys/windows#LazyProc.Call for more information - retCode, _, err := common.ProcNtQuerySystemInformation.Call( - win32_SystemProcessorPerformanceInformationClass, // System Information Class -> SystemProcessorPerformanceInformation - uintptr(unsafe.Pointer(&resultBuffer[0])), // pointer to first element in result buffer - bufferSize, // size of the buffer in memory - uintptr(unsafe.Pointer(&retSize)), // pointer to the size of the returned results the windows proc will set this - ) - - // check return code for errors - if retCode != 0 { - return nil, fmt.Errorf("call to NtQuerySystemInformation returned %d. err: %s", retCode, err.Error()) - } - - // calculate the number of returned elements based on the returned size - numReturnedElements := retSize / win32_SystemProcessorPerformanceInfoSize - - // trim results to the number of returned elements - resultBuffer = resultBuffer[:numReturnedElements] - - return resultBuffer, nil -} - -// SystemInfo is an equivalent representation of SYSTEM_INFO in the Windows API. -// https://msdn.microsoft.com/en-us/library/ms724958%28VS.85%29.aspx?f=255&MSPPError=-2147217396 -// https://github.com/elastic/go-windows/blob/bb1581babc04d5cb29a2bfa7a9ac6781c730c8dd/kernel32.go#L43 -type systemInfo struct { - wProcessorArchitecture uint16 - wReserved uint16 - dwPageSize uint32 - lpMinimumApplicationAddress uintptr - lpMaximumApplicationAddress uintptr - dwActiveProcessorMask uintptr - dwNumberOfProcessors uint32 - dwProcessorType uint32 - dwAllocationGranularity uint32 - wProcessorLevel uint16 - wProcessorRevision uint16 -} - -func CountsWithContext(ctx context.Context, logical bool) (int, error) { - if logical { - // https://github.com/giampaolo/psutil/blob/d01a9eaa35a8aadf6c519839e987a49d8be2d891/psutil/_psutil_windows.c#L97 - err := procGetActiveProcessorCount.Find() - if err == nil { // Win7+ - ret, _, _ := procGetActiveProcessorCount.Call(uintptr(0xffff)) // ALL_PROCESSOR_GROUPS is 0xffff according to Rust's winapi lib https://docs.rs/winapi/*/x86_64-pc-windows-msvc/src/winapi/shared/ntdef.rs.html#120 - if ret != 0 { - return int(ret), nil - } - } - var systemInfo systemInfo - _, _, err = procGetNativeSystemInfo.Call(uintptr(unsafe.Pointer(&systemInfo))) - if systemInfo.dwNumberOfProcessors == 0 { - return 0, err - } - return int(systemInfo.dwNumberOfProcessors), nil - } - // physical cores https://github.com/giampaolo/psutil/blob/d01a9eaa35a8aadf6c519839e987a49d8be2d891/psutil/_psutil_windows.c#L499 - // for the time being, try with unreliable and slow WMI call… - var dst []Win32_ProcessorWithoutLoadPct - q := wmi.CreateQuery(&dst, "") - q = strings.ReplaceAll(q, "Win32_ProcessorWithoutLoadPct", "Win32_Processor") - if err := common.WMIQueryWithContext(ctx, q, &dst); err != nil { - return 0, err - } - var count uint32 - for _, d := range dst { - count += d.NumberOfCores - } - return int(count), nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/binary.go b/test/integration/vendor/github.com/shirou/gopsutil/internal/common/binary.go deleted file mode 100644 index bf385fd4f..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/binary.go +++ /dev/null @@ -1,634 +0,0 @@ -package common - -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package binary implements simple translation between numbers and byte -// sequences and encoding and decoding of varints. -// -// Numbers are translated by reading and writing fixed-size values. -// A fixed-size value is either a fixed-size arithmetic -// type (int8, uint8, int16, float32, complex64, ...) -// or an array or struct containing only fixed-size values. -// -// The varint functions encode and decode single integer values using -// a variable-length encoding; smaller values require fewer bytes. -// For a specification, see -// http://code.google.com/apis/protocolbuffers/docs/encoding.html. -// -// This package favors simplicity over efficiency. Clients that require -// high-performance serialization, especially for large data structures, -// should look at more advanced solutions such as the encoding/gob -// package or protocol buffers. -import ( - "errors" - "io" - "math" - "reflect" -) - -// A ByteOrder specifies how to convert byte sequences into -// 16-, 32-, or 64-bit unsigned integers. -type ByteOrder interface { - Uint16([]byte) uint16 - Uint32([]byte) uint32 - Uint64([]byte) uint64 - PutUint16([]byte, uint16) - PutUint32([]byte, uint32) - PutUint64([]byte, uint64) - String() string -} - -// LittleEndian is the little-endian implementation of ByteOrder. -var LittleEndian littleEndian - -// BigEndian is the big-endian implementation of ByteOrder. -var BigEndian bigEndian - -type littleEndian struct{} - -func (littleEndian) Uint16(b []byte) uint16 { return uint16(b[0]) | uint16(b[1])<<8 } - -func (littleEndian) PutUint16(b []byte, v uint16) { - b[0] = byte(v) - b[1] = byte(v >> 8) -} - -func (littleEndian) Uint32(b []byte) uint32 { - return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 -} - -func (littleEndian) PutUint32(b []byte, v uint32) { - b[0] = byte(v) - b[1] = byte(v >> 8) - b[2] = byte(v >> 16) - b[3] = byte(v >> 24) -} - -func (littleEndian) Uint64(b []byte) uint64 { - return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | - uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 -} - -func (littleEndian) PutUint64(b []byte, v uint64) { - b[0] = byte(v) - b[1] = byte(v >> 8) - b[2] = byte(v >> 16) - b[3] = byte(v >> 24) - b[4] = byte(v >> 32) - b[5] = byte(v >> 40) - b[6] = byte(v >> 48) - b[7] = byte(v >> 56) -} - -func (littleEndian) String() string { return "LittleEndian" } - -func (littleEndian) GoString() string { return "binary.LittleEndian" } - -type bigEndian struct{} - -func (bigEndian) Uint16(b []byte) uint16 { return uint16(b[1]) | uint16(b[0])<<8 } - -func (bigEndian) PutUint16(b []byte, v uint16) { - b[0] = byte(v >> 8) - b[1] = byte(v) -} - -func (bigEndian) Uint32(b []byte) uint32 { - return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 -} - -func (bigEndian) PutUint32(b []byte, v uint32) { - b[0] = byte(v >> 24) - b[1] = byte(v >> 16) - b[2] = byte(v >> 8) - b[3] = byte(v) -} - -func (bigEndian) Uint64(b []byte) uint64 { - return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | - uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 -} - -func (bigEndian) PutUint64(b []byte, v uint64) { - b[0] = byte(v >> 56) - b[1] = byte(v >> 48) - b[2] = byte(v >> 40) - b[3] = byte(v >> 32) - b[4] = byte(v >> 24) - b[5] = byte(v >> 16) - b[6] = byte(v >> 8) - b[7] = byte(v) -} - -func (bigEndian) String() string { return "BigEndian" } - -func (bigEndian) GoString() string { return "binary.BigEndian" } - -// Read reads structured binary data from r into data. -// Data must be a pointer to a fixed-size value or a slice -// of fixed-size values. -// Bytes read from r are decoded using the specified byte order -// and written to successive fields of the data. -// When reading into structs, the field data for fields with -// blank (_) field names is skipped; i.e., blank field names -// may be used for padding. -// When reading into a struct, all non-blank fields must be exported. -func Read(r io.Reader, order ByteOrder, data interface{}) error { - // Fast path for basic types and slices. - if n := intDataSize(data); n != 0 { - var b [8]byte - var bs []byte - if n > len(b) { - bs = make([]byte, n) - } else { - bs = b[:n] - } - if _, err := io.ReadFull(r, bs); err != nil { - return err - } - switch data := data.(type) { - case *int8: - *data = int8(b[0]) - case *uint8: - *data = b[0] - case *int16: - *data = int16(order.Uint16(bs)) - case *uint16: - *data = order.Uint16(bs) - case *int32: - *data = int32(order.Uint32(bs)) - case *uint32: - *data = order.Uint32(bs) - case *int64: - *data = int64(order.Uint64(bs)) - case *uint64: - *data = order.Uint64(bs) - case []int8: - for i, x := range bs { // Easier to loop over the input for 8-bit values. - data[i] = int8(x) - } - case []uint8: - copy(data, bs) - case []int16: - for i := range data { - data[i] = int16(order.Uint16(bs[2*i:])) - } - case []uint16: - for i := range data { - data[i] = order.Uint16(bs[2*i:]) - } - case []int32: - for i := range data { - data[i] = int32(order.Uint32(bs[4*i:])) - } - case []uint32: - for i := range data { - data[i] = order.Uint32(bs[4*i:]) - } - case []int64: - for i := range data { - data[i] = int64(order.Uint64(bs[8*i:])) - } - case []uint64: - for i := range data { - data[i] = order.Uint64(bs[8*i:]) - } - } - return nil - } - - // Fallback to reflect-based decoding. - v := reflect.ValueOf(data) - size := -1 - switch v.Kind() { - case reflect.Ptr: - v = v.Elem() - size = dataSize(v) - case reflect.Slice: - size = dataSize(v) - } - if size < 0 { - return errors.New("binary.Read: invalid type " + reflect.TypeOf(data).String()) - } - d := &decoder{order: order, buf: make([]byte, size)} - if _, err := io.ReadFull(r, d.buf); err != nil { - return err - } - d.value(v) - return nil -} - -// Write writes the binary representation of data into w. -// Data must be a fixed-size value or a slice of fixed-size -// values, or a pointer to such data. -// Bytes written to w are encoded using the specified byte order -// and read from successive fields of the data. -// When writing structs, zero values are written for fields -// with blank (_) field names. -func Write(w io.Writer, order ByteOrder, data interface{}) error { - // Fast path for basic types and slices. - if n := intDataSize(data); n != 0 { - var b [8]byte - var bs []byte - if n > len(b) { - bs = make([]byte, n) - } else { - bs = b[:n] - } - switch v := data.(type) { - case *int8: - bs = b[:1] - b[0] = byte(*v) - case int8: - bs = b[:1] - b[0] = byte(v) - case []int8: - for i, x := range v { - bs[i] = byte(x) - } - case *uint8: - bs = b[:1] - b[0] = *v - case uint8: - bs = b[:1] - b[0] = v - case []uint8: - bs = v - case *int16: - bs = b[:2] - order.PutUint16(bs, uint16(*v)) - case int16: - bs = b[:2] - order.PutUint16(bs, uint16(v)) - case []int16: - for i, x := range v { - order.PutUint16(bs[2*i:], uint16(x)) - } - case *uint16: - bs = b[:2] - order.PutUint16(bs, *v) - case uint16: - bs = b[:2] - order.PutUint16(bs, v) - case []uint16: - for i, x := range v { - order.PutUint16(bs[2*i:], x) - } - case *int32: - bs = b[:4] - order.PutUint32(bs, uint32(*v)) - case int32: - bs = b[:4] - order.PutUint32(bs, uint32(v)) - case []int32: - for i, x := range v { - order.PutUint32(bs[4*i:], uint32(x)) - } - case *uint32: - bs = b[:4] - order.PutUint32(bs, *v) - case uint32: - bs = b[:4] - order.PutUint32(bs, v) - case []uint32: - for i, x := range v { - order.PutUint32(bs[4*i:], x) - } - case *int64: - bs = b[:8] - order.PutUint64(bs, uint64(*v)) - case int64: - bs = b[:8] - order.PutUint64(bs, uint64(v)) - case []int64: - for i, x := range v { - order.PutUint64(bs[8*i:], uint64(x)) - } - case *uint64: - bs = b[:8] - order.PutUint64(bs, *v) - case uint64: - bs = b[:8] - order.PutUint64(bs, v) - case []uint64: - for i, x := range v { - order.PutUint64(bs[8*i:], x) - } - } - _, err := w.Write(bs) - return err - } - - // Fallback to reflect-based encoding. - v := reflect.Indirect(reflect.ValueOf(data)) - size := dataSize(v) - if size < 0 { - return errors.New("binary.Write: invalid type " + reflect.TypeOf(data).String()) - } - buf := make([]byte, size) - e := &encoder{order: order, buf: buf} - e.value(v) - _, err := w.Write(buf) - return err -} - -// Size returns how many bytes Write would generate to encode the value v, which -// must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. -// If v is neither of these, Size returns -1. -func Size(v interface{}) int { - return dataSize(reflect.Indirect(reflect.ValueOf(v))) -} - -// dataSize returns the number of bytes the actual data represented by v occupies in memory. -// For compound structures, it sums the sizes of the elements. Thus, for instance, for a slice -// it returns the length of the slice times the element size and does not count the memory -// occupied by the header. If the type of v is not acceptable, dataSize returns -1. -func dataSize(v reflect.Value) int { - if v.Kind() == reflect.Slice { - if s := sizeof(v.Type().Elem()); s >= 0 { - return s * v.Len() - } - return -1 - } - return sizeof(v.Type()) -} - -// sizeof returns the size >= 0 of variables for the given type or -1 if the type is not acceptable. -func sizeof(t reflect.Type) int { - switch t.Kind() { - case reflect.Array: - if s := sizeof(t.Elem()); s >= 0 { - return s * t.Len() - } - - case reflect.Struct: - sum := 0 - for i, n := 0, t.NumField(); i < n; i++ { - s := sizeof(t.Field(i).Type) - if s < 0 { - return -1 - } - sum += s - } - return sum - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.Ptr: - return int(t.Size()) - } - - return -1 -} - -type coder struct { - order ByteOrder - buf []byte -} - -type decoder coder -type encoder coder - -func (d *decoder) uint8() uint8 { - x := d.buf[0] - d.buf = d.buf[1:] - return x -} - -func (e *encoder) uint8(x uint8) { - e.buf[0] = x - e.buf = e.buf[1:] -} - -func (d *decoder) uint16() uint16 { - x := d.order.Uint16(d.buf[0:2]) - d.buf = d.buf[2:] - return x -} - -func (e *encoder) uint16(x uint16) { - e.order.PutUint16(e.buf[0:2], x) - e.buf = e.buf[2:] -} - -func (d *decoder) uint32() uint32 { - x := d.order.Uint32(d.buf[0:4]) - d.buf = d.buf[4:] - return x -} - -func (e *encoder) uint32(x uint32) { - e.order.PutUint32(e.buf[0:4], x) - e.buf = e.buf[4:] -} - -func (d *decoder) uint64() uint64 { - x := d.order.Uint64(d.buf[0:8]) - d.buf = d.buf[8:] - return x -} - -func (e *encoder) uint64(x uint64) { - e.order.PutUint64(e.buf[0:8], x) - e.buf = e.buf[8:] -} - -func (d *decoder) int8() int8 { return int8(d.uint8()) } - -func (e *encoder) int8(x int8) { e.uint8(uint8(x)) } - -func (d *decoder) int16() int16 { return int16(d.uint16()) } - -func (e *encoder) int16(x int16) { e.uint16(uint16(x)) } - -func (d *decoder) int32() int32 { return int32(d.uint32()) } - -func (e *encoder) int32(x int32) { e.uint32(uint32(x)) } - -func (d *decoder) int64() int64 { return int64(d.uint64()) } - -func (e *encoder) int64(x int64) { e.uint64(uint64(x)) } - -func (d *decoder) value(v reflect.Value) { - switch v.Kind() { - case reflect.Array: - l := v.Len() - for i := 0; i < l; i++ { - d.value(v.Index(i)) - } - - case reflect.Struct: - t := v.Type() - l := v.NumField() - for i := 0; i < l; i++ { - // Note: Calling v.CanSet() below is an optimization. - // It would be sufficient to check the field name, - // but creating the StructField info for each field is - // costly (run "go test -bench=ReadStruct" and compare - // results when making changes to this code). - if v := v.Field(i); v.CanSet() || t.Field(i).Name != "_" { - d.value(v) - } else { - d.skip(v) - } - } - - case reflect.Slice: - l := v.Len() - for i := 0; i < l; i++ { - d.value(v.Index(i)) - } - - case reflect.Int8: - v.SetInt(int64(d.int8())) - case reflect.Int16: - v.SetInt(int64(d.int16())) - case reflect.Int32: - v.SetInt(int64(d.int32())) - case reflect.Int64: - v.SetInt(d.int64()) - - case reflect.Uint8: - v.SetUint(uint64(d.uint8())) - case reflect.Uint16: - v.SetUint(uint64(d.uint16())) - case reflect.Uint32: - v.SetUint(uint64(d.uint32())) - case reflect.Uint64: - v.SetUint(d.uint64()) - - case reflect.Float32: - v.SetFloat(float64(math.Float32frombits(d.uint32()))) - case reflect.Float64: - v.SetFloat(math.Float64frombits(d.uint64())) - - case reflect.Complex64: - v.SetComplex(complex( - float64(math.Float32frombits(d.uint32())), - float64(math.Float32frombits(d.uint32())), - )) - case reflect.Complex128: - v.SetComplex(complex( - math.Float64frombits(d.uint64()), - math.Float64frombits(d.uint64()), - )) - } -} - -func (e *encoder) value(v reflect.Value) { - switch v.Kind() { - case reflect.Array: - l := v.Len() - for i := 0; i < l; i++ { - e.value(v.Index(i)) - } - - case reflect.Struct: - t := v.Type() - l := v.NumField() - for i := 0; i < l; i++ { - // see comment for corresponding code in decoder.value() - if v := v.Field(i); v.CanSet() || t.Field(i).Name != "_" { - e.value(v) - } else { - e.skip(v) - } - } - - case reflect.Slice: - l := v.Len() - for i := 0; i < l; i++ { - e.value(v.Index(i)) - } - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - switch v.Type().Kind() { - case reflect.Int8: - e.int8(int8(v.Int())) - case reflect.Int16: - e.int16(int16(v.Int())) - case reflect.Int32: - e.int32(int32(v.Int())) - case reflect.Int64: - e.int64(v.Int()) - } - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - switch v.Type().Kind() { - case reflect.Uint8: - e.uint8(uint8(v.Uint())) - case reflect.Uint16: - e.uint16(uint16(v.Uint())) - case reflect.Uint32: - e.uint32(uint32(v.Uint())) - case reflect.Uint64: - e.uint64(v.Uint()) - } - - case reflect.Float32, reflect.Float64: - switch v.Type().Kind() { - case reflect.Float32: - e.uint32(math.Float32bits(float32(v.Float()))) - case reflect.Float64: - e.uint64(math.Float64bits(v.Float())) - } - - case reflect.Complex64, reflect.Complex128: - switch v.Type().Kind() { - case reflect.Complex64: - x := v.Complex() - e.uint32(math.Float32bits(float32(real(x)))) - e.uint32(math.Float32bits(float32(imag(x)))) - case reflect.Complex128: - x := v.Complex() - e.uint64(math.Float64bits(real(x))) - e.uint64(math.Float64bits(imag(x))) - } - } -} - -func (d *decoder) skip(v reflect.Value) { - d.buf = d.buf[dataSize(v):] -} - -func (e *encoder) skip(v reflect.Value) { - n := dataSize(v) - for i := range e.buf[0:n] { - e.buf[i] = 0 - } - e.buf = e.buf[n:] -} - -// intDataSize returns the size of the data required to represent the data when encoded. -// It returns zero if the type cannot be implemented by the fast path in Read or Write. -func intDataSize(data interface{}) int { - switch data := data.(type) { - case int8, *int8, *uint8: - return 1 - case []int8: - return len(data) - case []uint8: - return len(data) - case int16, *int16, *uint16: - return 2 - case []int16: - return 2 * len(data) - case []uint16: - return 2 * len(data) - case int32, *int32, *uint32: - return 4 - case []int32: - return 4 * len(data) - case []uint32: - return 4 * len(data) - case int64, *int64, *uint64: - return 8 - case []int64: - return 8 * len(data) - case []uint64: - return 8 * len(data) - } - return 0 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common.go b/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common.go deleted file mode 100644 index 63462885e..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common.go +++ /dev/null @@ -1,379 +0,0 @@ -package common - -// -// gopsutil is a port of psutil(http://pythonhosted.org/psutil/). -// This covers these architectures. -// - linux (amd64, arm) -// - freebsd (amd64) -// - windows (amd64) -import ( - "bufio" - "bytes" - "context" - "errors" - "fmt" - "io/ioutil" - "net/url" - "os" - "os/exec" - "path" - "path/filepath" - "reflect" - "runtime" - "strconv" - "strings" - "time" -) - -var ( - Timeout = 3 * time.Second - ErrTimeout = errors.New("command timed out") -) - -type Invoker interface { - Command(string, ...string) ([]byte, error) - CommandWithContext(context.Context, string, ...string) ([]byte, error) -} - -type Invoke struct{} - -func (i Invoke) Command(name string, arg ...string) ([]byte, error) { - ctx, cancel := context.WithTimeout(context.Background(), Timeout) - defer cancel() - return i.CommandWithContext(ctx, name, arg...) -} - -func (i Invoke) CommandWithContext(ctx context.Context, name string, arg ...string) ([]byte, error) { - cmd := exec.CommandContext(ctx, name, arg...) - - var buf bytes.Buffer - cmd.Stdout = &buf - cmd.Stderr = &buf - - if err := cmd.Start(); err != nil { - return buf.Bytes(), err - } - - if err := cmd.Wait(); err != nil { - return buf.Bytes(), err - } - - return buf.Bytes(), nil -} - -type FakeInvoke struct { - Suffix string // Suffix species expected file name suffix such as "fail" - Error error // If Error specfied, return the error. -} - -// Command in FakeInvoke returns from expected file if exists. -func (i FakeInvoke) Command(name string, arg ...string) ([]byte, error) { - if i.Error != nil { - return []byte{}, i.Error - } - - arch := runtime.GOOS - - commandName := filepath.Base(name) - - fname := strings.Join(append([]string{commandName}, arg...), "") - fname = url.QueryEscape(fname) - fpath := path.Join("testdata", arch, fname) - if i.Suffix != "" { - fpath += "_" + i.Suffix - } - if PathExists(fpath) { - return ioutil.ReadFile(fpath) - } - return []byte{}, fmt.Errorf("could not find testdata: %s", fpath) -} - -func (i FakeInvoke) CommandWithContext(ctx context.Context, name string, arg ...string) ([]byte, error) { - return i.Command(name, arg...) -} - -var ErrNotImplementedError = errors.New("not implemented yet") - -// ReadFile reads contents from a file. -func ReadFile(filename string) (string, error) { - content, err := ioutil.ReadFile(filename) - - if err != nil { - return "", err - } - - return string(content), nil -} - -// ReadLines reads contents from a file and splits them by new lines. -// A convenience wrapper to ReadLinesOffsetN(filename, 0, -1). -func ReadLines(filename string) ([]string, error) { - return ReadLinesOffsetN(filename, 0, -1) -} - -// ReadLinesOffsetN reads contents from file and splits them by new line. -// The offset tells at which line number to start. -// The count determines the number of lines to read (starting from offset): -// n >= 0: at most n lines -// n < 0: whole file -func ReadLinesOffsetN(filename string, offset uint, n int) ([]string, error) { - f, err := os.Open(filename) - if err != nil { - return []string{""}, err - } - defer f.Close() - - var ret []string - - r := bufio.NewReader(f) - for i := 0; i < n+int(offset) || n < 0; i++ { - line, err := r.ReadString('\n') - if err != nil { - break - } - if i < int(offset) { - continue - } - ret = append(ret, strings.Trim(line, "\n")) - } - - return ret, nil -} - -func IntToString(orig []int8) string { - ret := make([]byte, len(orig)) - size := -1 - for i, o := range orig { - if o == 0 { - size = i - break - } - ret[i] = byte(o) - } - if size == -1 { - size = len(orig) - } - - return string(ret[0:size]) -} - -func UintToString(orig []uint8) string { - ret := make([]byte, len(orig)) - size := -1 - for i, o := range orig { - if o == 0 { - size = i - break - } - ret[i] = o - } - if size == -1 { - size = len(orig) - } - - return string(ret[0:size]) -} - -func ByteToString(orig []byte) string { - n := -1 - l := -1 - for i, b := range orig { - // skip left side null - if l == -1 && b == 0 { - continue - } - if l == -1 { - l = i - } - - if b == 0 { - break - } - n = i + 1 - } - if n == -1 { - return string(orig) - } - return string(orig[l:n]) -} - -// ReadInts reads contents from single line file and returns them as []int32. -func ReadInts(filename string) ([]int64, error) { - f, err := os.Open(filename) - if err != nil { - return []int64{}, err - } - defer f.Close() - - var ret []int64 - - r := bufio.NewReader(f) - - // The int files that this is concerned with should only be one liners. - line, err := r.ReadString('\n') - if err != nil { - return []int64{}, err - } - - i, err := strconv.ParseInt(strings.Trim(line, "\n"), 10, 32) - if err != nil { - return []int64{}, err - } - ret = append(ret, i) - - return ret, nil -} - -// HexToUint32 parses Hex to uint32 without error. -func HexToUint32(hex string) uint32 { - vv, _ := strconv.ParseUint(hex, 16, 32) - return uint32(vv) -} - -// mustParseInt32 parses to int32 without error. -func mustParseInt32(val string) int32 { - vv, _ := strconv.ParseInt(val, 10, 32) - return int32(vv) -} - -// mustParseUint64 parses to uint64 without error. -func mustParseUint64(val string) uint64 { - vv, _ := strconv.ParseInt(val, 10, 64) - return uint64(vv) -} - -// mustParseFloat64 parses to Float64 without error. -func mustParseFloat64(val string) float64 { - vv, _ := strconv.ParseFloat(val, 64) - return vv -} - -// StringsHas checks the target string slice contains src or not. -func StringsHas(target []string, src string) bool { - for _, t := range target { - if strings.TrimSpace(t) == src { - return true - } - } - return false -} - -// StringsContains checks the src in any string of the target string slice. -func StringsContains(target []string, src string) bool { - for _, t := range target { - if strings.Contains(t, src) { - return true - } - } - return false -} - -// IntContains checks the src in any int of the target int slice. -func IntContains(target []int, src int) bool { - for _, t := range target { - if src == t { - return true - } - } - return false -} - -// get struct attributes. -// This method is used only for debugging platform dependent code. -func attributes(m interface{}) map[string]reflect.Type { - typ := reflect.TypeOf(m) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - } - - attrs := make(map[string]reflect.Type) - if typ.Kind() != reflect.Struct { - return nil - } - - for i := 0; i < typ.NumField(); i++ { - p := typ.Field(i) - if !p.Anonymous { - attrs[p.Name] = p.Type - } - } - - return attrs -} - -func PathExists(filename string) bool { - if _, err := os.Stat(filename); err == nil { - return true - } - return false -} - -// GetEnv retrieves the environment variable key. If it does not exist it returns the default. -func GetEnv(key string, dfault string, combineWith ...string) string { - value := os.Getenv(key) - if value == "" { - value = dfault - } - - switch len(combineWith) { - case 0: - return value - case 1: - return filepath.Join(value, combineWith[0]) - default: - all := make([]string, len(combineWith)+1) - all[0] = value - copy(all[1:], combineWith) - return filepath.Join(all...) - } -} - -func HostProc(combineWith ...string) string { - return GetEnv("HOST_PROC", "/proc", combineWith...) -} - -func HostSys(combineWith ...string) string { - return GetEnv("HOST_SYS", "/sys", combineWith...) -} - -func HostEtc(combineWith ...string) string { - return GetEnv("HOST_ETC", "/etc", combineWith...) -} - -func HostVar(combineWith ...string) string { - return GetEnv("HOST_VAR", "/var", combineWith...) -} - -func HostRun(combineWith ...string) string { - return GetEnv("HOST_RUN", "/run", combineWith...) -} - -func HostDev(combineWith ...string) string { - return GetEnv("HOST_DEV", "/dev", combineWith...) -} - -// MockEnv set environment variable and return revert function. -// MockEnv should be used testing only. -func MockEnv(key string, value string) func() { - original := os.Getenv(key) - os.Setenv(key, value) - return func() { - os.Setenv(key, original) - } -} - -// getSysctrlEnv sets LC_ALL=C in a list of env vars for use when running -// sysctl commands (see DoSysctrl). -func getSysctrlEnv(env []string) []string { - foundLC := false - for i, line := range env { - if strings.HasPrefix(line, "LC_ALL") { - env[i] = "LC_ALL=C" - foundLC = true - } - } - if !foundLC { - env = append(env, "LC_ALL=C") - } - return env -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_darwin.go b/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_darwin.go deleted file mode 100644 index be46af3d9..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_darwin.go +++ /dev/null @@ -1,69 +0,0 @@ -// +build darwin - -package common - -import ( - "context" - "os" - "os/exec" - "strings" - "unsafe" - - "golang.org/x/sys/unix" -) - -func DoSysctrlWithContext(ctx context.Context, mib string) ([]string, error) { - sysctl, err := exec.LookPath("sysctl") - if err != nil { - return []string{}, err - } - cmd := exec.CommandContext(ctx, sysctl, "-n", mib) - cmd.Env = getSysctrlEnv(os.Environ()) - out, err := cmd.Output() - if err != nil { - return []string{}, err - } - v := strings.Replace(string(out), "{ ", "", 1) - v = strings.Replace(string(v), " }", "", 1) - values := strings.Fields(string(v)) - - return values, nil -} - -func CallSyscall(mib []int32) ([]byte, uint64, error) { - miblen := uint64(len(mib)) - - // get required buffer size - length := uint64(0) - _, _, err := unix.Syscall6( - 202, // unix.SYS___SYSCTL https://github.com/golang/sys/blob/76b94024e4b621e672466e8db3d7f084e7ddcad2/unix/zsysnum_darwin_amd64.go#L146 - uintptr(unsafe.Pointer(&mib[0])), - uintptr(miblen), - 0, - uintptr(unsafe.Pointer(&length)), - 0, - 0) - if err != 0 { - var b []byte - return b, length, err - } - if length == 0 { - var b []byte - return b, length, err - } - // get proc info itself - buf := make([]byte, length) - _, _, err = unix.Syscall6( - 202, // unix.SYS___SYSCTL https://github.com/golang/sys/blob/76b94024e4b621e672466e8db3d7f084e7ddcad2/unix/zsysnum_darwin_amd64.go#L146 - uintptr(unsafe.Pointer(&mib[0])), - uintptr(miblen), - uintptr(unsafe.Pointer(&buf[0])), - uintptr(unsafe.Pointer(&length)), - 0, - 0) - if err != 0 { - return buf, length, err - } - - return buf, length, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_freebsd.go b/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_freebsd.go deleted file mode 100644 index 85bda0e22..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_freebsd.go +++ /dev/null @@ -1,85 +0,0 @@ -// +build freebsd openbsd - -package common - -import ( - "fmt" - "os" - "os/exec" - "strings" - "unsafe" - - "golang.org/x/sys/unix" -) - -func SysctlUint(mib string) (uint64, error) { - buf, err := unix.SysctlRaw(mib) - if err != nil { - return 0, err - } - if len(buf) == 8 { // 64 bit - return *(*uint64)(unsafe.Pointer(&buf[0])), nil - } - if len(buf) == 4 { // 32bit - t := *(*uint32)(unsafe.Pointer(&buf[0])) - return uint64(t), nil - } - return 0, fmt.Errorf("unexpected size: %s, %d", mib, len(buf)) -} - -func DoSysctrl(mib string) ([]string, error) { - sysctl, err := exec.LookPath("sysctl") - if err != nil { - return []string{}, err - } - cmd := exec.Command(sysctl, "-n", mib) - cmd.Env = getSysctrlEnv(os.Environ()) - out, err := cmd.Output() - if err != nil { - return []string{}, err - } - v := strings.Replace(string(out), "{ ", "", 1) - v = strings.Replace(string(v), " }", "", 1) - values := strings.Fields(string(v)) - - return values, nil -} - -func CallSyscall(mib []int32) ([]byte, uint64, error) { - mibptr := unsafe.Pointer(&mib[0]) - miblen := uint64(len(mib)) - - // get required buffer size - length := uint64(0) - _, _, err := unix.Syscall6( - unix.SYS___SYSCTL, - uintptr(mibptr), - uintptr(miblen), - 0, - uintptr(unsafe.Pointer(&length)), - 0, - 0) - if err != 0 { - var b []byte - return b, length, err - } - if length == 0 { - var b []byte - return b, length, err - } - // get proc info itself - buf := make([]byte, length) - _, _, err = unix.Syscall6( - unix.SYS___SYSCTL, - uintptr(mibptr), - uintptr(miblen), - uintptr(unsafe.Pointer(&buf[0])), - uintptr(unsafe.Pointer(&length)), - 0, - 0) - if err != 0 { - return buf, length, err - } - - return buf, length, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_linux.go b/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_linux.go deleted file mode 100644 index ca01c7557..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_linux.go +++ /dev/null @@ -1,291 +0,0 @@ -// +build linux - -package common - -import ( - "context" - "fmt" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "sync" - "time" -) - -func DoSysctrl(mib string) ([]string, error) { - sysctl, err := exec.LookPath("sysctl") - if err != nil { - return []string{}, err - } - cmd := exec.Command(sysctl, "-n", mib) - cmd.Env = getSysctrlEnv(os.Environ()) - out, err := cmd.Output() - if err != nil { - return []string{}, err - } - v := strings.Replace(string(out), "{ ", "", 1) - v = strings.Replace(v, " }", "", 1) - values := strings.Fields(v) - - return values, nil -} - -func NumProcs() (uint64, error) { - f, err := os.Open(HostProc()) - if err != nil { - return 0, err - } - defer f.Close() - - list, err := f.Readdirnames(-1) - if err != nil { - return 0, err - } - var cnt uint64 - - for _, v := range list { - if _, err = strconv.ParseUint(v, 10, 64); err == nil { - cnt++ - } - } - - return cnt, nil -} - -func BootTimeWithContext(ctx context.Context) (uint64, error) { - system, role, err := Virtualization() - if err != nil { - return 0, err - } - - statFile := "stat" - if system == "lxc" && role == "guest" { - // if lxc, /proc/uptime is used. - statFile = "uptime" - } else if system == "docker" && role == "guest" { - // also docker, guest - statFile = "uptime" - } - - filename := HostProc(statFile) - lines, err := ReadLines(filename) - if err != nil { - return 0, err - } - - if statFile == "uptime" { - if len(lines) != 1 { - return 0, fmt.Errorf("wrong uptime format") - } - f := strings.Fields(lines[0]) - b, err := strconv.ParseFloat(f[0], 64) - if err != nil { - return 0, err - } - t := uint64(time.Now().Unix()) - uint64(b) - return t, nil - } - if statFile == "stat" { - for _, line := range lines { - if strings.HasPrefix(line, "btime") { - f := strings.Fields(line) - if len(f) != 2 { - return 0, fmt.Errorf("wrong btime format") - } - b, err := strconv.ParseInt(f[1], 10, 64) - if err != nil { - return 0, err - } - t := uint64(b) - return t, nil - } - } - } - - return 0, fmt.Errorf("could not find btime") -} - -func Virtualization() (string, string, error) { - return VirtualizationWithContext(context.Background()) -} - -// required variables for concurrency safe virtualization caching. -var ( - cachedVirtMap map[string]string - cachedVirtMutex sync.RWMutex - cachedVirtOnce sync.Once -) - -func VirtualizationWithContext(ctx context.Context) (string, string, error) { - var system, role string - - // if cached already, return from cache - cachedVirtMutex.RLock() // unlock won't be deferred so concurrent reads don't wait for long - if cachedVirtMap != nil { - cachedSystem, cachedRole := cachedVirtMap["system"], cachedVirtMap["role"] - cachedVirtMutex.RUnlock() - return cachedSystem, cachedRole, nil - } - cachedVirtMutex.RUnlock() - - filename := HostProc("xen") - if PathExists(filename) { - system = "xen" - role = "guest" // assume guest - - if PathExists(filepath.Join(filename, "capabilities")) { - contents, err := ReadLines(filepath.Join(filename, "capabilities")) - if err == nil && StringsContains(contents, "control_d") { - role = "host" - } - } - } - - filename = HostProc("modules") - if PathExists(filename) { - contents, err := ReadLines(filename) - if err == nil { - switch { - case StringsContains(contents, "kvm"): - system = "kvm" - role = "host" - case StringsContains(contents, "vboxdrv"): - system = "vbox" - role = "host" - case StringsContains(contents, "vboxguest"): - system = "vbox" - role = "guest" - case StringsContains(contents, "vmware"): - system = "vmware" - role = "guest" - } - } - } - - filename = HostProc("cpuinfo") - if PathExists(filename) { - contents, err := ReadLines(filename) - if err == nil { - if StringsContains(contents, "QEMU Virtual CPU") || - StringsContains(contents, "Common KVM processor") || - StringsContains(contents, "Common 32-bit KVM processor") { - system = "kvm" - role = "guest" - } - } - } - - filename = HostProc("bus/pci/devices") - if PathExists(filename) { - contents, err := ReadLines(filename) - if err == nil { - if StringsContains(contents, "virtio-pci") { - role = "guest" - } - } - } - - filename = HostProc() - if PathExists(filepath.Join(filename, "bc", "0")) { - system = "openvz" - role = "host" - } else if PathExists(filepath.Join(filename, "vz")) { - system = "openvz" - role = "guest" - } - - // not use dmidecode because it requires root - if PathExists(filepath.Join(filename, "self", "status")) { - contents, err := ReadLines(filepath.Join(filename, "self", "status")) - if err == nil { - if StringsContains(contents, "s_context:") || - StringsContains(contents, "VxID:") { - system = "linux-vserver" - } - // TODO: guest or host - } - } - - if PathExists(filepath.Join(filename, "1", "environ")) { - contents, err := ReadFile(filepath.Join(filename, "1", "environ")) - - if err == nil { - if strings.Contains(contents, "container=lxc") { - system = "lxc" - role = "guest" - } - } - } - - if PathExists(filepath.Join(filename, "self", "cgroup")) { - contents, err := ReadLines(filepath.Join(filename, "self", "cgroup")) - if err == nil { - switch { - case StringsContains(contents, "lxc"): - system = "lxc" - role = "guest" - case StringsContains(contents, "docker"): - system = "docker" - role = "guest" - case StringsContains(contents, "machine-rkt"): - system = "rkt" - role = "guest" - case PathExists("/usr/bin/lxc-version"): - system = "lxc" - role = "host" - } - } - } - - if PathExists(HostEtc("os-release")) { - p, _, err := GetOSRelease() - if err == nil && p == "coreos" { - system = "rkt" // Is it true? - role = "host" - } - } - - // before returning for the first time, cache the system and role - cachedVirtOnce.Do(func() { - cachedVirtMutex.Lock() - defer cachedVirtMutex.Unlock() - cachedVirtMap = map[string]string{ - "system": system, - "role": role, - } - }) - - return system, role, nil -} - -func GetOSRelease() (platform string, version string, err error) { - contents, err := ReadLines(HostEtc("os-release")) - if err != nil { - return "", "", nil // return empty - } - for _, line := range contents { - field := strings.Split(line, "=") - if len(field) < 2 { - continue - } - switch field[0] { - case "ID": // use ID for lowercase - platform = trimQuotes(field[1]) - case "VERSION": - version = trimQuotes(field[1]) - } - } - return platform, version, nil -} - -// trimQuotes removes quotes in the source string. -func trimQuotes(s string) string { - if len(s) >= 2 { - if s[0] == '"' && s[len(s)-1] == '"' { - return s[1 : len(s)-1] - } - } - return s -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_openbsd.go b/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_openbsd.go deleted file mode 100644 index ba73a7eb5..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_openbsd.go +++ /dev/null @@ -1,69 +0,0 @@ -// +build openbsd - -package common - -import ( - "os" - "os/exec" - "strings" - "unsafe" - - "golang.org/x/sys/unix" -) - -func DoSysctrl(mib string) ([]string, error) { - sysctl, err := exec.LookPath("sysctl") - if err != nil { - return []string{}, err - } - cmd := exec.Command(sysctl, "-n", mib) - cmd.Env = getSysctrlEnv(os.Environ()) - out, err := cmd.Output() - if err != nil { - return []string{}, err - } - v := strings.Replace(string(out), "{ ", "", 1) - v = strings.Replace(string(v), " }", "", 1) - values := strings.Fields(string(v)) - - return values, nil -} - -func CallSyscall(mib []int32) ([]byte, uint64, error) { - mibptr := unsafe.Pointer(&mib[0]) - miblen := uint64(len(mib)) - - // get required buffer size - length := uint64(0) - _, _, err := unix.Syscall6( - unix.SYS___SYSCTL, - uintptr(mibptr), - uintptr(miblen), - 0, - uintptr(unsafe.Pointer(&length)), - 0, - 0) - if err != 0 { - var b []byte - return b, length, err - } - if length == 0 { - var b []byte - return b, length, err - } - // get proc info itself - buf := make([]byte, length) - _, _, err = unix.Syscall6( - unix.SYS___SYSCTL, - uintptr(mibptr), - uintptr(miblen), - uintptr(unsafe.Pointer(&buf[0])), - uintptr(unsafe.Pointer(&length)), - 0, - 0) - if err != 0 { - return buf, length, err - } - - return buf, length, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_unix.go b/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_unix.go deleted file mode 100644 index 605202815..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_unix.go +++ /dev/null @@ -1,66 +0,0 @@ -// +build linux freebsd darwin openbsd - -package common - -import ( - "context" - "os/exec" - "strconv" - "strings" -) - -func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args ...string) ([]string, error) { - var cmd []string - if pid == 0 { // will get from all processes. - cmd = []string{"-a", "-n", "-P"} - } else { - cmd = []string{"-a", "-n", "-P", "-p", strconv.Itoa(int(pid))} - } - cmd = append(cmd, args...) - lsof, err := exec.LookPath("lsof") - if err != nil { - return []string{}, err - } - out, err := invoke.CommandWithContext(ctx, lsof, cmd...) - if err != nil { - // if no pid found, lsof returns code 1. - if err.Error() == "exit status 1" && len(out) == 0 { - return []string{}, nil - } - } - lines := strings.Split(string(out), "\n") - - var ret []string - for _, l := range lines[1:] { - if len(l) == 0 { - continue - } - ret = append(ret, l) - } - return ret, nil -} - -func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int32, error) { - cmd := []string{"-P", strconv.Itoa(int(pid))} - pgrep, err := exec.LookPath("pgrep") - if err != nil { - return []int32{}, err - } - out, err := invoke.CommandWithContext(ctx, pgrep, cmd...) - if err != nil { - return []int32{}, err - } - lines := strings.Split(string(out), "\n") - ret := make([]int32, 0, len(lines)) - for _, l := range lines { - if len(l) == 0 { - continue - } - i, err := strconv.Atoi(l) - if err != nil { - continue - } - ret = append(ret, int32(i)) - } - return ret, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_windows.go b/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_windows.go deleted file mode 100644 index ba20136da..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/common_windows.go +++ /dev/null @@ -1,300 +0,0 @@ -// +build windows - -package common - -import ( - "context" - "fmt" - "path/filepath" - "reflect" - "strings" - "syscall" - "unsafe" - - "github.com/yusufpapurcu/wmi" - "golang.org/x/sys/windows" -) - -// for double values -type PDH_FMT_COUNTERVALUE_DOUBLE struct { - CStatus uint32 - DoubleValue float64 -} - -// for 64 bit integer values -type PDH_FMT_COUNTERVALUE_LARGE struct { - CStatus uint32 - LargeValue int64 -} - -// for long values -type PDH_FMT_COUNTERVALUE_LONG struct { - CStatus uint32 - LongValue int32 - padding [4]byte -} - -// windows system const -const ( - ERROR_SUCCESS = 0 - ERROR_FILE_NOT_FOUND = 2 - DRIVE_REMOVABLE = 2 - DRIVE_FIXED = 3 - HKEY_LOCAL_MACHINE = 0x80000002 - RRF_RT_REG_SZ = 0x00000002 - RRF_RT_REG_DWORD = 0x00000010 - PDH_FMT_LONG = 0x00000100 - PDH_FMT_DOUBLE = 0x00000200 - PDH_FMT_LARGE = 0x00000400 - PDH_INVALID_DATA = 0xc0000bc6 - PDH_INVALID_HANDLE = 0xC0000bbc - PDH_NO_DATA = 0x800007d5 - - STATUS_BUFFER_OVERFLOW = 0x80000005 - STATUS_BUFFER_TOO_SMALL = 0xC0000023 - STATUS_INFO_LENGTH_MISMATCH = 0xC0000004 -) - -const ( - ProcessBasicInformation = 0 - ProcessWow64Information = 26 - ProcessQueryInformation = windows.PROCESS_DUP_HANDLE | windows.PROCESS_QUERY_INFORMATION - - SystemExtendedHandleInformationClass = 64 -) - -var ( - Modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - ModNt = windows.NewLazySystemDLL("ntdll.dll") - ModPdh = windows.NewLazySystemDLL("pdh.dll") - ModPsapi = windows.NewLazySystemDLL("psapi.dll") - - ProcGetSystemTimes = Modkernel32.NewProc("GetSystemTimes") - ProcNtQuerySystemInformation = ModNt.NewProc("NtQuerySystemInformation") - ProcRtlGetNativeSystemInformation = ModNt.NewProc("RtlGetNativeSystemInformation") - ProcRtlNtStatusToDosError = ModNt.NewProc("RtlNtStatusToDosError") - ProcNtQueryInformationProcess = ModNt.NewProc("NtQueryInformationProcess") - ProcNtReadVirtualMemory = ModNt.NewProc("NtReadVirtualMemory") - ProcNtWow64QueryInformationProcess64 = ModNt.NewProc("NtWow64QueryInformationProcess64") - ProcNtWow64ReadVirtualMemory64 = ModNt.NewProc("NtWow64ReadVirtualMemory64") - - PdhOpenQuery = ModPdh.NewProc("PdhOpenQuery") - PdhAddEnglishCounterW = ModPdh.NewProc("PdhAddEnglishCounterW") - PdhCollectQueryData = ModPdh.NewProc("PdhCollectQueryData") - PdhGetFormattedCounterValue = ModPdh.NewProc("PdhGetFormattedCounterValue") - PdhCloseQuery = ModPdh.NewProc("PdhCloseQuery") - - procQueryDosDeviceW = Modkernel32.NewProc("QueryDosDeviceW") -) - -type FILETIME struct { - DwLowDateTime uint32 - DwHighDateTime uint32 -} - -// borrowed from net/interface_windows.go -func BytePtrToString(p *uint8) string { - a := (*[10000]uint8)(unsafe.Pointer(p)) - i := 0 - for a[i] != 0 { - i++ - } - return string(a[:i]) -} - -// CounterInfo struct is used to track a windows performance counter -// copied from https://github.com/mackerelio/mackerel-agent/ -type CounterInfo struct { - PostName string - CounterName string - Counter windows.Handle -} - -// CreateQuery with a PdhOpenQuery call -// copied from https://github.com/mackerelio/mackerel-agent/ -func CreateQuery() (windows.Handle, error) { - var query windows.Handle - r, _, err := PdhOpenQuery.Call(0, 0, uintptr(unsafe.Pointer(&query))) - if r != 0 { - return 0, err - } - return query, nil -} - -// CreateCounter with a PdhAddEnglishCounterW call -func CreateCounter(query windows.Handle, pname, cname string) (*CounterInfo, error) { - var counter windows.Handle - r, _, err := PdhAddEnglishCounterW.Call( - uintptr(query), - uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(cname))), - 0, - uintptr(unsafe.Pointer(&counter))) - if r != 0 { - return nil, err - } - return &CounterInfo{ - PostName: pname, - CounterName: cname, - Counter: counter, - }, nil -} - -// GetCounterValue get counter value from handle -// adapted from https://github.com/mackerelio/mackerel-agent/ -func GetCounterValue(counter windows.Handle) (float64, error) { - var value PDH_FMT_COUNTERVALUE_DOUBLE - r, _, err := PdhGetFormattedCounterValue.Call(uintptr(counter), PDH_FMT_DOUBLE, uintptr(0), uintptr(unsafe.Pointer(&value))) - if r != 0 && r != PDH_INVALID_DATA { - return 0.0, err - } - return value.DoubleValue, nil -} - -type Win32PerformanceCounter struct { - PostName string - CounterName string - Query windows.Handle - Counter windows.Handle -} - -func NewWin32PerformanceCounter(postName, counterName string) (*Win32PerformanceCounter, error) { - query, err := CreateQuery() - if err != nil { - return nil, err - } - var counter = Win32PerformanceCounter{ - Query: query, - PostName: postName, - CounterName: counterName, - } - r, _, err := PdhAddEnglishCounterW.Call( - uintptr(counter.Query), - uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(counter.CounterName))), - 0, - uintptr(unsafe.Pointer(&counter.Counter)), - ) - if r != 0 { - return nil, err - } - return &counter, nil -} - -func (w *Win32PerformanceCounter) GetValue() (float64, error) { - r, _, err := PdhCollectQueryData.Call(uintptr(w.Query)) - if r != 0 && err != nil { - if r == PDH_NO_DATA { - return 0.0, fmt.Errorf("%w: this counter has not data", err) - } - return 0.0, err - } - - return GetCounterValue(w.Counter) -} - -func ProcessorQueueLengthCounter() (*Win32PerformanceCounter, error) { - return NewWin32PerformanceCounter("processor_queue_length", `\System\Processor Queue Length`) -} - -// WMIQueryWithContext - wraps wmi.Query with a timed-out context to avoid hanging -func WMIQueryWithContext(ctx context.Context, query string, dst interface{}, connectServerArgs ...interface{}) error { - if _, ok := ctx.Deadline(); !ok { - ctxTimeout, cancel := context.WithTimeout(ctx, Timeout) - defer cancel() - ctx = ctxTimeout - } - - errChan := make(chan error, 1) - go func() { - errChan <- wmi.Query(query, dst, connectServerArgs...) - }() - - select { - case <-ctx.Done(): - return ctx.Err() - case err := <-errChan: - return err - } -} - -// Convert paths using native DOS format like: -// "\Device\HarddiskVolume1\Windows\systemew\file.txt" -// into: -// "C:\Windows\systemew\file.txt" -func ConvertDOSPath(p string) string { - rawDrive := strings.Join(strings.Split(p, `\`)[:3], `\`) - - for d := 'A'; d <= 'Z'; d++ { - szDeviceName := string(d) + ":" - szTarget := make([]uint16, 512) - ret, _, _ := procQueryDosDeviceW.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(szDeviceName))), - uintptr(unsafe.Pointer(&szTarget[0])), - uintptr(len(szTarget))) - if ret != 0 && windows.UTF16ToString(szTarget[:]) == rawDrive { - return filepath.Join(szDeviceName, p[len(rawDrive):]) - } - } - return p -} - -type NtStatus uint32 - -func (s NtStatus) Error() error { - if s == 0 { - return nil - } - return fmt.Errorf("NtStatus 0x%08x", uint32(s)) -} - -func (s NtStatus) IsError() bool { - return s>>30 == 3 -} - -type SystemExtendedHandleTableEntryInformation struct { - Object uintptr - UniqueProcessId uintptr - HandleValue uintptr - GrantedAccess uint32 - CreatorBackTraceIndex uint16 - ObjectTypeIndex uint16 - HandleAttributes uint32 - Reserved uint32 -} - -type SystemExtendedHandleInformation struct { - NumberOfHandles uintptr - Reserved uintptr - Handles [1]SystemExtendedHandleTableEntryInformation -} - -// CallWithExpandingBuffer https://github.com/hillu/go-ntdll -func CallWithExpandingBuffer(fn func() NtStatus, buf *[]byte, resultLength *uint32) NtStatus { - for { - if st := fn(); st == STATUS_BUFFER_OVERFLOW || st == STATUS_BUFFER_TOO_SMALL || st == STATUS_INFO_LENGTH_MISMATCH { - if int(*resultLength) <= cap(*buf) { - (*reflect.SliceHeader)(unsafe.Pointer(buf)).Len = int(*resultLength) - } else { - *buf = make([]byte, int(*resultLength)) - } - continue - } else { - if !st.IsError() { - *buf = (*buf)[:int(*resultLength)] - } - return st - } - } -} - -func NtQuerySystemInformation( - SystemInformationClass uint32, - SystemInformation *byte, - SystemInformationLength uint32, - ReturnLength *uint32, -) NtStatus { - r0, _, _ := ProcNtQuerySystemInformation.Call( - uintptr(SystemInformationClass), - uintptr(unsafe.Pointer(SystemInformation)), - uintptr(SystemInformationLength), - uintptr(unsafe.Pointer(ReturnLength))) - return NtStatus(r0) -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/sleep.go b/test/integration/vendor/github.com/shirou/gopsutil/internal/common/sleep.go deleted file mode 100644 index ee27e54d4..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/internal/common/sleep.go +++ /dev/null @@ -1,18 +0,0 @@ -package common - -import ( - "context" - "time" -) - -// Sleep awaits for provided interval. -// Can be interrupted by context cancelation. -func Sleep(ctx context.Context, interval time.Duration) error { - var timer = time.NewTimer(interval) - select { - case <-ctx.Done(): - return ctx.Err() - case <-timer.C: - return nil - } -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem.go deleted file mode 100644 index c7e9880b7..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem.go +++ /dev/null @@ -1,116 +0,0 @@ -package mem - -import ( - "encoding/json" - - "github.com/shirou/gopsutil/internal/common" -) - -var invoke common.Invoker = common.Invoke{} - -// Memory usage statistics. Total, Available and Used contain numbers of bytes -// for human consumption. -// -// The other fields in this struct contain kernel specific values. -type VirtualMemoryStat struct { - // Total amount of RAM on this system - Total uint64 `json:"total"` - - // RAM available for programs to allocate - // - // This value is computed from the kernel specific values. - Available uint64 `json:"available"` - - // RAM used by programs - // - // This value is computed from the kernel specific values. - Used uint64 `json:"used"` - - // Percentage of RAM used by programs - // - // This value is computed from the kernel specific values. - UsedPercent float64 `json:"usedPercent"` - - // This is the kernel's notion of free memory; RAM chips whose bits nobody - // cares about the value of right now. For a human consumable number, - // Available is what you really want. - Free uint64 `json:"free"` - - // OS X / BSD specific numbers: - // http://www.macyourself.com/2010/02/17/what-is-free-wired-active-and-inactive-system-memory-ram/ - Active uint64 `json:"active"` - Inactive uint64 `json:"inactive"` - Wired uint64 `json:"wired"` - - // FreeBSD specific numbers: - // https://reviews.freebsd.org/D8467 - Laundry uint64 `json:"laundry"` - - // Linux specific numbers - // https://www.centos.org/docs/5/html/5.1/Deployment_Guide/s2-proc-meminfo.html - // https://www.kernel.org/doc/Documentation/filesystems/proc.txt - // https://www.kernel.org/doc/Documentation/vm/overcommit-accounting - Buffers uint64 `json:"buffers"` - Cached uint64 `json:"cached"` - Writeback uint64 `json:"writeback"` - Dirty uint64 `json:"dirty"` - WritebackTmp uint64 `json:"writebacktmp"` - Shared uint64 `json:"shared"` - Slab uint64 `json:"slab"` - SReclaimable uint64 `json:"sreclaimable"` - SUnreclaim uint64 `json:"sunreclaim"` - PageTables uint64 `json:"pagetables"` - SwapCached uint64 `json:"swapcached"` - CommitLimit uint64 `json:"commitlimit"` - CommittedAS uint64 `json:"committedas"` - HighTotal uint64 `json:"hightotal"` - HighFree uint64 `json:"highfree"` - LowTotal uint64 `json:"lowtotal"` - LowFree uint64 `json:"lowfree"` - SwapTotal uint64 `json:"swaptotal"` - SwapFree uint64 `json:"swapfree"` - Mapped uint64 `json:"mapped"` - VMallocTotal uint64 `json:"vmalloctotal"` - VMallocUsed uint64 `json:"vmallocused"` - VMallocChunk uint64 `json:"vmallocchunk"` - HugePagesTotal uint64 `json:"hugepagestotal"` - HugePagesFree uint64 `json:"hugepagesfree"` - HugePageSize uint64 `json:"hugepagesize"` -} - -type SwapMemoryStat struct { - Total uint64 `json:"total"` - Used uint64 `json:"used"` - Free uint64 `json:"free"` - UsedPercent float64 `json:"usedPercent"` - Sin uint64 `json:"sin"` - Sout uint64 `json:"sout"` - PgIn uint64 `json:"pgin"` - PgOut uint64 `json:"pgout"` - PgFault uint64 `json:"pgfault"` - - // Linux specific numbers - // https://www.kernel.org/doc/Documentation/cgroup-v2.txt - PgMajFault uint64 `json:"pgmajfault"` -} - -func (m VirtualMemoryStat) String() string { - s, _ := json.Marshal(m) - return string(s) -} - -func (m SwapMemoryStat) String() string { - s, _ := json.Marshal(m) - return string(s) -} - -type SwapDevice struct { - Name string `json:"name"` - UsedBytes uint64 `json:"usedBytes"` - FreeBytes uint64 `json:"freeBytes"` -} - -func (m SwapDevice) String() string { - s, _ := json.Marshal(m) - return string(s) -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_bsd.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_bsd.go deleted file mode 100644 index 88db76209..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_bsd.go +++ /dev/null @@ -1,91 +0,0 @@ -// +build freebsd openbsd - -package mem - -import ( - "context" - "fmt" - "os/exec" - "strconv" - "strings" -) - -const swapCommand = "swapctl" - -// swapctl column indexes -const ( - nameCol = 0 - totalKiBCol = 1 - usedKiBCol = 2 -) - -func SwapDevices() ([]*SwapDevice, error) { - return SwapDevicesWithContext(context.Background()) -} - -func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - swapCommandPath, err := exec.LookPath(swapCommand) - if err != nil { - return nil, fmt.Errorf("could not find command %q: %w", swapCommand, err) - } - output, err := invoke.CommandWithContext(ctx, swapCommandPath, "-lk") - if err != nil { - return nil, fmt.Errorf("could not execute %q: %w", swapCommand, err) - } - - return parseSwapctlOutput(string(output)) -} - -func parseSwapctlOutput(output string) ([]*SwapDevice, error) { - lines := strings.Split(output, "\n") - if len(lines) == 0 { - return nil, fmt.Errorf("could not parse output of %q: no lines in %q", swapCommand, output) - } - - // Check header headerFields are as expected. - header := lines[0] - header = strings.ToLower(header) - header = strings.ReplaceAll(header, ":", "") - headerFields := strings.Fields(header) - if len(headerFields) < usedKiBCol { - return nil, fmt.Errorf("couldn't parse %q: too few fields in header %q", swapCommand, header) - } - if headerFields[nameCol] != "device" { - return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapCommand, headerFields[nameCol], "device") - } - if headerFields[totalKiBCol] != "1kb-blocks" && headerFields[totalKiBCol] != "1k-blocks" { - return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapCommand, headerFields[totalKiBCol], "1kb-blocks") - } - if headerFields[usedKiBCol] != "used" { - return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapCommand, headerFields[usedKiBCol], "used") - } - - var swapDevices []*SwapDevice - for _, line := range lines[1:] { - if line == "" { - continue // the terminal line is typically empty - } - fields := strings.Fields(line) - if len(fields) < usedKiBCol { - return nil, fmt.Errorf("couldn't parse %q: too few fields", swapCommand) - } - - totalKiB, err := strconv.ParseUint(fields[totalKiBCol], 10, 64) - if err != nil { - return nil, fmt.Errorf("couldn't parse 'Size' column in %q: %w", swapCommand, err) - } - - usedKiB, err := strconv.ParseUint(fields[usedKiBCol], 10, 64) - if err != nil { - return nil, fmt.Errorf("couldn't parse 'Used' column in %q: %w", swapCommand, err) - } - - swapDevices = append(swapDevices, &SwapDevice{ - Name: fields[nameCol], - UsedBytes: usedKiB * 1024, - FreeBytes: (totalKiB - usedKiB) * 1024, - }) - } - - return swapDevices, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin.go deleted file mode 100644 index 4b8f069d3..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin.go +++ /dev/null @@ -1,70 +0,0 @@ -// +build darwin - -package mem - -import ( - "context" - "fmt" - "unsafe" - - "github.com/shirou/gopsutil/internal/common" - "golang.org/x/sys/unix" -) - -func getHwMemsize() (uint64, error) { - total, err := unix.SysctlUint64("hw.memsize") - if err != nil { - return 0, err - } - return total, nil -} - -// xsw_usage in sys/sysctl.h -type swapUsage struct { - Total uint64 - Avail uint64 - Used uint64 - Pagesize int32 - Encrypted bool -} - -// SwapMemory returns swapinfo. -func SwapMemory() (*SwapMemoryStat, error) { - return SwapMemoryWithContext(context.Background()) -} - -func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { - // https://github.com/yanllearnn/go-osstat/blob/ae8a279d26f52ec946a03698c7f50a26cfb427e3/memory/memory_darwin.go - var ret *SwapMemoryStat - - value, err := unix.SysctlRaw("vm.swapusage") - if err != nil { - return ret, err - } - if len(value) != 32 { - return ret, fmt.Errorf("unexpected output of sysctl vm.swapusage: %v (len: %d)", value, len(value)) - } - swap := (*swapUsage)(unsafe.Pointer(&value[0])) - - u := float64(0) - if swap.Total != 0 { - u = ((float64(swap.Total) - float64(swap.Avail)) / float64(swap.Total)) * 100.0 - } - - ret = &SwapMemoryStat{ - Total: swap.Total, - Used: swap.Used, - Free: swap.Avail, - UsedPercent: u, - } - - return ret, nil -} - -func SwapDevices() ([]*SwapDevice, error) { - return SwapDevicesWithContext(context.Background()) -} - -func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - return nil, common.ErrNotImplementedError -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin_cgo.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin_cgo.go deleted file mode 100644 index ade3cecd4..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin_cgo.go +++ /dev/null @@ -1,58 +0,0 @@ -// +build darwin,cgo - -package mem - -/* -#include -*/ -import "C" - -import ( - "context" - "fmt" - "unsafe" - - "golang.org/x/sys/unix" -) - -// VirtualMemory returns VirtualmemoryStat. -func VirtualMemory() (*VirtualMemoryStat, error) { - return VirtualMemoryWithContext(context.Background()) -} - -func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { - count := C.mach_msg_type_number_t(C.HOST_VM_INFO_COUNT) - var vmstat C.vm_statistics_data_t - - status := C.host_statistics(C.host_t(C.mach_host_self()), - C.HOST_VM_INFO, - C.host_info_t(unsafe.Pointer(&vmstat)), - &count) - - if status != C.KERN_SUCCESS { - return nil, fmt.Errorf("host_statistics error=%d", status) - } - - pageSize := uint64(unix.Getpagesize()) - total, err := getHwMemsize() - if err != nil { - return nil, err - } - totalCount := C.natural_t(total / pageSize) - - availableCount := vmstat.inactive_count + vmstat.free_count - usedPercent := 100 * float64(totalCount-availableCount) / float64(totalCount) - - usedCount := totalCount - availableCount - - return &VirtualMemoryStat{ - Total: total, - Available: pageSize * uint64(availableCount), - Used: pageSize * uint64(usedCount), - UsedPercent: usedPercent, - Free: pageSize * uint64(vmstat.free_count), - Active: pageSize * uint64(vmstat.active_count), - Inactive: pageSize * uint64(vmstat.inactive_count), - Wired: pageSize * uint64(vmstat.wire_count), - }, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin_nocgo.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin_nocgo.go deleted file mode 100644 index 2e847cbe4..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_darwin_nocgo.go +++ /dev/null @@ -1,93 +0,0 @@ -// +build darwin,!cgo - -package mem - -import ( - "context" - "os/exec" - "strconv" - "strings" - - "golang.org/x/sys/unix" -) - -// Runs vm_stat and returns Free and inactive pages -func getVMStat(vms *VirtualMemoryStat) error { - vm_stat, err := exec.LookPath("vm_stat") - if err != nil { - return err - } - out, err := invoke.Command(vm_stat) - if err != nil { - return err - } - return parseVMStat(string(out), vms) -} - -func parseVMStat(out string, vms *VirtualMemoryStat) error { - var err error - - lines := strings.Split(out, "\n") - pagesize := uint64(unix.Getpagesize()) - for _, line := range lines { - fields := strings.Split(line, ":") - if len(fields) < 2 { - continue - } - key := strings.TrimSpace(fields[0]) - value := strings.Trim(fields[1], " .") - switch key { - case "Pages free": - free, e := strconv.ParseUint(value, 10, 64) - if e != nil { - err = e - } - vms.Free = free * pagesize - case "Pages inactive": - inactive, e := strconv.ParseUint(value, 10, 64) - if e != nil { - err = e - } - vms.Inactive = inactive * pagesize - case "Pages active": - active, e := strconv.ParseUint(value, 10, 64) - if e != nil { - err = e - } - vms.Active = active * pagesize - case "Pages wired down": - wired, e := strconv.ParseUint(value, 10, 64) - if e != nil { - err = e - } - vms.Wired = wired * pagesize - } - } - return err -} - -// VirtualMemory returns VirtualmemoryStat. -func VirtualMemory() (*VirtualMemoryStat, error) { - return VirtualMemoryWithContext(context.Background()) -} - -func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { - ret := &VirtualMemoryStat{} - - total, err := getHwMemsize() - if err != nil { - return nil, err - } - err = getVMStat(ret) - if err != nil { - return nil, err - } - - ret.Available = ret.Free + ret.Inactive - ret.Total = total - - ret.Used = ret.Total - ret.Available - ret.UsedPercent = 100 * float64(ret.Used) / float64(ret.Total) - - return ret, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_fallback.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_fallback.go deleted file mode 100644 index 02e87d7a9..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_fallback.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows - -package mem - -import ( - "context" - - "github.com/shirou/gopsutil/internal/common" -) - -func VirtualMemory() (*VirtualMemoryStat, error) { - return VirtualMemoryWithContext(context.Background()) -} - -func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { - return nil, common.ErrNotImplementedError -} - -func SwapMemory() (*SwapMemoryStat, error) { - return SwapMemoryWithContext(context.Background()) -} - -func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { - return nil, common.ErrNotImplementedError -} - -func SwapDevices() ([]*SwapDevice, error) { - return SwapDevicesWithContext(context.Background()) -} - -func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - return nil, common.ErrNotImplementedError -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_freebsd.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_freebsd.go deleted file mode 100644 index f91efc9e3..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_freebsd.go +++ /dev/null @@ -1,167 +0,0 @@ -// +build freebsd - -package mem - -import ( - "context" - "errors" - "unsafe" - - "golang.org/x/sys/unix" - - "github.com/shirou/gopsutil/internal/common" -) - -func VirtualMemory() (*VirtualMemoryStat, error) { - return VirtualMemoryWithContext(context.Background()) -} - -func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { - pageSize, err := common.SysctlUint("vm.stats.vm.v_page_size") - if err != nil { - return nil, err - } - physmem, err := common.SysctlUint("hw.physmem") - if err != nil { - return nil, err - } - - free, err := common.SysctlUint("vm.stats.vm.v_free_count") - if err != nil { - return nil, err - } - active, err := common.SysctlUint("vm.stats.vm.v_active_count") - if err != nil { - return nil, err - } - inactive, err := common.SysctlUint("vm.stats.vm.v_inactive_count") - if err != nil { - return nil, err - } - buffers, err := common.SysctlUint("vfs.bufspace") - if err != nil { - return nil, err - } - wired, err := common.SysctlUint("vm.stats.vm.v_wire_count") - if err != nil { - return nil, err - } - var cached, laundry uint64 - osreldate, _ := common.SysctlUint("kern.osreldate") - if osreldate < 1102000 { - cached, err = common.SysctlUint("vm.stats.vm.v_cache_count") - if err != nil { - return nil, err - } - } else { - laundry, err = common.SysctlUint("vm.stats.vm.v_laundry_count") - if err != nil { - return nil, err - } - } - - p := pageSize - ret := &VirtualMemoryStat{ - Total: physmem, - Free: free * p, - Active: active * p, - Inactive: inactive * p, - Cached: cached * p, - Buffers: buffers, - Wired: wired * p, - Laundry: laundry * p, - } - - ret.Available = ret.Inactive + ret.Cached + ret.Free + ret.Laundry - ret.Used = ret.Total - ret.Available - ret.UsedPercent = float64(ret.Used) / float64(ret.Total) * 100.0 - - return ret, nil -} - -// Return swapinfo -func SwapMemory() (*SwapMemoryStat, error) { - return SwapMemoryWithContext(context.Background()) -} - -// Constants from vm/vm_param.h -// nolint: golint -const ( - XSWDEV_VERSION11 = 1 - XSWDEV_VERSION = 2 -) - -// Types from vm/vm_param.h -type xswdev struct { - Version uint32 // Version is the version - Dev uint64 // Dev is the device identifier - Flags int32 // Flags is the swap flags applied to the device - NBlks int32 // NBlks is the total number of blocks - Used int32 // Used is the number of blocks used -} - -// xswdev11 is a compatibility for under FreeBSD 11 -// sys/vm/swap_pager.c -type xswdev11 struct { - Version uint32 // Version is the version - Dev uint32 // Dev is the device identifier - Flags int32 // Flags is the swap flags applied to the device - NBlks int32 // NBlks is the total number of blocks - Used int32 // Used is the number of blocks used -} - -func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { - // FreeBSD can have multiple swap devices so we total them up - i, err := common.SysctlUint("vm.nswapdev") - if err != nil { - return nil, err - } - - if i == 0 { - return nil, errors.New("no swap devices found") - } - - c := int(i) - - i, err = common.SysctlUint("vm.stats.vm.v_page_size") - if err != nil { - return nil, err - } - pageSize := i - - var buf []byte - s := &SwapMemoryStat{} - for n := 0; n < c; n++ { - buf, err = unix.SysctlRaw("vm.swap_info", n) - if err != nil { - return nil, err - } - - // first, try to parse with version 2 - xsw := (*xswdev)(unsafe.Pointer(&buf[0])) - if xsw.Version == XSWDEV_VERSION11 { - // this is version 1, so try to parse again - xsw := (*xswdev11)(unsafe.Pointer(&buf[0])) - if xsw.Version != XSWDEV_VERSION11 { - return nil, errors.New("xswdev version mismatch(11)") - } - s.Total += uint64(xsw.NBlks) - s.Used += uint64(xsw.Used) - } else if xsw.Version != XSWDEV_VERSION { - return nil, errors.New("xswdev version mismatch") - } else { - s.Total += uint64(xsw.NBlks) - s.Used += uint64(xsw.Used) - } - - } - - if s.Total != 0 { - s.UsedPercent = float64(s.Used) / float64(s.Total) * 100 - } - s.Total *= pageSize - s.Used *= pageSize - s.Free = s.Total - s.Used - - return s, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_linux.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_linux.go deleted file mode 100644 index cf3c64e9c..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_linux.go +++ /dev/null @@ -1,514 +0,0 @@ -// +build linux - -package mem - -import ( - "bufio" - "context" - "encoding/json" - "fmt" - "io" - "math" - "os" - "strconv" - "strings" - - "github.com/shirou/gopsutil/internal/common" - "golang.org/x/sys/unix" -) - -type VirtualMemoryExStat struct { - ActiveFile uint64 `json:"activefile"` - InactiveFile uint64 `json:"inactivefile"` - ActiveAnon uint64 `json:"activeanon"` - InactiveAnon uint64 `json:"inactiveanon"` - Unevictable uint64 `json:"unevictable"` -} - -func (v VirtualMemoryExStat) String() string { - s, _ := json.Marshal(v) - return string(s) -} - -func VirtualMemory() (*VirtualMemoryStat, error) { - return VirtualMemoryWithContext(context.Background()) -} - -func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { - vm, _, err := fillFromMeminfoWithContext(ctx) - if err != nil { - return nil, err - } - return vm, nil -} - -func VirtualMemoryEx() (*VirtualMemoryExStat, error) { - return VirtualMemoryExWithContext(context.Background()) -} - -func VirtualMemoryExWithContext(ctx context.Context) (*VirtualMemoryExStat, error) { - _, vmEx, err := fillFromMeminfoWithContext(ctx) - if err != nil { - return nil, err - } - return vmEx, nil -} - -func fillFromMeminfoWithContext(ctx context.Context) (*VirtualMemoryStat, *VirtualMemoryExStat, error) { - filename := common.HostProc("meminfo") - lines, _ := common.ReadLines(filename) - - // flag if MemAvailable is in /proc/meminfo (kernel 3.14+) - memavail := false - activeFile := false // "Active(file)" not available: 2.6.28 / Dec 2008 - inactiveFile := false // "Inactive(file)" not available: 2.6.28 / Dec 2008 - sReclaimable := false // "SReclaimable:" not available: 2.6.19 / Nov 2006 - - ret := &VirtualMemoryStat{} - retEx := &VirtualMemoryExStat{} - - for _, line := range lines { - fields := strings.Split(line, ":") - if len(fields) != 2 { - continue - } - key := strings.TrimSpace(fields[0]) - value := strings.TrimSpace(fields[1]) - value = strings.Replace(value, " kB", "", -1) - - switch key { - case "MemTotal": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Total = t * 1024 - case "MemFree": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Free = t * 1024 - case "MemAvailable": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - memavail = true - ret.Available = t * 1024 - case "Buffers": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Buffers = t * 1024 - case "Cached": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Cached = t * 1024 - case "Active": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Active = t * 1024 - case "Inactive": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Inactive = t * 1024 - case "Active(anon)": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - retEx.ActiveAnon = t * 1024 - case "Inactive(anon)": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - retEx.InactiveAnon = t * 1024 - case "Active(file)": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - activeFile = true - retEx.ActiveFile = t * 1024 - case "Inactive(file)": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - inactiveFile = true - retEx.InactiveFile = t * 1024 - case "Unevictable": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - retEx.Unevictable = t * 1024 - case "Writeback": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Writeback = t * 1024 - case "WritebackTmp": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.WritebackTmp = t * 1024 - case "Dirty": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Dirty = t * 1024 - case "Shmem": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Shared = t * 1024 - case "Slab": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Slab = t * 1024 - case "SReclaimable": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - sReclaimable = true - ret.SReclaimable = t * 1024 - case "SUnreclaim": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.SUnreclaim = t * 1024 - case "PageTables": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.PageTables = t * 1024 - case "SwapCached": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.SwapCached = t * 1024 - case "CommitLimit": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.CommitLimit = t * 1024 - case "Committed_AS": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.CommittedAS = t * 1024 - case "HighTotal": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.HighTotal = t * 1024 - case "HighFree": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.HighFree = t * 1024 - case "LowTotal": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.LowTotal = t * 1024 - case "LowFree": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.LowFree = t * 1024 - case "SwapTotal": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.SwapTotal = t * 1024 - case "SwapFree": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.SwapFree = t * 1024 - case "Mapped": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.Mapped = t * 1024 - case "VmallocTotal": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.VMallocTotal = t * 1024 - case "VmallocUsed": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.VMallocUsed = t * 1024 - case "VmallocChunk": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.VMallocChunk = t * 1024 - case "HugePages_Total": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.HugePagesTotal = t - case "HugePages_Free": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.HugePagesFree = t - case "Hugepagesize": - t, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return ret, retEx, err - } - ret.HugePageSize = t * 1024 - } - } - - ret.Cached += ret.SReclaimable - - if !memavail { - if activeFile && inactiveFile && sReclaimable { - ret.Available = calcuateAvailVmem(ret, retEx) - } else { - ret.Available = ret.Cached + ret.Free - } - } - - ret.Used = ret.Total - ret.Free - ret.Buffers - ret.Cached - ret.UsedPercent = float64(ret.Used) / float64(ret.Total) * 100.0 - - return ret, retEx, nil -} - -func SwapMemory() (*SwapMemoryStat, error) { - return SwapMemoryWithContext(context.Background()) -} - -func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { - sysinfo := &unix.Sysinfo_t{} - - if err := unix.Sysinfo(sysinfo); err != nil { - return nil, err - } - ret := &SwapMemoryStat{ - Total: uint64(sysinfo.Totalswap) * uint64(sysinfo.Unit), - Free: uint64(sysinfo.Freeswap) * uint64(sysinfo.Unit), - } - ret.Used = ret.Total - ret.Free - //check Infinity - if ret.Total != 0 { - ret.UsedPercent = float64(ret.Total-ret.Free) / float64(ret.Total) * 100.0 - } else { - ret.UsedPercent = 0 - } - filename := common.HostProc("vmstat") - lines, _ := common.ReadLines(filename) - for _, l := range lines { - fields := strings.Fields(l) - if len(fields) < 2 { - continue - } - switch fields[0] { - case "pswpin": - value, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { - continue - } - ret.Sin = value * 4 * 1024 - case "pswpout": - value, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { - continue - } - ret.Sout = value * 4 * 1024 - case "pgpgin": - value, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { - continue - } - ret.PgIn = value * 4 * 1024 - case "pgpgout": - value, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { - continue - } - ret.PgOut = value * 4 * 1024 - case "pgfault": - value, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { - continue - } - ret.PgFault = value * 4 * 1024 - case "pgmajfault": - value, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { - continue - } - ret.PgMajFault = value * 4 * 1024 - } - } - return ret, nil -} - -// calcuateAvailVmem is a fallback under kernel 3.14 where /proc/meminfo does not provide -// "MemAvailable:" column. It reimplements an algorithm from the link below -// https://github.com/giampaolo/psutil/pull/890 -func calcuateAvailVmem(ret *VirtualMemoryStat, retEx *VirtualMemoryExStat) uint64 { - var watermarkLow uint64 - - fn := common.HostProc("zoneinfo") - lines, err := common.ReadLines(fn) - - if err != nil { - return ret.Free + ret.Cached // fallback under kernel 2.6.13 - } - - pagesize := uint64(os.Getpagesize()) - watermarkLow = 0 - - for _, line := range lines { - fields := strings.Fields(line) - - if strings.HasPrefix(fields[0], "low") { - lowValue, err := strconv.ParseUint(fields[1], 10, 64) - - if err != nil { - lowValue = 0 - } - watermarkLow += lowValue - } - } - - watermarkLow *= pagesize - - availMemory := ret.Free - watermarkLow - pageCache := retEx.ActiveFile + retEx.InactiveFile - pageCache -= uint64(math.Min(float64(pageCache/2), float64(watermarkLow))) - availMemory += pageCache - availMemory += ret.SReclaimable - uint64(math.Min(float64(ret.SReclaimable/2.0), float64(watermarkLow))) - - if availMemory < 0 { - availMemory = 0 - } - - return availMemory -} - -const swapsFilename = "swaps" - -// swaps file column indexes -const ( - nameCol = 0 - // typeCol = 1 - totalCol = 2 - usedCol = 3 - // priorityCol = 4 -) - -func SwapDevices() ([]*SwapDevice, error) { - return SwapDevicesWithContext(context.Background()) -} - -func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - swapsFilePath := common.HostProc(swapsFilename) - f, err := os.Open(swapsFilePath) - if err != nil { - return nil, err - } - defer f.Close() - - return parseSwapsFile(f) -} - -func parseSwapsFile(r io.Reader) ([]*SwapDevice, error) { - swapsFilePath := common.HostProc(swapsFilename) - scanner := bufio.NewScanner(r) - if !scanner.Scan() { - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("couldn't read file %q: %w", swapsFilePath, err) - } - return nil, fmt.Errorf("unexpected end-of-file in %q", swapsFilePath) - - } - - // Check header headerFields are as expected - headerFields := strings.Fields(scanner.Text()) - if len(headerFields) < usedCol { - return nil, fmt.Errorf("couldn't parse %q: too few fields in header", swapsFilePath) - } - if headerFields[nameCol] != "Filename" { - return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapsFilePath, headerFields[nameCol], "Filename") - } - if headerFields[totalCol] != "Size" { - return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapsFilePath, headerFields[totalCol], "Size") - } - if headerFields[usedCol] != "Used" { - return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapsFilePath, headerFields[usedCol], "Used") - } - - var swapDevices []*SwapDevice - for scanner.Scan() { - fields := strings.Fields(scanner.Text()) - if len(fields) < usedCol { - return nil, fmt.Errorf("couldn't parse %q: too few fields", swapsFilePath) - } - - totalKiB, err := strconv.ParseUint(fields[totalCol], 10, 64) - if err != nil { - return nil, fmt.Errorf("couldn't parse 'Size' column in %q: %w", swapsFilePath, err) - } - - usedKiB, err := strconv.ParseUint(fields[usedCol], 10, 64) - if err != nil { - return nil, fmt.Errorf("couldn't parse 'Used' column in %q: %w", swapsFilePath, err) - } - - swapDevices = append(swapDevices, &SwapDevice{ - Name: fields[nameCol], - UsedBytes: usedKiB * 1024, - FreeBytes: (totalKiB - usedKiB) * 1024, - }) - } - - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("couldn't read file %q: %w", swapsFilePath, err) - } - - return swapDevices, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd.go deleted file mode 100644 index 7ecdae9fd..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd.go +++ /dev/null @@ -1,105 +0,0 @@ -// +build openbsd - -package mem - -import ( - "bytes" - "context" - "encoding/binary" - "errors" - "fmt" - "os/exec" - - "github.com/shirou/gopsutil/internal/common" - "golang.org/x/sys/unix" -) - -func GetPageSize() (uint64, error) { - return GetPageSizeWithContext(context.Background()) -} - -func GetPageSizeWithContext(ctx context.Context) (uint64, error) { - uvmexp, err := unix.SysctlUvmexp("vm.uvmexp") - if err != nil { - return 0, err - } - return uint64(uvmexp.Pagesize), nil -} - -func VirtualMemory() (*VirtualMemoryStat, error) { - return VirtualMemoryWithContext(context.Background()) -} - -func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { - uvmexp, err := unix.SysctlUvmexp("vm.uvmexp") - if err != nil { - return nil, err - } - p := uint64(uvmexp.Pagesize) - - ret := &VirtualMemoryStat{ - Total: uint64(uvmexp.Npages) * p, - Free: uint64(uvmexp.Free) * p, - Active: uint64(uvmexp.Active) * p, - Inactive: uint64(uvmexp.Inactive) * p, - Cached: 0, // not available - Wired: uint64(uvmexp.Wired) * p, - } - - ret.Available = ret.Inactive + ret.Cached + ret.Free - ret.Used = ret.Total - ret.Available - ret.UsedPercent = float64(ret.Used) / float64(ret.Total) * 100.0 - - mib := []int32{CTLVfs, VfsGeneric, VfsBcacheStat} - buf, length, err := common.CallSyscall(mib) - if err != nil { - return nil, err - } - if length < sizeOfBcachestats { - return nil, fmt.Errorf("short syscall ret %d bytes", length) - } - var bcs Bcachestats - br := bytes.NewReader(buf) - err = common.Read(br, binary.LittleEndian, &bcs) - if err != nil { - return nil, err - } - ret.Buffers = uint64(bcs.Numbufpages) * p - - return ret, nil -} - -// Return swapctl summary info -func SwapMemory() (*SwapMemoryStat, error) { - return SwapMemoryWithContext(context.Background()) -} - -func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { - swapctl, err := exec.LookPath("swapctl") - if err != nil { - return nil, err - } - - out, err := invoke.CommandWithContext(ctx, swapctl, "-sk") - if err != nil { - return &SwapMemoryStat{}, nil - } - - line := string(out) - var total, used, free uint64 - - _, err = fmt.Sscanf(line, - "total: %d 1K-blocks allocated, %d used, %d available", - &total, &used, &free) - if err != nil { - return nil, errors.New("failed to parse swapctl output") - } - - percent := float64(used) / float64(total) * 100 - return &SwapMemoryStat{ - Total: total * 1024, - Used: used * 1024, - Free: free * 1024, - UsedPercent: percent, - }, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_386.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_386.go deleted file mode 100644 index 0fa65d9c7..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_386.go +++ /dev/null @@ -1,37 +0,0 @@ -// +build openbsd,386 - -// Code generated by cmd/cgo -godefs; DO NOT EDIT. -// cgo -godefs mem/types_openbsd.go - -package mem - -const ( - CTLVfs = 10 - VfsGeneric = 0 - VfsBcacheStat = 3 -) - -const ( - sizeOfBcachestats = 0x90 -) - -type Bcachestats struct { - Numbufs int64 - Numbufpages int64 - Numdirtypages int64 - Numcleanpages int64 - Pendingwrites int64 - Pendingreads int64 - Numwrites int64 - Numreads int64 - Cachehits int64 - Busymapped int64 - Dmapages int64 - Highpages int64 - Delwribufs int64 - Kvaslots int64 - Avail int64 - Highflips int64 - Highflops int64 - Dmaflips int64 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_amd64.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_amd64.go deleted file mode 100644 index d187abf01..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_amd64.go +++ /dev/null @@ -1,32 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_openbsd.go - -package mem - -const ( - CTLVfs = 10 - VfsGeneric = 0 - VfsBcacheStat = 3 -) - -const ( - sizeOfBcachestats = 0x78 -) - -type Bcachestats struct { - Numbufs int64 - Numbufpages int64 - Numdirtypages int64 - Numcleanpages int64 - Pendingwrites int64 - Pendingreads int64 - Numwrites int64 - Numreads int64 - Cachehits int64 - Busymapped int64 - Dmapages int64 - Highpages int64 - Delwribufs int64 - Kvaslots int64 - Avail int64 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_arm64.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_arm64.go deleted file mode 100644 index 35f8517b6..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_openbsd_arm64.go +++ /dev/null @@ -1,37 +0,0 @@ -// +build openbsd,arm64 - -// Code generated by cmd/cgo -godefs; DO NOT EDIT. -// cgo -godefs mem/types_openbsd.go - -package mem - -const ( - CTLVfs = 10 - VfsGeneric = 0 - VfsBcacheStat = 3 -) - -const ( - sizeOfBcachestats = 0x90 -) - -type Bcachestats struct { - Numbufs int64 - Numbufpages int64 - Numdirtypages int64 - Numcleanpages int64 - Pendingwrites int64 - Pendingreads int64 - Numwrites int64 - Numreads int64 - Cachehits int64 - Busymapped int64 - Dmapages int64 - Highpages int64 - Delwribufs int64 - Kvaslots int64 - Avail int64 - Highflips int64 - Highflops int64 - Dmaflips int64 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_solaris.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_solaris.go deleted file mode 100644 index 8b549588a..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_solaris.go +++ /dev/null @@ -1,204 +0,0 @@ -// +build solaris - -package mem - -import ( - "context" - "fmt" - "os/exec" - "regexp" - "strconv" - "strings" - - "github.com/shirou/gopsutil/internal/common" -) - -// VirtualMemory for Solaris is a minimal implementation which only returns -// what Nomad needs. It does take into account global vs zone, however. -func VirtualMemory() (*VirtualMemoryStat, error) { - return VirtualMemoryWithContext(context.Background()) -} - -func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { - result := &VirtualMemoryStat{} - - zoneName, err := zoneName() - if err != nil { - return nil, err - } - - if zoneName == "global" { - cap, err := globalZoneMemoryCapacity() - if err != nil { - return nil, err - } - result.Total = cap - } else { - cap, err := nonGlobalZoneMemoryCapacity() - if err != nil { - return nil, err - } - result.Total = cap - } - - return result, nil -} - -func SwapMemory() (*SwapMemoryStat, error) { - return SwapMemoryWithContext(context.Background()) -} - -func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { - return nil, common.ErrNotImplementedError -} - -func zoneName() (string, error) { - zonename, err := exec.LookPath("zonename") - if err != nil { - return "", err - } - - ctx := context.Background() - out, err := invoke.CommandWithContext(ctx, zonename) - if err != nil { - return "", err - } - - return strings.TrimSpace(string(out)), nil -} - -var globalZoneMemoryCapacityMatch = regexp.MustCompile(`[Mm]emory size: (\d+) Megabytes`) - -func globalZoneMemoryCapacity() (uint64, error) { - prtconf, err := exec.LookPath("prtconf") - if err != nil { - return 0, err - } - - ctx := context.Background() - out, err := invoke.CommandWithContext(ctx, prtconf) - if err != nil { - return 0, err - } - - match := globalZoneMemoryCapacityMatch.FindAllStringSubmatch(string(out), -1) - if len(match) != 1 { - return 0, fmt.Errorf("memory size not contained in output of %q", prtconf) - } - - totalMB, err := strconv.ParseUint(match[0][1], 10, 64) - if err != nil { - return 0, err - } - - return totalMB * 1024 * 1024, nil -} - -var kstatMatch = regexp.MustCompile(`(\S+)\s+(\S*)`) - -func nonGlobalZoneMemoryCapacity() (uint64, error) { - kstat, err := exec.LookPath("kstat") - if err != nil { - return 0, err - } - - ctx := context.Background() - out, err := invoke.CommandWithContext(ctx, kstat, "-p", "-c", "zone_memory_cap", "memory_cap:*:*:physcap") - if err != nil { - return 0, err - } - - kstats := kstatMatch.FindAllStringSubmatch(string(out), -1) - if len(kstats) != 1 { - return 0, fmt.Errorf("expected 1 kstat, found %d", len(kstats)) - } - - memSizeBytes, err := strconv.ParseUint(kstats[0][2], 10, 64) - if err != nil { - return 0, err - } - - return memSizeBytes, nil -} - -const swapCommand = "swap" - -// The blockSize as reported by `swap -l`. See https://docs.oracle.com/cd/E23824_01/html/821-1459/fsswap-52195.html -const blockSize = 512 - -// swapctl column indexes -const ( - nameCol = 0 - // devCol = 1 - // swaploCol = 2 - totalBlocksCol = 3 - freeBlocksCol = 4 -) - -func SwapDevices() ([]*SwapDevice, error) { - return SwapDevicesWithContext(context.Background()) -} - -func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - swapCommandPath, err := exec.LookPath(swapCommand) - if err != nil { - return nil, fmt.Errorf("could not find command %q: %w", swapCommand, err) - } - output, err := invoke.CommandWithContext(ctx, swapCommandPath, "-l") - if err != nil { - return nil, fmt.Errorf("could not execute %q: %w", swapCommand, err) - } - - return parseSwapsCommandOutput(string(output)) -} - -func parseSwapsCommandOutput(output string) ([]*SwapDevice, error) { - lines := strings.Split(output, "\n") - if len(lines) == 0 { - return nil, fmt.Errorf("could not parse output of %q: no lines in %q", swapCommand, output) - } - - // Check header headerFields are as expected. - headerFields := strings.Fields(lines[0]) - if len(headerFields) < freeBlocksCol { - return nil, fmt.Errorf("couldn't parse %q: too few fields in header %q", swapCommand, lines[0]) - } - if headerFields[nameCol] != "swapfile" { - return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapCommand, headerFields[nameCol], "swapfile") - } - if headerFields[totalBlocksCol] != "blocks" { - return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapCommand, headerFields[totalBlocksCol], "blocks") - } - if headerFields[freeBlocksCol] != "free" { - return nil, fmt.Errorf("couldn't parse %q: expected %q to be %q", swapCommand, headerFields[freeBlocksCol], "free") - } - - var swapDevices []*SwapDevice - for _, line := range lines[1:] { - if line == "" { - continue // the terminal line is typically empty - } - fields := strings.Fields(line) - if len(fields) < freeBlocksCol { - return nil, fmt.Errorf("couldn't parse %q: too few fields", swapCommand) - } - - totalBlocks, err := strconv.ParseUint(fields[totalBlocksCol], 10, 64) - if err != nil { - return nil, fmt.Errorf("couldn't parse 'Size' column in %q: %w", swapCommand, err) - } - - freeBlocks, err := strconv.ParseUint(fields[freeBlocksCol], 10, 64) - if err != nil { - return nil, fmt.Errorf("couldn't parse 'Used' column in %q: %w", swapCommand, err) - } - - swapDevices = append(swapDevices, &SwapDevice{ - Name: fields[nameCol], - UsedBytes: (totalBlocks - freeBlocks) * blockSize, - FreeBytes: freeBlocks * blockSize, - }) - } - - return swapDevices, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_windows.go b/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_windows.go deleted file mode 100644 index 7c2f3bc68..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/mem/mem_windows.go +++ /dev/null @@ -1,165 +0,0 @@ -// +build windows - -package mem - -import ( - "context" - "sync" - "syscall" - "unsafe" - - "github.com/shirou/gopsutil/internal/common" - "golang.org/x/sys/windows" -) - -var ( - procEnumPageFilesW = common.ModPsapi.NewProc("EnumPageFilesW") - procGetNativeSystemInfo = common.Modkernel32.NewProc("GetNativeSystemInfo") - procGetPerformanceInfo = common.ModPsapi.NewProc("GetPerformanceInfo") - procGlobalMemoryStatusEx = common.Modkernel32.NewProc("GlobalMemoryStatusEx") -) - -type memoryStatusEx struct { - cbSize uint32 - dwMemoryLoad uint32 - ullTotalPhys uint64 // in bytes - ullAvailPhys uint64 - ullTotalPageFile uint64 - ullAvailPageFile uint64 - ullTotalVirtual uint64 - ullAvailVirtual uint64 - ullAvailExtendedVirtual uint64 -} - -func VirtualMemory() (*VirtualMemoryStat, error) { - return VirtualMemoryWithContext(context.Background()) -} - -func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { - var memInfo memoryStatusEx - memInfo.cbSize = uint32(unsafe.Sizeof(memInfo)) - mem, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&memInfo))) - if mem == 0 { - return nil, windows.GetLastError() - } - - ret := &VirtualMemoryStat{ - Total: memInfo.ullTotalPhys, - Available: memInfo.ullAvailPhys, - Free: memInfo.ullAvailPhys, - UsedPercent: float64(memInfo.dwMemoryLoad), - } - - ret.Used = ret.Total - ret.Available - return ret, nil -} - -type performanceInformation struct { - cb uint32 - commitTotal uint64 - commitLimit uint64 - commitPeak uint64 - physicalTotal uint64 - physicalAvailable uint64 - systemCache uint64 - kernelTotal uint64 - kernelPaged uint64 - kernelNonpaged uint64 - pageSize uint64 - handleCount uint32 - processCount uint32 - threadCount uint32 -} - -func SwapMemory() (*SwapMemoryStat, error) { - return SwapMemoryWithContext(context.Background()) -} - -func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { - var perfInfo performanceInformation - perfInfo.cb = uint32(unsafe.Sizeof(perfInfo)) - mem, _, _ := procGetPerformanceInfo.Call(uintptr(unsafe.Pointer(&perfInfo)), uintptr(perfInfo.cb)) - if mem == 0 { - return nil, windows.GetLastError() - } - tot := perfInfo.commitLimit * perfInfo.pageSize - used := perfInfo.commitTotal * perfInfo.pageSize - free := tot - used - var usedPercent float64 - if tot == 0 { - usedPercent = 0 - } else { - usedPercent = float64(used) / float64(tot) * 100 - } - ret := &SwapMemoryStat{ - Total: tot, - Used: used, - Free: free, - UsedPercent: usedPercent, - } - - return ret, nil -} - -var ( - pageSize uint64 - pageSizeOnce sync.Once -) - -type systemInfo struct { - wProcessorArchitecture uint16 - wReserved uint16 - dwPageSize uint32 - lpMinimumApplicationAddress uintptr - lpMaximumApplicationAddress uintptr - dwActiveProcessorMask uintptr - dwNumberOfProcessors uint32 - dwProcessorType uint32 - dwAllocationGranularity uint32 - wProcessorLevel uint16 - wProcessorRevision uint16 -} - -// system type as defined in https://docs.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-enum_page_file_information -type enumPageFileInformation struct { - cb uint32 - reserved uint32 - totalSize uint64 - totalInUse uint64 - peakUsage uint64 -} - -func SwapDevices() ([]*SwapDevice, error) { - return SwapDevicesWithContext(context.Background()) -} - -func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - pageSizeOnce.Do(func() { - var sysInfo systemInfo - procGetNativeSystemInfo.Call(uintptr(unsafe.Pointer(&sysInfo))) - pageSize = uint64(sysInfo.dwPageSize) - }) - - // the following system call invokes the supplied callback function once for each page file before returning - // see https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-enumpagefilesw - var swapDevices []*SwapDevice - result, _, _ := procEnumPageFilesW.Call(windows.NewCallback(pEnumPageFileCallbackW), uintptr(unsafe.Pointer(&swapDevices))) - if result == 0 { - return nil, windows.GetLastError() - } - - return swapDevices, nil -} - -// system callback as defined in https://docs.microsoft.com/en-us/windows/win32/api/psapi/nc-psapi-penum_page_file_callbackw -func pEnumPageFileCallbackW(swapDevices *[]*SwapDevice, enumPageFileInfo *enumPageFileInformation, lpFilenamePtr *[syscall.MAX_LONG_PATH]uint16) *bool { - *swapDevices = append(*swapDevices, &SwapDevice{ - Name: syscall.UTF16ToString((*lpFilenamePtr)[:]), - UsedBytes: enumPageFileInfo.totalInUse * pageSize, - FreeBytes: (enumPageFileInfo.totalSize - enumPageFileInfo.totalInUse) * pageSize, - }) - - // return true to continue enumerating page files - ret := true - return &ret -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/net/net.go b/test/integration/vendor/github.com/shirou/gopsutil/net/net.go deleted file mode 100644 index f1f99dc3a..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/net/net.go +++ /dev/null @@ -1,263 +0,0 @@ -package net - -import ( - "context" - "encoding/json" - "net" - - "github.com/shirou/gopsutil/internal/common" -) - -var invoke common.Invoker = common.Invoke{} - -type IOCountersStat struct { - Name string `json:"name"` // interface name - BytesSent uint64 `json:"bytesSent"` // number of bytes sent - BytesRecv uint64 `json:"bytesRecv"` // number of bytes received - PacketsSent uint64 `json:"packetsSent"` // number of packets sent - PacketsRecv uint64 `json:"packetsRecv"` // number of packets received - Errin uint64 `json:"errin"` // total number of errors while receiving - Errout uint64 `json:"errout"` // total number of errors while sending - Dropin uint64 `json:"dropin"` // total number of incoming packets which were dropped - Dropout uint64 `json:"dropout"` // total number of outgoing packets which were dropped (always 0 on OSX and BSD) - Fifoin uint64 `json:"fifoin"` // total number of FIFO buffers errors while receiving - Fifoout uint64 `json:"fifoout"` // total number of FIFO buffers errors while sending - -} - -// Addr is implemented compatibility to psutil -type Addr struct { - IP string `json:"ip"` - Port uint32 `json:"port"` -} - -type ConnectionStat struct { - Fd uint32 `json:"fd"` - Family uint32 `json:"family"` - Type uint32 `json:"type"` - Laddr Addr `json:"localaddr"` - Raddr Addr `json:"remoteaddr"` - Status string `json:"status"` - Uids []int32 `json:"uids"` - Pid int32 `json:"pid"` -} - -// System wide stats about different network protocols -type ProtoCountersStat struct { - Protocol string `json:"protocol"` - Stats map[string]int64 `json:"stats"` -} - -// NetInterfaceAddr is designed for represent interface addresses -type InterfaceAddr struct { - Addr string `json:"addr"` -} - -type InterfaceStat struct { - Index int `json:"index"` - MTU int `json:"mtu"` // maximum transmission unit - Name string `json:"name"` // e.g., "en0", "lo0", "eth0.100" - HardwareAddr string `json:"hardwareaddr"` // IEEE MAC-48, EUI-48 and EUI-64 form - Flags []string `json:"flags"` // e.g., FlagUp, FlagLoopback, FlagMulticast - Addrs []InterfaceAddr `json:"addrs"` -} - -type FilterStat struct { - ConnTrackCount int64 `json:"conntrackCount"` - ConnTrackMax int64 `json:"conntrackMax"` -} - -// ConntrackStat has conntrack summary info -type ConntrackStat struct { - Entries uint32 `json:"entries"` // Number of entries in the conntrack table - Searched uint32 `json:"searched"` // Number of conntrack table lookups performed - Found uint32 `json:"found"` // Number of searched entries which were successful - New uint32 `json:"new"` // Number of entries added which were not expected before - Invalid uint32 `json:"invalid"` // Number of packets seen which can not be tracked - Ignore uint32 `json:"ignore"` // Packets seen which are already connected to an entry - Delete uint32 `json:"delete"` // Number of entries which were removed - DeleteList uint32 `json:"delete_list"` // Number of entries which were put to dying list - Insert uint32 `json:"insert"` // Number of entries inserted into the list - InsertFailed uint32 `json:"insert_failed"` // # insertion attempted but failed (same entry exists) - Drop uint32 `json:"drop"` // Number of packets dropped due to conntrack failure. - EarlyDrop uint32 `json:"early_drop"` // Dropped entries to make room for new ones, if maxsize reached - IcmpError uint32 `json:"icmp_error"` // Subset of invalid. Packets that can't be tracked d/t error - ExpectNew uint32 `json:"expect_new"` // Entries added after an expectation was already present - ExpectCreate uint32 `json:"expect_create"` // Expectations added - ExpectDelete uint32 `json:"expect_delete"` // Expectations deleted - SearchRestart uint32 `json:"search_restart"` // Conntrack table lookups restarted due to hashtable resizes -} - -func NewConntrackStat(e uint32, s uint32, f uint32, n uint32, inv uint32, ign uint32, del uint32, dlst uint32, ins uint32, insfail uint32, drop uint32, edrop uint32, ie uint32, en uint32, ec uint32, ed uint32, sr uint32) *ConntrackStat { - return &ConntrackStat{ - Entries: e, - Searched: s, - Found: f, - New: n, - Invalid: inv, - Ignore: ign, - Delete: del, - DeleteList: dlst, - Insert: ins, - InsertFailed: insfail, - Drop: drop, - EarlyDrop: edrop, - IcmpError: ie, - ExpectNew: en, - ExpectCreate: ec, - ExpectDelete: ed, - SearchRestart: sr, - } -} - -type ConntrackStatList struct { - items []*ConntrackStat -} - -func NewConntrackStatList() *ConntrackStatList { - return &ConntrackStatList{ - items: []*ConntrackStat{}, - } -} - -func (l *ConntrackStatList) Append(c *ConntrackStat) { - l.items = append(l.items, c) -} - -func (l *ConntrackStatList) Items() []ConntrackStat { - items := make([]ConntrackStat, len(l.items), len(l.items)) - for i, el := range l.items { - items[i] = *el - } - return items -} - -// Summary returns a single-element list with totals from all list items. -func (l *ConntrackStatList) Summary() []ConntrackStat { - summary := NewConntrackStat(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - for _, cs := range l.items { - summary.Entries += cs.Entries - summary.Searched += cs.Searched - summary.Found += cs.Found - summary.New += cs.New - summary.Invalid += cs.Invalid - summary.Ignore += cs.Ignore - summary.Delete += cs.Delete - summary.DeleteList += cs.DeleteList - summary.Insert += cs.Insert - summary.InsertFailed += cs.InsertFailed - summary.Drop += cs.Drop - summary.EarlyDrop += cs.EarlyDrop - summary.IcmpError += cs.IcmpError - summary.ExpectNew += cs.ExpectNew - summary.ExpectCreate += cs.ExpectCreate - summary.ExpectDelete += cs.ExpectDelete - summary.SearchRestart += cs.SearchRestart - } - return []ConntrackStat{*summary} -} - -func (n IOCountersStat) String() string { - s, _ := json.Marshal(n) - return string(s) -} - -func (n ConnectionStat) String() string { - s, _ := json.Marshal(n) - return string(s) -} - -func (n ProtoCountersStat) String() string { - s, _ := json.Marshal(n) - return string(s) -} - -func (a Addr) String() string { - s, _ := json.Marshal(a) - return string(s) -} - -func (n InterfaceStat) String() string { - s, _ := json.Marshal(n) - return string(s) -} - -func (n InterfaceAddr) String() string { - s, _ := json.Marshal(n) - return string(s) -} - -func (n ConntrackStat) String() string { - s, _ := json.Marshal(n) - return string(s) -} - -func Interfaces() ([]InterfaceStat, error) { - return InterfacesWithContext(context.Background()) -} - -func InterfacesWithContext(ctx context.Context) ([]InterfaceStat, error) { - is, err := net.Interfaces() - if err != nil { - return nil, err - } - ret := make([]InterfaceStat, 0, len(is)) - for _, ifi := range is { - - var flags []string - if ifi.Flags&net.FlagUp != 0 { - flags = append(flags, "up") - } - if ifi.Flags&net.FlagBroadcast != 0 { - flags = append(flags, "broadcast") - } - if ifi.Flags&net.FlagLoopback != 0 { - flags = append(flags, "loopback") - } - if ifi.Flags&net.FlagPointToPoint != 0 { - flags = append(flags, "pointtopoint") - } - if ifi.Flags&net.FlagMulticast != 0 { - flags = append(flags, "multicast") - } - - r := InterfaceStat{ - Index: ifi.Index, - Name: ifi.Name, - MTU: ifi.MTU, - HardwareAddr: ifi.HardwareAddr.String(), - Flags: flags, - } - addrs, err := ifi.Addrs() - if err == nil { - r.Addrs = make([]InterfaceAddr, 0, len(addrs)) - for _, addr := range addrs { - r.Addrs = append(r.Addrs, InterfaceAddr{ - Addr: addr.String(), - }) - } - - } - ret = append(ret, r) - } - - return ret, nil -} - -func getIOCountersAll(n []IOCountersStat) ([]IOCountersStat, error) { - r := IOCountersStat{ - Name: "all", - } - for _, nic := range n { - r.BytesRecv += nic.BytesRecv - r.PacketsRecv += nic.PacketsRecv - r.Errin += nic.Errin - r.Dropin += nic.Dropin - r.BytesSent += nic.BytesSent - r.PacketsSent += nic.PacketsSent - r.Errout += nic.Errout - r.Dropout += nic.Dropout - } - - return []IOCountersStat{r}, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/net/net_aix.go b/test/integration/vendor/github.com/shirou/gopsutil/net/net_aix.go deleted file mode 100644 index 4ac849701..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/net/net_aix.go +++ /dev/null @@ -1,425 +0,0 @@ -// +build aix - -package net - -import ( - "context" - "fmt" - "os/exec" - "regexp" - "strconv" - "strings" - "syscall" - - "github.com/shirou/gopsutil/internal/common" -) - -func parseNetstatI(output string) ([]IOCountersStat, error) { - lines := strings.Split(string(output), "\n") - ret := make([]IOCountersStat, 0, len(lines)-1) - exists := make([]string, 0, len(ret)) - - // Check first line is header - if len(lines) > 0 && strings.Fields(lines[0])[0] != "Name" { - return nil, fmt.Errorf("not a 'netstat -i' output") - } - - for _, line := range lines[1:] { - values := strings.Fields(line) - if len(values) < 1 || values[0] == "Name" { - continue - } - if common.StringsHas(exists, values[0]) { - // skip if already get - continue - } - exists = append(exists, values[0]) - - if len(values) < 9 { - continue - } - - base := 1 - // sometimes Address is omitted - if len(values) < 10 { - base = 0 - } - - parsed := make([]uint64, 0, 5) - vv := []string{ - values[base+3], // Ipkts == PacketsRecv - values[base+4], // Ierrs == Errin - values[base+5], // Opkts == PacketsSent - values[base+6], // Oerrs == Errout - values[base+8], // Drops == Dropout - } - - for _, target := range vv { - if target == "-" { - parsed = append(parsed, 0) - continue - } - - t, err := strconv.ParseUint(target, 10, 64) - if err != nil { - return nil, err - } - parsed = append(parsed, t) - } - - n := IOCountersStat{ - Name: values[0], - PacketsRecv: parsed[0], - Errin: parsed[1], - PacketsSent: parsed[2], - Errout: parsed[3], - Dropout: parsed[4], - } - ret = append(ret, n) - } - return ret, nil -} - -func IOCounters(pernic bool) ([]IOCountersStat, error) { - return IOCountersWithContext(context.Background(), pernic) -} - -func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { - netstat, err := exec.LookPath("netstat") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, netstat, "-idn") - if err != nil { - return nil, err - } - - iocounters, err := parseNetstatI(string(out)) - if err != nil { - return nil, err - } - if pernic == false { - return getIOCountersAll(iocounters) - } - return iocounters, nil - -} - -// NetIOCountersByFile is an method which is added just a compatibility for linux. -func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { - return IOCountersByFileWithContext(context.Background(), pernic, filename) -} - -func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename string) ([]IOCountersStat, error) { - return IOCounters(pernic) -} - -func FilterCounters() ([]FilterStat, error) { - return FilterCountersWithContext(context.Background()) -} - -func FilterCountersWithContext(ctx context.Context) ([]FilterStat, error) { - return nil, common.ErrNotImplementedError -} - -func ConntrackStats(percpu bool) ([]ConntrackStat, error) { - return ConntrackStatsWithContext(context.Background(), percpu) -} - -func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackStat, error) { - return nil, common.ErrNotImplementedError -} - -func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) { - return ProtoCountersWithContext(context.Background(), protocols) -} - -func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func parseNetstatNetLine(line string) (ConnectionStat, error) { - f := strings.Fields(line) - if len(f) < 5 { - return ConnectionStat{}, fmt.Errorf("wrong line,%s", line) - } - - var netType, netFamily uint32 - switch f[0] { - case "tcp", "tcp4": - netType = syscall.SOCK_STREAM - netFamily = syscall.AF_INET - case "udp", "udp4": - netType = syscall.SOCK_DGRAM - netFamily = syscall.AF_INET - case "tcp6": - netType = syscall.SOCK_STREAM - netFamily = syscall.AF_INET6 - case "udp6": - netType = syscall.SOCK_DGRAM - netFamily = syscall.AF_INET6 - default: - return ConnectionStat{}, fmt.Errorf("unknown type, %s", f[0]) - } - - laddr, raddr, err := parseNetstatAddr(f[3], f[4], netFamily) - if err != nil { - return ConnectionStat{}, fmt.Errorf("failed to parse netaddr, %s %s", f[3], f[4]) - } - - n := ConnectionStat{ - Fd: uint32(0), // not supported - Family: uint32(netFamily), - Type: uint32(netType), - Laddr: laddr, - Raddr: raddr, - Pid: int32(0), // not supported - } - if len(f) == 6 { - n.Status = f[5] - } - - return n, nil -} - -var portMatch = regexp.MustCompile(`(.*)\.(\d+)$`) - -// This function only works for netstat returning addresses with a "." -// before the port (0.0.0.0.22 instead of 0.0.0.0:22). -func parseNetstatAddr(local string, remote string, family uint32) (laddr Addr, raddr Addr, err error) { - parse := func(l string) (Addr, error) { - matches := portMatch.FindStringSubmatch(l) - if matches == nil { - return Addr{}, fmt.Errorf("wrong addr, %s", l) - } - host := matches[1] - port := matches[2] - if host == "*" { - switch family { - case syscall.AF_INET: - host = "0.0.0.0" - case syscall.AF_INET6: - host = "::" - default: - return Addr{}, fmt.Errorf("unknown family, %d", family) - } - } - lport, err := strconv.Atoi(port) - if err != nil { - return Addr{}, err - } - return Addr{IP: host, Port: uint32(lport)}, nil - } - - laddr, err = parse(local) - if remote != "*.*" { // remote addr exists - raddr, err = parse(remote) - if err != nil { - return laddr, raddr, err - } - } - - return laddr, raddr, err -} - -func parseNetstatUnixLine(f []string) (ConnectionStat, error) { - if len(f) < 8 { - return ConnectionStat{}, fmt.Errorf("wrong number of fields: expected >=8 got %d", len(f)) - } - - var netType uint32 - - switch f[1] { - case "dgram": - netType = syscall.SOCK_DGRAM - case "stream": - netType = syscall.SOCK_STREAM - default: - return ConnectionStat{}, fmt.Errorf("unknown type: %s", f[1]) - } - - // Some Unix Socket don't have any address associated - addr := "" - if len(f) == 9 { - addr = f[8] - } - - c := ConnectionStat{ - Fd: uint32(0), // not supported - Family: uint32(syscall.AF_UNIX), - Type: uint32(netType), - Laddr: Addr{ - IP: addr, - }, - Status: "NONE", - Pid: int32(0), // not supported - } - - return c, nil -} - -// Return true if proto is the corresponding to the kind parameter -// Only for Inet lines -func hasCorrectInetProto(kind, proto string) bool { - switch kind { - case "all", "inet": - return true - case "unix": - return false - case "inet4": - return !strings.HasSuffix(proto, "6") - case "inet6": - return strings.HasSuffix(proto, "6") - case "tcp": - return proto == "tcp" || proto == "tcp4" || proto == "tcp6" - case "tcp4": - return proto == "tcp" || proto == "tcp4" - case "tcp6": - return proto == "tcp6" - case "udp": - return proto == "udp" || proto == "udp4" || proto == "udp6" - case "udp4": - return proto == "udp" || proto == "udp4" - case "udp6": - return proto == "udp6" - } - return false -} - -func parseNetstatA(output string, kind string) ([]ConnectionStat, error) { - var ret []ConnectionStat - lines := strings.Split(string(output), "\n") - - for _, line := range lines { - fields := strings.Fields(line) - if len(fields) < 1 { - continue - } - - if strings.HasPrefix(fields[0], "f1") { - // Unix lines - if len(fields) < 2 { - // every unix connections have two lines - continue - } - - c, err := parseNetstatUnixLine(fields) - if err != nil { - return nil, fmt.Errorf("failed to parse Unix Address (%s): %s", line, err) - } - - ret = append(ret, c) - - } else if strings.HasPrefix(fields[0], "tcp") || strings.HasPrefix(fields[0], "udp") { - // Inet lines - if !hasCorrectInetProto(kind, fields[0]) { - continue - } - - // On AIX, netstat display some connections with "*.*" as local addresses - // Skip them as they aren't real connections. - if fields[3] == "*.*" { - continue - } - - c, err := parseNetstatNetLine(line) - if err != nil { - return nil, fmt.Errorf("failed to parse Inet Address (%s): %s", line, err) - } - - ret = append(ret, c) - } else { - // Header lines - continue - } - } - - return ret, nil - -} - -func Connections(kind string) ([]ConnectionStat, error) { - return ConnectionsWithContext(context.Background(), kind) -} - -func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - - args := []string{"-na"} - switch strings.ToLower(kind) { - default: - fallthrough - case "": - kind = "all" - case "all": - // nothing to add - case "inet", "inet4", "inet6": - args = append(args, "-finet") - case "tcp", "tcp4", "tcp6": - args = append(args, "-finet") - case "udp", "udp4", "udp6": - args = append(args, "-finet") - case "unix": - args = append(args, "-funix") - } - - netstat, err := exec.LookPath("netstat") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, netstat, args...) - - if err != nil { - return nil, err - } - - ret, err := parseNetstatA(string(out), kind) - if err != nil { - return nil, err - } - - return ret, nil - -} - -func ConnectionsMax(kind string, max int) ([]ConnectionStat, error) { - return ConnectionsMaxWithContext(context.Background(), kind, max) -} - -func ConnectionsMaxWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return []ConnectionStat{}, common.ErrNotImplementedError -} - -// Return a list of network connections opened, omitting `Uids`. -// WithoutUids functions are reliant on implementation details. They may be altered to be an alias for Connections or be -// removed from the API in the future. -func ConnectionsWithoutUids(kind string) ([]ConnectionStat, error) { - return ConnectionsWithoutUidsWithContext(context.Background(), kind) -} - -func ConnectionsWithoutUidsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return ConnectionsMaxWithoutUidsWithContext(ctx, kind, 0) -} - -func ConnectionsMaxWithoutUidsWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(ctx, kind, 0, max) -} - -func ConnectionsPidWithoutUids(kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidWithoutUidsWithContext(context.Background(), kind, pid) -} - -func ConnectionsPidWithoutUidsWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, 0) -} - -func ConnectionsPidMaxWithoutUids(kind string, pid int32, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(context.Background(), kind, pid, max) -} - -func ConnectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return connectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, max) -} - -func connectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return []ConnectionStat{}, common.ErrNotImplementedError -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/net/net_darwin.go b/test/integration/vendor/github.com/shirou/gopsutil/net/net_darwin.go deleted file mode 100644 index 8e6e7f953..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/net/net_darwin.go +++ /dev/null @@ -1,293 +0,0 @@ -// +build darwin - -package net - -import ( - "context" - "errors" - "fmt" - "github.com/shirou/gopsutil/internal/common" - "os/exec" - "regexp" - "strconv" - "strings" -) - -var ( - errNetstatHeader = errors.New("Can't parse header of netstat output") - netstatLinkRegexp = regexp.MustCompile(`^$`) -) - -const endOfLine = "\n" - -func parseNetstatLine(line string) (stat *IOCountersStat, linkID *uint, err error) { - var ( - numericValue uint64 - columns = strings.Fields(line) - ) - - if columns[0] == "Name" { - err = errNetstatHeader - return - } - - // try to extract the numeric value from - if subMatch := netstatLinkRegexp.FindStringSubmatch(columns[2]); len(subMatch) == 2 { - numericValue, err = strconv.ParseUint(subMatch[1], 10, 64) - if err != nil { - return - } - linkIDUint := uint(numericValue) - linkID = &linkIDUint - } - - base := 1 - numberColumns := len(columns) - // sometimes Address is omitted - if numberColumns < 12 { - base = 0 - } - if numberColumns < 11 || numberColumns > 13 { - err = fmt.Errorf("Line %q do have an invalid number of columns %d", line, numberColumns) - return - } - - parsed := make([]uint64, 0, 7) - vv := []string{ - columns[base+3], // Ipkts == PacketsRecv - columns[base+4], // Ierrs == Errin - columns[base+5], // Ibytes == BytesRecv - columns[base+6], // Opkts == PacketsSent - columns[base+7], // Oerrs == Errout - columns[base+8], // Obytes == BytesSent - } - if len(columns) == 12 { - vv = append(vv, columns[base+10]) - } - - for _, target := range vv { - if target == "-" { - parsed = append(parsed, 0) - continue - } - - if numericValue, err = strconv.ParseUint(target, 10, 64); err != nil { - return - } - parsed = append(parsed, numericValue) - } - - stat = &IOCountersStat{ - Name: strings.Trim(columns[0], "*"), // remove the * that sometimes is on right on interface - PacketsRecv: parsed[0], - Errin: parsed[1], - BytesRecv: parsed[2], - PacketsSent: parsed[3], - Errout: parsed[4], - BytesSent: parsed[5], - } - if len(parsed) == 7 { - stat.Dropout = parsed[6] - } - return -} - -type netstatInterface struct { - linkID *uint - stat *IOCountersStat -} - -func parseNetstatOutput(output string) ([]netstatInterface, error) { - var ( - err error - lines = strings.Split(strings.Trim(output, endOfLine), endOfLine) - ) - - // number of interfaces is number of lines less one for the header - numberInterfaces := len(lines) - 1 - - interfaces := make([]netstatInterface, numberInterfaces) - // no output beside header - if numberInterfaces == 0 { - return interfaces, nil - } - - for index := 0; index < numberInterfaces; index++ { - nsIface := netstatInterface{} - if nsIface.stat, nsIface.linkID, err = parseNetstatLine(lines[index+1]); err != nil { - return nil, err - } - interfaces[index] = nsIface - } - return interfaces, nil -} - -// map that hold the name of a network interface and the number of usage -type mapInterfaceNameUsage map[string]uint - -func newMapInterfaceNameUsage(ifaces []netstatInterface) mapInterfaceNameUsage { - output := make(mapInterfaceNameUsage) - for index := range ifaces { - if ifaces[index].linkID != nil { - ifaceName := ifaces[index].stat.Name - usage, ok := output[ifaceName] - if ok { - output[ifaceName] = usage + 1 - } else { - output[ifaceName] = 1 - } - } - } - return output -} - -func (min mapInterfaceNameUsage) isTruncated() bool { - for _, usage := range min { - if usage > 1 { - return true - } - } - return false -} - -func (min mapInterfaceNameUsage) notTruncated() []string { - output := make([]string, 0) - for ifaceName, usage := range min { - if usage == 1 { - output = append(output, ifaceName) - } - } - return output -} - -// example of `netstat -ibdnW` output on yosemite -// Name Mtu Network Address Ipkts Ierrs Ibytes Opkts Oerrs Obytes Coll Drop -// lo0 16384 869107 0 169411755 869107 0 169411755 0 0 -// lo0 16384 ::1/128 ::1 869107 - 169411755 869107 - 169411755 - - -// lo0 16384 127 127.0.0.1 869107 - 169411755 869107 - 169411755 - - -func IOCounters(pernic bool) ([]IOCountersStat, error) { - return IOCountersWithContext(context.Background(), pernic) -} - -func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { - var ( - ret []IOCountersStat - retIndex int - ) - - netstat, err := exec.LookPath("netstat") - if err != nil { - return nil, err - } - - // try to get all interface metrics, and hope there won't be any truncated - out, err := invoke.CommandWithContext(ctx, netstat, "-ibdnW") - if err != nil { - return nil, err - } - - nsInterfaces, err := parseNetstatOutput(string(out)) - if err != nil { - return nil, err - } - - ifaceUsage := newMapInterfaceNameUsage(nsInterfaces) - notTruncated := ifaceUsage.notTruncated() - ret = make([]IOCountersStat, len(notTruncated)) - - if !ifaceUsage.isTruncated() { - // no truncated interface name, return stats of all interface with - for index := range nsInterfaces { - if nsInterfaces[index].linkID != nil { - ret[retIndex] = *nsInterfaces[index].stat - retIndex++ - } - } - } else { - // duplicated interface, list all interfaces - ifconfig, err := exec.LookPath("ifconfig") - if err != nil { - return nil, err - } - if out, err = invoke.CommandWithContext(ctx, ifconfig, "-l"); err != nil { - return nil, err - } - interfaceNames := strings.Fields(strings.TrimRight(string(out), endOfLine)) - - // for each of the interface name, run netstat if we don't have any stats yet - for _, interfaceName := range interfaceNames { - truncated := true - for index := range nsInterfaces { - if nsInterfaces[index].linkID != nil && nsInterfaces[index].stat.Name == interfaceName { - // handle the non truncated name to avoid execute netstat for them again - ret[retIndex] = *nsInterfaces[index].stat - retIndex++ - truncated = false - break - } - } - if truncated { - // run netstat with -I$ifacename - if out, err = invoke.CommandWithContext(ctx, netstat, "-ibdnWI"+interfaceName); err != nil { - return nil, err - } - parsedIfaces, err := parseNetstatOutput(string(out)) - if err != nil { - return nil, err - } - if len(parsedIfaces) == 0 { - // interface had been removed since `ifconfig -l` had been executed - continue - } - for index := range parsedIfaces { - if parsedIfaces[index].linkID != nil { - ret = append(ret, *parsedIfaces[index].stat) - break - } - } - } - } - } - - if pernic == false { - return getIOCountersAll(ret) - } - return ret, nil -} - -// NetIOCountersByFile is an method which is added just a compatibility for linux. -func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { - return IOCountersByFileWithContext(context.Background(), pernic, filename) -} - -func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename string) ([]IOCountersStat, error) { - return IOCounters(pernic) -} - -func FilterCounters() ([]FilterStat, error) { - return FilterCountersWithContext(context.Background()) -} - -func FilterCountersWithContext(ctx context.Context) ([]FilterStat, error) { - return nil, common.ErrNotImplementedError -} - -func ConntrackStats(percpu bool) ([]ConntrackStat, error) { - return ConntrackStatsWithContext(context.Background(), percpu) -} - -func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackStat, error) { - return nil, common.ErrNotImplementedError -} - -// NetProtoCounters returns network statistics for the entire system -// If protocols is empty then all protocols are returned, otherwise -// just the protocols in the list are returned. -// Not Implemented for Darwin -func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) { - return ProtoCountersWithContext(context.Background(), protocols) -} - -func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoCountersStat, error) { - return nil, common.ErrNotImplementedError -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/net/net_fallback.go b/test/integration/vendor/github.com/shirou/gopsutil/net/net_fallback.go deleted file mode 100644 index 7d9a26591..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/net/net_fallback.go +++ /dev/null @@ -1,92 +0,0 @@ -// +build !aix,!darwin,!linux,!freebsd,!openbsd,!windows - -package net - -import ( - "context" - - "github.com/shirou/gopsutil/internal/common" -) - -func IOCounters(pernic bool) ([]IOCountersStat, error) { - return IOCountersWithContext(context.Background(), pernic) -} - -func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { - return []IOCountersStat{}, common.ErrNotImplementedError -} - -func FilterCounters() ([]FilterStat, error) { - return FilterCountersWithContext(context.Background()) -} - -func FilterCountersWithContext(ctx context.Context) ([]FilterStat, error) { - return []FilterStat{}, common.ErrNotImplementedError -} - -func ConntrackStats(percpu bool) ([]ConntrackStat, error) { - return ConntrackStatsWithContext(context.Background(), percpu) -} - -func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackStat, error) { - return nil, common.ErrNotImplementedError -} - -func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) { - return ProtoCountersWithContext(context.Background(), protocols) -} - -func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoCountersStat, error) { - return []ProtoCountersStat{}, common.ErrNotImplementedError -} - -func Connections(kind string) ([]ConnectionStat, error) { - return ConnectionsWithContext(context.Background(), kind) -} - -func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return []ConnectionStat{}, common.ErrNotImplementedError -} - -func ConnectionsMax(kind string, max int) ([]ConnectionStat, error) { - return ConnectionsMaxWithContext(context.Background(), kind, max) -} - -func ConnectionsMaxWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return []ConnectionStat{}, common.ErrNotImplementedError -} - -// Return a list of network connections opened, omitting `Uids`. -// WithoutUids functions are reliant on implementation details. They may be altered to be an alias for Connections or be -// removed from the API in the future. -func ConnectionsWithoutUids(kind string) ([]ConnectionStat, error) { - return ConnectionsWithoutUidsWithContext(context.Background(), kind) -} - -func ConnectionsWithoutUidsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return ConnectionsMaxWithoutUidsWithContext(ctx, kind, 0) -} - -func ConnectionsMaxWithoutUidsWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(ctx, kind, 0, max) -} - -func ConnectionsPidWithoutUids(kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidWithoutUidsWithContext(context.Background(), kind, pid) -} - -func ConnectionsPidWithoutUidsWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, 0) -} - -func ConnectionsPidMaxWithoutUids(kind string, pid int32, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(context.Background(), kind, pid, max) -} - -func ConnectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return connectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, max) -} - -func connectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return []ConnectionStat{}, common.ErrNotImplementedError -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/net/net_freebsd.go b/test/integration/vendor/github.com/shirou/gopsutil/net/net_freebsd.go deleted file mode 100644 index 1204f5977..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/net/net_freebsd.go +++ /dev/null @@ -1,132 +0,0 @@ -// +build freebsd - -package net - -import ( - "context" - "os/exec" - "strconv" - "strings" - - "github.com/shirou/gopsutil/internal/common" -) - -func IOCounters(pernic bool) ([]IOCountersStat, error) { - return IOCountersWithContext(context.Background(), pernic) -} - -func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { - netstat, err := exec.LookPath("netstat") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, netstat, "-ibdnW") - if err != nil { - return nil, err - } - - lines := strings.Split(string(out), "\n") - ret := make([]IOCountersStat, 0, len(lines)-1) - exists := make([]string, 0, len(ret)) - - for _, line := range lines { - values := strings.Fields(line) - if len(values) < 1 || values[0] == "Name" { - continue - } - if common.StringsHas(exists, values[0]) { - // skip if already get - continue - } - exists = append(exists, values[0]) - - if len(values) < 12 { - continue - } - base := 1 - // sometimes Address is omitted - if len(values) < 13 { - base = 0 - } - - parsed := make([]uint64, 0, 8) - vv := []string{ - values[base+3], // PacketsRecv - values[base+4], // Errin - values[base+5], // Dropin - values[base+6], // BytesRecvn - values[base+7], // PacketSent - values[base+8], // Errout - values[base+9], // BytesSent - values[base+11], // Dropout - } - for _, target := range vv { - if target == "-" { - parsed = append(parsed, 0) - continue - } - - t, err := strconv.ParseUint(target, 10, 64) - if err != nil { - return nil, err - } - parsed = append(parsed, t) - } - - n := IOCountersStat{ - Name: values[0], - PacketsRecv: parsed[0], - Errin: parsed[1], - Dropin: parsed[2], - BytesRecv: parsed[3], - PacketsSent: parsed[4], - Errout: parsed[5], - BytesSent: parsed[6], - Dropout: parsed[7], - } - ret = append(ret, n) - } - - if pernic == false { - return getIOCountersAll(ret) - } - - return ret, nil -} - -// NetIOCountersByFile is an method which is added just a compatibility for linux. -func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { - return IOCountersByFileWithContext(context.Background(), pernic, filename) -} - -func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename string) ([]IOCountersStat, error) { - return IOCounters(pernic) -} - -func FilterCounters() ([]FilterStat, error) { - return FilterCountersWithContext(context.Background()) -} - -func FilterCountersWithContext(ctx context.Context) ([]FilterStat, error) { - return nil, common.ErrNotImplementedError -} - -func ConntrackStats(percpu bool) ([]ConntrackStat, error) { - return ConntrackStatsWithContext(context.Background(), percpu) -} - -func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackStat, error) { - return nil, common.ErrNotImplementedError -} - -// NetProtoCounters returns network statistics for the entire system -// If protocols is empty then all protocols are returned, otherwise -// just the protocols in the list are returned. -// Not Implemented for FreeBSD -func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) { - return ProtoCountersWithContext(context.Background(), protocols) -} - -func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoCountersStat, error) { - return nil, common.ErrNotImplementedError -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/net/net_linux.go b/test/integration/vendor/github.com/shirou/gopsutil/net/net_linux.go deleted file mode 100644 index ed5d027b8..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/net/net_linux.go +++ /dev/null @@ -1,884 +0,0 @@ -// +build linux - -package net - -import ( - "bytes" - "context" - "encoding/hex" - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "os" - "strconv" - "strings" - "syscall" - - "github.com/shirou/gopsutil/internal/common" -) - -const ( // Conntrack Column numbers - CT_ENTRIES = iota - CT_SEARCHED - CT_FOUND - CT_NEW - CT_INVALID - CT_IGNORE - CT_DELETE - CT_DELETE_LIST - CT_INSERT - CT_INSERT_FAILED - CT_DROP - CT_EARLY_DROP - CT_ICMP_ERROR - CT_EXPECT_NEW - CT_EXPECT_CREATE - CT_EXPECT_DELETE - CT_SEARCH_RESTART -) - -// NetIOCounters returnes network I/O statistics for every network -// interface installed on the system. If pernic argument is false, -// return only sum of all information (which name is 'all'). If true, -// every network interface installed on the system is returned -// separately. -func IOCounters(pernic bool) ([]IOCountersStat, error) { - return IOCountersWithContext(context.Background(), pernic) -} - -func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { - filename := common.HostProc("net/dev") - return IOCountersByFileWithContext(ctx, pernic, filename) -} - -func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { - return IOCountersByFileWithContext(context.Background(), pernic, filename) -} - -func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename string) ([]IOCountersStat, error) { - lines, err := common.ReadLines(filename) - if err != nil { - return nil, err - } - - parts := make([]string, 2) - - statlen := len(lines) - 1 - - ret := make([]IOCountersStat, 0, statlen) - - for _, line := range lines[2:] { - separatorPos := strings.LastIndex(line, ":") - if separatorPos == -1 { - continue - } - parts[0] = line[0:separatorPos] - parts[1] = line[separatorPos+1:] - - interfaceName := strings.TrimSpace(parts[0]) - if interfaceName == "" { - continue - } - - fields := strings.Fields(strings.TrimSpace(parts[1])) - bytesRecv, err := strconv.ParseUint(fields[0], 10, 64) - if err != nil { - return ret, err - } - packetsRecv, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { - return ret, err - } - errIn, err := strconv.ParseUint(fields[2], 10, 64) - if err != nil { - return ret, err - } - dropIn, err := strconv.ParseUint(fields[3], 10, 64) - if err != nil { - return ret, err - } - fifoIn, err := strconv.ParseUint(fields[4], 10, 64) - if err != nil { - return ret, err - } - bytesSent, err := strconv.ParseUint(fields[8], 10, 64) - if err != nil { - return ret, err - } - packetsSent, err := strconv.ParseUint(fields[9], 10, 64) - if err != nil { - return ret, err - } - errOut, err := strconv.ParseUint(fields[10], 10, 64) - if err != nil { - return ret, err - } - dropOut, err := strconv.ParseUint(fields[11], 10, 64) - if err != nil { - return ret, err - } - fifoOut, err := strconv.ParseUint(fields[12], 10, 64) - if err != nil { - return ret, err - } - - nic := IOCountersStat{ - Name: interfaceName, - BytesRecv: bytesRecv, - PacketsRecv: packetsRecv, - Errin: errIn, - Dropin: dropIn, - Fifoin: fifoIn, - BytesSent: bytesSent, - PacketsSent: packetsSent, - Errout: errOut, - Dropout: dropOut, - Fifoout: fifoOut, - } - ret = append(ret, nic) - } - - if pernic == false { - return getIOCountersAll(ret) - } - - return ret, nil -} - -var netProtocols = []string{ - "ip", - "icmp", - "icmpmsg", - "tcp", - "udp", - "udplite", -} - -// NetProtoCounters returns network statistics for the entire system -// If protocols is empty then all protocols are returned, otherwise -// just the protocols in the list are returned. -// Available protocols: -// ip,icmp,icmpmsg,tcp,udp,udplite -func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) { - return ProtoCountersWithContext(context.Background(), protocols) -} - -func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoCountersStat, error) { - if len(protocols) == 0 { - protocols = netProtocols - } - - stats := make([]ProtoCountersStat, 0, len(protocols)) - protos := make(map[string]bool, len(protocols)) - for _, p := range protocols { - protos[p] = true - } - - filename := common.HostProc("net/snmp") - lines, err := common.ReadLines(filename) - if err != nil { - return nil, err - } - - linecount := len(lines) - for i := 0; i < linecount; i++ { - line := lines[i] - r := strings.IndexRune(line, ':') - if r == -1 { - return nil, errors.New(filename + " is not fomatted correctly, expected ':'.") - } - proto := strings.ToLower(line[:r]) - if !protos[proto] { - // skip protocol and data line - i++ - continue - } - - // Read header line - statNames := strings.Split(line[r+2:], " ") - - // Read data line - i++ - statValues := strings.Split(lines[i][r+2:], " ") - if len(statNames) != len(statValues) { - return nil, errors.New(filename + " is not fomatted correctly, expected same number of columns.") - } - stat := ProtoCountersStat{ - Protocol: proto, - Stats: make(map[string]int64, len(statNames)), - } - for j := range statNames { - value, err := strconv.ParseInt(statValues[j], 10, 64) - if err != nil { - return nil, err - } - stat.Stats[statNames[j]] = value - } - stats = append(stats, stat) - } - return stats, nil -} - -// NetFilterCounters returns iptables conntrack statistics -// the currently in use conntrack count and the max. -// If the file does not exist or is invalid it will return nil. -func FilterCounters() ([]FilterStat, error) { - return FilterCountersWithContext(context.Background()) -} - -func FilterCountersWithContext(ctx context.Context) ([]FilterStat, error) { - countfile := common.HostProc("sys/net/netfilter/nf_conntrack_count") - maxfile := common.HostProc("sys/net/netfilter/nf_conntrack_max") - - count, err := common.ReadInts(countfile) - - if err != nil { - return nil, err - } - stats := make([]FilterStat, 0, 1) - - max, err := common.ReadInts(maxfile) - if err != nil { - return nil, err - } - - payload := FilterStat{ - ConnTrackCount: count[0], - ConnTrackMax: max[0], - } - - stats = append(stats, payload) - return stats, nil -} - -// ConntrackStats returns more detailed info about the conntrack table -func ConntrackStats(percpu bool) ([]ConntrackStat, error) { - return ConntrackStatsWithContext(context.Background(), percpu) -} - -// ConntrackStatsWithContext returns more detailed info about the conntrack table -func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackStat, error) { - return conntrackStatsFromFile(common.HostProc("net/stat/nf_conntrack"), percpu) -} - -// conntrackStatsFromFile returns more detailed info about the conntrack table -// from `filename` -// If 'percpu' is false, the result will contain exactly one item with totals/summary -func conntrackStatsFromFile(filename string, percpu bool) ([]ConntrackStat, error) { - lines, err := common.ReadLines(filename) - if err != nil { - return nil, err - } - - statlist := NewConntrackStatList() - - for _, line := range lines { - fields := strings.Fields(line) - if len(fields) == 17 && fields[0] != "entries" { - statlist.Append(NewConntrackStat( - common.HexToUint32(fields[CT_ENTRIES]), - common.HexToUint32(fields[CT_SEARCHED]), - common.HexToUint32(fields[CT_FOUND]), - common.HexToUint32(fields[CT_NEW]), - common.HexToUint32(fields[CT_INVALID]), - common.HexToUint32(fields[CT_IGNORE]), - common.HexToUint32(fields[CT_DELETE]), - common.HexToUint32(fields[CT_DELETE_LIST]), - common.HexToUint32(fields[CT_INSERT]), - common.HexToUint32(fields[CT_INSERT_FAILED]), - common.HexToUint32(fields[CT_DROP]), - common.HexToUint32(fields[CT_EARLY_DROP]), - common.HexToUint32(fields[CT_ICMP_ERROR]), - common.HexToUint32(fields[CT_EXPECT_NEW]), - common.HexToUint32(fields[CT_EXPECT_CREATE]), - common.HexToUint32(fields[CT_EXPECT_DELETE]), - common.HexToUint32(fields[CT_SEARCH_RESTART]), - )) - } - } - - if percpu { - return statlist.Items(), nil - } - return statlist.Summary(), nil -} - -// http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h -var TCPStatuses = map[string]string{ - "01": "ESTABLISHED", - "02": "SYN_SENT", - "03": "SYN_RECV", - "04": "FIN_WAIT1", - "05": "FIN_WAIT2", - "06": "TIME_WAIT", - "07": "CLOSE", - "08": "CLOSE_WAIT", - "09": "LAST_ACK", - "0A": "LISTEN", - "0B": "CLOSING", -} - -type netConnectionKindType struct { - family uint32 - sockType uint32 - filename string -} - -var kindTCP4 = netConnectionKindType{ - family: syscall.AF_INET, - sockType: syscall.SOCK_STREAM, - filename: "tcp", -} -var kindTCP6 = netConnectionKindType{ - family: syscall.AF_INET6, - sockType: syscall.SOCK_STREAM, - filename: "tcp6", -} -var kindUDP4 = netConnectionKindType{ - family: syscall.AF_INET, - sockType: syscall.SOCK_DGRAM, - filename: "udp", -} -var kindUDP6 = netConnectionKindType{ - family: syscall.AF_INET6, - sockType: syscall.SOCK_DGRAM, - filename: "udp6", -} -var kindUNIX = netConnectionKindType{ - family: syscall.AF_UNIX, - filename: "unix", -} - -var netConnectionKindMap = map[string][]netConnectionKindType{ - "all": {kindTCP4, kindTCP6, kindUDP4, kindUDP6, kindUNIX}, - "tcp": {kindTCP4, kindTCP6}, - "tcp4": {kindTCP4}, - "tcp6": {kindTCP6}, - "udp": {kindUDP4, kindUDP6}, - "udp4": {kindUDP4}, - "udp6": {kindUDP6}, - "unix": {kindUNIX}, - "inet": {kindTCP4, kindTCP6, kindUDP4, kindUDP6}, - "inet4": {kindTCP4, kindUDP4}, - "inet6": {kindTCP6, kindUDP6}, -} - -type inodeMap struct { - pid int32 - fd uint32 -} - -type connTmp struct { - fd uint32 - family uint32 - sockType uint32 - laddr Addr - raddr Addr - status string - pid int32 - boundPid int32 - path string -} - -// Return a list of network connections opened. -func Connections(kind string) ([]ConnectionStat, error) { - return ConnectionsWithContext(context.Background(), kind) -} - -func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return ConnectionsPid(kind, 0) -} - -// Return a list of network connections opened returning at most `max` -// connections for each running process. -func ConnectionsMax(kind string, max int) ([]ConnectionStat, error) { - return ConnectionsMaxWithContext(context.Background(), kind, max) -} - -func ConnectionsMaxWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return ConnectionsPidMax(kind, 0, max) -} - -// Return a list of network connections opened, omitting `Uids`. -// WithoutUids functions are reliant on implementation details. They may be altered to be an alias for Connections or be -// removed from the API in the future. -func ConnectionsWithoutUids(kind string) ([]ConnectionStat, error) { - return ConnectionsWithoutUidsWithContext(context.Background(), kind) -} - -func ConnectionsWithoutUidsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return ConnectionsMaxWithoutUidsWithContext(ctx, kind, 0) -} - -func ConnectionsMaxWithoutUidsWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(ctx, kind, 0, max) -} - -// Return a list of network connections opened by a process. -func ConnectionsPid(kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidWithContext(context.Background(), kind, pid) -} - -func ConnectionsPidWithoutUids(kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidWithoutUidsWithContext(context.Background(), kind, pid) -} - -func ConnectionsPidWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithContext(ctx, kind, pid, 0) -} - -func ConnectionsPidWithoutUidsWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, 0) -} - -// Return up to `max` network connections opened by a process. -func ConnectionsPidMax(kind string, pid int32, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithContext(context.Background(), kind, pid, max) -} - -func ConnectionsPidMaxWithoutUids(kind string, pid int32, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(context.Background(), kind, pid, max) -} - -func ConnectionsPidMaxWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return connectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, max, false) -} - -func ConnectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return connectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, max, true) -} - -func connectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, max int, skipUids bool) ([]ConnectionStat, error) { - tmap, ok := netConnectionKindMap[kind] - if !ok { - return nil, fmt.Errorf("invalid kind, %s", kind) - } - root := common.HostProc() - var err error - var inodes map[string][]inodeMap - if pid == 0 { - inodes, err = getProcInodesAll(root, max) - } else { - inodes, err = getProcInodes(root, pid, max) - if len(inodes) == 0 { - // no connection for the pid - return []ConnectionStat{}, nil - } - } - if err != nil { - return nil, fmt.Errorf("cound not get pid(s), %d: %s", pid, err) - } - return statsFromInodes(root, pid, tmap, inodes, skipUids) -} - -func statsFromInodes(root string, pid int32, tmap []netConnectionKindType, inodes map[string][]inodeMap, skipUids bool) ([]ConnectionStat, error) { - dupCheckMap := make(map[string]struct{}) - var ret []ConnectionStat - - var err error - for _, t := range tmap { - var path string - var connKey string - var ls []connTmp - if pid == 0 { - path = fmt.Sprintf("%s/net/%s", root, t.filename) - } else { - path = fmt.Sprintf("%s/%d/net/%s", root, pid, t.filename) - } - switch t.family { - case syscall.AF_INET, syscall.AF_INET6: - ls, err = processInet(path, t, inodes, pid) - case syscall.AF_UNIX: - ls, err = processUnix(path, t, inodes, pid) - } - if err != nil { - return nil, err - } - for _, c := range ls { - // Build TCP key to id the connection uniquely - // socket type, src ip, src port, dst ip, dst port and state should be enough - // to prevent duplications. - connKey = fmt.Sprintf("%d-%s:%d-%s:%d-%s", c.sockType, c.laddr.IP, c.laddr.Port, c.raddr.IP, c.raddr.Port, c.status) - if _, ok := dupCheckMap[connKey]; ok { - continue - } - - conn := ConnectionStat{ - Fd: c.fd, - Family: c.family, - Type: c.sockType, - Laddr: c.laddr, - Raddr: c.raddr, - Status: c.status, - Pid: c.pid, - } - if c.pid == 0 { - conn.Pid = c.boundPid - } else { - conn.Pid = c.pid - } - - if !skipUids { - // fetch process owner Real, effective, saved set, and filesystem UIDs - proc := process{Pid: conn.Pid} - conn.Uids, _ = proc.getUids() - } - - ret = append(ret, conn) - dupCheckMap[connKey] = struct{}{} - } - - } - - return ret, nil -} - -// getProcInodes returnes fd of the pid. -func getProcInodes(root string, pid int32, max int) (map[string][]inodeMap, error) { - ret := make(map[string][]inodeMap) - - dir := fmt.Sprintf("%s/%d/fd", root, pid) - f, err := os.Open(dir) - if err != nil { - return ret, err - } - defer f.Close() - files, err := f.Readdir(max) - if err != nil { - return ret, err - } - for _, fd := range files { - inodePath := fmt.Sprintf("%s/%d/fd/%s", root, pid, fd.Name()) - - inode, err := os.Readlink(inodePath) - if err != nil { - continue - } - if !strings.HasPrefix(inode, "socket:[") { - continue - } - // the process is using a socket - l := len(inode) - inode = inode[8 : l-1] - _, ok := ret[inode] - if !ok { - ret[inode] = make([]inodeMap, 0) - } - fd, err := strconv.Atoi(fd.Name()) - if err != nil { - continue - } - - i := inodeMap{ - pid: pid, - fd: uint32(fd), - } - ret[inode] = append(ret[inode], i) - } - return ret, nil -} - -// Pids retunres all pids. -// Note: this is a copy of process_linux.Pids() -// FIXME: Import process occures import cycle. -// move to common made other platform breaking. Need consider. -func Pids() ([]int32, error) { - return PidsWithContext(context.Background()) -} - -func PidsWithContext(ctx context.Context) ([]int32, error) { - var ret []int32 - - d, err := os.Open(common.HostProc()) - if err != nil { - return nil, err - } - defer d.Close() - - fnames, err := d.Readdirnames(-1) - if err != nil { - return nil, err - } - for _, fname := range fnames { - pid, err := strconv.ParseInt(fname, 10, 32) - if err != nil { - // if not numeric name, just skip - continue - } - ret = append(ret, int32(pid)) - } - - return ret, nil -} - -// Note: the following is based off process_linux structs and methods -// we need these to fetch the owner of a process ID -// FIXME: Import process occures import cycle. -// see remarks on pids() -type process struct { - Pid int32 `json:"pid"` - uids []int32 -} - -// Uids returns user ids of the process as a slice of the int -func (p *process) getUids() ([]int32, error) { - err := p.fillFromStatus() - if err != nil { - return []int32{}, err - } - return p.uids, nil -} - -// Get status from /proc/(pid)/status -func (p *process) fillFromStatus() error { - pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "status") - contents, err := ioutil.ReadFile(statPath) - if err != nil { - return err - } - lines := strings.Split(string(contents), "\n") - for _, line := range lines { - tabParts := strings.SplitN(line, "\t", 2) - if len(tabParts) < 2 { - continue - } - value := tabParts[1] - switch strings.TrimRight(tabParts[0], ":") { - case "Uid": - p.uids = make([]int32, 0, 4) - for _, i := range strings.Split(value, "\t") { - v, err := strconv.ParseInt(i, 10, 32) - if err != nil { - return err - } - p.uids = append(p.uids, int32(v)) - } - } - } - return nil -} - -func getProcInodesAll(root string, max int) (map[string][]inodeMap, error) { - pids, err := Pids() - if err != nil { - return nil, err - } - ret := make(map[string][]inodeMap) - - for _, pid := range pids { - t, err := getProcInodes(root, pid, max) - if err != nil { - // skip if permission error or no longer exists - if os.IsPermission(err) || os.IsNotExist(err) || err == io.EOF { - continue - } - return ret, err - } - if len(t) == 0 { - continue - } - // TODO: update ret. - ret = updateMap(ret, t) - } - return ret, nil -} - -// decodeAddress decode addresse represents addr in proc/net/* -// ex: -// "0500000A:0016" -> "10.0.0.5", 22 -// "0085002452100113070057A13F025401:0035" -> "2400:8500:1301:1052:a157:7:154:23f", 53 -func decodeAddress(family uint32, src string) (Addr, error) { - t := strings.Split(src, ":") - if len(t) != 2 { - return Addr{}, fmt.Errorf("does not contain port, %s", src) - } - addr := t[0] - port, err := strconv.ParseUint(t[1], 16, 16) - if err != nil { - return Addr{}, fmt.Errorf("invalid port, %s", src) - } - decoded, err := hex.DecodeString(addr) - if err != nil { - return Addr{}, fmt.Errorf("decode error, %s", err) - } - var ip net.IP - // Assumes this is little_endian - if family == syscall.AF_INET { - ip = net.IP(Reverse(decoded)) - } else { // IPv6 - ip, err = parseIPv6HexString(decoded) - if err != nil { - return Addr{}, err - } - } - return Addr{ - IP: ip.String(), - Port: uint32(port), - }, nil -} - -// Reverse reverses array of bytes. -func Reverse(s []byte) []byte { - return ReverseWithContext(context.Background(), s) -} - -func ReverseWithContext(ctx context.Context, s []byte) []byte { - for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { - s[i], s[j] = s[j], s[i] - } - return s -} - -// parseIPv6HexString parse array of bytes to IPv6 string -func parseIPv6HexString(src []byte) (net.IP, error) { - if len(src) != 16 { - return nil, fmt.Errorf("invalid IPv6 string") - } - - buf := make([]byte, 0, 16) - for i := 0; i < len(src); i += 4 { - r := Reverse(src[i : i+4]) - buf = append(buf, r...) - } - return net.IP(buf), nil -} - -func processInet(file string, kind netConnectionKindType, inodes map[string][]inodeMap, filterPid int32) ([]connTmp, error) { - - if strings.HasSuffix(file, "6") && !common.PathExists(file) { - // IPv6 not supported, return empty. - return []connTmp{}, nil - } - - // Read the contents of the /proc file with a single read sys call. - // This minimizes duplicates in the returned connections - // For more info: - // https://github.com/shirou/gopsutil/pull/361 - contents, err := ioutil.ReadFile(file) - if err != nil { - return nil, err - } - - lines := bytes.Split(contents, []byte("\n")) - - var ret []connTmp - // skip first line - for _, line := range lines[1:] { - l := strings.Fields(string(line)) - if len(l) < 10 { - continue - } - laddr := l[1] - raddr := l[2] - status := l[3] - inode := l[9] - pid := int32(0) - fd := uint32(0) - i, exists := inodes[inode] - if exists { - pid = i[0].pid - fd = i[0].fd - } - if filterPid > 0 && filterPid != pid { - continue - } - if kind.sockType == syscall.SOCK_STREAM { - status = TCPStatuses[status] - } else { - status = "NONE" - } - la, err := decodeAddress(kind.family, laddr) - if err != nil { - continue - } - ra, err := decodeAddress(kind.family, raddr) - if err != nil { - continue - } - - ret = append(ret, connTmp{ - fd: fd, - family: kind.family, - sockType: kind.sockType, - laddr: la, - raddr: ra, - status: status, - pid: pid, - }) - } - - return ret, nil -} - -func processUnix(file string, kind netConnectionKindType, inodes map[string][]inodeMap, filterPid int32) ([]connTmp, error) { - // Read the contents of the /proc file with a single read sys call. - // This minimizes duplicates in the returned connections - // For more info: - // https://github.com/shirou/gopsutil/pull/361 - contents, err := ioutil.ReadFile(file) - if err != nil { - return nil, err - } - - lines := bytes.Split(contents, []byte("\n")) - - var ret []connTmp - // skip first line - for _, line := range lines[1:] { - tokens := strings.Fields(string(line)) - if len(tokens) < 6 { - continue - } - st, err := strconv.Atoi(tokens[4]) - if err != nil { - return nil, err - } - - inode := tokens[6] - - var pairs []inodeMap - pairs, exists := inodes[inode] - if !exists { - pairs = []inodeMap{ - {}, - } - } - for _, pair := range pairs { - if filterPid > 0 && filterPid != pair.pid { - continue - } - var path string - if len(tokens) == 8 { - path = tokens[len(tokens)-1] - } - ret = append(ret, connTmp{ - fd: pair.fd, - family: kind.family, - sockType: uint32(st), - laddr: Addr{ - IP: path, - }, - pid: pair.pid, - status: "NONE", - path: path, - }) - } - } - - return ret, nil -} - -func updateMap(src map[string][]inodeMap, add map[string][]inodeMap) map[string][]inodeMap { - for key, value := range add { - a, exists := src[key] - if !exists { - src[key] = value - continue - } - src[key] = append(a, value...) - } - return src -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/net/net_openbsd.go b/test/integration/vendor/github.com/shirou/gopsutil/net/net_openbsd.go deleted file mode 100644 index cfed2bee4..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/net/net_openbsd.go +++ /dev/null @@ -1,319 +0,0 @@ -// +build openbsd - -package net - -import ( - "context" - "fmt" - "os/exec" - "regexp" - "strconv" - "strings" - "syscall" - - "github.com/shirou/gopsutil/internal/common" -) - -var portMatch = regexp.MustCompile(`(.*)\.(\d+)$`) - -func ParseNetstat(output string, mode string, - iocs map[string]IOCountersStat) error { - lines := strings.Split(output, "\n") - - exists := make([]string, 0, len(lines)-1) - - columns := 6 - if mode == "ind" { - columns = 10 - } - for _, line := range lines { - values := strings.Fields(line) - if len(values) < 1 || values[0] == "Name" { - continue - } - if common.StringsHas(exists, values[0]) { - // skip if already get - continue - } - - if len(values) < columns { - continue - } - base := 1 - // sometimes Address is omitted - if len(values) < columns { - base = 0 - } - - parsed := make([]uint64, 0, 8) - var vv []string - if mode == "inb" { - vv = []string{ - values[base+3], // BytesRecv - values[base+4], // BytesSent - } - } else { - vv = []string{ - values[base+3], // Ipkts - values[base+4], // Ierrs - values[base+5], // Opkts - values[base+6], // Oerrs - values[base+8], // Drops - } - } - for _, target := range vv { - if target == "-" { - parsed = append(parsed, 0) - continue - } - - t, err := strconv.ParseUint(target, 10, 64) - if err != nil { - return err - } - parsed = append(parsed, t) - } - exists = append(exists, values[0]) - - n, present := iocs[values[0]] - if !present { - n = IOCountersStat{Name: values[0]} - } - if mode == "inb" { - n.BytesRecv = parsed[0] - n.BytesSent = parsed[1] - } else { - n.PacketsRecv = parsed[0] - n.Errin = parsed[1] - n.PacketsSent = parsed[2] - n.Errout = parsed[3] - n.Dropin = parsed[4] - n.Dropout = parsed[4] - } - - iocs[n.Name] = n - } - return nil -} - -func IOCounters(pernic bool) ([]IOCountersStat, error) { - return IOCountersWithContext(context.Background(), pernic) -} - -func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { - netstat, err := exec.LookPath("netstat") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, netstat, "-inb") - if err != nil { - return nil, err - } - out2, err := invoke.CommandWithContext(ctx, netstat, "-ind") - if err != nil { - return nil, err - } - iocs := make(map[string]IOCountersStat) - - lines := strings.Split(string(out), "\n") - ret := make([]IOCountersStat, 0, len(lines)-1) - - err = ParseNetstat(string(out), "inb", iocs) - if err != nil { - return nil, err - } - err = ParseNetstat(string(out2), "ind", iocs) - if err != nil { - return nil, err - } - - for _, ioc := range iocs { - ret = append(ret, ioc) - } - - if pernic == false { - return getIOCountersAll(ret) - } - - return ret, nil -} - -// NetIOCountersByFile is an method which is added just a compatibility for linux. -func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { - return IOCountersByFileWithContext(context.Background(), pernic, filename) -} - -func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename string) ([]IOCountersStat, error) { - return IOCounters(pernic) -} - -func FilterCounters() ([]FilterStat, error) { - return FilterCountersWithContext(context.Background()) -} - -func FilterCountersWithContext(ctx context.Context) ([]FilterStat, error) { - return nil, common.ErrNotImplementedError -} - -func ConntrackStats(percpu bool) ([]ConntrackStat, error) { - return ConntrackStatsWithContext(context.Background(), percpu) -} - -func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackStat, error) { - return nil, common.ErrNotImplementedError -} - -// NetProtoCounters returns network statistics for the entire system -// If protocols is empty then all protocols are returned, otherwise -// just the protocols in the list are returned. -// Not Implemented for OpenBSD -func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) { - return ProtoCountersWithContext(context.Background(), protocols) -} - -func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func parseNetstatLine(line string) (ConnectionStat, error) { - f := strings.Fields(line) - if len(f) < 5 { - return ConnectionStat{}, fmt.Errorf("wrong line,%s", line) - } - - var netType, netFamily uint32 - switch f[0] { - case "tcp": - netType = syscall.SOCK_STREAM - netFamily = syscall.AF_INET - case "udp": - netType = syscall.SOCK_DGRAM - netFamily = syscall.AF_INET - case "tcp6": - netType = syscall.SOCK_STREAM - netFamily = syscall.AF_INET6 - case "udp6": - netType = syscall.SOCK_DGRAM - netFamily = syscall.AF_INET6 - default: - return ConnectionStat{}, fmt.Errorf("unknown type, %s", f[0]) - } - - laddr, raddr, err := parseNetstatAddr(f[3], f[4], netFamily) - if err != nil { - return ConnectionStat{}, fmt.Errorf("failed to parse netaddr, %s %s", f[3], f[4]) - } - - n := ConnectionStat{ - Fd: uint32(0), // not supported - Family: uint32(netFamily), - Type: uint32(netType), - Laddr: laddr, - Raddr: raddr, - Pid: int32(0), // not supported - } - if len(f) == 6 { - n.Status = f[5] - } - - return n, nil -} - -func parseNetstatAddr(local string, remote string, family uint32) (laddr Addr, raddr Addr, err error) { - parse := func(l string) (Addr, error) { - matches := portMatch.FindStringSubmatch(l) - if matches == nil { - return Addr{}, fmt.Errorf("wrong addr, %s", l) - } - host := matches[1] - port := matches[2] - if host == "*" { - switch family { - case syscall.AF_INET: - host = "0.0.0.0" - case syscall.AF_INET6: - host = "::" - default: - return Addr{}, fmt.Errorf("unknown family, %d", family) - } - } - lport, err := strconv.Atoi(port) - if err != nil { - return Addr{}, err - } - return Addr{IP: host, Port: uint32(lport)}, nil - } - - laddr, err = parse(local) - if remote != "*.*" { // remote addr exists - raddr, err = parse(remote) - if err != nil { - return laddr, raddr, err - } - } - - return laddr, raddr, err -} - -// Return a list of network connections opened. -func Connections(kind string) ([]ConnectionStat, error) { - return ConnectionsWithContext(context.Background(), kind) -} - -func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - var ret []ConnectionStat - - args := []string{"-na"} - switch strings.ToLower(kind) { - default: - fallthrough - case "": - fallthrough - case "all": - fallthrough - case "inet": - // nothing to add - case "inet4": - args = append(args, "-finet") - case "inet6": - args = append(args, "-finet6") - case "tcp": - args = append(args, "-ptcp") - case "tcp4": - args = append(args, "-ptcp", "-finet") - case "tcp6": - args = append(args, "-ptcp", "-finet6") - case "udp": - args = append(args, "-pudp") - case "udp4": - args = append(args, "-pudp", "-finet") - case "udp6": - args = append(args, "-pudp", "-finet6") - case "unix": - return ret, common.ErrNotImplementedError - } - - netstat, err := exec.LookPath("netstat") - if err != nil { - return nil, err - } - out, err := invoke.CommandWithContext(ctx, netstat, args...) - - if err != nil { - return nil, err - } - lines := strings.Split(string(out), "\n") - for _, line := range lines { - if !(strings.HasPrefix(line, "tcp") || strings.HasPrefix(line, "udp")) { - continue - } - n, err := parseNetstatLine(line) - if err != nil { - continue - } - - ret = append(ret, n) - } - - return ret, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/net/net_unix.go b/test/integration/vendor/github.com/shirou/gopsutil/net/net_unix.go deleted file mode 100644 index abe25c4ed..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/net/net_unix.go +++ /dev/null @@ -1,224 +0,0 @@ -// +build freebsd darwin - -package net - -import ( - "context" - "fmt" - "net" - "strconv" - "strings" - "syscall" - - "github.com/shirou/gopsutil/internal/common" -) - -// Return a list of network connections opened. -func Connections(kind string) ([]ConnectionStat, error) { - return ConnectionsWithContext(context.Background(), kind) -} - -func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return ConnectionsPid(kind, 0) -} - -// Return a list of network connections opened returning at most `max` -// connections for each running process. -func ConnectionsMax(kind string, max int) ([]ConnectionStat, error) { - return ConnectionsMaxWithContext(context.Background(), kind, max) -} - -func ConnectionsMaxWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return []ConnectionStat{}, common.ErrNotImplementedError -} - -// Return a list of network connections opened by a process. -func ConnectionsPid(kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidWithContext(context.Background(), kind, pid) -} - -func ConnectionsPidWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error) { - var ret []ConnectionStat - - args := []string{"-i"} - switch strings.ToLower(kind) { - default: - fallthrough - case "": - fallthrough - case "all": - fallthrough - case "inet": - args = append(args, "tcp", "-i", "udp") - case "inet4": - args = append(args, "4") - case "inet6": - args = append(args, "6") - case "tcp": - args = append(args, "tcp") - case "tcp4": - args = append(args, "4tcp") - case "tcp6": - args = append(args, "6tcp") - case "udp": - args = append(args, "udp") - case "udp4": - args = append(args, "4udp") - case "udp6": - args = append(args, "6udp") - case "unix": - args = []string{"-U"} - } - - r, err := common.CallLsofWithContext(ctx, invoke, pid, args...) - if err != nil { - return nil, err - } - for _, rr := range r { - if strings.HasPrefix(rr, "COMMAND") { - continue - } - n, err := parseNetLine(rr) - if err != nil { - - continue - } - - ret = append(ret, n) - } - - return ret, nil -} - -var constMap = map[string]int{ - "unix": syscall.AF_UNIX, - "TCP": syscall.SOCK_STREAM, - "UDP": syscall.SOCK_DGRAM, - "IPv4": syscall.AF_INET, - "IPv6": syscall.AF_INET6, -} - -func parseNetLine(line string) (ConnectionStat, error) { - f := strings.Fields(line) - if len(f) < 8 { - return ConnectionStat{}, fmt.Errorf("wrong line,%s", line) - } - - if len(f) == 8 { - f = append(f, f[7]) - f[7] = "unix" - } - - pid, err := strconv.Atoi(f[1]) - if err != nil { - return ConnectionStat{}, err - } - fd, err := strconv.Atoi(strings.Trim(f[3], "u")) - if err != nil { - return ConnectionStat{}, fmt.Errorf("unknown fd, %s", f[3]) - } - netFamily, ok := constMap[f[4]] - if !ok { - return ConnectionStat{}, fmt.Errorf("unknown family, %s", f[4]) - } - netType, ok := constMap[f[7]] - if !ok { - return ConnectionStat{}, fmt.Errorf("unknown type, %s", f[7]) - } - - var laddr, raddr Addr - if f[7] == "unix" { - laddr.IP = f[8] - } else { - laddr, raddr, err = parseNetAddr(f[8]) - if err != nil { - return ConnectionStat{}, fmt.Errorf("failed to parse netaddr, %s", f[8]) - } - } - - n := ConnectionStat{ - Fd: uint32(fd), - Family: uint32(netFamily), - Type: uint32(netType), - Laddr: laddr, - Raddr: raddr, - Pid: int32(pid), - } - if len(f) == 10 { - n.Status = strings.Trim(f[9], "()") - } - - return n, nil -} - -func parseNetAddr(line string) (laddr Addr, raddr Addr, err error) { - parse := func(l string) (Addr, error) { - host, port, err := net.SplitHostPort(l) - if err != nil { - return Addr{}, fmt.Errorf("wrong addr, %s", l) - } - lport, err := strconv.Atoi(port) - if err != nil { - return Addr{}, err - } - return Addr{IP: host, Port: uint32(lport)}, nil - } - - addrs := strings.Split(line, "->") - if len(addrs) == 0 { - return laddr, raddr, fmt.Errorf("wrong netaddr, %s", line) - } - laddr, err = parse(addrs[0]) - if len(addrs) == 2 { // remote addr exists - raddr, err = parse(addrs[1]) - if err != nil { - return laddr, raddr, err - } - } - - return laddr, raddr, err -} - -// Return up to `max` network connections opened by a process. -func ConnectionsPidMax(kind string, pid int32, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithContext(context.Background(), kind, pid, max) -} - -func ConnectionsPidMaxWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return []ConnectionStat{}, common.ErrNotImplementedError -} - -// Return a list of network connections opened, omitting `Uids`. -// WithoutUids functions are reliant on implementation details. They may be altered to be an alias for Connections or be -// removed from the API in the future. -func ConnectionsWithoutUids(kind string) ([]ConnectionStat, error) { - return ConnectionsWithoutUidsWithContext(context.Background(), kind) -} - -func ConnectionsWithoutUidsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return ConnectionsMaxWithoutUidsWithContext(ctx, kind, 0) -} - -func ConnectionsMaxWithoutUidsWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(ctx, kind, 0, max) -} - -func ConnectionsPidWithoutUids(kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidWithoutUidsWithContext(context.Background(), kind, pid) -} - -func ConnectionsPidWithoutUidsWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, 0) -} - -func ConnectionsPidMaxWithoutUids(kind string, pid int32, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(context.Background(), kind, pid, max) -} - -func ConnectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return connectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, max) -} - -func connectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return []ConnectionStat{}, common.ErrNotImplementedError -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/net/net_windows.go b/test/integration/vendor/github.com/shirou/gopsutil/net/net_windows.go deleted file mode 100644 index bdc928798..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/net/net_windows.go +++ /dev/null @@ -1,773 +0,0 @@ -// +build windows - -package net - -import ( - "context" - "fmt" - "net" - "os" - "syscall" - "unsafe" - - "github.com/shirou/gopsutil/internal/common" - "golang.org/x/sys/windows" -) - -var ( - modiphlpapi = windows.NewLazySystemDLL("iphlpapi.dll") - procGetExtendedTCPTable = modiphlpapi.NewProc("GetExtendedTcpTable") - procGetExtendedUDPTable = modiphlpapi.NewProc("GetExtendedUdpTable") - procGetIfEntry2 = modiphlpapi.NewProc("GetIfEntry2") -) - -const ( - TCPTableBasicListener = iota - TCPTableBasicConnections - TCPTableBasicAll - TCPTableOwnerPIDListener - TCPTableOwnerPIDConnections - TCPTableOwnerPIDAll - TCPTableOwnerModuleListener - TCPTableOwnerModuleConnections - TCPTableOwnerModuleAll -) - -type netConnectionKindType struct { - family uint32 - sockType uint32 - filename string -} - -var kindTCP4 = netConnectionKindType{ - family: syscall.AF_INET, - sockType: syscall.SOCK_STREAM, - filename: "tcp", -} -var kindTCP6 = netConnectionKindType{ - family: syscall.AF_INET6, - sockType: syscall.SOCK_STREAM, - filename: "tcp6", -} -var kindUDP4 = netConnectionKindType{ - family: syscall.AF_INET, - sockType: syscall.SOCK_DGRAM, - filename: "udp", -} -var kindUDP6 = netConnectionKindType{ - family: syscall.AF_INET6, - sockType: syscall.SOCK_DGRAM, - filename: "udp6", -} - -var netConnectionKindMap = map[string][]netConnectionKindType{ - "all": {kindTCP4, kindTCP6, kindUDP4, kindUDP6}, - "tcp": {kindTCP4, kindTCP6}, - "tcp4": {kindTCP4}, - "tcp6": {kindTCP6}, - "udp": {kindUDP4, kindUDP6}, - "udp4": {kindUDP4}, - "udp6": {kindUDP6}, - "inet": {kindTCP4, kindTCP6, kindUDP4, kindUDP6}, - "inet4": {kindTCP4, kindUDP4}, - "inet6": {kindTCP6, kindUDP6}, -} - -// https://github.com/microsoft/ethr/blob/aecdaf923970e5a9b4c461b4e2e3963d781ad2cc/plt_windows.go#L114-L170 -type guid struct { - Data1 uint32 - Data2 uint16 - Data3 uint16 - Data4 [8]byte -} - -const ( - maxStringSize = 256 - maxPhysAddressLength = 32 - pad0for64_4for32 = 0 -) - -type mibIfRow2 struct { - InterfaceLuid uint64 - InterfaceIndex uint32 - InterfaceGuid guid - Alias [maxStringSize + 1]uint16 - Description [maxStringSize + 1]uint16 - PhysicalAddressLength uint32 - PhysicalAddress [maxPhysAddressLength]uint8 - PermanentPhysicalAddress [maxPhysAddressLength]uint8 - Mtu uint32 - Type uint32 - TunnelType uint32 - MediaType uint32 - PhysicalMediumType uint32 - AccessType uint32 - DirectionType uint32 - InterfaceAndOperStatusFlags uint32 - OperStatus uint32 - AdminStatus uint32 - MediaConnectState uint32 - NetworkGuid guid - ConnectionType uint32 - padding1 [pad0for64_4for32]byte - TransmitLinkSpeed uint64 - ReceiveLinkSpeed uint64 - InOctets uint64 - InUcastPkts uint64 - InNUcastPkts uint64 - InDiscards uint64 - InErrors uint64 - InUnknownProtos uint64 - InUcastOctets uint64 - InMulticastOctets uint64 - InBroadcastOctets uint64 - OutOctets uint64 - OutUcastPkts uint64 - OutNUcastPkts uint64 - OutDiscards uint64 - OutErrors uint64 - OutUcastOctets uint64 - OutMulticastOctets uint64 - OutBroadcastOctets uint64 - OutQLen uint64 -} - -func IOCounters(pernic bool) ([]IOCountersStat, error) { - return IOCountersWithContext(context.Background(), pernic) -} - -func IOCountersWithContext(ctx context.Context, pernic bool) ([]IOCountersStat, error) { - ifs, err := net.Interfaces() - if err != nil { - return nil, err - } - var counters []IOCountersStat - - err = procGetIfEntry2.Find() - if err == nil { // Vista+, uint64 values (issue#693) - for _, ifi := range ifs { - c := IOCountersStat{ - Name: ifi.Name, - } - - row := mibIfRow2{InterfaceIndex: uint32(ifi.Index)} - ret, _, err := procGetIfEntry2.Call(uintptr(unsafe.Pointer(&row))) - if ret != 0 { - return nil, os.NewSyscallError("GetIfEntry2", err) - } - c.BytesSent = uint64(row.OutOctets) - c.BytesRecv = uint64(row.InOctets) - c.PacketsSent = uint64(row.OutUcastPkts) - c.PacketsRecv = uint64(row.InUcastPkts) - c.Errin = uint64(row.InErrors) - c.Errout = uint64(row.OutErrors) - c.Dropin = uint64(row.InDiscards) - c.Dropout = uint64(row.OutDiscards) - - counters = append(counters, c) - } - } else { // WinXP fallback, uint32 values - for _, ifi := range ifs { - c := IOCountersStat{ - Name: ifi.Name, - } - - row := windows.MibIfRow{Index: uint32(ifi.Index)} - err = windows.GetIfEntry(&row) - if err != nil { - return nil, os.NewSyscallError("GetIfEntry", err) - } - c.BytesSent = uint64(row.OutOctets) - c.BytesRecv = uint64(row.InOctets) - c.PacketsSent = uint64(row.OutUcastPkts) - c.PacketsRecv = uint64(row.InUcastPkts) - c.Errin = uint64(row.InErrors) - c.Errout = uint64(row.OutErrors) - c.Dropin = uint64(row.InDiscards) - c.Dropout = uint64(row.OutDiscards) - - counters = append(counters, c) - } - } - - if !pernic { - return getIOCountersAll(counters) - } - return counters, nil -} - -// NetIOCountersByFile is an method which is added just a compatibility for linux. -func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) { - return IOCountersByFileWithContext(context.Background(), pernic, filename) -} - -func IOCountersByFileWithContext(ctx context.Context, pernic bool, filename string) ([]IOCountersStat, error) { - return IOCounters(pernic) -} - -// Return a list of network connections -// Available kind: -// reference to netConnectionKindMap -func Connections(kind string) ([]ConnectionStat, error) { - return ConnectionsWithContext(context.Background(), kind) -} - -func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return ConnectionsPidWithContext(ctx, kind, 0) -} - -// ConnectionsPid Return a list of network connections opened by a process -func ConnectionsPid(kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidWithContext(context.Background(), kind, pid) -} - -func ConnectionsPidWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error) { - tmap, ok := netConnectionKindMap[kind] - if !ok { - return nil, fmt.Errorf("invalid kind, %s", kind) - } - return getProcInet(tmap, pid) -} - -func getProcInet(kinds []netConnectionKindType, pid int32) ([]ConnectionStat, error) { - stats := make([]ConnectionStat, 0) - - for _, kind := range kinds { - s, err := getNetStatWithKind(kind) - if err != nil { - continue - } - - if pid == 0 { - stats = append(stats, s...) - } else { - for _, ns := range s { - if ns.Pid != pid { - continue - } - stats = append(stats, ns) - } - } - } - - return stats, nil -} - -func getNetStatWithKind(kindType netConnectionKindType) ([]ConnectionStat, error) { - if kindType.filename == "" { - return nil, fmt.Errorf("kind filename must be required") - } - - switch kindType.filename { - case kindTCP4.filename: - return getTCPConnections(kindTCP4.family) - case kindTCP6.filename: - return getTCPConnections(kindTCP6.family) - case kindUDP4.filename: - return getUDPConnections(kindUDP4.family) - case kindUDP6.filename: - return getUDPConnections(kindUDP6.family) - } - - return nil, fmt.Errorf("invalid kind filename, %s", kindType.filename) -} - -// Return a list of network connections opened returning at most `max` -// connections for each running process. -func ConnectionsMax(kind string, max int) ([]ConnectionStat, error) { - return ConnectionsMaxWithContext(context.Background(), kind, max) -} - -func ConnectionsMaxWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return []ConnectionStat{}, common.ErrNotImplementedError -} - -// Return a list of network connections opened, omitting `Uids`. -// WithoutUids functions are reliant on implementation details. They may be altered to be an alias for Connections or be -// removed from the API in the future. -func ConnectionsWithoutUids(kind string) ([]ConnectionStat, error) { - return ConnectionsWithoutUidsWithContext(context.Background(), kind) -} - -func ConnectionsWithoutUidsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) { - return ConnectionsMaxWithoutUidsWithContext(ctx, kind, 0) -} - -func ConnectionsMaxWithoutUidsWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(ctx, kind, 0, max) -} - -func ConnectionsPidWithoutUids(kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidWithoutUidsWithContext(context.Background(), kind, pid) -} - -func ConnectionsPidWithoutUidsWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, 0) -} - -func ConnectionsPidMaxWithoutUids(kind string, pid int32, max int) ([]ConnectionStat, error) { - return ConnectionsPidMaxWithoutUidsWithContext(context.Background(), kind, pid, max) -} - -func ConnectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return connectionsPidMaxWithoutUidsWithContext(ctx, kind, pid, max) -} - -func connectionsPidMaxWithoutUidsWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) { - return []ConnectionStat{}, common.ErrNotImplementedError -} - -func FilterCounters() ([]FilterStat, error) { - return FilterCountersWithContext(context.Background()) -} - -func FilterCountersWithContext(ctx context.Context) ([]FilterStat, error) { - return nil, common.ErrNotImplementedError -} - -func ConntrackStats(percpu bool) ([]ConntrackStat, error) { - return ConntrackStatsWithContext(context.Background(), percpu) -} - -func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackStat, error) { - return nil, common.ErrNotImplementedError -} - - -// NetProtoCounters returns network statistics for the entire system -// If protocols is empty then all protocols are returned, otherwise -// just the protocols in the list are returned. -// Not Implemented for Windows -func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) { - return ProtoCountersWithContext(context.Background(), protocols) -} - -func ProtoCountersWithContext(ctx context.Context, protocols []string) ([]ProtoCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func getTableUintptr(family uint32, buf []byte) uintptr { - var ( - pmibTCPTable pmibTCPTableOwnerPidAll - pmibTCP6Table pmibTCP6TableOwnerPidAll - - p uintptr - ) - switch family { - case kindTCP4.family: - if len(buf) > 0 { - pmibTCPTable = (*mibTCPTableOwnerPid)(unsafe.Pointer(&buf[0])) - p = uintptr(unsafe.Pointer(pmibTCPTable)) - } else { - p = uintptr(unsafe.Pointer(pmibTCPTable)) - } - case kindTCP6.family: - if len(buf) > 0 { - pmibTCP6Table = (*mibTCP6TableOwnerPid)(unsafe.Pointer(&buf[0])) - p = uintptr(unsafe.Pointer(pmibTCP6Table)) - } else { - p = uintptr(unsafe.Pointer(pmibTCP6Table)) - } - } - return p -} - -func getTableInfo(filename string, table interface{}) (index, step, length int) { - switch filename { - case kindTCP4.filename: - index = int(unsafe.Sizeof(table.(pmibTCPTableOwnerPidAll).DwNumEntries)) - step = int(unsafe.Sizeof(table.(pmibTCPTableOwnerPidAll).Table)) - length = int(table.(pmibTCPTableOwnerPidAll).DwNumEntries) - case kindTCP6.filename: - index = int(unsafe.Sizeof(table.(pmibTCP6TableOwnerPidAll).DwNumEntries)) - step = int(unsafe.Sizeof(table.(pmibTCP6TableOwnerPidAll).Table)) - length = int(table.(pmibTCP6TableOwnerPidAll).DwNumEntries) - case kindUDP4.filename: - index = int(unsafe.Sizeof(table.(pmibUDPTableOwnerPid).DwNumEntries)) - step = int(unsafe.Sizeof(table.(pmibUDPTableOwnerPid).Table)) - length = int(table.(pmibUDPTableOwnerPid).DwNumEntries) - case kindUDP6.filename: - index = int(unsafe.Sizeof(table.(pmibUDP6TableOwnerPid).DwNumEntries)) - step = int(unsafe.Sizeof(table.(pmibUDP6TableOwnerPid).Table)) - length = int(table.(pmibUDP6TableOwnerPid).DwNumEntries) - } - - return -} - -func getTCPConnections(family uint32) ([]ConnectionStat, error) { - var ( - p uintptr - buf []byte - size uint32 - - pmibTCPTable pmibTCPTableOwnerPidAll - pmibTCP6Table pmibTCP6TableOwnerPidAll - ) - - if family == 0 { - return nil, fmt.Errorf("faimly must be required") - } - - for { - switch family { - case kindTCP4.family: - if len(buf) > 0 { - pmibTCPTable = (*mibTCPTableOwnerPid)(unsafe.Pointer(&buf[0])) - p = uintptr(unsafe.Pointer(pmibTCPTable)) - } else { - p = uintptr(unsafe.Pointer(pmibTCPTable)) - } - case kindTCP6.family: - if len(buf) > 0 { - pmibTCP6Table = (*mibTCP6TableOwnerPid)(unsafe.Pointer(&buf[0])) - p = uintptr(unsafe.Pointer(pmibTCP6Table)) - } else { - p = uintptr(unsafe.Pointer(pmibTCP6Table)) - } - } - - err := getExtendedTcpTable(p, - &size, - true, - family, - tcpTableOwnerPidAll, - 0) - if err == nil { - break - } - if err != windows.ERROR_INSUFFICIENT_BUFFER { - return nil, err - } - buf = make([]byte, size) - } - - var ( - index, step int - length int - ) - - stats := make([]ConnectionStat, 0) - switch family { - case kindTCP4.family: - index, step, length = getTableInfo(kindTCP4.filename, pmibTCPTable) - case kindTCP6.family: - index, step, length = getTableInfo(kindTCP6.filename, pmibTCP6Table) - } - - if length == 0 { - return nil, nil - } - - for i := 0; i < length; i++ { - switch family { - case kindTCP4.family: - mibs := (*mibTCPRowOwnerPid)(unsafe.Pointer(&buf[index])) - ns := mibs.convertToConnectionStat() - stats = append(stats, ns) - case kindTCP6.family: - mibs := (*mibTCP6RowOwnerPid)(unsafe.Pointer(&buf[index])) - ns := mibs.convertToConnectionStat() - stats = append(stats, ns) - } - - index += step - } - return stats, nil -} - -func getUDPConnections(family uint32) ([]ConnectionStat, error) { - var ( - p uintptr - buf []byte - size uint32 - - pmibUDPTable pmibUDPTableOwnerPid - pmibUDP6Table pmibUDP6TableOwnerPid - ) - - if family == 0 { - return nil, fmt.Errorf("faimly must be required") - } - - for { - switch family { - case kindUDP4.family: - if len(buf) > 0 { - pmibUDPTable = (*mibUDPTableOwnerPid)(unsafe.Pointer(&buf[0])) - p = uintptr(unsafe.Pointer(pmibUDPTable)) - } else { - p = uintptr(unsafe.Pointer(pmibUDPTable)) - } - case kindUDP6.family: - if len(buf) > 0 { - pmibUDP6Table = (*mibUDP6TableOwnerPid)(unsafe.Pointer(&buf[0])) - p = uintptr(unsafe.Pointer(pmibUDP6Table)) - } else { - p = uintptr(unsafe.Pointer(pmibUDP6Table)) - } - } - - err := getExtendedUdpTable( - p, - &size, - true, - family, - udpTableOwnerPid, - 0, - ) - if err == nil { - break - } - if err != windows.ERROR_INSUFFICIENT_BUFFER { - return nil, err - } - buf = make([]byte, size) - } - - var ( - index, step, length int - ) - - stats := make([]ConnectionStat, 0) - switch family { - case kindUDP4.family: - index, step, length = getTableInfo(kindUDP4.filename, pmibUDPTable) - case kindUDP6.family: - index, step, length = getTableInfo(kindUDP6.filename, pmibUDP6Table) - } - - if length == 0 { - return nil, nil - } - - for i := 0; i < length; i++ { - switch family { - case kindUDP4.family: - mibs := (*mibUDPRowOwnerPid)(unsafe.Pointer(&buf[index])) - ns := mibs.convertToConnectionStat() - stats = append(stats, ns) - case kindUDP6.family: - mibs := (*mibUDP6RowOwnerPid)(unsafe.Pointer(&buf[index])) - ns := mibs.convertToConnectionStat() - stats = append(stats, ns) - } - - index += step - } - return stats, nil -} - -// tcpStatuses https://msdn.microsoft.com/en-us/library/windows/desktop/bb485761(v=vs.85).aspx -var tcpStatuses = map[mibTCPState]string{ - 1: "CLOSED", - 2: "LISTEN", - 3: "SYN_SENT", - 4: "SYN_RECEIVED", - 5: "ESTABLISHED", - 6: "FIN_WAIT_1", - 7: "FIN_WAIT_2", - 8: "CLOSE_WAIT", - 9: "CLOSING", - 10: "LAST_ACK", - 11: "TIME_WAIT", - 12: "DELETE", -} - -func getExtendedTcpTable(pTcpTable uintptr, pdwSize *uint32, bOrder bool, ulAf uint32, tableClass tcpTableClass, reserved uint32) (errcode error) { - r1, _, _ := syscall.Syscall6(procGetExtendedTCPTable.Addr(), 6, pTcpTable, uintptr(unsafe.Pointer(pdwSize)), getUintptrFromBool(bOrder), uintptr(ulAf), uintptr(tableClass), uintptr(reserved)) - if r1 != 0 { - errcode = syscall.Errno(r1) - } - return -} - -func getExtendedUdpTable(pUdpTable uintptr, pdwSize *uint32, bOrder bool, ulAf uint32, tableClass udpTableClass, reserved uint32) (errcode error) { - r1, _, _ := syscall.Syscall6(procGetExtendedUDPTable.Addr(), 6, pUdpTable, uintptr(unsafe.Pointer(pdwSize)), getUintptrFromBool(bOrder), uintptr(ulAf), uintptr(tableClass), uintptr(reserved)) - if r1 != 0 { - errcode = syscall.Errno(r1) - } - return -} - -func getUintptrFromBool(b bool) uintptr { - if b { - return 1 - } - return 0 -} - -const anySize = 1 - -// type MIB_TCP_STATE int32 -type mibTCPState int32 - -type tcpTableClass int32 - -const ( - tcpTableBasicListener tcpTableClass = iota - tcpTableBasicConnections - tcpTableBasicAll - tcpTableOwnerPidListener - tcpTableOwnerPidConnections - tcpTableOwnerPidAll - tcpTableOwnerModuleListener - tcpTableOwnerModuleConnections - tcpTableOwnerModuleAll -) - -type udpTableClass int32 - -const ( - udpTableBasic udpTableClass = iota - udpTableOwnerPid - udpTableOwnerModule -) - -// TCP - -type mibTCPRowOwnerPid struct { - DwState uint32 - DwLocalAddr uint32 - DwLocalPort uint32 - DwRemoteAddr uint32 - DwRemotePort uint32 - DwOwningPid uint32 -} - -func (m *mibTCPRowOwnerPid) convertToConnectionStat() ConnectionStat { - ns := ConnectionStat{ - Family: kindTCP4.family, - Type: kindTCP4.sockType, - Laddr: Addr{ - IP: parseIPv4HexString(m.DwLocalAddr), - Port: uint32(decodePort(m.DwLocalPort)), - }, - Raddr: Addr{ - IP: parseIPv4HexString(m.DwRemoteAddr), - Port: uint32(decodePort(m.DwRemotePort)), - }, - Pid: int32(m.DwOwningPid), - Status: tcpStatuses[mibTCPState(m.DwState)], - } - - return ns -} - -type mibTCPTableOwnerPid struct { - DwNumEntries uint32 - Table [anySize]mibTCPRowOwnerPid -} - -type mibTCP6RowOwnerPid struct { - UcLocalAddr [16]byte - DwLocalScopeId uint32 - DwLocalPort uint32 - UcRemoteAddr [16]byte - DwRemoteScopeId uint32 - DwRemotePort uint32 - DwState uint32 - DwOwningPid uint32 -} - -func (m *mibTCP6RowOwnerPid) convertToConnectionStat() ConnectionStat { - ns := ConnectionStat{ - Family: kindTCP6.family, - Type: kindTCP6.sockType, - Laddr: Addr{ - IP: parseIPv6HexString(m.UcLocalAddr), - Port: uint32(decodePort(m.DwLocalPort)), - }, - Raddr: Addr{ - IP: parseIPv6HexString(m.UcRemoteAddr), - Port: uint32(decodePort(m.DwRemotePort)), - }, - Pid: int32(m.DwOwningPid), - Status: tcpStatuses[mibTCPState(m.DwState)], - } - - return ns -} - -type mibTCP6TableOwnerPid struct { - DwNumEntries uint32 - Table [anySize]mibTCP6RowOwnerPid -} - -type pmibTCPTableOwnerPidAll *mibTCPTableOwnerPid -type pmibTCP6TableOwnerPidAll *mibTCP6TableOwnerPid - -// UDP - -type mibUDPRowOwnerPid struct { - DwLocalAddr uint32 - DwLocalPort uint32 - DwOwningPid uint32 -} - -func (m *mibUDPRowOwnerPid) convertToConnectionStat() ConnectionStat { - ns := ConnectionStat{ - Family: kindUDP4.family, - Type: kindUDP4.sockType, - Laddr: Addr{ - IP: parseIPv4HexString(m.DwLocalAddr), - Port: uint32(decodePort(m.DwLocalPort)), - }, - Pid: int32(m.DwOwningPid), - } - - return ns -} - -type mibUDPTableOwnerPid struct { - DwNumEntries uint32 - Table [anySize]mibUDPRowOwnerPid -} - -type mibUDP6RowOwnerPid struct { - UcLocalAddr [16]byte - DwLocalScopeId uint32 - DwLocalPort uint32 - DwOwningPid uint32 -} - -func (m *mibUDP6RowOwnerPid) convertToConnectionStat() ConnectionStat { - ns := ConnectionStat{ - Family: kindUDP6.family, - Type: kindUDP6.sockType, - Laddr: Addr{ - IP: parseIPv6HexString(m.UcLocalAddr), - Port: uint32(decodePort(m.DwLocalPort)), - }, - Pid: int32(m.DwOwningPid), - } - - return ns -} - -type mibUDP6TableOwnerPid struct { - DwNumEntries uint32 - Table [anySize]mibUDP6RowOwnerPid -} - -type pmibUDPTableOwnerPid *mibUDPTableOwnerPid -type pmibUDP6TableOwnerPid *mibUDP6TableOwnerPid - -func decodePort(port uint32) uint16 { - return syscall.Ntohs(uint16(port)) -} - -func parseIPv4HexString(addr uint32) string { - return fmt.Sprintf("%d.%d.%d.%d", addr&255, addr>>8&255, addr>>16&255, addr>>24&255) -} - -func parseIPv6HexString(addr [16]byte) string { - var ret [16]byte - for i := 0; i < 16; i++ { - ret[i] = uint8(addr[i]) - } - - // convert []byte to net.IP - ip := net.IP(ret[:]) - return ip.String() -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process.go deleted file mode 100644 index fc1c5f4cb..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process.go +++ /dev/null @@ -1,549 +0,0 @@ -package process - -import ( - "context" - "encoding/json" - "errors" - "runtime" - "sort" - "sync" - "syscall" - "time" - - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/mem" - "github.com/shirou/gopsutil/net" -) - -var ( - invoke common.Invoker = common.Invoke{} - ErrorNoChildren = errors.New("process does not have children") - ErrorProcessNotRunning = errors.New("process does not exist") -) - -type Process struct { - Pid int32 `json:"pid"` - name string - status string - parent int32 - parentMutex sync.RWMutex // for windows ppid cache - numCtxSwitches *NumCtxSwitchesStat - uids []int32 - gids []int32 - groups []int32 - numThreads int32 - memInfo *MemoryInfoStat - sigInfo *SignalInfoStat - createTime int64 - - lastCPUTimes *cpu.TimesStat - lastCPUTime time.Time - - tgid int32 -} - -type OpenFilesStat struct { - Path string `json:"path"` - Fd uint64 `json:"fd"` -} - -type MemoryInfoStat struct { - RSS uint64 `json:"rss"` // bytes - VMS uint64 `json:"vms"` // bytes - HWM uint64 `json:"hwm"` // bytes - Data uint64 `json:"data"` // bytes - Stack uint64 `json:"stack"` // bytes - Locked uint64 `json:"locked"` // bytes - Swap uint64 `json:"swap"` // bytes -} - -type SignalInfoStat struct { - PendingProcess uint64 `json:"pending_process"` - PendingThread uint64 `json:"pending_thread"` - Blocked uint64 `json:"blocked"` - Ignored uint64 `json:"ignored"` - Caught uint64 `json:"caught"` -} - -type RlimitStat struct { - Resource int32 `json:"resource"` - Soft int32 `json:"soft"` //TODO too small. needs to be uint64 - Hard int32 `json:"hard"` //TODO too small. needs to be uint64 - Used uint64 `json:"used"` -} - -type IOCountersStat struct { - ReadCount uint64 `json:"readCount"` - WriteCount uint64 `json:"writeCount"` - ReadBytes uint64 `json:"readBytes"` - WriteBytes uint64 `json:"writeBytes"` -} - -type NumCtxSwitchesStat struct { - Voluntary int64 `json:"voluntary"` - Involuntary int64 `json:"involuntary"` -} - -type PageFaultsStat struct { - MinorFaults uint64 `json:"minorFaults"` - MajorFaults uint64 `json:"majorFaults"` - ChildMinorFaults uint64 `json:"childMinorFaults"` - ChildMajorFaults uint64 `json:"childMajorFaults"` -} - -// Resource limit constants are from /usr/include/x86_64-linux-gnu/bits/resource.h -// from libc6-dev package in Ubuntu 16.10 -const ( - RLIMIT_CPU int32 = 0 - RLIMIT_FSIZE int32 = 1 - RLIMIT_DATA int32 = 2 - RLIMIT_STACK int32 = 3 - RLIMIT_CORE int32 = 4 - RLIMIT_RSS int32 = 5 - RLIMIT_NPROC int32 = 6 - RLIMIT_NOFILE int32 = 7 - RLIMIT_MEMLOCK int32 = 8 - RLIMIT_AS int32 = 9 - RLIMIT_LOCKS int32 = 10 - RLIMIT_SIGPENDING int32 = 11 - RLIMIT_MSGQUEUE int32 = 12 - RLIMIT_NICE int32 = 13 - RLIMIT_RTPRIO int32 = 14 - RLIMIT_RTTIME int32 = 15 -) - -func (p Process) String() string { - s, _ := json.Marshal(p) - return string(s) -} - -func (o OpenFilesStat) String() string { - s, _ := json.Marshal(o) - return string(s) -} - -func (m MemoryInfoStat) String() string { - s, _ := json.Marshal(m) - return string(s) -} - -func (r RlimitStat) String() string { - s, _ := json.Marshal(r) - return string(s) -} - -func (i IOCountersStat) String() string { - s, _ := json.Marshal(i) - return string(s) -} - -func (p NumCtxSwitchesStat) String() string { - s, _ := json.Marshal(p) - return string(s) -} - -// Pids returns a slice of process ID list which are running now. -func Pids() ([]int32, error) { - return PidsWithContext(context.Background()) -} - -func PidsWithContext(ctx context.Context) ([]int32, error) { - pids, err := pidsWithContext(ctx) - sort.Slice(pids, func(i, j int) bool { return pids[i] < pids[j] }) - return pids, err -} - -// Processes returns a slice of pointers to Process structs for all -// currently running processes. -func Processes() ([]*Process, error) { - return ProcessesWithContext(context.Background()) -} - -// NewProcess creates a new Process instance, it only stores the pid and -// checks that the process exists. Other method on Process can be used -// to get more information about the process. An error will be returned -// if the process does not exist. -func NewProcess(pid int32) (*Process, error) { - return NewProcessWithContext(context.Background(), pid) -} - -func NewProcessWithContext(ctx context.Context, pid int32) (*Process, error) { - p := &Process{ - Pid: pid, - } - - exists, err := PidExistsWithContext(ctx, pid) - if err != nil { - return p, err - } - if !exists { - return p, ErrorProcessNotRunning - } - p.CreateTimeWithContext(ctx) - return p, nil -} - -func PidExists(pid int32) (bool, error) { - return PidExistsWithContext(context.Background(), pid) -} - -// Background returns true if the process is in background, false otherwise. -func (p *Process) Background() (bool, error) { - return p.BackgroundWithContext(context.Background()) -} - -func (p *Process) BackgroundWithContext(ctx context.Context) (bool, error) { - fg, err := p.ForegroundWithContext(ctx) - if err != nil { - return false, err - } - return !fg, err -} - -// If interval is 0, return difference from last call(non-blocking). -// If interval > 0, wait interval sec and return diffrence between start and end. -func (p *Process) Percent(interval time.Duration) (float64, error) { - return p.PercentWithContext(context.Background(), interval) -} - -func (p *Process) PercentWithContext(ctx context.Context, interval time.Duration) (float64, error) { - cpuTimes, err := p.TimesWithContext(ctx) - if err != nil { - return 0, err - } - now := time.Now() - - if interval > 0 { - p.lastCPUTimes = cpuTimes - p.lastCPUTime = now - if err := common.Sleep(ctx, interval); err != nil { - return 0, err - } - cpuTimes, err = p.TimesWithContext(ctx) - now = time.Now() - if err != nil { - return 0, err - } - } else { - if p.lastCPUTimes == nil { - // invoked first time - p.lastCPUTimes = cpuTimes - p.lastCPUTime = now - return 0, nil - } - } - - numcpu := runtime.NumCPU() - delta := (now.Sub(p.lastCPUTime).Seconds()) * float64(numcpu) - ret := calculatePercent(p.lastCPUTimes, cpuTimes, delta, numcpu) - p.lastCPUTimes = cpuTimes - p.lastCPUTime = now - return ret, nil -} - -// IsRunning returns whether the process is still running or not. -func (p *Process) IsRunning() (bool, error) { - return p.IsRunningWithContext(context.Background()) -} - -func (p *Process) IsRunningWithContext(ctx context.Context) (bool, error) { - createTime, err := p.CreateTimeWithContext(ctx) - if err != nil { - return false, err - } - p2, err := NewProcessWithContext(ctx, p.Pid) - if err == ErrorProcessNotRunning { - return false, nil - } - createTime2, err := p2.CreateTimeWithContext(ctx) - if err != nil { - return false, err - } - return createTime == createTime2, nil -} - -// CreateTime returns created time of the process in milliseconds since the epoch, in UTC. -func (p *Process) CreateTime() (int64, error) { - return p.CreateTimeWithContext(context.Background()) -} - -func (p *Process) CreateTimeWithContext(ctx context.Context) (int64, error) { - if p.createTime != 0 { - return p.createTime, nil - } - createTime, err := p.createTimeWithContext(ctx) - p.createTime = createTime - return p.createTime, err -} - -func calculatePercent(t1, t2 *cpu.TimesStat, delta float64, numcpu int) float64 { - if delta == 0 { - return 0 - } - delta_proc := t2.Total() - t1.Total() - overall_percent := ((delta_proc / delta) * 100) * float64(numcpu) - return overall_percent -} - -// MemoryPercent returns how many percent of the total RAM this process uses -func (p *Process) MemoryPercent() (float32, error) { - return p.MemoryPercentWithContext(context.Background()) -} - -func (p *Process) MemoryPercentWithContext(ctx context.Context) (float32, error) { - machineMemory, err := mem.VirtualMemoryWithContext(ctx) - if err != nil { - return 0, err - } - total := machineMemory.Total - - processMemory, err := p.MemoryInfoWithContext(ctx) - if err != nil { - return 0, err - } - used := processMemory.RSS - - return (100 * float32(used) / float32(total)), nil -} - -// CPU_Percent returns how many percent of the CPU time this process uses -func (p *Process) CPUPercent() (float64, error) { - return p.CPUPercentWithContext(context.Background()) -} - -func (p *Process) CPUPercentWithContext(ctx context.Context) (float64, error) { - crt_time, err := p.createTimeWithContext(ctx) - if err != nil { - return 0, err - } - - cput, err := p.TimesWithContext(ctx) - if err != nil { - return 0, err - } - - created := time.Unix(0, crt_time*int64(time.Millisecond)) - totalTime := time.Since(created).Seconds() - if totalTime <= 0 { - return 0, nil - } - - return 100 * cput.Total() / totalTime, nil -} - -// Groups returns all group IDs(include supplementary groups) of the process as a slice of the int -func (p *Process) Groups() ([]int32, error) { - return p.GroupsWithContext(context.Background()) -} - -// Ppid returns Parent Process ID of the process. -func (p *Process) Ppid() (int32, error) { - return p.PpidWithContext(context.Background()) -} - -// Name returns name of the process. -func (p *Process) Name() (string, error) { - return p.NameWithContext(context.Background()) -} - -// Exe returns executable path of the process. -func (p *Process) Exe() (string, error) { - return p.ExeWithContext(context.Background()) -} - -// Cmdline returns the command line arguments of the process as a string with -// each argument separated by 0x20 ascii character. -func (p *Process) Cmdline() (string, error) { - return p.CmdlineWithContext(context.Background()) -} - -// CmdlineSlice returns the command line arguments of the process as a slice with each -// element being an argument. -func (p *Process) CmdlineSlice() ([]string, error) { - return p.CmdlineSliceWithContext(context.Background()) -} - -// Cwd returns current working directory of the process. -func (p *Process) Cwd() (string, error) { - return p.CwdWithContext(context.Background()) -} - -// Parent returns parent Process of the process. -func (p *Process) Parent() (*Process, error) { - return p.ParentWithContext(context.Background()) -} - -// Status returns the process status. -// Return value could be one of these. -// R: Running S: Sleep T: Stop I: Idle -// Z: Zombie W: Wait L: Lock -// The character is same within all supported platforms. -func (p *Process) Status() (string, error) { - return p.StatusWithContext(context.Background()) -} - -// Foreground returns true if the process is in foreground, false otherwise. -func (p *Process) Foreground() (bool, error) { - return p.ForegroundWithContext(context.Background()) -} - -// Uids returns user ids of the process as a slice of the int -func (p *Process) Uids() ([]int32, error) { - return p.UidsWithContext(context.Background()) -} - -// Gids returns group ids of the process as a slice of the int -func (p *Process) Gids() ([]int32, error) { - return p.GidsWithContext(context.Background()) -} - -// Terminal returns a terminal which is associated with the process. -func (p *Process) Terminal() (string, error) { - return p.TerminalWithContext(context.Background()) -} - -// Nice returns a nice value (priority). -func (p *Process) Nice() (int32, error) { - return p.NiceWithContext(context.Background()) -} - -// IOnice returns process I/O nice value (priority). -func (p *Process) IOnice() (int32, error) { - return p.IOniceWithContext(context.Background()) -} - -// Rlimit returns Resource Limits. -func (p *Process) Rlimit() ([]RlimitStat, error) { - return p.RlimitWithContext(context.Background()) -} - -// RlimitUsage returns Resource Limits. -// If gatherUsed is true, the currently used value will be gathered and added -// to the resulting RlimitStat. -func (p *Process) RlimitUsage(gatherUsed bool) ([]RlimitStat, error) { - return p.RlimitUsageWithContext(context.Background(), gatherUsed) -} - -// IOCounters returns IO Counters. -func (p *Process) IOCounters() (*IOCountersStat, error) { - return p.IOCountersWithContext(context.Background()) -} - -// NumCtxSwitches returns the number of the context switches of the process. -func (p *Process) NumCtxSwitches() (*NumCtxSwitchesStat, error) { - return p.NumCtxSwitchesWithContext(context.Background()) -} - -// NumFDs returns the number of File Descriptors used by the process. -func (p *Process) NumFDs() (int32, error) { - return p.NumFDsWithContext(context.Background()) -} - -// NumThreads returns the number of threads used by the process. -func (p *Process) NumThreads() (int32, error) { - return p.NumThreadsWithContext(context.Background()) -} - -func (p *Process) Threads() (map[int32]*cpu.TimesStat, error) { - return p.ThreadsWithContext(context.Background()) -} - -// Times returns CPU times of the process. -func (p *Process) Times() (*cpu.TimesStat, error) { - return p.TimesWithContext(context.Background()) -} - -// CPUAffinity returns CPU affinity of the process. -func (p *Process) CPUAffinity() ([]int32, error) { - return p.CPUAffinityWithContext(context.Background()) -} - -// MemoryInfo returns generic process memory information, -// such as RSS and VMS. -func (p *Process) MemoryInfo() (*MemoryInfoStat, error) { - return p.MemoryInfoWithContext(context.Background()) -} - -// MemoryInfoEx returns platform-specific process memory information. -func (p *Process) MemoryInfoEx() (*MemoryInfoExStat, error) { - return p.MemoryInfoExWithContext(context.Background()) -} - -// PageFaultsInfo returns the process's page fault counters. -func (p *Process) PageFaults() (*PageFaultsStat, error) { - return p.PageFaultsWithContext(context.Background()) -} - -// Children returns the children of the process represented as a slice -// of pointers to Process type. -func (p *Process) Children() ([]*Process, error) { - return p.ChildrenWithContext(context.Background()) -} - -// OpenFiles returns a slice of OpenFilesStat opend by the process. -// OpenFilesStat includes a file path and file descriptor. -func (p *Process) OpenFiles() ([]OpenFilesStat, error) { - return p.OpenFilesWithContext(context.Background()) -} - -// Connections returns a slice of net.ConnectionStat used by the process. -// This returns all kind of the connection. This means TCP, UDP or UNIX. -func (p *Process) Connections() ([]net.ConnectionStat, error) { - return p.ConnectionsWithContext(context.Background()) -} - -// Connections returns a slice of net.ConnectionStat used by the process at most `max`. -func (p *Process) ConnectionsMax(max int) ([]net.ConnectionStat, error) { - return p.ConnectionsMaxWithContext(context.Background(), max) -} - -// NetIOCounters returns NetIOCounters of the process. -func (p *Process) NetIOCounters(pernic bool) ([]net.IOCountersStat, error) { - return p.NetIOCountersWithContext(context.Background(), pernic) -} - -// MemoryMaps get memory maps from /proc/(pid)/smaps -func (p *Process) MemoryMaps(grouped bool) (*[]MemoryMapsStat, error) { - return p.MemoryMapsWithContext(context.Background(), grouped) -} - -// Tgid returns thread group id of the process. -func (p *Process) Tgid() (int32, error) { - return p.TgidWithContext(context.Background()) -} - -// SendSignal sends a unix.Signal to the process. -func (p *Process) SendSignal(sig syscall.Signal) error { - return p.SendSignalWithContext(context.Background(), sig) -} - -// Suspend sends SIGSTOP to the process. -func (p *Process) Suspend() error { - return p.SuspendWithContext(context.Background()) -} - -// Resume sends SIGCONT to the process. -func (p *Process) Resume() error { - return p.ResumeWithContext(context.Background()) -} - -// Terminate sends SIGTERM to the process. -func (p *Process) Terminate() error { - return p.TerminateWithContext(context.Background()) -} - -// Kill sends SIGKILL to the process. -func (p *Process) Kill() error { - return p.KillWithContext(context.Background()) -} - -// Username returns a username of the process. -func (p *Process) Username() (string, error) { - return p.UsernameWithContext(context.Background()) -} - -// Environ returns the environment variables of the process. -func (p *Process) Environ() ([]string, error) { - return p.EnvironWithContext(context.Background()) -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_bsd.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_bsd.go deleted file mode 100644 index 545e44f31..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_bsd.go +++ /dev/null @@ -1,84 +0,0 @@ -// +build darwin freebsd openbsd - -package process - -import ( - "bytes" - "context" - "encoding/binary" - - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" -) - -type MemoryInfoExStat struct{} - -type MemoryMapsStat struct{} - -func (p *Process) TgidWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) CwdWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) IOniceWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) RlimitWithContext(ctx context.Context) ([]RlimitStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) RlimitUsageWithContext(ctx context.Context, gatherUsed bool) ([]RlimitStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NumCtxSwitchesWithContext(ctx context.Context) (*NumCtxSwitchesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NumFDsWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) CPUAffinityWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryInfoExWithContext(ctx context.Context) (*MemoryInfoExStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) PageFaultsWithContext(ctx context.Context) (*PageFaultsStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) OpenFilesWithContext(ctx context.Context) ([]OpenFilesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) ThreadsWithContext(ctx context.Context) (map[int32]*cpu.TimesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) EnvironWithContext(ctx context.Context) ([]string, error) { - return nil, common.ErrNotImplementedError -} - -func parseKinfoProc(buf []byte) (KinfoProc, error) { - var k KinfoProc - br := bytes.NewReader(buf) - err := common.Read(br, binary.LittleEndian, &k) - return k, err -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin.go deleted file mode 100644 index 383e0994d..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin.go +++ /dev/null @@ -1,485 +0,0 @@ -// +build darwin - -package process - -import ( - "context" - "fmt" - "os/exec" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" - "github.com/tklauser/go-sysconf" - "golang.org/x/sys/unix" -) - -// copied from sys/sysctl.h -const ( - CTLKern = 1 // "high kernel": proc, limits - KernProc = 14 // struct: process entries - KernProcPID = 1 // by process id - KernProcProc = 8 // only return procs - KernProcAll = 0 // everything - KernProcPathname = 12 // path to executable -) - -var ClockTicks = 100 // default value - -func init() { - clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) - // ignore errors - if err == nil { - ClockTicks = int(clkTck) - } -} - -type _Ctype_struct___0 struct { - Pad uint64 -} - -func pidsWithContext(ctx context.Context) ([]int32, error) { - var ret []int32 - - pids, err := callPsWithContext(ctx, "pid", 0, false, false) - if err != nil { - return ret, err - } - - for _, pid := range pids { - v, err := strconv.Atoi(pid[0]) - if err != nil { - return ret, err - } - ret = append(ret, int32(v)) - } - - return ret, nil -} - -func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { - r, err := callPsWithContext(ctx, "ppid", p.Pid, false, false) - if err != nil { - return 0, err - } - - v, err := strconv.Atoi(r[0][0]) - if err != nil { - return 0, err - } - - return int32(v), err -} - -func (p *Process) NameWithContext(ctx context.Context) (string, error) { - k, err := p.getKProc() - if err != nil { - return "", err - } - name := common.IntToString(k.Proc.P_comm[:]) - - if len(name) >= 15 { - cmdName, err := p.cmdNameWithContext(ctx) - if err != nil { - return "", err - } - if len(cmdName) > 0 { - extendedName := filepath.Base(cmdName[0]) - if strings.HasPrefix(extendedName, p.name) { - name = extendedName - } else { - name = cmdName[0] - } - } - } - - return name, nil -} - -func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { - r, err := callPsWithContext(ctx, "command", p.Pid, false, false) - if err != nil { - return "", err - } - return strings.Join(r[0], " "), err -} - -// cmdNameWithContext returns the command name (including spaces) without any arguments -func (p *Process) cmdNameWithContext(ctx context.Context) ([]string, error) { - r, err := callPsWithContext(ctx, "command", p.Pid, false, true) - if err != nil { - return nil, err - } - return r[0], err -} - -// CmdlineSliceWithContext returns the command line arguments of the process as a slice with each -// element being an argument. Because of current deficiencies in the way that the command -// line arguments are found, single arguments that have spaces in the will actually be -// reported as two separate items. In order to do something better CGO would be needed -// to use the native darwin functions. -func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { - r, err := callPsWithContext(ctx, "command", p.Pid, false, false) - if err != nil { - return nil, err - } - return r[0], err -} - -func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { - r, err := callPsWithContext(ctx, "etime", p.Pid, false, false) - if err != nil { - return 0, err - } - - elapsedSegments := strings.Split(strings.Replace(r[0][0], "-", ":", 1), ":") - var elapsedDurations []time.Duration - for i := len(elapsedSegments) - 1; i >= 0; i-- { - p, err := strconv.ParseInt(elapsedSegments[i], 10, 0) - if err != nil { - return 0, err - } - elapsedDurations = append(elapsedDurations, time.Duration(p)) - } - - var elapsed = time.Duration(elapsedDurations[0]) * time.Second - if len(elapsedDurations) > 1 { - elapsed += time.Duration(elapsedDurations[1]) * time.Minute - } - if len(elapsedDurations) > 2 { - elapsed += time.Duration(elapsedDurations[2]) * time.Hour - } - if len(elapsedDurations) > 3 { - elapsed += time.Duration(elapsedDurations[3]) * time.Hour * 24 - } - - start := time.Now().Add(-elapsed) - return start.Unix() * 1000, nil -} - -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - out, err := common.CallLsofWithContext(ctx, invoke, p.Pid, "-FR") - if err != nil { - return nil, err - } - for _, line := range out { - if len(line) >= 1 && line[0] == 'R' { - v, err := strconv.Atoi(line[1:]) - if err != nil { - return nil, err - } - return NewProcessWithContext(ctx, int32(v)) - } - } - return nil, fmt.Errorf("could not find parent line") -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - r, err := callPsWithContext(ctx, "state", p.Pid, false, false) - if err != nil { - return "", err - } - - return r[0][0][0:1], err -} - -func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { - // see https://github.com/shirou/gopsutil/issues/596#issuecomment-432707831 for implementation details - pid := p.Pid - ps, err := exec.LookPath("ps") - if err != nil { - return false, err - } - out, err := invoke.CommandWithContext(ctx, ps, "-o", "stat=", "-p", strconv.Itoa(int(pid))) - if err != nil { - return false, err - } - return strings.IndexByte(string(out), '+') != -1, nil -} - -func (p *Process) UidsWithContext(ctx context.Context) ([]int32, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - - // See: http://unix.superglobalmegacorp.com/Net2/newsrc/sys/ucred.h.html - userEffectiveUID := int32(k.Eproc.Ucred.UID) - - return []int32{userEffectiveUID}, nil -} - -func (p *Process) GidsWithContext(ctx context.Context) ([]int32, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - - gids := make([]int32, 0, 3) - gids = append(gids, int32(k.Eproc.Pcred.P_rgid), int32(k.Eproc.Ucred.Ngroups), int32(k.Eproc.Pcred.P_svgid)) - - return gids, nil -} - -func (p *Process) GroupsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError - // k, err := p.getKProc() - // if err != nil { - // return nil, err - // } - - // groups := make([]int32, k.Eproc.Ucred.Ngroups) - // for i := int16(0); i < k.Eproc.Ucred.Ngroups; i++ { - // groups[i] = int32(k.Eproc.Ucred.Groups[i]) - // } - - // return groups, nil -} - -func (p *Process) TerminalWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError - /* - k, err := p.getKProc() - if err != nil { - return "", err - } - - ttyNr := uint64(k.Eproc.Tdev) - termmap, err := getTerminalMap() - if err != nil { - return "", err - } - - return termmap[ttyNr], nil - */ -} - -func (p *Process) NiceWithContext(ctx context.Context) (int32, error) { - k, err := p.getKProc() - if err != nil { - return 0, err - } - return int32(k.Proc.P_nice), nil -} - -func (p *Process) IOCountersWithContext(ctx context.Context) (*IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { - r, err := callPsWithContext(ctx, "utime,stime", p.Pid, true, false) - if err != nil { - return 0, err - } - return int32(len(r)), nil -} - -func convertCPUTimes(s string) (ret float64, err error) { - var t int - var _tmp string - if strings.Contains(s, ":") { - _t := strings.Split(s, ":") - switch len(_t) { - case 3: - hour, err := strconv.Atoi(_t[0]) - if err != nil { - return ret, err - } - t += hour * 60 * 60 * ClockTicks - - mins, err := strconv.Atoi(_t[1]) - if err != nil { - return ret, err - } - t += mins * 60 * ClockTicks - _tmp = _t[2] - case 2: - mins, err := strconv.Atoi(_t[0]) - if err != nil { - return ret, err - } - t += mins * 60 * ClockTicks - _tmp = _t[1] - case 1, 0: - _tmp = s - default: - return ret, fmt.Errorf("wrong cpu time string") - } - } else { - _tmp = s - } - - _t := strings.Split(_tmp, ".") - if err != nil { - return ret, err - } - h, err := strconv.Atoi(_t[0]) - t += h * ClockTicks - h, err = strconv.Atoi(_t[1]) - t += h - return float64(t) / float64(ClockTicks), nil -} - -func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { - r, err := callPsWithContext(ctx, "utime,stime", p.Pid, false, false) - - if err != nil { - return nil, err - } - - utime, err := convertCPUTimes(r[0][0]) - if err != nil { - return nil, err - } - stime, err := convertCPUTimes(r[0][1]) - if err != nil { - return nil, err - } - - ret := &cpu.TimesStat{ - CPU: "cpu", - User: utime, - System: stime, - } - return ret, nil -} - -func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { - r, err := callPsWithContext(ctx, "rss,vsize,pagein", p.Pid, false, false) - if err != nil { - return nil, err - } - rss, err := strconv.Atoi(r[0][0]) - if err != nil { - return nil, err - } - vms, err := strconv.Atoi(r[0][1]) - if err != nil { - return nil, err - } - pagein, err := strconv.Atoi(r[0][2]) - if err != nil { - return nil, err - } - - ret := &MemoryInfoStat{ - RSS: uint64(rss) * 1024, - VMS: uint64(vms) * 1024, - Swap: uint64(pagein), - } - - return ret, nil -} - -func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { - pids, err := common.CallPgrepWithContext(ctx, invoke, p.Pid) - if err != nil { - return nil, err - } - ret := make([]*Process, 0, len(pids)) - for _, pid := range pids { - np, err := NewProcessWithContext(ctx, pid) - if err != nil { - return nil, err - } - ret = append(ret, np) - } - return ret, nil -} - -func (p *Process) ConnectionsWithContext(ctx context.Context) ([]net.ConnectionStat, error) { - return net.ConnectionsPidWithContext(ctx, "all", p.Pid) -} - -func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net.ConnectionStat, error) { - return net.ConnectionsPidMaxWithContext(ctx, "all", p.Pid, max) -} - -func ProcessesWithContext(ctx context.Context) ([]*Process, error) { - out := []*Process{} - - pids, err := PidsWithContext(ctx) - if err != nil { - return out, err - } - - for _, pid := range pids { - p, err := NewProcessWithContext(ctx, pid) - if err != nil { - continue - } - out = append(out, p) - } - - return out, nil -} - -// Returns a proc as defined here: -// http://unix.superglobalmegacorp.com/Net2/newsrc/sys/kinfo_proc.h.html -func (p *Process) getKProc() (*KinfoProc, error) { - buf, err := unix.SysctlRaw("kern.proc.pid", int(p.Pid)) - if err != nil { - return nil, err - } - k, err := parseKinfoProc(buf) - if err != nil { - return nil, err - } - - return &k, nil -} - -// call ps command. -// Return value deletes Header line(you must not input wrong arg). -// And split by space. Caller have responsibility to manage. -// If passed arg pid is 0, get information from all process. -func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption bool, nameOption bool) ([][]string, error) { - bin, err := exec.LookPath("ps") - if err != nil { - return [][]string{}, err - } - - var cmd []string - if pid == 0 { // will get from all processes. - cmd = []string{"-ax", "-o", arg} - } else if threadOption { - cmd = []string{"-x", "-o", arg, "-M", "-p", strconv.Itoa(int(pid))} - } else { - cmd = []string{"-x", "-o", arg, "-p", strconv.Itoa(int(pid))} - } - - if nameOption { - cmd = append(cmd, "-c") - } - out, err := invoke.CommandWithContext(ctx, bin, cmd...) - if err != nil { - return [][]string{}, err - } - lines := strings.Split(string(out), "\n") - - var ret [][]string - for _, l := range lines[1:] { - - var lr []string - if nameOption { - lr = append(lr, l) - } else { - for _, r := range strings.Split(l, " ") { - if r == "" { - continue - } - lr = append(lr, strings.TrimSpace(r)) - } - } - - if len(lr) != 0 { - ret = append(ret, lr) - } - } - - return ret, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_386.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_386.go deleted file mode 100644 index f8e922385..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_386.go +++ /dev/null @@ -1,234 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_darwin.go - -package process - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int32 - Pad_cgo_0 [4]byte -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type UGid_t uint32 - -type KinfoProc struct { - Proc ExternProc - Eproc Eproc -} - -type Eproc struct { - Paddr *uint64 - Sess *Session - Pcred Upcred - Ucred Uucred - Pad_cgo_0 [4]byte - Vm Vmspace - Ppid int32 - Pgid int32 - Jobc int16 - Pad_cgo_1 [2]byte - Tdev int32 - Tpgid int32 - Pad_cgo_2 [4]byte - Tsess *Session - Wmesg [8]int8 - Xsize int32 - Xrssize int16 - Xccount int16 - Xswrss int16 - Pad_cgo_3 [2]byte - Flag int32 - Login [12]int8 - Spare [4]int32 - Pad_cgo_4 [4]byte -} - -type Proc struct{} - -type Session struct{} - -type ucred struct { - Link _Ctype_struct___0 - Ref uint64 - Posix Posix_cred - Label *Label - Audit Au_session -} - -type Uucred struct { - Ref int32 - UID uint32 - Ngroups int16 - Pad_cgo_0 [2]byte - Groups [16]uint32 -} - -type Upcred struct { - Pc_lock [72]int8 - Pc_ucred *ucred - P_ruid uint32 - P_svuid uint32 - P_rgid uint32 - P_svgid uint32 - P_refcnt int32 - Pad_cgo_0 [4]byte -} - -type Vmspace struct { - Dummy int32 - Pad_cgo_0 [4]byte - Dummy2 *int8 - Dummy3 [5]int32 - Pad_cgo_1 [4]byte - Dummy4 [3]*int8 -} - -type Sigacts struct{} - -type ExternProc struct { - P_un [16]byte - P_vmspace uint64 - P_sigacts uint64 - Pad_cgo_0 [3]byte - P_flag int32 - P_stat int8 - P_pid int32 - P_oppid int32 - P_dupfd int32 - Pad_cgo_1 [4]byte - User_stack uint64 - Exit_thread uint64 - P_debugger int32 - Sigwait int32 - P_estcpu uint32 - P_cpticks int32 - P_pctcpu uint32 - Pad_cgo_2 [4]byte - P_wchan uint64 - P_wmesg uint64 - P_swtime uint32 - P_slptime uint32 - P_realtimer Itimerval - P_rtime Timeval - P_uticks uint64 - P_sticks uint64 - P_iticks uint64 - P_traceflag int32 - Pad_cgo_3 [4]byte - P_tracep uint64 - P_siglist int32 - Pad_cgo_4 [4]byte - P_textvp uint64 - P_holdcnt int32 - P_sigmask uint32 - P_sigignore uint32 - P_sigcatch uint32 - P_priority uint8 - P_usrpri uint8 - P_nice int8 - P_comm [17]int8 - Pad_cgo_5 [4]byte - P_pgrp uint64 - P_addr uint64 - P_xstat uint16 - P_acflag uint16 - Pad_cgo_6 [4]byte - P_ru uint64 -} - -type Itimerval struct { - Interval Timeval - Value Timeval -} - -type Vnode struct{} - -type Pgrp struct{} - -type UserStruct struct{} - -type Au_session struct { - Aia_p *AuditinfoAddr - Mask AuMask -} - -type Posix_cred struct { - UID uint32 - Ruid uint32 - Svuid uint32 - Ngroups int16 - Pad_cgo_0 [2]byte - Groups [16]uint32 - Rgid uint32 - Svgid uint32 - Gmuid uint32 - Flags int32 -} - -type Label struct{} - -type AuditinfoAddr struct { - Auid uint32 - Mask AuMask - Termid AuTidAddr - Asid int32 - Flags uint64 -} -type AuMask struct { - Success uint32 - Failure uint32 -} -type AuTidAddr struct { - Port int32 - Type uint32 - Addr [4]uint32 -} - -type UcredQueue struct { - Next *ucred - Prev **ucred -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_amd64.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_amd64.go deleted file mode 100644 index f8e922385..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_amd64.go +++ /dev/null @@ -1,234 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_darwin.go - -package process - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int32 - Pad_cgo_0 [4]byte -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type UGid_t uint32 - -type KinfoProc struct { - Proc ExternProc - Eproc Eproc -} - -type Eproc struct { - Paddr *uint64 - Sess *Session - Pcred Upcred - Ucred Uucred - Pad_cgo_0 [4]byte - Vm Vmspace - Ppid int32 - Pgid int32 - Jobc int16 - Pad_cgo_1 [2]byte - Tdev int32 - Tpgid int32 - Pad_cgo_2 [4]byte - Tsess *Session - Wmesg [8]int8 - Xsize int32 - Xrssize int16 - Xccount int16 - Xswrss int16 - Pad_cgo_3 [2]byte - Flag int32 - Login [12]int8 - Spare [4]int32 - Pad_cgo_4 [4]byte -} - -type Proc struct{} - -type Session struct{} - -type ucred struct { - Link _Ctype_struct___0 - Ref uint64 - Posix Posix_cred - Label *Label - Audit Au_session -} - -type Uucred struct { - Ref int32 - UID uint32 - Ngroups int16 - Pad_cgo_0 [2]byte - Groups [16]uint32 -} - -type Upcred struct { - Pc_lock [72]int8 - Pc_ucred *ucred - P_ruid uint32 - P_svuid uint32 - P_rgid uint32 - P_svgid uint32 - P_refcnt int32 - Pad_cgo_0 [4]byte -} - -type Vmspace struct { - Dummy int32 - Pad_cgo_0 [4]byte - Dummy2 *int8 - Dummy3 [5]int32 - Pad_cgo_1 [4]byte - Dummy4 [3]*int8 -} - -type Sigacts struct{} - -type ExternProc struct { - P_un [16]byte - P_vmspace uint64 - P_sigacts uint64 - Pad_cgo_0 [3]byte - P_flag int32 - P_stat int8 - P_pid int32 - P_oppid int32 - P_dupfd int32 - Pad_cgo_1 [4]byte - User_stack uint64 - Exit_thread uint64 - P_debugger int32 - Sigwait int32 - P_estcpu uint32 - P_cpticks int32 - P_pctcpu uint32 - Pad_cgo_2 [4]byte - P_wchan uint64 - P_wmesg uint64 - P_swtime uint32 - P_slptime uint32 - P_realtimer Itimerval - P_rtime Timeval - P_uticks uint64 - P_sticks uint64 - P_iticks uint64 - P_traceflag int32 - Pad_cgo_3 [4]byte - P_tracep uint64 - P_siglist int32 - Pad_cgo_4 [4]byte - P_textvp uint64 - P_holdcnt int32 - P_sigmask uint32 - P_sigignore uint32 - P_sigcatch uint32 - P_priority uint8 - P_usrpri uint8 - P_nice int8 - P_comm [17]int8 - Pad_cgo_5 [4]byte - P_pgrp uint64 - P_addr uint64 - P_xstat uint16 - P_acflag uint16 - Pad_cgo_6 [4]byte - P_ru uint64 -} - -type Itimerval struct { - Interval Timeval - Value Timeval -} - -type Vnode struct{} - -type Pgrp struct{} - -type UserStruct struct{} - -type Au_session struct { - Aia_p *AuditinfoAddr - Mask AuMask -} - -type Posix_cred struct { - UID uint32 - Ruid uint32 - Svuid uint32 - Ngroups int16 - Pad_cgo_0 [2]byte - Groups [16]uint32 - Rgid uint32 - Svgid uint32 - Gmuid uint32 - Flags int32 -} - -type Label struct{} - -type AuditinfoAddr struct { - Auid uint32 - Mask AuMask - Termid AuTidAddr - Asid int32 - Flags uint64 -} -type AuMask struct { - Success uint32 - Failure uint32 -} -type AuTidAddr struct { - Port int32 - Type uint32 - Addr [4]uint32 -} - -type UcredQueue struct { - Next *ucred - Prev **ucred -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_arm64.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_arm64.go deleted file mode 100644 index 92bd4259b..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_arm64.go +++ /dev/null @@ -1,212 +0,0 @@ -// +build darwin -// +build arm64 -// Code generated by cmd/cgo -godefs; DO NOT EDIT. -// cgo -godefs process/types_darwin.go - -package process - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int32 - Pad_cgo_0 [4]byte -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type UGid_t uint32 - -type KinfoProc struct { - Proc ExternProc - Eproc Eproc -} - -type Eproc struct { - Paddr *Proc - Sess *Session - Pcred Upcred - Ucred Uucred - Vm Vmspace - Ppid int32 - Pgid int32 - Jobc int16 - Tdev int32 - Tpgid int32 - Tsess *Session - Wmesg [8]int8 - Xsize int32 - Xrssize int16 - Xccount int16 - Xswrss int16 - Flag int32 - Login [12]int8 - Spare [4]int32 - Pad_cgo_0 [4]byte -} - -type Proc struct{} - -type Session struct{} - -type ucred struct{} - -type Uucred struct { - Ref int32 - UID uint32 - Ngroups int16 - Groups [16]uint32 -} - -type Upcred struct { - Pc_lock [72]int8 - Pc_ucred *ucred - P_ruid uint32 - P_svuid uint32 - P_rgid uint32 - P_svgid uint32 - P_refcnt int32 - Pad_cgo_0 [4]byte -} - -type Vmspace struct { - Dummy int32 - Dummy2 *int8 - Dummy3 [5]int32 - Dummy4 [3]*int8 -} - -type Sigacts struct{} - -type ExternProc struct { - P_un [16]byte - P_vmspace uint64 - P_sigacts uint64 - Pad_cgo_0 [3]byte - P_flag int32 - P_stat int8 - P_pid int32 - P_oppid int32 - P_dupfd int32 - Pad_cgo_1 [4]byte - User_stack uint64 - Exit_thread uint64 - P_debugger int32 - Sigwait int32 - P_estcpu uint32 - P_cpticks int32 - P_pctcpu uint32 - Pad_cgo_2 [4]byte - P_wchan uint64 - P_wmesg uint64 - P_swtime uint32 - P_slptime uint32 - P_realtimer Itimerval - P_rtime Timeval - P_uticks uint64 - P_sticks uint64 - P_iticks uint64 - P_traceflag int32 - Pad_cgo_3 [4]byte - P_tracep uint64 - P_siglist int32 - Pad_cgo_4 [4]byte - P_textvp uint64 - P_holdcnt int32 - P_sigmask uint32 - P_sigignore uint32 - P_sigcatch uint32 - P_priority uint8 - P_usrpri uint8 - P_nice int8 - P_comm [17]int8 - Pad_cgo_5 [4]byte - P_pgrp uint64 - P_addr uint64 - P_xstat uint16 - P_acflag uint16 - Pad_cgo_6 [4]byte - P_ru uint64 -} - -type Itimerval struct { - Interval Timeval - Value Timeval -} - -type Vnode struct{} - -type Pgrp struct{} - -type UserStruct struct{} - -type Au_session struct { - Aia_p *AuditinfoAddr - Mask AuMask -} - -type Posix_cred struct{} - -type Label struct{} - -type AuditinfoAddr struct { - Auid uint32 - Mask AuMask - Termid AuTidAddr - Asid int32 - Flags uint64 -} -type AuMask struct { - Success uint32 - Failure uint32 -} -type AuTidAddr struct { - Port int32 - Type uint32 - Addr [4]uint32 -} - -type UcredQueue struct { - Next *ucred - Prev **ucred -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_cgo.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_cgo.go deleted file mode 100644 index a80817755..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_cgo.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build darwin -// +build cgo - -package process - -// #include -// #include -import "C" -import ( - "context" - "fmt" - "unsafe" -) - -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { - var c C.char // need a var for unsafe.Sizeof need a var - const bufsize = C.PROC_PIDPATHINFO_MAXSIZE * unsafe.Sizeof(c) - buffer := (*C.char)(C.malloc(C.size_t(bufsize))) - defer C.free(unsafe.Pointer(buffer)) - - ret, err := C.proc_pidpath(C.int(p.Pid), unsafe.Pointer(buffer), C.uint32_t(bufsize)) - if err != nil { - return "", err - } - if ret <= 0 { - return "", fmt.Errorf("unknown error: proc_pidpath returned %d", ret) - } - - return C.GoString(buffer), nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_nocgo.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_nocgo.go deleted file mode 100644 index 3583e1987..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_darwin_nocgo.go +++ /dev/null @@ -1,34 +0,0 @@ -// +build darwin -// +build !cgo - -package process - -import ( - "context" - "fmt" - "os/exec" - "strconv" - "strings" -) - -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { - lsof_bin, err := exec.LookPath("lsof") - if err != nil { - return "", err - } - out, err := invoke.CommandWithContext(ctx, lsof_bin, "-p", strconv.Itoa(int(p.Pid)), "-Fpfn") - if err != nil { - return "", fmt.Errorf("bad call to lsof: %s", err) - } - txtFound := 0 - lines := strings.Split(string(out), "\n") - for i := 1; i < len(lines); i++ { - if lines[i] == "ftxt" { - txtFound++ - if txtFound == 2 { - return lines[i-1][1:], nil - } - } - } - return "", fmt.Errorf("missing txt data returned by lsof") -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_fallback.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_fallback.go deleted file mode 100644 index 0d54900b1..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_fallback.go +++ /dev/null @@ -1,209 +0,0 @@ -// +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris - -package process - -import ( - "context" - "syscall" - - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" -) - -type MemoryMapsStat struct { - Path string `json:"path"` - Rss uint64 `json:"rss"` - Size uint64 `json:"size"` - Pss uint64 `json:"pss"` - SharedClean uint64 `json:"sharedClean"` - SharedDirty uint64 `json:"sharedDirty"` - PrivateClean uint64 `json:"privateClean"` - PrivateDirty uint64 `json:"privateDirty"` - Referenced uint64 `json:"referenced"` - Anonymous uint64 `json:"anonymous"` - Swap uint64 `json:"swap"` -} - -type MemoryInfoExStat struct { -} - -func pidsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func ProcessesWithContext(ctx context.Context) ([]*Process, error) { - return nil, common.ErrNotImplementedError -} - -func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { - return false, common.ErrNotImplementedError -} - -func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) NameWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) TgidWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) CwdWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { - return false, common.ErrNotImplementedError -} - -func (p *Process) UidsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) GidsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) GroupsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) TerminalWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) NiceWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) IOniceWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) RlimitWithContext(ctx context.Context) ([]RlimitStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) RlimitUsageWithContext(ctx context.Context, gatherUsed bool) ([]RlimitStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) IOCountersWithContext(ctx context.Context) (*IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NumCtxSwitchesWithContext(ctx context.Context) (*NumCtxSwitchesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NumFDsWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) ThreadsWithContext(ctx context.Context) (map[int32]*cpu.TimesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) CPUAffinityWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryInfoExWithContext(ctx context.Context) (*MemoryInfoExStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) PageFaultsWithContext(ctx context.Context) (*PageFaultsStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) OpenFilesWithContext(ctx context.Context) ([]OpenFilesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) ConnectionsWithContext(ctx context.Context) ([]net.ConnectionStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net.ConnectionStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) SendSignalWithContext(ctx context.Context, sig syscall.Signal) error { - return common.ErrNotImplementedError -} - -func (p *Process) SuspendWithContext(ctx context.Context) error { - return common.ErrNotImplementedError -} - -func (p *Process) ResumeWithContext(ctx context.Context) error { - return common.ErrNotImplementedError -} - -func (p *Process) TerminateWithContext(ctx context.Context) error { - return common.ErrNotImplementedError -} - -func (p *Process) KillWithContext(ctx context.Context) error { - return common.ErrNotImplementedError -} - -func (p *Process) UsernameWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) EnvironWithContext(ctx context.Context) ([]string, error) { - return nil, common.ErrNotImplementedError -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd.go deleted file mode 100644 index 0666e7f42..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd.go +++ /dev/null @@ -1,338 +0,0 @@ -// +build freebsd - -package process - -import ( - "bytes" - "context" - "os/exec" - "path/filepath" - "strconv" - "strings" - - cpu "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - net "github.com/shirou/gopsutil/net" - "golang.org/x/sys/unix" -) - -func pidsWithContext(ctx context.Context) ([]int32, error) { - var ret []int32 - procs, err := ProcessesWithContext(ctx) - if err != nil { - return ret, nil - } - - for _, p := range procs { - ret = append(ret, p.Pid) - } - - return ret, nil -} - -func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { - k, err := p.getKProc() - if err != nil { - return 0, err - } - - return k.Ppid, nil -} - -func (p *Process) NameWithContext(ctx context.Context) (string, error) { - k, err := p.getKProc() - if err != nil { - return "", err - } - name := common.IntToString(k.Comm[:]) - - if len(name) >= 15 { - cmdlineSlice, err := p.CmdlineSliceWithContext(ctx) - if err != nil { - return "", err - } - if len(cmdlineSlice) > 0 { - extendedName := filepath.Base(cmdlineSlice[0]) - if strings.HasPrefix(extendedName, p.name) { - name = extendedName - } else { - name = cmdlineSlice[0] - } - } - } - - return name, nil -} - -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { - mib := []int32{CTLKern, KernProc, KernProcArgs, p.Pid} - buf, _, err := common.CallSyscall(mib) - if err != nil { - return "", err - } - ret := strings.FieldsFunc(string(buf), func(r rune) bool { - if r == '\u0000' { - return true - } - return false - }) - - return strings.Join(ret, " "), nil -} - -func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { - mib := []int32{CTLKern, KernProc, KernProcArgs, p.Pid} - buf, _, err := common.CallSyscall(mib) - if err != nil { - return nil, err - } - if len(buf) == 0 { - return nil, nil - } - if buf[len(buf)-1] == 0 { - buf = buf[:len(buf)-1] - } - parts := bytes.Split(buf, []byte{0}) - var strParts []string - for _, p := range parts { - strParts = append(strParts, string(p)) - } - - return strParts, nil -} - -func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - k, err := p.getKProc() - if err != nil { - return "", err - } - var s string - switch k.Stat { - case SIDL: - s = "I" - case SRUN: - s = "R" - case SSLEEP: - s = "S" - case SSTOP: - s = "T" - case SZOMB: - s = "Z" - case SWAIT: - s = "W" - case SLOCK: - s = "L" - } - - return s, nil -} - -func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { - // see https://github.com/shirou/gopsutil/issues/596#issuecomment-432707831 for implementation details - pid := p.Pid - ps, err := exec.LookPath("ps") - if err != nil { - return false, err - } - out, err := invoke.CommandWithContext(ctx, ps, "-o", "stat=", "-p", strconv.Itoa(int(pid))) - if err != nil { - return false, err - } - return strings.IndexByte(string(out), '+') != -1, nil -} - -func (p *Process) UidsWithContext(ctx context.Context) ([]int32, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - - uids := make([]int32, 0, 3) - - uids = append(uids, int32(k.Ruid), int32(k.Uid), int32(k.Svuid)) - - return uids, nil -} - -func (p *Process) GidsWithContext(ctx context.Context) ([]int32, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - - gids := make([]int32, 0, 3) - gids = append(gids, int32(k.Rgid), int32(k.Ngroups), int32(k.Svgid)) - - return gids, nil -} - -func (p *Process) GroupsWithContext(ctx context.Context) ([]int32, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - - groups := make([]int32, k.Ngroups) - for i := int16(0); i < k.Ngroups; i++ { - groups[i] = int32(k.Groups[i]) - } - - return groups, nil -} - -func (p *Process) TerminalWithContext(ctx context.Context) (string, error) { - k, err := p.getKProc() - if err != nil { - return "", err - } - - ttyNr := uint64(k.Tdev) - - termmap, err := getTerminalMap() - if err != nil { - return "", err - } - - return termmap[ttyNr], nil -} - -func (p *Process) NiceWithContext(ctx context.Context) (int32, error) { - k, err := p.getKProc() - if err != nil { - return 0, err - } - return int32(k.Nice), nil -} - -func (p *Process) IOCountersWithContext(ctx context.Context) (*IOCountersStat, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - return &IOCountersStat{ - ReadCount: uint64(k.Rusage.Inblock), - WriteCount: uint64(k.Rusage.Oublock), - }, nil -} - -func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { - k, err := p.getKProc() - if err != nil { - return 0, err - } - - return k.Numthreads, nil -} - -func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - return &cpu.TimesStat{ - CPU: "cpu", - User: float64(k.Rusage.Utime.Sec) + float64(k.Rusage.Utime.Usec)/1000000, - System: float64(k.Rusage.Stime.Sec) + float64(k.Rusage.Stime.Usec)/1000000, - }, nil -} - -func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - v, err := unix.Sysctl("vm.stats.vm.v_page_size") - if err != nil { - return nil, err - } - pageSize := common.LittleEndian.Uint16([]byte(v)) - - return &MemoryInfoStat{ - RSS: uint64(k.Rssize) * uint64(pageSize), - VMS: uint64(k.Size), - }, nil -} - -func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { - pids, err := common.CallPgrepWithContext(ctx, invoke, p.Pid) - if err != nil { - return nil, err - } - ret := make([]*Process, 0, len(pids)) - for _, pid := range pids { - np, err := NewProcessWithContext(ctx, pid) - if err != nil { - return nil, err - } - ret = append(ret, np) - } - return ret, nil -} - -func (p *Process) ConnectionsWithContext(ctx context.Context) ([]net.ConnectionStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net.ConnectionStat, error) { - return nil, common.ErrNotImplementedError -} - -func ProcessesWithContext(ctx context.Context) ([]*Process, error) { - results := []*Process{} - - mib := []int32{CTLKern, KernProc, KernProcProc, 0} - buf, length, err := common.CallSyscall(mib) - if err != nil { - return results, err - } - - // get kinfo_proc size - count := int(length / uint64(sizeOfKinfoProc)) - - // parse buf to procs - for i := 0; i < count; i++ { - b := buf[i*sizeOfKinfoProc : (i+1)*sizeOfKinfoProc] - k, err := parseKinfoProc(b) - if err != nil { - continue - } - p, err := NewProcessWithContext(ctx, int32(k.Pid)) - if err != nil { - continue - } - - results = append(results, p) - } - - return results, nil -} - -func (p *Process) getKProc() (*KinfoProc, error) { - mib := []int32{CTLKern, KernProc, KernProcPID, p.Pid} - - buf, length, err := common.CallSyscall(mib) - if err != nil { - return nil, err - } - if length != sizeOfKinfoProc { - return nil, err - } - - k, err := parseKinfoProc(buf) - if err != nil { - return nil, err - } - return &k, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_386.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_386.go deleted file mode 100644 index 08ab333b4..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_386.go +++ /dev/null @@ -1,192 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_freebsd.go - -package process - -const ( - CTLKern = 1 - KernProc = 14 - KernProcPID = 1 - KernProcProc = 8 - KernProcPathname = 12 - KernProcArgs = 7 -) - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -const ( - sizeOfKinfoVmentry = 0x488 - sizeOfKinfoProc = 0x300 -) - -const ( - SIDL = 1 - SRUN = 2 - SSLEEP = 3 - SSTOP = 4 - SZOMB = 5 - SWAIT = 6 - SLOCK = 7 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int32 - Nsec int32 -} - -type Timeval struct { - Sec int32 - Usec int32 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur int64 - Max int64 -} - -type KinfoProc struct { - Structsize int32 - Layout int32 - Args int32 /* pargs */ - Paddr int32 /* proc */ - Addr int32 /* user */ - Tracep int32 /* vnode */ - Textvp int32 /* vnode */ - Fd int32 /* filedesc */ - Vmspace int32 /* vmspace */ - Wchan int32 - Pid int32 - Ppid int32 - Pgid int32 - Tpgid int32 - Sid int32 - Tsid int32 - Jobc int16 - Spare_short1 int16 - Tdev uint32 - Siglist [16]byte /* sigset */ - Sigmask [16]byte /* sigset */ - Sigignore [16]byte /* sigset */ - Sigcatch [16]byte /* sigset */ - Uid uint32 - Ruid uint32 - Svuid uint32 - Rgid uint32 - Svgid uint32 - Ngroups int16 - Spare_short2 int16 - Groups [16]uint32 - Size uint32 - Rssize int32 - Swrss int32 - Tsize int32 - Dsize int32 - Ssize int32 - Xstat uint16 - Acflag uint16 - Pctcpu uint32 - Estcpu uint32 - Slptime uint32 - Swtime uint32 - Cow uint32 - Runtime uint64 - Start Timeval - Childtime Timeval - Flag int32 - Kiflag int32 - Traceflag int32 - Stat int8 - Nice int8 - Lock int8 - Rqindex int8 - Oncpu uint8 - Lastcpu uint8 - Tdname [17]int8 - Wmesg [9]int8 - Login [18]int8 - Lockname [9]int8 - Comm [20]int8 - Emul [17]int8 - Loginclass [18]int8 - Sparestrings [50]int8 - Spareints [7]int32 - Flag2 int32 - Fibnum int32 - Cr_flags uint32 - Jid int32 - Numthreads int32 - Tid int32 - Pri Priority - Rusage Rusage - Rusage_ch Rusage - Pcb int32 /* pcb */ - Kstack int32 - Udata int32 - Tdaddr int32 /* thread */ - Spareptrs [6]int32 - Sparelongs [12]int32 - Sflag int32 - Tdflags int32 -} - -type Priority struct { - Class uint8 - Level uint8 - Native uint8 - User uint8 -} - -type KinfoVmentry struct { - Structsize int32 - Type int32 - Start uint64 - End uint64 - Offset uint64 - Vn_fileid uint64 - Vn_fsid uint32 - Flags int32 - Resident int32 - Private_resident int32 - Protection int32 - Ref_count int32 - Shadow_count int32 - Vn_type int32 - Vn_size uint64 - Vn_rdev uint32 - Vn_mode uint16 - Status uint16 - X_kve_ispare [12]int32 - Path [1024]int8 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_amd64.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_amd64.go deleted file mode 100644 index 560e627d2..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_amd64.go +++ /dev/null @@ -1,192 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_freebsd.go - -package process - -const ( - CTLKern = 1 - KernProc = 14 - KernProcPID = 1 - KernProcProc = 8 - KernProcPathname = 12 - KernProcArgs = 7 -) - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -const ( - sizeOfKinfoVmentry = 0x488 - sizeOfKinfoProc = 0x440 -) - -const ( - SIDL = 1 - SRUN = 2 - SSLEEP = 3 - SSTOP = 4 - SZOMB = 5 - SWAIT = 6 - SLOCK = 7 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur int64 - Max int64 -} - -type KinfoProc struct { - Structsize int32 - Layout int32 - Args int64 /* pargs */ - Paddr int64 /* proc */ - Addr int64 /* user */ - Tracep int64 /* vnode */ - Textvp int64 /* vnode */ - Fd int64 /* filedesc */ - Vmspace int64 /* vmspace */ - Wchan int64 - Pid int32 - Ppid int32 - Pgid int32 - Tpgid int32 - Sid int32 - Tsid int32 - Jobc int16 - Spare_short1 int16 - Tdev uint32 - Siglist [16]byte /* sigset */ - Sigmask [16]byte /* sigset */ - Sigignore [16]byte /* sigset */ - Sigcatch [16]byte /* sigset */ - Uid uint32 - Ruid uint32 - Svuid uint32 - Rgid uint32 - Svgid uint32 - Ngroups int16 - Spare_short2 int16 - Groups [16]uint32 - Size uint64 - Rssize int64 - Swrss int64 - Tsize int64 - Dsize int64 - Ssize int64 - Xstat uint16 - Acflag uint16 - Pctcpu uint32 - Estcpu uint32 - Slptime uint32 - Swtime uint32 - Cow uint32 - Runtime uint64 - Start Timeval - Childtime Timeval - Flag int64 - Kiflag int64 - Traceflag int32 - Stat int8 - Nice int8 - Lock int8 - Rqindex int8 - Oncpu uint8 - Lastcpu uint8 - Tdname [17]int8 - Wmesg [9]int8 - Login [18]int8 - Lockname [9]int8 - Comm [20]int8 - Emul [17]int8 - Loginclass [18]int8 - Sparestrings [50]int8 - Spareints [7]int32 - Flag2 int32 - Fibnum int32 - Cr_flags uint32 - Jid int32 - Numthreads int32 - Tid int32 - Pri Priority - Rusage Rusage - Rusage_ch Rusage - Pcb int64 /* pcb */ - Kstack int64 - Udata int64 - Tdaddr int64 /* thread */ - Spareptrs [6]int64 - Sparelongs [12]int64 - Sflag int64 - Tdflags int64 -} - -type Priority struct { - Class uint8 - Level uint8 - Native uint8 - User uint8 -} - -type KinfoVmentry struct { - Structsize int32 - Type int32 - Start uint64 - End uint64 - Offset uint64 - Vn_fileid uint64 - Vn_fsid uint32 - Flags int32 - Resident int32 - Private_resident int32 - Protection int32 - Ref_count int32 - Shadow_count int32 - Vn_type int32 - Vn_size uint64 - Vn_rdev uint32 - Vn_mode uint16 - Status uint16 - X_kve_ispare [12]int32 - Path [1024]int8 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm.go deleted file mode 100644 index 81ae0b9a8..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm.go +++ /dev/null @@ -1,192 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_freebsd.go - -package process - -const ( - CTLKern = 1 - KernProc = 14 - KernProcPID = 1 - KernProcProc = 8 - KernProcPathname = 12 - KernProcArgs = 7 -) - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -const ( - sizeOfKinfoVmentry = 0x488 - sizeOfKinfoProc = 0x440 -) - -const ( - SIDL = 1 - SRUN = 2 - SSLEEP = 3 - SSTOP = 4 - SZOMB = 5 - SWAIT = 6 - SLOCK = 7 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur int32 - Max int32 -} - -type KinfoProc struct { - Structsize int32 - Layout int32 - Args int32 /* pargs */ - Paddr int32 /* proc */ - Addr int32 /* user */ - Tracep int32 /* vnode */ - Textvp int32 /* vnode */ - Fd int32 /* filedesc */ - Vmspace int32 /* vmspace */ - Wchan int32 - Pid int32 - Ppid int32 - Pgid int32 - Tpgid int32 - Sid int32 - Tsid int32 - Jobc int16 - Spare_short1 int16 - Tdev uint32 - Siglist [16]byte /* sigset */ - Sigmask [16]byte /* sigset */ - Sigignore [16]byte /* sigset */ - Sigcatch [16]byte /* sigset */ - Uid uint32 - Ruid uint32 - Svuid uint32 - Rgid uint32 - Svgid uint32 - Ngroups int16 - Spare_short2 int16 - Groups [16]uint32 - Size uint32 - Rssize int32 - Swrss int32 - Tsize int32 - Dsize int32 - Ssize int32 - Xstat uint16 - Acflag uint16 - Pctcpu uint32 - Estcpu uint32 - Slptime uint32 - Swtime uint32 - Cow uint32 - Runtime uint64 - Start Timeval - Childtime Timeval - Flag int32 - Kiflag int32 - Traceflag int32 - Stat int8 - Nice int8 - Lock int8 - Rqindex int8 - Oncpu uint8 - Lastcpu uint8 - Tdname [17]int8 - Wmesg [9]int8 - Login [18]int8 - Lockname [9]int8 - Comm [20]int8 - Emul [17]int8 - Loginclass [18]int8 - Sparestrings [50]int8 - Spareints [4]int32 - Flag2 int32 - Fibnum int32 - Cr_flags uint32 - Jid int32 - Numthreads int32 - Tid int32 - Pri Priority - Rusage Rusage - Rusage_ch Rusage - Pcb int32 /* pcb */ - Kstack int32 - Udata int32 - Tdaddr int32 /* thread */ - Spareptrs [6]int64 - Sparelongs [12]int64 - Sflag int64 - Tdflags int64 -} - -type Priority struct { - Class uint8 - Level uint8 - Native uint8 - User uint8 -} - -type KinfoVmentry struct { - Structsize int32 - Type int32 - Start uint64 - End uint64 - Offset uint64 - Vn_fileid uint64 - Vn_fsid uint32 - Flags int32 - Resident int32 - Private_resident int32 - Protection int32 - Ref_count int32 - Shadow_count int32 - Vn_type int32 - Vn_size uint64 - Vn_rdev uint32 - Vn_mode uint16 - Status uint16 - X_kve_ispare [12]int32 - Path [1024]int8 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm64.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm64.go deleted file mode 100644 index 99781d1a2..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_freebsd_arm64.go +++ /dev/null @@ -1,201 +0,0 @@ -// +build freebsd -// +build arm64 -// Code generated by cmd/cgo -godefs; DO NOT EDIT. -// cgo -godefs process/types_freebsd.go - -package process - -const ( - CTLKern = 1 - KernProc = 14 - KernProcPID = 1 - KernProcProc = 8 - KernProcPathname = 12 - KernProcArgs = 7 -) - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -const ( - sizeOfKinfoVmentry = 0x488 - sizeOfKinfoProc = 0x440 -) - -const ( - SIDL = 1 - SRUN = 2 - SSLEEP = 3 - SSTOP = 4 - SZOMB = 5 - SWAIT = 6 - SLOCK = 7 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur int64 - Max int64 -} - -type KinfoProc struct { - Structsize int32 - Layout int32 - Args *int64 /* pargs */ - Paddr *int64 /* proc */ - Addr *int64 /* user */ - Tracep *int64 /* vnode */ - Textvp *int64 /* vnode */ - Fd *int64 /* filedesc */ - Vmspace *int64 /* vmspace */ - Wchan *byte - Pid int32 - Ppid int32 - Pgid int32 - Tpgid int32 - Sid int32 - Tsid int32 - Jobc int16 - Spare_short1 int16 - Tdev_freebsd11 uint32 - Siglist [16]byte /* sigset */ - Sigmask [16]byte /* sigset */ - Sigignore [16]byte /* sigset */ - Sigcatch [16]byte /* sigset */ - Uid uint32 - Ruid uint32 - Svuid uint32 - Rgid uint32 - Svgid uint32 - Ngroups int16 - Spare_short2 int16 - Groups [16]uint32 - Size uint64 - Rssize int64 - Swrss int64 - Tsize int64 - Dsize int64 - Ssize int64 - Xstat uint16 - Acflag uint16 - Pctcpu uint32 - Estcpu uint32 - Slptime uint32 - Swtime uint32 - Cow uint32 - Runtime uint64 - Start Timeval - Childtime Timeval - Flag int64 - Kiflag int64 - Traceflag int32 - Stat uint8 - Nice int8 - Lock uint8 - Rqindex uint8 - Oncpu_old uint8 - Lastcpu_old uint8 - Tdname [17]uint8 - Wmesg [9]uint8 - Login [18]uint8 - Lockname [9]uint8 - Comm [20]int8 - Emul [17]uint8 - Loginclass [18]uint8 - Moretdname [4]uint8 - Sparestrings [46]uint8 - Spareints [2]int32 - Tdev uint64 - Oncpu int32 - Lastcpu int32 - Tracer int32 - Flag2 int32 - Fibnum int32 - Cr_flags uint32 - Jid int32 - Numthreads int32 - Tid int32 - Pri Priority - Rusage Rusage - Rusage_ch Rusage - Pcb *int64 /* pcb */ - Kstack *byte - Udata *byte - Tdaddr *int64 /* thread */ - Spareptrs [6]*byte - Sparelongs [12]int64 - Sflag int64 - Tdflags int64 -} - -type Priority struct { - Class uint8 - Level uint8 - Native uint8 - User uint8 -} - -type KinfoVmentry struct { - Structsize int32 - Type int32 - Start uint64 - End uint64 - Offset uint64 - Vn_fileid uint64 - Vn_fsid_freebsd11 uint32 - Flags int32 - Resident int32 - Private_resident int32 - Protection int32 - Ref_count int32 - Shadow_count int32 - Vn_type int32 - Vn_size uint64 - Vn_rdev_freebsd11 uint32 - Vn_mode uint16 - Status uint16 - Vn_fsid uint64 - Vn_rdev uint64 - X_kve_ispare [8]int32 - Path [1024]uint8 -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_linux.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_linux.go deleted file mode 100644 index de742fbde..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_linux.go +++ /dev/null @@ -1,1195 +0,0 @@ -// +build linux - -package process - -import ( - "bufio" - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "math" - "os" - "path/filepath" - "strconv" - "strings" - - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" - "github.com/tklauser/go-sysconf" - "golang.org/x/sys/unix" -) - -var PageSize = uint64(os.Getpagesize()) - -const PrioProcess = 0 // linux/resource.h - -var ClockTicks = 100 // default value - -func init() { - clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) - // ignore errors - if err == nil { - ClockTicks = int(clkTck) - } -} - -// MemoryInfoExStat is different between OSes -type MemoryInfoExStat struct { - RSS uint64 `json:"rss"` // bytes - VMS uint64 `json:"vms"` // bytes - Shared uint64 `json:"shared"` // bytes - Text uint64 `json:"text"` // bytes - Lib uint64 `json:"lib"` // bytes - Data uint64 `json:"data"` // bytes - Dirty uint64 `json:"dirty"` // bytes -} - -func (m MemoryInfoExStat) String() string { - s, _ := json.Marshal(m) - return string(s) -} - -type MemoryMapsStat struct { - Path string `json:"path"` - Rss uint64 `json:"rss"` - Size uint64 `json:"size"` - Pss uint64 `json:"pss"` - SharedClean uint64 `json:"sharedClean"` - SharedDirty uint64 `json:"sharedDirty"` - PrivateClean uint64 `json:"privateClean"` - PrivateDirty uint64 `json:"privateDirty"` - Referenced uint64 `json:"referenced"` - Anonymous uint64 `json:"anonymous"` - Swap uint64 `json:"swap"` -} - -// String returns JSON value of the process. -func (m MemoryMapsStat) String() string { - s, _ := json.Marshal(m) - return string(s) -} - -func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { - _, ppid, _, _, _, _, _, err := p.fillFromStatWithContext(ctx) - if err != nil { - return -1, err - } - return ppid, nil -} - -func (p *Process) NameWithContext(ctx context.Context) (string, error) { - if p.name == "" { - if err := p.fillNameWithContext(ctx); err != nil { - return "", err - } - } - return p.name, nil -} - -func (p *Process) TgidWithContext(ctx context.Context) (int32, error) { - if p.tgid == 0 { - if err := p.fillFromStatusWithContext(ctx); err != nil { - return 0, err - } - } - return p.tgid, nil -} - -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { - return p.fillFromExeWithContext(ctx) -} - -func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { - return p.fillFromCmdlineWithContext(ctx) -} - -func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { - return p.fillSliceFromCmdlineWithContext(ctx) -} - -func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { - _, _, _, createTime, _, _, _, err := p.fillFromStatWithContext(ctx) - if err != nil { - return 0, err - } - return createTime, nil -} - -func (p *Process) CwdWithContext(ctx context.Context) (string, error) { - return p.fillFromCwdWithContext(ctx) -} - -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - err := p.fillFromStatusWithContext(ctx) - if err != nil { - return nil, err - } - if p.parent == 0 { - return nil, fmt.Errorf("wrong number of parents") - } - return NewProcessWithContext(ctx, p.parent) -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - err := p.fillFromStatusWithContext(ctx) - if err != nil { - return "", err - } - return p.status, nil -} - -func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { - // see https://github.com/shirou/gopsutil/issues/596#issuecomment-432707831 for implementation details - pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "stat") - contents, err := ioutil.ReadFile(statPath) - if err != nil { - return false, err - } - fields := strings.Fields(string(contents)) - if len(fields) < 8 { - return false, fmt.Errorf("insufficient data in %s", statPath) - } - pgid := fields[4] - tpgid := fields[7] - return pgid == tpgid, nil -} - -func (p *Process) UidsWithContext(ctx context.Context) ([]int32, error) { - err := p.fillFromStatusWithContext(ctx) - if err != nil { - return []int32{}, err - } - return p.uids, nil -} - -func (p *Process) GidsWithContext(ctx context.Context) ([]int32, error) { - err := p.fillFromStatusWithContext(ctx) - if err != nil { - return []int32{}, err - } - return p.gids, nil -} - -func (p *Process) GroupsWithContext(ctx context.Context) ([]int32, error) { - err := p.fillFromStatusWithContext(ctx) - if err != nil { - return []int32{}, err - } - return p.groups, nil -} - -func (p *Process) TerminalWithContext(ctx context.Context) (string, error) { - t, _, _, _, _, _, _, err := p.fillFromStatWithContext(ctx) - if err != nil { - return "", err - } - termmap, err := getTerminalMap() - if err != nil { - return "", err - } - terminal := termmap[t] - return terminal, nil -} - -func (p *Process) NiceWithContext(ctx context.Context) (int32, error) { - _, _, _, _, _, nice, _, err := p.fillFromStatWithContext(ctx) - if err != nil { - return 0, err - } - return nice, nil -} - -func (p *Process) IOniceWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) RlimitWithContext(ctx context.Context) ([]RlimitStat, error) { - return p.RlimitUsageWithContext(ctx, false) -} - -func (p *Process) RlimitUsageWithContext(ctx context.Context, gatherUsed bool) ([]RlimitStat, error) { - rlimits, err := p.fillFromLimitsWithContext(ctx) - if !gatherUsed || err != nil { - return rlimits, err - } - - _, _, _, _, rtprio, nice, _, err := p.fillFromStatWithContext(ctx) - if err != nil { - return nil, err - } - if err := p.fillFromStatusWithContext(ctx); err != nil { - return nil, err - } - - for i := range rlimits { - rs := &rlimits[i] - switch rs.Resource { - case RLIMIT_CPU: - times, err := p.TimesWithContext(ctx) - if err != nil { - return nil, err - } - rs.Used = uint64(times.User + times.System) - case RLIMIT_DATA: - rs.Used = uint64(p.memInfo.Data) - case RLIMIT_STACK: - rs.Used = uint64(p.memInfo.Stack) - case RLIMIT_RSS: - rs.Used = uint64(p.memInfo.RSS) - case RLIMIT_NOFILE: - n, err := p.NumFDsWithContext(ctx) - if err != nil { - return nil, err - } - rs.Used = uint64(n) - case RLIMIT_MEMLOCK: - rs.Used = uint64(p.memInfo.Locked) - case RLIMIT_AS: - rs.Used = uint64(p.memInfo.VMS) - case RLIMIT_LOCKS: - //TODO we can get the used value from /proc/$pid/locks. But linux doesn't enforce it, so not a high priority. - case RLIMIT_SIGPENDING: - rs.Used = p.sigInfo.PendingProcess - case RLIMIT_NICE: - // The rlimit for nice is a little unusual, in that 0 means the niceness cannot be decreased beyond the current value, but it can be increased. - // So effectively: if rs.Soft == 0 { rs.Soft = rs.Used } - rs.Used = uint64(nice) - case RLIMIT_RTPRIO: - rs.Used = uint64(rtprio) - } - } - - return rlimits, err -} - -func (p *Process) IOCountersWithContext(ctx context.Context) (*IOCountersStat, error) { - return p.fillFromIOWithContext(ctx) -} - -func (p *Process) NumCtxSwitchesWithContext(ctx context.Context) (*NumCtxSwitchesStat, error) { - err := p.fillFromStatusWithContext(ctx) - if err != nil { - return nil, err - } - return p.numCtxSwitches, nil -} - -func (p *Process) NumFDsWithContext(ctx context.Context) (int32, error) { - _, fnames, err := p.fillFromfdListWithContext(ctx) - return int32(len(fnames)), err -} - -func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { - err := p.fillFromStatusWithContext(ctx) - if err != nil { - return 0, err - } - return p.numThreads, nil -} - -func (p *Process) ThreadsWithContext(ctx context.Context) (map[int32]*cpu.TimesStat, error) { - ret := make(map[int32]*cpu.TimesStat) - taskPath := common.HostProc(strconv.Itoa(int(p.Pid)), "task") - - tids, err := readPidsFromDir(taskPath) - if err != nil { - return nil, err - } - - for _, tid := range tids { - _, _, cpuTimes, _, _, _, _, err := p.fillFromTIDStatWithContext(ctx, tid) - if err != nil { - return nil, err - } - ret[tid] = cpuTimes - } - - return ret, nil -} - -func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { - _, _, cpuTimes, _, _, _, _, err := p.fillFromStatWithContext(ctx) - if err != nil { - return nil, err - } - return cpuTimes, nil -} - -func (p *Process) CPUAffinityWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { - meminfo, _, err := p.fillFromStatmWithContext(ctx) - if err != nil { - return nil, err - } - return meminfo, nil -} - -func (p *Process) MemoryInfoExWithContext(ctx context.Context) (*MemoryInfoExStat, error) { - _, memInfoEx, err := p.fillFromStatmWithContext(ctx) - if err != nil { - return nil, err - } - return memInfoEx, nil -} - -func (p *Process) PageFaultsWithContext(ctx context.Context) (*PageFaultsStat, error) { - _, _, _, _, _, _, pageFaults, err := p.fillFromStatWithContext(ctx) - if err != nil { - return nil, err - } - return pageFaults, nil - -} - -func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { - pids, err := common.CallPgrepWithContext(ctx, invoke, p.Pid) - if err != nil { - if len(pids) == 0 { - return nil, ErrorNoChildren - } - return nil, err - } - ret := make([]*Process, 0, len(pids)) - for _, pid := range pids { - np, err := NewProcessWithContext(ctx, pid) - if err != nil { - return nil, err - } - ret = append(ret, np) - } - return ret, nil -} - -func (p *Process) OpenFilesWithContext(ctx context.Context) ([]OpenFilesStat, error) { - _, ofs, err := p.fillFromfdWithContext(ctx) - if err != nil { - return nil, err - } - ret := make([]OpenFilesStat, len(ofs)) - for i, o := range ofs { - ret[i] = *o - } - - return ret, nil -} - -func (p *Process) ConnectionsWithContext(ctx context.Context) ([]net.ConnectionStat, error) { - return net.ConnectionsPidWithContext(ctx, "all", p.Pid) -} - -func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net.ConnectionStat, error) { - return net.ConnectionsPidMaxWithContext(ctx, "all", p.Pid, max) -} - -func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { - filename := common.HostProc(strconv.Itoa(int(p.Pid)), "net/dev") - return net.IOCountersByFileWithContext(ctx, pernic, filename) -} - -func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { - pid := p.Pid - var ret []MemoryMapsStat - if grouped { - ret = make([]MemoryMapsStat, 1) - } - smapsPath := common.HostProc(strconv.Itoa(int(pid)), "smaps") - contents, err := ioutil.ReadFile(smapsPath) - if err != nil { - return nil, err - } - lines := strings.Split(string(contents), "\n") - - // function of parsing a block - getBlock := func(firstLine []string, block []string) (MemoryMapsStat, error) { - m := MemoryMapsStat{} - m.Path = firstLine[len(firstLine)-1] - - for _, line := range block { - if strings.Contains(line, "VmFlags") { - continue - } - field := strings.Split(line, ":") - if len(field) < 2 { - continue - } - v := strings.Trim(field[1], "kB") // remove last "kB" - v = strings.TrimSpace(v) - t, err := strconv.ParseUint(v, 10, 64) - if err != nil { - return m, err - } - - switch field[0] { - case "Size": - m.Size = t - case "Rss": - m.Rss = t - case "Pss": - m.Pss = t - case "Shared_Clean": - m.SharedClean = t - case "Shared_Dirty": - m.SharedDirty = t - case "Private_Clean": - m.PrivateClean = t - case "Private_Dirty": - m.PrivateDirty = t - case "Referenced": - m.Referenced = t - case "Anonymous": - m.Anonymous = t - case "Swap": - m.Swap = t - } - } - return m, nil - } - - var firstLine []string - blocks := make([]string, 0, 16) - for i, line := range lines { - fields := strings.Fields(line) - - if (len(fields) > 0 && !strings.HasSuffix(fields[0], ":")) || i == len(lines)-1 { - // new block section - if len(firstLine) > 0 && len(blocks) > 0 { - g, err := getBlock(firstLine, blocks) - if err != nil { - return &ret, err - } - if grouped { - ret[0].Size += g.Size - ret[0].Rss += g.Rss - ret[0].Pss += g.Pss - ret[0].SharedClean += g.SharedClean - ret[0].SharedDirty += g.SharedDirty - ret[0].PrivateClean += g.PrivateClean - ret[0].PrivateDirty += g.PrivateDirty - ret[0].Referenced += g.Referenced - ret[0].Anonymous += g.Anonymous - ret[0].Swap += g.Swap - } else { - ret = append(ret, g) - } - } - // starts new block - blocks = make([]string, 0, 16) - firstLine = fields - } else { - blocks = append(blocks, line) - } - } - - return &ret, nil -} - -func (p *Process) EnvironWithContext(ctx context.Context) ([]string, error) { - environPath := common.HostProc(strconv.Itoa(int(p.Pid)), "environ") - - environContent, err := ioutil.ReadFile(environPath) - if err != nil { - return nil, err - } - - return strings.Split(string(environContent), "\000"), nil -} - -/** -** Internal functions -**/ - -func limitToInt(val string) (int32, error) { - if val == "unlimited" { - return math.MaxInt32, nil - } else { - res, err := strconv.ParseInt(val, 10, 32) - if err != nil { - return 0, err - } - return int32(res), nil - } -} - -// Get name from /proc/(pid)/comm or /proc/(pid)/status -func (p *Process) fillNameWithContext(ctx context.Context) error { - err := p.fillFromCommWithContext(ctx) - if err == nil && p.name != "" && len(p.name) < 15 { - return nil - } - return p.fillFromStatusWithContext(ctx) -} - -// Get name from /proc/(pid)/comm -func (p *Process) fillFromCommWithContext(ctx context.Context) error { - pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "comm") - contents, err := ioutil.ReadFile(statPath) - if err != nil { - return err - } - - p.name = strings.TrimSuffix(string(contents), "\n") - return nil -} - -// Get num_fds from /proc/(pid)/limits -func (p *Process) fillFromLimitsWithContext(ctx context.Context) ([]RlimitStat, error) { - pid := p.Pid - limitsFile := common.HostProc(strconv.Itoa(int(pid)), "limits") - d, err := os.Open(limitsFile) - if err != nil { - return nil, err - } - defer d.Close() - - var limitStats []RlimitStat - - limitsScanner := bufio.NewScanner(d) - for limitsScanner.Scan() { - var statItem RlimitStat - - str := strings.Fields(limitsScanner.Text()) - - // Remove the header line - if strings.Contains(str[len(str)-1], "Units") { - continue - } - - // Assert that last item is a Hard limit - statItem.Hard, err = limitToInt(str[len(str)-1]) - if err != nil { - // On error remove last item an try once again since it can be unit or header line - str = str[:len(str)-1] - statItem.Hard, err = limitToInt(str[len(str)-1]) - if err != nil { - return nil, err - } - } - // Remove last item from string - str = str[:len(str)-1] - - //Now last item is a Soft limit - statItem.Soft, err = limitToInt(str[len(str)-1]) - if err != nil { - return nil, err - } - // Remove last item from string - str = str[:len(str)-1] - - //The rest is a stats name - resourceName := strings.Join(str, " ") - switch resourceName { - case "Max cpu time": - statItem.Resource = RLIMIT_CPU - case "Max file size": - statItem.Resource = RLIMIT_FSIZE - case "Max data size": - statItem.Resource = RLIMIT_DATA - case "Max stack size": - statItem.Resource = RLIMIT_STACK - case "Max core file size": - statItem.Resource = RLIMIT_CORE - case "Max resident set": - statItem.Resource = RLIMIT_RSS - case "Max processes": - statItem.Resource = RLIMIT_NPROC - case "Max open files": - statItem.Resource = RLIMIT_NOFILE - case "Max locked memory": - statItem.Resource = RLIMIT_MEMLOCK - case "Max address space": - statItem.Resource = RLIMIT_AS - case "Max file locks": - statItem.Resource = RLIMIT_LOCKS - case "Max pending signals": - statItem.Resource = RLIMIT_SIGPENDING - case "Max msgqueue size": - statItem.Resource = RLIMIT_MSGQUEUE - case "Max nice priority": - statItem.Resource = RLIMIT_NICE - case "Max realtime priority": - statItem.Resource = RLIMIT_RTPRIO - case "Max realtime timeout": - statItem.Resource = RLIMIT_RTTIME - default: - continue - } - - limitStats = append(limitStats, statItem) - } - - if err := limitsScanner.Err(); err != nil { - return nil, err - } - - return limitStats, nil -} - -// Get list of /proc/(pid)/fd files -func (p *Process) fillFromfdListWithContext(ctx context.Context) (string, []string, error) { - pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "fd") - d, err := os.Open(statPath) - if err != nil { - return statPath, []string{}, err - } - defer d.Close() - fnames, err := d.Readdirnames(-1) - return statPath, fnames, err -} - -// Get num_fds from /proc/(pid)/fd -func (p *Process) fillFromfdWithContext(ctx context.Context) (int32, []*OpenFilesStat, error) { - statPath, fnames, err := p.fillFromfdListWithContext(ctx) - if err != nil { - return 0, nil, err - } - numFDs := int32(len(fnames)) - - var openfiles []*OpenFilesStat - for _, fd := range fnames { - fpath := filepath.Join(statPath, fd) - filepath, err := os.Readlink(fpath) - if err != nil { - continue - } - t, err := strconv.ParseUint(fd, 10, 64) - if err != nil { - return numFDs, openfiles, err - } - o := &OpenFilesStat{ - Path: filepath, - Fd: t, - } - openfiles = append(openfiles, o) - } - - return numFDs, openfiles, nil -} - -// Get cwd from /proc/(pid)/cwd -func (p *Process) fillFromCwdWithContext(ctx context.Context) (string, error) { - pid := p.Pid - cwdPath := common.HostProc(strconv.Itoa(int(pid)), "cwd") - cwd, err := os.Readlink(cwdPath) - if err != nil { - return "", err - } - return string(cwd), nil -} - -// Get exe from /proc/(pid)/exe -func (p *Process) fillFromExeWithContext(ctx context.Context) (string, error) { - pid := p.Pid - exePath := common.HostProc(strconv.Itoa(int(pid)), "exe") - exe, err := os.Readlink(exePath) - if err != nil { - return "", err - } - return string(exe), nil -} - -// Get cmdline from /proc/(pid)/cmdline -func (p *Process) fillFromCmdlineWithContext(ctx context.Context) (string, error) { - pid := p.Pid - cmdPath := common.HostProc(strconv.Itoa(int(pid)), "cmdline") - cmdline, err := ioutil.ReadFile(cmdPath) - if err != nil { - return "", err - } - ret := strings.FieldsFunc(string(cmdline), func(r rune) bool { - return r == '\u0000' - }) - - return strings.Join(ret, " "), nil -} - -func (p *Process) fillSliceFromCmdlineWithContext(ctx context.Context) ([]string, error) { - pid := p.Pid - cmdPath := common.HostProc(strconv.Itoa(int(pid)), "cmdline") - cmdline, err := ioutil.ReadFile(cmdPath) - if err != nil { - return nil, err - } - if len(cmdline) == 0 { - return nil, nil - } - if cmdline[len(cmdline)-1] == 0 { - cmdline = cmdline[:len(cmdline)-1] - } - parts := bytes.Split(cmdline, []byte{0}) - var strParts []string - for _, p := range parts { - strParts = append(strParts, string(p)) - } - - return strParts, nil -} - -// Get IO status from /proc/(pid)/io -func (p *Process) fillFromIOWithContext(ctx context.Context) (*IOCountersStat, error) { - pid := p.Pid - ioPath := common.HostProc(strconv.Itoa(int(pid)), "io") - ioline, err := ioutil.ReadFile(ioPath) - if err != nil { - return nil, err - } - lines := strings.Split(string(ioline), "\n") - ret := &IOCountersStat{} - - for _, line := range lines { - field := strings.Fields(line) - if len(field) < 2 { - continue - } - t, err := strconv.ParseUint(field[1], 10, 64) - if err != nil { - return nil, err - } - param := field[0] - if strings.HasSuffix(param, ":") { - param = param[:len(param)-1] - } - switch param { - case "syscr": - ret.ReadCount = t - case "syscw": - ret.WriteCount = t - case "read_bytes": - ret.ReadBytes = t - case "write_bytes": - ret.WriteBytes = t - } - } - - return ret, nil -} - -// Get memory info from /proc/(pid)/statm -func (p *Process) fillFromStatmWithContext(ctx context.Context) (*MemoryInfoStat, *MemoryInfoExStat, error) { - pid := p.Pid - memPath := common.HostProc(strconv.Itoa(int(pid)), "statm") - contents, err := ioutil.ReadFile(memPath) - if err != nil { - return nil, nil, err - } - fields := strings.Split(string(contents), " ") - - vms, err := strconv.ParseUint(fields[0], 10, 64) - if err != nil { - return nil, nil, err - } - rss, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { - return nil, nil, err - } - memInfo := &MemoryInfoStat{ - RSS: rss * PageSize, - VMS: vms * PageSize, - } - - shared, err := strconv.ParseUint(fields[2], 10, 64) - if err != nil { - return nil, nil, err - } - text, err := strconv.ParseUint(fields[3], 10, 64) - if err != nil { - return nil, nil, err - } - lib, err := strconv.ParseUint(fields[4], 10, 64) - if err != nil { - return nil, nil, err - } - dirty, err := strconv.ParseUint(fields[5], 10, 64) - if err != nil { - return nil, nil, err - } - - memInfoEx := &MemoryInfoExStat{ - RSS: rss * PageSize, - VMS: vms * PageSize, - Shared: shared * PageSize, - Text: text * PageSize, - Lib: lib * PageSize, - Dirty: dirty * PageSize, - } - - return memInfo, memInfoEx, nil -} - -// Get various status from /proc/(pid)/status -func (p *Process) fillFromStatusWithContext(ctx context.Context) error { - pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "status") - contents, err := ioutil.ReadFile(statPath) - if err != nil { - return err - } - lines := strings.Split(string(contents), "\n") - p.numCtxSwitches = &NumCtxSwitchesStat{} - p.memInfo = &MemoryInfoStat{} - p.sigInfo = &SignalInfoStat{} - for _, line := range lines { - tabParts := strings.SplitN(line, "\t", 2) - if len(tabParts) < 2 { - continue - } - value := tabParts[1] - switch strings.TrimRight(tabParts[0], ":") { - case "Name": - p.name = strings.Trim(value, " \t") - if len(p.name) >= 15 { - cmdlineSlice, err := p.CmdlineSlice() - if err != nil { - return err - } - if len(cmdlineSlice) > 0 { - extendedName := filepath.Base(cmdlineSlice[0]) - if strings.HasPrefix(extendedName, p.name) { - p.name = extendedName - } else { - p.name = cmdlineSlice[0] - } - } - } - // Ensure we have a copy and not reference into slice - p.name = string([]byte(p.name)) - case "State": - p.status = value[0:1] - // Ensure we have a copy and not reference into slice - p.status = string([]byte(p.status)) - case "PPid", "Ppid": - pval, err := strconv.ParseInt(value, 10, 32) - if err != nil { - return err - } - p.parent = int32(pval) - case "Tgid": - pval, err := strconv.ParseInt(value, 10, 32) - if err != nil { - return err - } - p.tgid = int32(pval) - case "Uid": - p.uids = make([]int32, 0, 4) - for _, i := range strings.Split(value, "\t") { - v, err := strconv.ParseInt(i, 10, 32) - if err != nil { - return err - } - p.uids = append(p.uids, int32(v)) - } - case "Gid": - p.gids = make([]int32, 0, 4) - for _, i := range strings.Split(value, "\t") { - v, err := strconv.ParseInt(i, 10, 32) - if err != nil { - return err - } - p.gids = append(p.gids, int32(v)) - } - case "Groups": - groups := strings.Fields(value) - p.groups = make([]int32, 0, len(groups)) - for _, i := range groups { - v, err := strconv.ParseInt(i, 10, 32) - if err != nil { - return err - } - p.groups = append(p.groups, int32(v)) - } - case "Threads": - v, err := strconv.ParseInt(value, 10, 32) - if err != nil { - return err - } - p.numThreads = int32(v) - case "voluntary_ctxt_switches": - v, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - p.numCtxSwitches.Voluntary = v - case "nonvoluntary_ctxt_switches": - v, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - p.numCtxSwitches.Involuntary = v - case "VmRSS": - value := strings.Trim(value, " kB") // remove last "kB" - v, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return err - } - p.memInfo.RSS = v * 1024 - case "VmSize": - value := strings.Trim(value, " kB") // remove last "kB" - v, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return err - } - p.memInfo.VMS = v * 1024 - case "VmSwap": - value := strings.Trim(value, " kB") // remove last "kB" - v, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return err - } - p.memInfo.Swap = v * 1024 - case "VmHWM": - value := strings.Trim(value, " kB") // remove last "kB" - v, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return err - } - p.memInfo.HWM = v * 1024 - case "VmData": - value := strings.Trim(value, " kB") // remove last "kB" - v, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return err - } - p.memInfo.Data = v * 1024 - case "VmStk": - value := strings.Trim(value, " kB") // remove last "kB" - v, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return err - } - p.memInfo.Stack = v * 1024 - case "VmLck": - value := strings.Trim(value, " kB") // remove last "kB" - v, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return err - } - p.memInfo.Locked = v * 1024 - case "SigPnd": - if len(value) > 16 { - value = value[len(value)-16:] - } - v, err := strconv.ParseUint(value, 16, 64) - if err != nil { - return err - } - p.sigInfo.PendingThread = v - case "ShdPnd": - if len(value) > 16 { - value = value[len(value)-16:] - } - v, err := strconv.ParseUint(value, 16, 64) - if err != nil { - return err - } - p.sigInfo.PendingProcess = v - case "SigBlk": - if len(value) > 16 { - value = value[len(value)-16:] - } - v, err := strconv.ParseUint(value, 16, 64) - if err != nil { - return err - } - p.sigInfo.Blocked = v - case "SigIgn": - if len(value) > 16 { - value = value[len(value)-16:] - } - v, err := strconv.ParseUint(value, 16, 64) - if err != nil { - return err - } - p.sigInfo.Ignored = v - case "SigCgt": - if len(value) > 16 { - value = value[len(value)-16:] - } - v, err := strconv.ParseUint(value, 16, 64) - if err != nil { - return err - } - p.sigInfo.Caught = v - } - - } - return nil -} - -func (p *Process) fillFromTIDStatWithContext(ctx context.Context, tid int32) (uint64, int32, *cpu.TimesStat, int64, uint32, int32, *PageFaultsStat, error) { - pid := p.Pid - var statPath string - - if tid == -1 { - statPath = common.HostProc(strconv.Itoa(int(pid)), "stat") - } else { - statPath = common.HostProc(strconv.Itoa(int(pid)), "task", strconv.Itoa(int(tid)), "stat") - } - - contents, err := ioutil.ReadFile(statPath) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - // Indexing from one, as described in `man proc` about the file /proc/[pid]/stat - fields := splitProcStat(contents) - - terminal, err := strconv.ParseUint(fields[7], 10, 64) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - - ppid, err := strconv.ParseInt(fields[4], 10, 32) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - utime, err := strconv.ParseFloat(fields[14], 64) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - - stime, err := strconv.ParseFloat(fields[15], 64) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - - // There is no such thing as iotime in stat file. As an approximation, we - // will use delayacct_blkio_ticks (aggregated block I/O delays, as per Linux - // docs). Note: I am assuming at least Linux 2.6.18 - var iotime float64 - if len(fields) > 42 { - iotime, err = strconv.ParseFloat(fields[42], 64) - if err != nil { - iotime = 0 // Ancient linux version, most likely - } - } else { - iotime = 0 // e.g. SmartOS containers - } - - cpuTimes := &cpu.TimesStat{ - CPU: "cpu", - User: utime / float64(ClockTicks), - System: stime / float64(ClockTicks), - Iowait: iotime / float64(ClockTicks), - } - - bootTime, _ := common.BootTimeWithContext(ctx) - t, err := strconv.ParseUint(fields[22], 10, 64) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - ctime := (t / uint64(ClockTicks)) + uint64(bootTime) - createTime := int64(ctime * 1000) - - rtpriority, err := strconv.ParseInt(fields[18], 10, 32) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - if rtpriority < 0 { - rtpriority = rtpriority*-1 - 1 - } else { - rtpriority = 0 - } - - // p.Nice = mustParseInt32(fields[18]) - // use syscall instead of parse Stat file - snice, _ := unix.Getpriority(PrioProcess, int(pid)) - nice := int32(snice) // FIXME: is this true? - - minFault, err := strconv.ParseUint(fields[10], 10, 64) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - cMinFault, err := strconv.ParseUint(fields[11], 10, 64) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - majFault, err := strconv.ParseUint(fields[12], 10, 64) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - cMajFault, err := strconv.ParseUint(fields[13], 10, 64) - if err != nil { - return 0, 0, nil, 0, 0, 0, nil, err - } - - faults := &PageFaultsStat{ - MinorFaults: minFault, - MajorFaults: majFault, - ChildMinorFaults: cMinFault, - ChildMajorFaults: cMajFault, - } - - return terminal, int32(ppid), cpuTimes, createTime, uint32(rtpriority), nice, faults, nil -} - -func (p *Process) fillFromStatWithContext(ctx context.Context) (uint64, int32, *cpu.TimesStat, int64, uint32, int32, *PageFaultsStat, error) { - return p.fillFromTIDStatWithContext(ctx, -1) -} - -func pidsWithContext(ctx context.Context) ([]int32, error) { - return readPidsFromDir(common.HostProc()) -} - -func ProcessesWithContext(ctx context.Context) ([]*Process, error) { - out := []*Process{} - - pids, err := PidsWithContext(ctx) - if err != nil { - return out, err - } - - for _, pid := range pids { - p, err := NewProcessWithContext(ctx, pid) - if err != nil { - continue - } - out = append(out, p) - } - - return out, nil -} - -func readPidsFromDir(path string) ([]int32, error) { - var ret []int32 - - d, err := os.Open(path) - if err != nil { - return nil, err - } - defer d.Close() - - fnames, err := d.Readdirnames(-1) - if err != nil { - return nil, err - } - for _, fname := range fnames { - pid, err := strconv.ParseInt(fname, 10, 32) - if err != nil { - // if not numeric name, just skip - continue - } - ret = append(ret, int32(pid)) - } - - return ret, nil -} - -func splitProcStat(content []byte) []string { - nameStart := bytes.IndexByte(content, '(') - nameEnd := bytes.LastIndexByte(content, ')') - restFields := strings.Fields(string(content[nameEnd+2:])) // +2 skip ') ' - name := content[nameStart+1 : nameEnd] - pid := strings.TrimSpace(string(content[:nameStart])) - fields := make([]string, 3, len(restFields)+3) - fields[1] = string(pid) - fields[2] = string(name) - fields = append(fields, restFields...) - return fields -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd.go deleted file mode 100644 index 902664b06..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd.go +++ /dev/null @@ -1,395 +0,0 @@ -// +build openbsd - -package process - -import ( - "bytes" - "context" - "encoding/binary" - "fmt" - "io" - "os/exec" - "path/filepath" - "strconv" - "strings" - "unsafe" - - cpu "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - mem "github.com/shirou/gopsutil/mem" - net "github.com/shirou/gopsutil/net" - "golang.org/x/sys/unix" -) - -func pidsWithContext(ctx context.Context) ([]int32, error) { - var ret []int32 - procs, err := ProcessesWithContext(ctx) - if err != nil { - return ret, nil - } - - for _, p := range procs { - ret = append(ret, p.Pid) - } - - return ret, nil -} - -func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { - k, err := p.getKProc() - if err != nil { - return 0, err - } - - return k.Ppid, nil -} - -func (p *Process) NameWithContext(ctx context.Context) (string, error) { - k, err := p.getKProc() - if err != nil { - return "", err - } - name := common.IntToString(k.Comm[:]) - - if len(name) >= 15 { - cmdlineSlice, err := p.CmdlineSliceWithContext(ctx) - if err != nil { - return "", err - } - if len(cmdlineSlice) > 0 { - extendedName := filepath.Base(cmdlineSlice[0]) - if strings.HasPrefix(extendedName, p.name) { - name = extendedName - } else { - name = cmdlineSlice[0] - } - } - } - - return name, nil -} - -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { - mib := []int32{CTLKern, KernProcArgs, p.Pid, KernProcArgv} - buf, _, err := common.CallSyscall(mib) - - if err != nil { - return nil, err - } - - /* From man sysctl(2): - The buffer pointed to by oldp is filled with an array of char - pointers followed by the strings themselves. The last char - pointer is a NULL pointer. */ - var strParts []string - r := bytes.NewReader(buf) - baseAddr := uintptr(unsafe.Pointer(&buf[0])) - for { - argvp, err := readPtr(r) - if err != nil { - return nil, err - } - if argvp == 0 { // check for a NULL pointer - break - } - offset := argvp - baseAddr - length := uintptr(bytes.IndexByte(buf[offset:], 0)) - str := string(buf[offset : offset+length]) - strParts = append(strParts, str) - } - - return strParts, nil -} - -// readPtr reads a pointer data from a given reader. WARNING: only little -// endian architectures are supported. -func readPtr(r io.Reader) (uintptr, error) { - switch sizeofPtr { - case 4: - var p uint32 - if err := binary.Read(r, binary.LittleEndian, &p); err != nil { - return 0, err - } - return uintptr(p), nil - case 8: - var p uint64 - if err := binary.Read(r, binary.LittleEndian, &p); err != nil { - return 0, err - } - return uintptr(p), nil - default: - return 0, fmt.Errorf("unsupported pointer size") - } -} - -func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { - argv, err := p.CmdlineSliceWithContext(ctx) - if err != nil { - return "", err - } - return strings.Join(argv, " "), nil -} - -func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - k, err := p.getKProc() - if err != nil { - return "", err - } - var s string - switch k.Stat { - case SIDL: - case SRUN: - case SONPROC: - s = "R" - case SSLEEP: - s = "S" - case SSTOP: - s = "T" - case SDEAD: - s = "Z" - } - - return s, nil -} - -func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { - // see https://github.com/shirou/gopsutil/issues/596#issuecomment-432707831 for implementation details - pid := p.Pid - ps, err := exec.LookPath("ps") - if err != nil { - return false, err - } - out, err := invoke.CommandWithContext(ctx, ps, "-o", "stat=", "-p", strconv.Itoa(int(pid))) - if err != nil { - return false, err - } - return strings.IndexByte(string(out), '+') != -1, nil -} - -func (p *Process) UidsWithContext(ctx context.Context) ([]int32, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - - uids := make([]int32, 0, 3) - - uids = append(uids, int32(k.Ruid), int32(k.Uid), int32(k.Svuid)) - - return uids, nil -} - -func (p *Process) GidsWithContext(ctx context.Context) ([]int32, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - - gids := make([]int32, 0, 3) - gids = append(gids, int32(k.Rgid), int32(k.Ngroups), int32(k.Svgid)) - - return gids, nil -} - -func (p *Process) GroupsWithContext(ctx context.Context) ([]int32, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - - groups := make([]int32, k.Ngroups) - for i := int16(0); i < k.Ngroups; i++ { - groups[i] = int32(k.Groups[i]) - } - - return groups, nil -} - -func (p *Process) TerminalWithContext(ctx context.Context) (string, error) { - k, err := p.getKProc() - if err != nil { - return "", err - } - - ttyNr := uint64(k.Tdev) - - termmap, err := getTerminalMap() - if err != nil { - return "", err - } - - return termmap[ttyNr], nil -} - -func (p *Process) NiceWithContext(ctx context.Context) (int32, error) { - k, err := p.getKProc() - if err != nil { - return 0, err - } - return int32(k.Nice), nil -} - -func (p *Process) IOCountersWithContext(ctx context.Context) (*IOCountersStat, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - return &IOCountersStat{ - ReadCount: uint64(k.Uru_inblock), - WriteCount: uint64(k.Uru_oublock), - }, nil -} - -func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { - /* not supported, just return 1 */ - return 1, nil -} - -func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - return &cpu.TimesStat{ - CPU: "cpu", - User: float64(k.Uutime_sec) + float64(k.Uutime_usec)/1000000, - System: float64(k.Ustime_sec) + float64(k.Ustime_usec)/1000000, - }, nil -} - -func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { - k, err := p.getKProc() - if err != nil { - return nil, err - } - pageSize, err := mem.GetPageSizeWithContext(ctx) - if err != nil { - return nil, err - } - - return &MemoryInfoStat{ - RSS: uint64(k.Vm_rssize) * pageSize, - VMS: uint64(k.Vm_tsize) + uint64(k.Vm_dsize) + - uint64(k.Vm_ssize), - }, nil -} - -func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { - pids, err := common.CallPgrepWithContext(ctx, invoke, p.Pid) - if err != nil { - return nil, err - } - ret := make([]*Process, 0, len(pids)) - for _, pid := range pids { - np, err := NewProcessWithContext(ctx, pid) - if err != nil { - return nil, err - } - ret = append(ret, np) - } - return ret, nil -} - -func (p *Process) ConnectionsWithContext(ctx context.Context) ([]net.ConnectionStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net.ConnectionStat, error) { - return nil, common.ErrNotImplementedError -} - -func ProcessesWithContext(ctx context.Context) ([]*Process, error) { - results := []*Process{} - - buf, length, err := callKernProcSyscall(KernProcAll, 0) - - if err != nil { - return results, err - } - - // get kinfo_proc size - count := int(length / uint64(sizeOfKinfoProc)) - - // parse buf to procs - for i := 0; i < count; i++ { - b := buf[i*sizeOfKinfoProc : (i+1)*sizeOfKinfoProc] - k, err := parseKinfoProc(b) - if err != nil { - continue - } - p, err := NewProcessWithContext(ctx, int32(k.Pid)) - if err != nil { - continue - } - - results = append(results, p) - } - - return results, nil -} - -func (p *Process) getKProc() (*KinfoProc, error) { - buf, length, err := callKernProcSyscall(KernProcPID, p.Pid) - if err != nil { - return nil, err - } - if length != sizeOfKinfoProc { - return nil, err - } - - k, err := parseKinfoProc(buf) - if err != nil { - return nil, err - } - return &k, nil -} - -func callKernProcSyscall(op int32, arg int32) ([]byte, uint64, error) { - mib := []int32{CTLKern, KernProc, op, arg, sizeOfKinfoProc, 0} - mibptr := unsafe.Pointer(&mib[0]) - miblen := uint64(len(mib)) - length := uint64(0) - _, _, err := unix.Syscall6( - unix.SYS___SYSCTL, - uintptr(mibptr), - uintptr(miblen), - 0, - uintptr(unsafe.Pointer(&length)), - 0, - 0) - if err != 0 { - return nil, length, err - } - - count := int32(length / uint64(sizeOfKinfoProc)) - mib = []int32{CTLKern, KernProc, op, arg, sizeOfKinfoProc, count} - mibptr = unsafe.Pointer(&mib[0]) - miblen = uint64(len(mib)) - // get proc info itself - buf := make([]byte, length) - _, _, err = unix.Syscall6( - unix.SYS___SYSCTL, - uintptr(mibptr), - uintptr(miblen), - uintptr(unsafe.Pointer(&buf[0])), - uintptr(unsafe.Pointer(&length)), - 0, - 0) - if err != 0 { - return buf, length, err - } - - return buf, length, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_386.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_386.go deleted file mode 100644 index b89fb8dc2..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_386.go +++ /dev/null @@ -1,201 +0,0 @@ -// +build openbsd -// +build 386 -// Code generated by cmd/cgo -godefs; DO NOT EDIT. -// cgo -godefs process/types_openbsd.go - -package process - -const ( - CTLKern = 1 - KernProc = 66 - KernProcAll = 0 - KernProcPID = 1 - KernProcProc = 8 - KernProcPathname = 12 - KernProcArgs = 55 - KernProcArgv = 1 - KernProcEnv = 3 -) - -const ( - ArgMax = 256 * 1024 -) - -const ( - sizeofPtr = 0x4 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x4 - sizeofLongLong = 0x8 -) - -const ( - sizeOfKinfoVmentry = 0x38 - sizeOfKinfoProc = 0x264 -) - -const ( - SIDL = 1 - SRUN = 2 - SSLEEP = 3 - SSTOP = 4 - SZOMB = 5 - SDEAD = 6 - SONPROC = 7 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int32 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int32 -} - -type Timeval struct { - Sec int64 - Usec int32 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int32 - Ixrss int32 - Idrss int32 - Isrss int32 - Minflt int32 - Majflt int32 - Nswap int32 - Inblock int32 - Oublock int32 - Msgsnd int32 - Msgrcv int32 - Nsignals int32 - Nvcsw int32 - Nivcsw int32 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type KinfoProc struct { - Forw uint64 - Back uint64 - Paddr uint64 - Addr uint64 - Fd uint64 - Stats uint64 - Limit uint64 - Vmspace uint64 - Sigacts uint64 - Sess uint64 - Tsess uint64 - Ru uint64 - Eflag int32 - Exitsig int32 - Flag int32 - Pid int32 - Ppid int32 - Sid int32 - X_pgid int32 - Tpgid int32 - Uid uint32 - Ruid uint32 - Gid uint32 - Rgid uint32 - Groups [16]uint32 - Ngroups int16 - Jobc int16 - Tdev uint32 - Estcpu uint32 - Rtime_sec uint32 - Rtime_usec uint32 - Cpticks int32 - Pctcpu uint32 - Swtime uint32 - Slptime uint32 - Schedflags int32 - Uticks uint64 - Sticks uint64 - Iticks uint64 - Tracep uint64 - Traceflag int32 - Holdcnt int32 - Siglist int32 - Sigmask uint32 - Sigignore uint32 - Sigcatch uint32 - Stat int8 - Priority uint8 - Usrpri uint8 - Nice uint8 - Xstat uint16 - Acflag uint16 - Comm [24]int8 - Wmesg [8]int8 - Wchan uint64 - Login [32]int8 - Vm_rssize int32 - Vm_tsize int32 - Vm_dsize int32 - Vm_ssize int32 - Uvalid int64 - Ustart_sec uint64 - Ustart_usec uint32 - Uutime_sec uint32 - Uutime_usec uint32 - Ustime_sec uint32 - Ustime_usec uint32 - Uru_maxrss uint64 - Uru_ixrss uint64 - Uru_idrss uint64 - Uru_isrss uint64 - Uru_minflt uint64 - Uru_majflt uint64 - Uru_nswap uint64 - Uru_inblock uint64 - Uru_oublock uint64 - Uru_msgsnd uint64 - Uru_msgrcv uint64 - Uru_nsignals uint64 - Uru_nvcsw uint64 - Uru_nivcsw uint64 - Uctime_sec uint32 - Uctime_usec uint32 - Psflags int32 - Spare int32 - Svuid uint32 - Svgid uint32 - Emul [8]int8 - Rlim_rss_cur uint64 - Cpuid uint64 - Vm_map_size uint64 - Tid int32 - Rtableid uint32 -} - -type Priority struct{} - -type KinfoVmentry struct { - Start uint32 - End uint32 - Guard uint32 - Fspace uint32 - Fspace_augment uint32 - Offset uint64 - Wired_count int32 - Etype int32 - Protection int32 - Max_protection int32 - Advice int32 - Inheritance int32 - Flags uint8 - Pad_cgo_0 [3]byte -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_amd64.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_amd64.go deleted file mode 100644 index 8607422b5..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_amd64.go +++ /dev/null @@ -1,200 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs types_openbsd.go - -package process - -const ( - CTLKern = 1 - KernProc = 66 - KernProcAll = 0 - KernProcPID = 1 - KernProcProc = 8 - KernProcPathname = 12 - KernProcArgs = 55 - KernProcArgv = 1 - KernProcEnv = 3 -) - -const ( - ArgMax = 256 * 1024 -) - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -const ( - sizeOfKinfoVmentry = 0x50 - sizeOfKinfoProc = 0x268 -) - -const ( - SIDL = 1 - SRUN = 2 - SSLEEP = 3 - SSTOP = 4 - SZOMB = 5 - SDEAD = 6 - SONPROC = 7 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type KinfoProc struct { - Forw uint64 - Back uint64 - Paddr uint64 - Addr uint64 - Fd uint64 - Stats uint64 - Limit uint64 - Vmspace uint64 - Sigacts uint64 - Sess uint64 - Tsess uint64 - Ru uint64 - Eflag int32 - Exitsig int32 - Flag int32 - Pid int32 - Ppid int32 - Sid int32 - X_pgid int32 - Tpgid int32 - Uid uint32 - Ruid uint32 - Gid uint32 - Rgid uint32 - Groups [16]uint32 - Ngroups int16 - Jobc int16 - Tdev uint32 - Estcpu uint32 - Rtime_sec uint32 - Rtime_usec uint32 - Cpticks int32 - Pctcpu uint32 - Swtime uint32 - Slptime uint32 - Schedflags int32 - Uticks uint64 - Sticks uint64 - Iticks uint64 - Tracep uint64 - Traceflag int32 - Holdcnt int32 - Siglist int32 - Sigmask uint32 - Sigignore uint32 - Sigcatch uint32 - Stat int8 - Priority uint8 - Usrpri uint8 - Nice uint8 - Xstat uint16 - Acflag uint16 - Comm [24]int8 - Wmesg [8]int8 - Wchan uint64 - Login [32]int8 - Vm_rssize int32 - Vm_tsize int32 - Vm_dsize int32 - Vm_ssize int32 - Uvalid int64 - Ustart_sec uint64 - Ustart_usec uint32 - Uutime_sec uint32 - Uutime_usec uint32 - Ustime_sec uint32 - Ustime_usec uint32 - Pad_cgo_0 [4]byte - Uru_maxrss uint64 - Uru_ixrss uint64 - Uru_idrss uint64 - Uru_isrss uint64 - Uru_minflt uint64 - Uru_majflt uint64 - Uru_nswap uint64 - Uru_inblock uint64 - Uru_oublock uint64 - Uru_msgsnd uint64 - Uru_msgrcv uint64 - Uru_nsignals uint64 - Uru_nvcsw uint64 - Uru_nivcsw uint64 - Uctime_sec uint32 - Uctime_usec uint32 - Psflags int32 - Spare int32 - Svuid uint32 - Svgid uint32 - Emul [8]int8 - Rlim_rss_cur uint64 - Cpuid uint64 - Vm_map_size uint64 - Tid int32 - Rtableid uint32 -} - -type Priority struct{} - -type KinfoVmentry struct { - Start uint64 - End uint64 - Guard uint64 - Fspace uint64 - Fspace_augment uint64 - Offset uint64 - Wired_count int32 - Etype int32 - Protection int32 - Max_protection int32 - Advice int32 - Inheritance int32 - Flags uint8 - Pad_cgo_0 [7]byte -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_arm64.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_arm64.go deleted file mode 100644 index 2d97fbc5c..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_openbsd_arm64.go +++ /dev/null @@ -1,202 +0,0 @@ -// +build openbsd -// +build arm64 -// Code generated by cmd/cgo -godefs; DO NOT EDIT. -// cgo -godefs process/types_openbsd.go - -package process - -const ( - CTLKern = 1 - KernProc = 66 - KernProcAll = 0 - KernProcPID = 1 - KernProcProc = 8 - KernProcPathname = 12 - KernProcArgs = 55 - KernProcArgv = 1 - KernProcEnv = 3 -) - -const ( - ArgMax = 256 * 1024 -) - -const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 -) - -const ( - sizeOfKinfoVmentry = 0x50 - sizeOfKinfoProc = 0x270 -) - -const ( - SIDL = 1 - SRUN = 2 - SSLEEP = 3 - SSTOP = 4 - SZOMB = 5 - SDEAD = 6 - SONPROC = 7 -) - -type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 -) - -type Timespec struct { - Sec int64 - Nsec int64 -} - -type Timeval struct { - Sec int64 - Usec int64 -} - -type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 -} - -type Rlimit struct { - Cur uint64 - Max uint64 -} - -type KinfoProc struct { - Forw uint64 - Back uint64 - Paddr uint64 - Addr uint64 - Fd uint64 - Stats uint64 - Limit uint64 - Vmspace uint64 - Sigacts uint64 - Sess uint64 - Tsess uint64 - Ru uint64 - Eflag int32 - Exitsig int32 - Flag int32 - Pid int32 - Ppid int32 - Sid int32 - X_pgid int32 - Tpgid int32 - Uid uint32 - Ruid uint32 - Gid uint32 - Rgid uint32 - Groups [16]uint32 - Ngroups int16 - Jobc int16 - Tdev uint32 - Estcpu uint32 - Rtime_sec uint32 - Rtime_usec uint32 - Cpticks int32 - Pctcpu uint32 - Swtime uint32 - Slptime uint32 - Schedflags int32 - Uticks uint64 - Sticks uint64 - Iticks uint64 - Tracep uint64 - Traceflag int32 - Holdcnt int32 - Siglist int32 - Sigmask uint32 - Sigignore uint32 - Sigcatch uint32 - Stat int8 - Priority uint8 - Usrpri uint8 - Nice uint8 - Xstat uint16 - Acflag uint16 - Comm [24]int8 - Wmesg [8]uint8 - Wchan uint64 - Login [32]uint8 - Vm_rssize int32 - Vm_tsize int32 - Vm_dsize int32 - Vm_ssize int32 - Uvalid int64 - Ustart_sec uint64 - Ustart_usec uint32 - Uutime_sec uint32 - Uutime_usec uint32 - Ustime_sec uint32 - Ustime_usec uint32 - Uru_maxrss uint64 - Uru_ixrss uint64 - Uru_idrss uint64 - Uru_isrss uint64 - Uru_minflt uint64 - Uru_majflt uint64 - Uru_nswap uint64 - Uru_inblock uint64 - Uru_oublock uint64 - Uru_msgsnd uint64 - Uru_msgrcv uint64 - Uru_nsignals uint64 - Uru_nvcsw uint64 - Uru_nivcsw uint64 - Uctime_sec uint32 - Uctime_usec uint32 - Psflags uint32 - Spare int32 - Svuid uint32 - Svgid uint32 - Emul [8]uint8 - Rlim_rss_cur uint64 - Cpuid uint64 - Vm_map_size uint64 - Tid int32 - Rtableid uint32 - Pledge uint64 -} - -type Priority struct{} - -type KinfoVmentry struct { - Start uint64 - End uint64 - Guard uint64 - Fspace uint64 - Fspace_augment uint64 - Offset uint64 - Wired_count int32 - Etype int32 - Protection int32 - Max_protection int32 - Advice int32 - Inheritance int32 - Flags uint8 - Pad_cgo_0 [7]byte -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_posix.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_posix.go deleted file mode 100644 index 45e6d1389..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_posix.go +++ /dev/null @@ -1,180 +0,0 @@ -// +build linux freebsd openbsd darwin solaris - -package process - -import ( - "context" - "fmt" - "os" - "os/user" - "path/filepath" - "strconv" - "strings" - "syscall" - - "github.com/shirou/gopsutil/internal/common" - "golang.org/x/sys/unix" -) - -// POSIX -func getTerminalMap() (map[uint64]string, error) { - ret := make(map[uint64]string) - var termfiles []string - - d, err := os.Open("/dev") - if err != nil { - return nil, err - } - defer d.Close() - - devnames, err := d.Readdirnames(-1) - if err != nil { - return nil, err - } - for _, devname := range devnames { - if strings.HasPrefix(devname, "/dev/tty") { - termfiles = append(termfiles, "/dev/tty/"+devname) - } - } - - var ptsnames []string - ptsd, err := os.Open("/dev/pts") - if err != nil { - ptsnames, _ = filepath.Glob("/dev/ttyp*") - if ptsnames == nil { - return nil, err - } - } - defer ptsd.Close() - - if ptsnames == nil { - defer ptsd.Close() - ptsnames, err = ptsd.Readdirnames(-1) - if err != nil { - return nil, err - } - for _, ptsname := range ptsnames { - termfiles = append(termfiles, "/dev/pts/"+ptsname) - } - } else { - termfiles = ptsnames - } - - for _, name := range termfiles { - stat := unix.Stat_t{} - if err = unix.Stat(name, &stat); err != nil { - return nil, err - } - rdev := uint64(stat.Rdev) - ret[rdev] = strings.Replace(name, "/dev", "", -1) - } - return ret, nil -} - -// isMount is a port of python's os.path.ismount() -// https://github.com/python/cpython/blob/08ff4369afca84587b1c82034af4e9f64caddbf2/Lib/posixpath.py#L186-L216 -// https://docs.python.org/3/library/os.path.html#os.path.ismount -func isMount(path string) bool { - // Check symlinkness with os.Lstat; unix.DT_LNK is not portable - fileInfo, err := os.Lstat(path) - if err != nil { - return false - } - if fileInfo.Mode() & os.ModeSymlink != 0 { - return false - } - var stat1 unix.Stat_t - if err := unix.Lstat(path, &stat1); err != nil { - return false - } - parent := filepath.Join(path, "..") - var stat2 unix.Stat_t - if err := unix.Lstat(parent, &stat2); err != nil { - return false - } - return stat1.Dev != stat2.Dev || stat1.Ino == stat2.Ino -} - -func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { - if pid <= 0 { - return false, fmt.Errorf("invalid pid %v", pid) - } - proc, err := os.FindProcess(int(pid)) - if err != nil { - return false, err - } - - if isMount(common.HostProc()) { // if //proc exists and is mounted, check if //proc/ folder exists - _, err := os.Stat(common.HostProc(strconv.Itoa(int(pid)))) - if os.IsNotExist(err) { - return false, nil - } - return err == nil, err - } - - // procfs does not exist or is not mounted, check PID existence by signalling the pid - err = proc.Signal(syscall.Signal(0)) - if err == nil { - return true, nil - } - if err.Error() == "os: process already finished" { - return false, nil - } - errno, ok := err.(syscall.Errno) - if !ok { - return false, err - } - switch errno { - case syscall.ESRCH: - return false, nil - case syscall.EPERM: - return true, nil - } - - return false, err -} - -func (p *Process) SendSignalWithContext(ctx context.Context, sig syscall.Signal) error { - process, err := os.FindProcess(int(p.Pid)) - if err != nil { - return err - } - - err = process.Signal(sig) - if err != nil { - return err - } - - return nil -} - -func (p *Process) SuspendWithContext(ctx context.Context) error { - return p.SendSignalWithContext(ctx, unix.SIGSTOP) -} - -func (p *Process) ResumeWithContext(ctx context.Context) error { - return p.SendSignalWithContext(ctx, unix.SIGCONT) -} - -func (p *Process) TerminateWithContext(ctx context.Context) error { - return p.SendSignalWithContext(ctx, unix.SIGTERM) -} - -func (p *Process) KillWithContext(ctx context.Context) error { - return p.SendSignalWithContext(ctx, unix.SIGKILL) -} - -func (p *Process) UsernameWithContext(ctx context.Context) (string, error) { - uids, err := p.UidsWithContext(ctx) - if err != nil { - return "", err - } - if len(uids) > 0 { - u, err := user.LookupId(strconv.Itoa(int(uids[0]))) - if err != nil { - return "", err - } - return u.Username, nil - } - return "", nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_solaris.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_solaris.go deleted file mode 100644 index f24a327b1..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_solaris.go +++ /dev/null @@ -1,313 +0,0 @@ -package process - -import ( - "bytes" - "context" - "io/ioutil" - "os" - "strconv" - "strings" - - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" -) - -type MemoryMapsStat struct { - Path string `json:"path"` - Rss uint64 `json:"rss"` - Size uint64 `json:"size"` - Pss uint64 `json:"pss"` - SharedClean uint64 `json:"sharedClean"` - SharedDirty uint64 `json:"sharedDirty"` - PrivateClean uint64 `json:"privateClean"` - PrivateDirty uint64 `json:"privateDirty"` - Referenced uint64 `json:"referenced"` - Anonymous uint64 `json:"anonymous"` - Swap uint64 `json:"swap"` -} - -type MemoryInfoExStat struct { -} - -func pidsWithContext(ctx context.Context) ([]int32, error) { - return readPidsFromDir(common.HostProc()) -} - -func ProcessesWithContext(ctx context.Context) ([]*Process, error) { - out := []*Process{} - - pids, err := PidsWithContext(ctx) - if err != nil { - return out, err - } - - for _, pid := range pids { - p, err := NewProcessWithContext(ctx, pid) - if err != nil { - continue - } - out = append(out, p) - } - - return out, nil -} - -func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) NameWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) TgidWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { - exe, err := p.fillFromPathAOutWithContext(ctx) - if os.IsNotExist(err) { - exe, err = p.fillFromExecnameWithContext(ctx) - } - return exe, err -} - -func (p *Process) CmdlineWithContext(ctx context.Context) (string, error) { - return p.fillFromCmdlineWithContext(ctx) -} - -func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { - return p.fillSliceFromCmdlineWithContext(ctx) -} - -func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) CwdWithContext(ctx context.Context) (string, error) { - return p.fillFromPathCwdWithContext(ctx) -} - -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { - return false, common.ErrNotImplementedError -} - -func (p *Process) UidsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) GidsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) GroupsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) TerminalWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) NiceWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) IOniceWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) RlimitWithContext(ctx context.Context) ([]RlimitStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) RlimitUsageWithContext(ctx context.Context, gatherUsed bool) ([]RlimitStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) IOCountersWithContext(ctx context.Context) (*IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NumCtxSwitchesWithContext(ctx context.Context) (*NumCtxSwitchesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NumFDsWithContext(ctx context.Context) (int32, error) { - _, fnames, err := p.fillFromfdListWithContext(ctx) - return int32(len(fnames)), err -} - -func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) ThreadsWithContext(ctx context.Context) (map[int32]*cpu.TimesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) CPUAffinityWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryInfoExWithContext(ctx context.Context) (*MemoryInfoExStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) PageFaultsWithContext(ctx context.Context) (*PageFaultsStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) OpenFilesWithContext(ctx context.Context) ([]OpenFilesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) ConnectionsWithContext(ctx context.Context) ([]net.ConnectionStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net.ConnectionStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) EnvironWithContext(ctx context.Context) ([]string, error) { - return nil, common.ErrNotImplementedError -} - -/** -** Internal functions -**/ - -func (p *Process) fillFromfdListWithContext(ctx context.Context) (string, []string, error) { - pid := p.Pid - statPath := common.HostProc(strconv.Itoa(int(pid)), "fd") - d, err := os.Open(statPath) - if err != nil { - return statPath, []string{}, err - } - defer d.Close() - fnames, err := d.Readdirnames(-1) - return statPath, fnames, err -} - -func (p *Process) fillFromPathCwdWithContext(ctx context.Context) (string, error) { - pid := p.Pid - cwdPath := common.HostProc(strconv.Itoa(int(pid)), "path", "cwd") - cwd, err := os.Readlink(cwdPath) - if err != nil { - return "", err - } - return cwd, nil -} - -func (p *Process) fillFromPathAOutWithContext(ctx context.Context) (string, error) { - pid := p.Pid - cwdPath := common.HostProc(strconv.Itoa(int(pid)), "path", "a.out") - exe, err := os.Readlink(cwdPath) - if err != nil { - return "", err - } - return exe, nil -} - -func (p *Process) fillFromExecnameWithContext(ctx context.Context) (string, error) { - pid := p.Pid - execNamePath := common.HostProc(strconv.Itoa(int(pid)), "execname") - exe, err := ioutil.ReadFile(execNamePath) - if err != nil { - return "", err - } - return string(exe), nil -} - -func (p *Process) fillFromCmdlineWithContext(ctx context.Context) (string, error) { - pid := p.Pid - cmdPath := common.HostProc(strconv.Itoa(int(pid)), "cmdline") - cmdline, err := ioutil.ReadFile(cmdPath) - if err != nil { - return "", err - } - ret := strings.FieldsFunc(string(cmdline), func(r rune) bool { - if r == '\u0000' { - return true - } - return false - }) - - return strings.Join(ret, " "), nil -} - -func (p *Process) fillSliceFromCmdlineWithContext(ctx context.Context) ([]string, error) { - pid := p.Pid - cmdPath := common.HostProc(strconv.Itoa(int(pid)), "cmdline") - cmdline, err := ioutil.ReadFile(cmdPath) - if err != nil { - return nil, err - } - if len(cmdline) == 0 { - return nil, nil - } - if cmdline[len(cmdline)-1] == 0 { - cmdline = cmdline[:len(cmdline)-1] - } - parts := bytes.Split(cmdline, []byte{0}) - var strParts []string - for _, p := range parts { - strParts = append(strParts, string(p)) - } - - return strParts, nil -} - -func readPidsFromDir(path string) ([]int32, error) { - var ret []int32 - - d, err := os.Open(path) - if err != nil { - return nil, err - } - defer d.Close() - - fnames, err := d.Readdirnames(-1) - if err != nil { - return nil, err - } - for _, fname := range fnames { - pid, err := strconv.ParseInt(fname, 10, 32) - if err != nil { - // if not numeric name, just skip - continue - } - ret = append(ret, int32(pid)) - } - - return ret, nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows.go deleted file mode 100644 index e410a0eb1..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows.go +++ /dev/null @@ -1,1194 +0,0 @@ -// +build windows - -package process - -import ( - "bufio" - "context" - "errors" - "fmt" - "io" - "os" - "reflect" - "strings" - "syscall" - "time" - "unicode/utf16" - "unsafe" - - "github.com/shirou/gopsutil/cpu" - "github.com/shirou/gopsutil/internal/common" - "github.com/shirou/gopsutil/net" - "golang.org/x/sys/windows" -) - -var ( - modntdll = windows.NewLazySystemDLL("ntdll.dll") - procNtResumeProcess = modntdll.NewProc("NtResumeProcess") - procNtSuspendProcess = modntdll.NewProc("NtSuspendProcess") - - modpsapi = windows.NewLazySystemDLL("psapi.dll") - procGetProcessMemoryInfo = modpsapi.NewProc("GetProcessMemoryInfo") - procGetProcessImageFileNameW = modpsapi.NewProc("GetProcessImageFileNameW") - - advapi32 = windows.NewLazySystemDLL("advapi32.dll") - procLookupPrivilegeValue = advapi32.NewProc("LookupPrivilegeValueW") - procAdjustTokenPrivileges = advapi32.NewProc("AdjustTokenPrivileges") - - procQueryFullProcessImageNameW = common.Modkernel32.NewProc("QueryFullProcessImageNameW") - procGetPriorityClass = common.Modkernel32.NewProc("GetPriorityClass") - procGetProcessIoCounters = common.Modkernel32.NewProc("GetProcessIoCounters") - procGetNativeSystemInfo = common.Modkernel32.NewProc("GetNativeSystemInfo") - - processorArchitecture uint -) - -const processQueryInformation = windows.PROCESS_QUERY_LIMITED_INFORMATION - -type SystemProcessInformation struct { - NextEntryOffset uint64 - NumberOfThreads uint64 - Reserved1 [48]byte - Reserved2 [3]byte - UniqueProcessID uintptr - Reserved3 uintptr - HandleCount uint64 - Reserved4 [4]byte - Reserved5 [11]byte - PeakPagefileUsage uint64 - PrivatePageCount uint64 - Reserved6 [6]uint64 -} - -type systemProcessorInformation struct { - ProcessorArchitecture uint16 - ProcessorLevel uint16 - ProcessorRevision uint16 - Reserved uint16 - ProcessorFeatureBits uint16 -} - -type systemInfo struct { - wProcessorArchitecture uint16 - wReserved uint16 - dwPageSize uint32 - lpMinimumApplicationAddress uintptr - lpMaximumApplicationAddress uintptr - dwActiveProcessorMask uintptr - dwNumberOfProcessors uint32 - dwProcessorType uint32 - dwAllocationGranularity uint32 - wProcessorLevel uint16 - wProcessorRevision uint16 -} - -// Memory_info_ex is different between OSes -type MemoryInfoExStat struct { -} - -type MemoryMapsStat struct { -} - -// ioCounters is an equivalent representation of IO_COUNTERS in the Windows API. -// https://docs.microsoft.com/windows/win32/api/winnt/ns-winnt-io_counters -type ioCounters struct { - ReadOperationCount uint64 - WriteOperationCount uint64 - OtherOperationCount uint64 - ReadTransferCount uint64 - WriteTransferCount uint64 - OtherTransferCount uint64 -} - -type processBasicInformation32 struct { - Reserved1 uint32 - PebBaseAddress uint32 - Reserved2 uint32 - Reserved3 uint32 - UniqueProcessId uint32 - Reserved4 uint32 -} - -type processBasicInformation64 struct { - Reserved1 uint64 - PebBaseAddress uint64 - Reserved2 uint64 - Reserved3 uint64 - UniqueProcessId uint64 - Reserved4 uint64 -} - -type processEnvironmentBlock32 struct { - Reserved1 [2]uint8 - BeingDebugged uint8 - Reserved2 uint8 - Reserved3 [2]uint32 - Ldr uint32 - ProcessParameters uint32 - // More fields which we don't use so far -} - -type processEnvironmentBlock64 struct { - Reserved1 [2]uint8 - BeingDebugged uint8 - Reserved2 uint8 - _ [4]uint8 // padding, since we are 64 bit, the next pointer is 64 bit aligned (when compiling for 32 bit, this is not the case without manual padding) - Reserved3 [2]uint64 - Ldr uint64 - ProcessParameters uint64 - // More fields which we don't use so far -} - -type rtlUserProcessParameters32 struct { - Reserved1 [16]uint8 - ConsoleHandle uint32 - ConsoleFlags uint32 - StdInputHandle uint32 - StdOutputHandle uint32 - StdErrorHandle uint32 - CurrentDirectoryPathNameLength uint16 - _ uint16 // Max Length - CurrentDirectoryPathAddress uint32 - CurrentDirectoryHandle uint32 - DllPathNameLength uint16 - _ uint16 // Max Length - DllPathAddress uint32 - ImagePathNameLength uint16 - _ uint16 // Max Length - ImagePathAddress uint32 - CommandLineLength uint16 - _ uint16 // Max Length - CommandLineAddress uint32 - EnvironmentAddress uint32 - // More fields which we don't use so far -} - -type rtlUserProcessParameters64 struct { - Reserved1 [16]uint8 - ConsoleHandle uint64 - ConsoleFlags uint64 - StdInputHandle uint64 - StdOutputHandle uint64 - StdErrorHandle uint64 - CurrentDirectoryPathNameLength uint16 - _ uint16 // Max Length - _ uint32 // Padding - CurrentDirectoryPathAddress uint64 - CurrentDirectoryHandle uint64 - DllPathNameLength uint16 - _ uint16 // Max Length - _ uint32 // Padding - DllPathAddress uint64 - ImagePathNameLength uint16 - _ uint16 // Max Length - _ uint32 // Padding - ImagePathAddress uint64 - CommandLineLength uint16 - _ uint16 // Max Length - _ uint32 // Padding - CommandLineAddress uint64 - EnvironmentAddress uint64 - // More fields which we don't use so far -} - -type winLUID struct { - LowPart winDWord - HighPart winLong -} - -// LUID_AND_ATTRIBUTES -type winLUIDAndAttributes struct { - Luid winLUID - Attributes winDWord -} - -// TOKEN_PRIVILEGES -type winTokenPriviledges struct { - PrivilegeCount winDWord - Privileges [1]winLUIDAndAttributes -} - -type winLong int32 -type winDWord uint32 - -func init() { - var systemInfo systemInfo - - procGetNativeSystemInfo.Call(uintptr(unsafe.Pointer(&systemInfo))) - processorArchitecture = uint(systemInfo.wProcessorArchitecture) - - // enable SeDebugPrivilege https://github.com/midstar/proci/blob/6ec79f57b90ba3d9efa2a7b16ef9c9369d4be875/proci_windows.go#L80-L119 - handle, err := syscall.GetCurrentProcess() - if err != nil { - return - } - - var token syscall.Token - err = syscall.OpenProcessToken(handle, 0x0028, &token) - if err != nil { - return - } - defer token.Close() - - tokenPriviledges := winTokenPriviledges{PrivilegeCount: 1} - lpName := syscall.StringToUTF16("SeDebugPrivilege") - ret, _, _ := procLookupPrivilegeValue.Call( - 0, - uintptr(unsafe.Pointer(&lpName[0])), - uintptr(unsafe.Pointer(&tokenPriviledges.Privileges[0].Luid))) - if ret == 0 { - return - } - - tokenPriviledges.Privileges[0].Attributes = 0x00000002 // SE_PRIVILEGE_ENABLED - - procAdjustTokenPrivileges.Call( - uintptr(token), - 0, - uintptr(unsafe.Pointer(&tokenPriviledges)), - uintptr(unsafe.Sizeof(tokenPriviledges)), - 0, - 0) -} - -func pidsWithContext(ctx context.Context) ([]int32, error) { - // inspired by https://gist.github.com/henkman/3083408 - // and https://github.com/giampaolo/psutil/blob/1c3a15f637521ba5c0031283da39c733fda53e4c/psutil/arch/windows/process_info.c#L315-L329 - var ret []int32 - var read uint32 = 0 - var psSize uint32 = 1024 - const dwordSize uint32 = 4 - - for { - ps := make([]uint32, psSize) - if err := windows.EnumProcesses(ps, &read); err != nil { - return nil, err - } - if uint32(len(ps)) == read { // ps buffer was too small to host every results, retry with a bigger one - psSize += 1024 - continue - } - for _, pid := range ps[:read/dwordSize] { - ret = append(ret, int32(pid)) - } - return ret, nil - - } - -} - -func PidExistsWithContext(ctx context.Context, pid int32) (bool, error) { - if pid == 0 { // special case for pid 0 System Idle Process - return true, nil - } - if pid < 0 { - return false, fmt.Errorf("invalid pid %v", pid) - } - if pid%4 != 0 { - // OpenProcess will succeed even on non-existing pid here https://devblogs.microsoft.com/oldnewthing/20080606-00/?p=22043 - // so we list every pid just to be sure and be future-proof - pids, err := PidsWithContext(ctx) - if err != nil { - return false, err - } - for _, i := range pids { - if i == pid { - return true, err - } - } - return false, err - } - const STILL_ACTIVE = 259 // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getexitcodeprocess - h, err := windows.OpenProcess(processQueryInformation, false, uint32(pid)) - if err == windows.ERROR_ACCESS_DENIED { - return true, nil - } - if err == windows.ERROR_INVALID_PARAMETER { - return false, nil - } - if err != nil { - return false, err - } - defer syscall.CloseHandle(syscall.Handle(h)) - var exitCode uint32 - err = windows.GetExitCodeProcess(h, &exitCode) - return exitCode == STILL_ACTIVE, err -} - -func (p *Process) PpidWithContext(ctx context.Context) (int32, error) { - // if cached already, return from cache - cachedPpid := p.getPpid() - if cachedPpid != 0 { - return cachedPpid, nil - } - - ppid, _, _, err := getFromSnapProcess(p.Pid) - if err != nil { - return 0, err - } - - // no errors and not cached already, so cache it - p.setPpid(ppid) - - return ppid, nil -} - -func (p *Process) NameWithContext(ctx context.Context) (string, error) { - ppid, _, name, err := getFromSnapProcess(p.Pid) - if err != nil { - return "", fmt.Errorf("could not get Name: %s", err) - } - - // if no errors and not cached already, cache ppid - p.parent = ppid - if 0 == p.getPpid() { - p.setPpid(ppid) - } - - return name, nil -} - -func (p *Process) TgidWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) ExeWithContext(ctx context.Context) (string, error) { - c, err := windows.OpenProcess(processQueryInformation, false, uint32(p.Pid)) - if err != nil { - return "", err - } - defer windows.CloseHandle(c) - buf := make([]uint16, syscall.MAX_LONG_PATH) - size := uint32(syscall.MAX_LONG_PATH) - if err := procQueryFullProcessImageNameW.Find(); err == nil { // Vista+ - ret, _, err := procQueryFullProcessImageNameW.Call( - uintptr(c), - uintptr(0), - uintptr(unsafe.Pointer(&buf[0])), - uintptr(unsafe.Pointer(&size))) - if ret == 0 { - return "", err - } - return windows.UTF16ToString(buf[:]), nil - } - // XP fallback - ret, _, err := procGetProcessImageFileNameW.Call(uintptr(c), uintptr(unsafe.Pointer(&buf[0])), uintptr(size)) - if ret == 0 { - return "", err - } - return common.ConvertDOSPath(windows.UTF16ToString(buf[:])), nil -} - -func (p *Process) CmdlineWithContext(_ context.Context) (string, error) { - cmdline, err := getProcessCommandLine(p.Pid) - if err != nil { - return "", fmt.Errorf("could not get CommandLine: %s", err) - } - return cmdline, nil -} - -func (p *Process) CmdlineSliceWithContext(ctx context.Context) ([]string, error) { - cmdline, err := p.CmdlineWithContext(ctx) - if err != nil { - return nil, err - } - return strings.Split(cmdline, " "), nil -} - -func (p *Process) createTimeWithContext(ctx context.Context) (int64, error) { - ru, err := getRusage(p.Pid) - if err != nil { - return 0, fmt.Errorf("could not get CreationDate: %s", err) - } - - return ru.CreationTime.Nanoseconds() / 1000000, nil -} - -func (p *Process) CwdWithContext(_ context.Context) (string, error) { - h, err := windows.OpenProcess(processQueryInformation|windows.PROCESS_VM_READ, false, uint32(p.Pid)) - if err == windows.ERROR_ACCESS_DENIED || err == windows.ERROR_INVALID_PARAMETER { - return "", nil - } - if err != nil { - return "", err - } - defer syscall.CloseHandle(syscall.Handle(h)) - - procIs32Bits := is32BitProcess(h) - - if procIs32Bits { - userProcParams, err := getUserProcessParams32(h) - if err != nil { - return "", err - } - if userProcParams.CurrentDirectoryPathNameLength > 0 { - cwd := readProcessMemory(syscall.Handle(h), procIs32Bits, uint64(userProcParams.CurrentDirectoryPathAddress), uint(userProcParams.CurrentDirectoryPathNameLength)) - if len(cwd) != int(userProcParams.CurrentDirectoryPathAddress) { - return "", errors.New("cannot read current working directory") - } - - return convertUTF16ToString(cwd), nil - } - } else { - userProcParams, err := getUserProcessParams64(h) - if err != nil { - return "", err - } - if userProcParams.CurrentDirectoryPathNameLength > 0 { - cwd := readProcessMemory(syscall.Handle(h), procIs32Bits, userProcParams.CurrentDirectoryPathAddress, uint(userProcParams.CurrentDirectoryPathNameLength)) - if len(cwd) != int(userProcParams.CurrentDirectoryPathNameLength) { - return "", errors.New("cannot read current working directory") - } - - return convertUTF16ToString(cwd), nil - } - } - - //if we reach here, we have no cwd - return "", nil -} - -func (p *Process) ParentWithContext(ctx context.Context) (*Process, error) { - ppid, err := p.PpidWithContext(ctx) - if err != nil { - return nil, fmt.Errorf("could not get ParentProcessID: %s", err) - } - - return NewProcessWithContext(ctx, ppid) -} - -func (p *Process) StatusWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -func (p *Process) ForegroundWithContext(ctx context.Context) (bool, error) { - return false, common.ErrNotImplementedError -} - -func (p *Process) UsernameWithContext(ctx context.Context) (string, error) { - pid := p.Pid - c, err := windows.OpenProcess(processQueryInformation, false, uint32(pid)) - if err != nil { - return "", err - } - defer windows.CloseHandle(c) - - var token syscall.Token - err = syscall.OpenProcessToken(syscall.Handle(c), syscall.TOKEN_QUERY, &token) - if err != nil { - return "", err - } - defer token.Close() - tokenUser, err := token.GetTokenUser() - if err != nil { - return "", err - } - - user, domain, _, err := tokenUser.User.Sid.LookupAccount("") - return domain + "\\" + user, err -} - -func (p *Process) UidsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) GidsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) GroupsWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) TerminalWithContext(ctx context.Context) (string, error) { - return "", common.ErrNotImplementedError -} - -// priorityClasses maps a win32 priority class to its WMI equivalent Win32_Process.Priority -// https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-getpriorityclass -// https://docs.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-process -var priorityClasses = map[int]int32{ - 0x00008000: 10, // ABOVE_NORMAL_PRIORITY_CLASS - 0x00004000: 6, // BELOW_NORMAL_PRIORITY_CLASS - 0x00000080: 13, // HIGH_PRIORITY_CLASS - 0x00000040: 4, // IDLE_PRIORITY_CLASS - 0x00000020: 8, // NORMAL_PRIORITY_CLASS - 0x00000100: 24, // REALTIME_PRIORITY_CLASS -} - -func (p *Process) NiceWithContext(ctx context.Context) (int32, error) { - c, err := windows.OpenProcess(processQueryInformation, false, uint32(p.Pid)) - if err != nil { - return 0, err - } - defer windows.CloseHandle(c) - ret, _, err := procGetPriorityClass.Call(uintptr(c)) - if ret == 0 { - return 0, err - } - priority, ok := priorityClasses[int(ret)] - if !ok { - return 0, fmt.Errorf("unknown priority class %v", ret) - } - return priority, nil -} - -func (p *Process) IOniceWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) RlimitWithContext(ctx context.Context) ([]RlimitStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) RlimitUsageWithContext(ctx context.Context, gatherUsed bool) ([]RlimitStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) IOCountersWithContext(ctx context.Context) (*IOCountersStat, error) { - c, err := windows.OpenProcess(processQueryInformation, false, uint32(p.Pid)) - if err != nil { - return nil, err - } - defer windows.CloseHandle(c) - var ioCounters ioCounters - ret, _, err := procGetProcessIoCounters.Call(uintptr(c), uintptr(unsafe.Pointer(&ioCounters))) - if ret == 0 { - return nil, err - } - stats := &IOCountersStat{ - ReadCount: ioCounters.ReadOperationCount, - ReadBytes: ioCounters.ReadTransferCount, - WriteCount: ioCounters.WriteOperationCount, - WriteBytes: ioCounters.WriteTransferCount, - } - - return stats, nil -} - -func (p *Process) NumCtxSwitchesWithContext(ctx context.Context) (*NumCtxSwitchesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NumFDsWithContext(ctx context.Context) (int32, error) { - return 0, common.ErrNotImplementedError -} - -func (p *Process) NumThreadsWithContext(ctx context.Context) (int32, error) { - ppid, ret, _, err := getFromSnapProcess(p.Pid) - if err != nil { - return 0, err - } - - // if no errors and not cached already, cache ppid - p.parent = ppid - if 0 == p.getPpid() { - p.setPpid(ppid) - } - - return ret, nil -} - -func (p *Process) ThreadsWithContext(ctx context.Context) (map[int32]*cpu.TimesStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) TimesWithContext(ctx context.Context) (*cpu.TimesStat, error) { - sysTimes, err := getProcessCPUTimes(p.Pid) - if err != nil { - return nil, err - } - - // User and kernel times are represented as a FILETIME structure - // which contains a 64-bit value representing the number of - // 100-nanosecond intervals since January 1, 1601 (UTC): - // http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx - // To convert it into a float representing the seconds that the - // process has executed in user/kernel mode I borrowed the code - // below from psutil's _psutil_windows.c, and in turn from Python's - // Modules/posixmodule.c - - user := float64(sysTimes.UserTime.HighDateTime)*429.4967296 + float64(sysTimes.UserTime.LowDateTime)*1e-7 - kernel := float64(sysTimes.KernelTime.HighDateTime)*429.4967296 + float64(sysTimes.KernelTime.LowDateTime)*1e-7 - - return &cpu.TimesStat{ - User: user, - System: kernel, - }, nil -} - -func (p *Process) CPUAffinityWithContext(ctx context.Context) ([]int32, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryInfoWithContext(ctx context.Context) (*MemoryInfoStat, error) { - mem, err := getMemoryInfo(p.Pid) - if err != nil { - return nil, err - } - - ret := &MemoryInfoStat{ - RSS: uint64(mem.WorkingSetSize), - VMS: uint64(mem.PagefileUsage), - } - - return ret, nil -} - -func (p *Process) MemoryInfoExWithContext(ctx context.Context) (*MemoryInfoExStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) PageFaultsWithContext(ctx context.Context) (*PageFaultsStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) { - out := []*Process{} - snap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, uint32(0)) - if err != nil { - return out, err - } - defer windows.CloseHandle(snap) - var pe32 windows.ProcessEntry32 - pe32.Size = uint32(unsafe.Sizeof(pe32)) - if err := windows.Process32First(snap, &pe32); err != nil { - return out, err - } - for { - if pe32.ParentProcessID == uint32(p.Pid) { - p, err := NewProcessWithContext(ctx, int32(pe32.ProcessID)) - if err == nil { - out = append(out, p) - } - } - if err = windows.Process32Next(snap, &pe32); err != nil { - break - } - } - return out, nil -} - -func (p *Process) OpenFilesWithContext(ctx context.Context) ([]OpenFilesStat, error) { - files := make([]OpenFilesStat, 0) - fileExists := make(map[string]bool) - - process, err := windows.OpenProcess(common.ProcessQueryInformation, false, uint32(p.Pid)) - if err != nil { - return nil, err - } - - buffer := make([]byte, 1024) - var size uint32 - - st := common.CallWithExpandingBuffer( - func() common.NtStatus { - return common.NtQuerySystemInformation( - common.SystemExtendedHandleInformationClass, - &buffer[0], - uint32(len(buffer)), - &size, - ) - }, - &buffer, - &size, - ) - if st.IsError() { - return nil, st.Error() - } - - handlesList := (*common.SystemExtendedHandleInformation)(unsafe.Pointer(&buffer[0])) - handles := make([]common.SystemExtendedHandleTableEntryInformation, int(handlesList.NumberOfHandles)) - hdr := (*reflect.SliceHeader)(unsafe.Pointer(&handles)) - hdr.Data = uintptr(unsafe.Pointer(&handlesList.Handles[0])) - - currentProcess, err := windows.GetCurrentProcess() - if err != nil { - return nil, err - } - - for _, handle := range handles { - var file uintptr - if int32(handle.UniqueProcessId) != p.Pid { - continue - } - if windows.DuplicateHandle(process, windows.Handle(handle.HandleValue), currentProcess, (*windows.Handle)(&file), - 0, true, windows.DUPLICATE_SAME_ACCESS) != nil { - continue - } - fileType, _ := windows.GetFileType(windows.Handle(file)) - if fileType != windows.FILE_TYPE_DISK { - continue - } - - var fileName string - ch := make(chan struct{}) - - go func() { - var buf [syscall.MAX_LONG_PATH]uint16 - n, err := windows.GetFinalPathNameByHandle(windows.Handle(file), &buf[0], syscall.MAX_LONG_PATH, 0) - if err != nil { - return - } - - fileName = string(utf16.Decode(buf[:n])) - ch <- struct{}{} - }() - - select { - case <-time.NewTimer(100 * time.Millisecond).C: - continue - case <-ch: - fileInfo, _ := os.Stat(fileName) - if fileInfo.IsDir() { - continue - } - - if _, exists := fileExists[fileName]; !exists { - files = append(files, OpenFilesStat{ - Path: fileName, - Fd: uint64(file), - }) - fileExists[fileName] = true - } - case <-ctx.Done(): - return files, ctx.Err() - } - } - - return files, nil -} - -func (p *Process) ConnectionsWithContext(ctx context.Context) ([]net.ConnectionStat, error) { - return net.ConnectionsPidWithContext(ctx, "all", p.Pid) -} - -func (p *Process) ConnectionsMaxWithContext(ctx context.Context, max int) ([]net.ConnectionStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) NetIOCountersWithContext(ctx context.Context, pernic bool) ([]net.IOCountersStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) MemoryMapsWithContext(ctx context.Context, grouped bool) (*[]MemoryMapsStat, error) { - return nil, common.ErrNotImplementedError -} - -func (p *Process) SendSignalWithContext(ctx context.Context, sig syscall.Signal) error { - return common.ErrNotImplementedError -} - -func (p *Process) SuspendWithContext(ctx context.Context) error { - c, err := windows.OpenProcess(windows.PROCESS_SUSPEND_RESUME, false, uint32(p.Pid)) - if err != nil { - return err - } - defer windows.CloseHandle(c) - - r1, _, _ := procNtSuspendProcess.Call(uintptr(c)) - if r1 != 0 { - // See https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55 - return fmt.Errorf("NtStatus='0x%.8X'", r1) - } - - return nil -} - -func (p *Process) ResumeWithContext(ctx context.Context) error { - c, err := windows.OpenProcess(windows.PROCESS_SUSPEND_RESUME, false, uint32(p.Pid)) - if err != nil { - return err - } - defer windows.CloseHandle(c) - - r1, _, _ := procNtResumeProcess.Call(uintptr(c)) - if r1 != 0 { - // See https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55 - return fmt.Errorf("NtStatus='0x%.8X'", r1) - } - - return nil -} - -func (p *Process) TerminateWithContext(ctx context.Context) error { - proc, err := windows.OpenProcess(windows.PROCESS_TERMINATE, false, uint32(p.Pid)) - if err != nil { - return err - } - err = windows.TerminateProcess(proc, 0) - windows.CloseHandle(proc) - return err -} - -func (p *Process) KillWithContext(ctx context.Context) error { - process, err := os.FindProcess(int(p.Pid)) - if err != nil { - return err - } - return process.Kill() -} - -func (p *Process) EnvironWithContext(ctx context.Context) ([]string, error) { - envVars, err := getProcessEnvironmentVariables(p.Pid, ctx) - if err != nil { - return nil, fmt.Errorf("could not get environment variables: %s", err) - } - return envVars, nil -} - -// retrieve Ppid in a thread-safe manner -func (p *Process) getPpid() int32 { - p.parentMutex.RLock() - defer p.parentMutex.RUnlock() - return p.parent -} - -// cache Ppid in a thread-safe manner (WINDOWS ONLY) -// see https://psutil.readthedocs.io/en/latest/#psutil.Process.ppid -func (p *Process) setPpid(ppid int32) { - p.parentMutex.Lock() - defer p.parentMutex.Unlock() - p.parent = ppid -} - -func getFromSnapProcess(pid int32) (int32, int32, string, error) { - snap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, uint32(pid)) - if err != nil { - return 0, 0, "", err - } - defer windows.CloseHandle(snap) - var pe32 windows.ProcessEntry32 - pe32.Size = uint32(unsafe.Sizeof(pe32)) - if err = windows.Process32First(snap, &pe32); err != nil { - return 0, 0, "", err - } - for { - if pe32.ProcessID == uint32(pid) { - szexe := windows.UTF16ToString(pe32.ExeFile[:]) - return int32(pe32.ParentProcessID), int32(pe32.Threads), szexe, nil - } - if err = windows.Process32Next(snap, &pe32); err != nil { - break - } - } - return 0, 0, "", fmt.Errorf("couldn't find pid: %d", pid) -} - -func ProcessesWithContext(ctx context.Context) ([]*Process, error) { - out := []*Process{} - - pids, err := PidsWithContext(ctx) - if err != nil { - return out, fmt.Errorf("could not get Processes %s", err) - } - - for _, pid := range pids { - p, err := NewProcessWithContext(ctx, pid) - if err != nil { - continue - } - out = append(out, p) - } - - return out, nil -} - -func getRusage(pid int32) (*windows.Rusage, error) { - var CPU windows.Rusage - - c, err := windows.OpenProcess(processQueryInformation, false, uint32(pid)) - if err != nil { - return nil, err - } - defer windows.CloseHandle(c) - - if err := windows.GetProcessTimes(c, &CPU.CreationTime, &CPU.ExitTime, &CPU.KernelTime, &CPU.UserTime); err != nil { - return nil, err - } - - return &CPU, nil -} - -func getMemoryInfo(pid int32) (PROCESS_MEMORY_COUNTERS, error) { - var mem PROCESS_MEMORY_COUNTERS - c, err := windows.OpenProcess(processQueryInformation, false, uint32(pid)) - if err != nil { - return mem, err - } - defer windows.CloseHandle(c) - if err := getProcessMemoryInfo(c, &mem); err != nil { - return mem, err - } - - return mem, err -} - -func getProcessMemoryInfo(h windows.Handle, mem *PROCESS_MEMORY_COUNTERS) (err error) { - r1, _, e1 := syscall.Syscall(procGetProcessMemoryInfo.Addr(), 3, uintptr(h), uintptr(unsafe.Pointer(mem)), uintptr(unsafe.Sizeof(*mem))) - if r1 == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -type SYSTEM_TIMES struct { - CreateTime syscall.Filetime - ExitTime syscall.Filetime - KernelTime syscall.Filetime - UserTime syscall.Filetime -} - -func getProcessCPUTimes(pid int32) (SYSTEM_TIMES, error) { - var times SYSTEM_TIMES - - h, err := windows.OpenProcess(processQueryInformation, false, uint32(pid)) - if err != nil { - return times, err - } - defer windows.CloseHandle(h) - - err = syscall.GetProcessTimes( - syscall.Handle(h), - ×.CreateTime, - ×.ExitTime, - ×.KernelTime, - ×.UserTime, - ) - - return times, err -} - -func getUserProcessParams32(handle windows.Handle) (rtlUserProcessParameters32, error) { - pebAddress, err := queryPebAddress(syscall.Handle(handle), true) - if err != nil { - return rtlUserProcessParameters32{}, fmt.Errorf("cannot locate process PEB: %w", err) - } - - buf := readProcessMemory(syscall.Handle(handle), true, pebAddress, uint(unsafe.Sizeof(processEnvironmentBlock32{}))) - if len(buf) != int(unsafe.Sizeof(processEnvironmentBlock32{})) { - return rtlUserProcessParameters32{}, fmt.Errorf("cannot read process PEB") - } - peb := (*processEnvironmentBlock32)(unsafe.Pointer(&buf[0])) - userProcessAddress := uint64(peb.ProcessParameters) - buf = readProcessMemory(syscall.Handle(handle), true, userProcessAddress, uint(unsafe.Sizeof(rtlUserProcessParameters32{}))) - if len(buf) != int(unsafe.Sizeof(rtlUserProcessParameters32{})) { - return rtlUserProcessParameters32{}, fmt.Errorf("cannot read user process parameters") - } - return *(*rtlUserProcessParameters32)(unsafe.Pointer(&buf[0])), nil -} - -func getUserProcessParams64(handle windows.Handle) (rtlUserProcessParameters64, error) { - pebAddress, err := queryPebAddress(syscall.Handle(handle), false) - if err != nil { - return rtlUserProcessParameters64{}, fmt.Errorf("cannot locate process PEB: %w", err) - } - - buf := readProcessMemory(syscall.Handle(handle), false, pebAddress, uint(unsafe.Sizeof(processEnvironmentBlock64{}))) - if len(buf) != int(unsafe.Sizeof(processEnvironmentBlock64{})) { - return rtlUserProcessParameters64{}, fmt.Errorf("cannot read process PEB") - } - peb := (*processEnvironmentBlock64)(unsafe.Pointer(&buf[0])) - userProcessAddress := peb.ProcessParameters - buf = readProcessMemory(syscall.Handle(handle), false, userProcessAddress, uint(unsafe.Sizeof(rtlUserProcessParameters64{}))) - if len(buf) != int(unsafe.Sizeof(rtlUserProcessParameters64{})) { - return rtlUserProcessParameters64{}, fmt.Errorf("cannot read user process parameters") - } - return *(*rtlUserProcessParameters64)(unsafe.Pointer(&buf[0])), nil -} - -func is32BitProcess(h windows.Handle) bool { - const ( - PROCESSOR_ARCHITECTURE_INTEL = 0 - PROCESSOR_ARCHITECTURE_ARM = 5 - PROCESSOR_ARCHITECTURE_ARM64 = 12 - PROCESSOR_ARCHITECTURE_IA64 = 6 - PROCESSOR_ARCHITECTURE_AMD64 = 9 - ) - - var procIs32Bits bool - switch processorArchitecture { - case PROCESSOR_ARCHITECTURE_INTEL: - fallthrough - case PROCESSOR_ARCHITECTURE_ARM: - procIs32Bits = true - case PROCESSOR_ARCHITECTURE_ARM64: - fallthrough - case PROCESSOR_ARCHITECTURE_IA64: - fallthrough - case PROCESSOR_ARCHITECTURE_AMD64: - var wow64 uint - - ret, _, _ := common.ProcNtQueryInformationProcess.Call( - uintptr(h), - uintptr(common.ProcessWow64Information), - uintptr(unsafe.Pointer(&wow64)), - uintptr(unsafe.Sizeof(wow64)), - uintptr(0), - ) - if int(ret) >= 0 { - if wow64 != 0 { - procIs32Bits = true - } - } else { - //if the OS does not support the call, we fallback into the bitness of the app - if unsafe.Sizeof(wow64) == 4 { - procIs32Bits = true - } - } - - default: - //for other unknown platforms, we rely on process platform - if unsafe.Sizeof(processorArchitecture) == 8 { - procIs32Bits = false - } else { - procIs32Bits = true - } - } - return procIs32Bits -} - -func getProcessEnvironmentVariables(pid int32, ctx context.Context) ([]string, error) { - h, err := windows.OpenProcess(processQueryInformation|windows.PROCESS_VM_READ, false, uint32(pid)) - if err == windows.ERROR_ACCESS_DENIED || err == windows.ERROR_INVALID_PARAMETER { - return nil, nil - } - if err != nil { - return nil, err - } - defer syscall.CloseHandle(syscall.Handle(h)) - - procIs32Bits := is32BitProcess(h) - - var processParameterBlockAddress uint64 - - if procIs32Bits { - peb, err := getUserProcessParams32(h) - if err != nil { - return nil, err - } - processParameterBlockAddress = uint64(peb.EnvironmentAddress) - } else { - peb, err := getUserProcessParams64(h) - if err != nil { - return nil, err - } - processParameterBlockAddress = peb.EnvironmentAddress - } - envvarScanner := bufio.NewScanner(&processReader{ - processHandle: h, - is32BitProcess: procIs32Bits, - offset: processParameterBlockAddress, - }) - envvarScanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) { - if atEOF && len(data) == 0 { - return 0, nil, nil - } - // Check for UTF-16 zero character - for i := 0; i < len(data)-1; i += 2 { - if data[i] == 0 && data[i+1] == 0 { - return i + 2, data[0:i], nil - } - } - if atEOF { - return len(data), data, nil - } - // Request more data - return 0, nil, nil - }) - var envVars []string - for envvarScanner.Scan() { - entry := envvarScanner.Bytes() - if len(entry) == 0 { - break // Block is finished - } - envVars = append(envVars, convertUTF16ToString(entry)) - select { - case <-ctx.Done(): - break - default: - continue - } - } - if err := envvarScanner.Err(); err != nil { - return nil, err - } - return envVars, nil -} - -type processReader struct { - processHandle windows.Handle - is32BitProcess bool - offset uint64 -} - -func (p *processReader) Read(buf []byte) (int, error) { - processMemory := readProcessMemory(syscall.Handle(p.processHandle), p.is32BitProcess, p.offset, uint(len(buf))) - if len(processMemory) == 0 { - return 0, io.EOF - } - copy(buf, processMemory) - p.offset += uint64(len(processMemory)) - return len(processMemory), nil -} - -func getProcessCommandLine(pid int32) (string, error) { - h, err := windows.OpenProcess(processQueryInformation|windows.PROCESS_VM_READ, false, uint32(pid)) - if err == windows.ERROR_ACCESS_DENIED || err == windows.ERROR_INVALID_PARAMETER { - return "", nil - } - if err != nil { - return "", err - } - defer syscall.CloseHandle(syscall.Handle(h)) - - procIs32Bits := is32BitProcess(h) - - if procIs32Bits { - userProcParams, err := getUserProcessParams32(h) - if err != nil { - return "", err - } - if userProcParams.CommandLineLength > 0 { - cmdLine := readProcessMemory(syscall.Handle(h), procIs32Bits, uint64(userProcParams.CommandLineAddress), uint(userProcParams.CommandLineLength)) - if len(cmdLine) != int(userProcParams.CommandLineLength) { - return "", errors.New("cannot read cmdline") - } - - return convertUTF16ToString(cmdLine), nil - } - } else { - userProcParams, err := getUserProcessParams64(h) - if err != nil { - return "", err - } - if userProcParams.CommandLineLength > 0 { - cmdLine := readProcessMemory(syscall.Handle(h), procIs32Bits, userProcParams.CommandLineAddress, uint(userProcParams.CommandLineLength)) - if len(cmdLine) != int(userProcParams.CommandLineLength) { - return "", errors.New("cannot read cmdline") - } - - return convertUTF16ToString(cmdLine), nil - } - } - - //if we reach here, we have no command line - return "", nil -} - -func convertUTF16ToString(src []byte) string { - srcLen := len(src) / 2 - - codePoints := make([]uint16, srcLen) - - srcIdx := 0 - for i := 0; i < srcLen; i++ { - codePoints[i] = uint16(src[srcIdx]) | uint16(src[srcIdx+1])<<8 - srcIdx += 2 - } - return syscall.UTF16ToString(codePoints) -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_386.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_386.go deleted file mode 100644 index 71d4b2ff1..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_386.go +++ /dev/null @@ -1,107 +0,0 @@ -// +build windows - -package process - -import ( - "errors" - "syscall" - "unsafe" - - "github.com/shirou/gopsutil/internal/common" - "golang.org/x/sys/windows" -) - -type PROCESS_MEMORY_COUNTERS struct { - CB uint32 - PageFaultCount uint32 - PeakWorkingSetSize uint32 - WorkingSetSize uint32 - QuotaPeakPagedPoolUsage uint32 - QuotaPagedPoolUsage uint32 - QuotaPeakNonPagedPoolUsage uint32 - QuotaNonPagedPoolUsage uint32 - PagefileUsage uint32 - PeakPagefileUsage uint32 -} - -func queryPebAddress(procHandle syscall.Handle, is32BitProcess bool) (uint64, error) { - if is32BitProcess { - //we are on a 32-bit process reading an external 32-bit process - var info processBasicInformation32 - - ret, _, _ := common.ProcNtQueryInformationProcess.Call( - uintptr(procHandle), - uintptr(common.ProcessBasicInformation), - uintptr(unsafe.Pointer(&info)), - uintptr(unsafe.Sizeof(info)), - uintptr(0), - ) - if status := windows.NTStatus(ret); status == windows.STATUS_SUCCESS { - return uint64(info.PebBaseAddress), nil - } else { - return 0, windows.NTStatus(ret) - } - } else { - //we are on a 32-bit process reading an external 64-bit process - if common.ProcNtWow64QueryInformationProcess64.Find() == nil { //avoid panic - var info processBasicInformation64 - - ret, _, _ := common.ProcNtWow64QueryInformationProcess64.Call( - uintptr(procHandle), - uintptr(common.ProcessBasicInformation), - uintptr(unsafe.Pointer(&info)), - uintptr(unsafe.Sizeof(info)), - uintptr(0), - ) - if status := windows.NTStatus(ret); status == windows.STATUS_SUCCESS { - return info.PebBaseAddress, nil - } else { - return 0, windows.NTStatus(ret) - } - } else { - return 0, errors.New("can't find API to query 64 bit process from 32 bit") - } - } -} - -func readProcessMemory(h syscall.Handle, is32BitProcess bool, address uint64, size uint) []byte { - if is32BitProcess { - var read uint - - buffer := make([]byte, size) - - ret, _, _ := common.ProcNtReadVirtualMemory.Call( - uintptr(h), - uintptr(address), - uintptr(unsafe.Pointer(&buffer[0])), - uintptr(size), - uintptr(unsafe.Pointer(&read)), - ) - if int(ret) >= 0 && read > 0 { - return buffer[:read] - } - } else { - //reading a 64-bit process from a 32-bit one - if common.ProcNtWow64ReadVirtualMemory64.Find() == nil { //avoid panic - var read uint64 - - buffer := make([]byte, size) - - ret, _, _ := common.ProcNtWow64ReadVirtualMemory64.Call( - uintptr(h), - uintptr(address & 0xFFFFFFFF), //the call expects a 64-bit value - uintptr(address >> 32), - uintptr(unsafe.Pointer(&buffer[0])), - uintptr(size), //the call expects a 64-bit value - uintptr(0), //but size is 32-bit so pass zero as the high dword - uintptr(unsafe.Pointer(&read)), - ) - if int(ret) >= 0 && read > 0 { - return buffer[:uint(read)] - } - } - } - - //if we reach here, an error happened - return nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_amd64.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_amd64.go deleted file mode 100644 index 14308e4d3..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_amd64.go +++ /dev/null @@ -1,78 +0,0 @@ -// +build windows - -package process - -import ( - "syscall" - "unsafe" - - "github.com/shirou/gopsutil/internal/common" - "golang.org/x/sys/windows" -) - -type PROCESS_MEMORY_COUNTERS struct { - CB uint32 - PageFaultCount uint32 - PeakWorkingSetSize uint64 - WorkingSetSize uint64 - QuotaPeakPagedPoolUsage uint64 - QuotaPagedPoolUsage uint64 - QuotaPeakNonPagedPoolUsage uint64 - QuotaNonPagedPoolUsage uint64 - PagefileUsage uint64 - PeakPagefileUsage uint64 -} - -func queryPebAddress(procHandle syscall.Handle, is32BitProcess bool) (uint64, error) { - if is32BitProcess { - //we are on a 64-bit process reading an external 32-bit process - var wow64 uint - - ret, _, _ := common.ProcNtQueryInformationProcess.Call( - uintptr(procHandle), - uintptr(common.ProcessWow64Information), - uintptr(unsafe.Pointer(&wow64)), - uintptr(unsafe.Sizeof(wow64)), - uintptr(0), - ) - if status := windows.NTStatus(ret); status == windows.STATUS_SUCCESS { - return uint64(wow64), nil - } else { - return 0, windows.NTStatus(ret) - } - } else { - //we are on a 64-bit process reading an external 64-bit process - var info processBasicInformation64 - - ret, _, _ := common.ProcNtQueryInformationProcess.Call( - uintptr(procHandle), - uintptr(common.ProcessBasicInformation), - uintptr(unsafe.Pointer(&info)), - uintptr(unsafe.Sizeof(info)), - uintptr(0), - ) - if status := windows.NTStatus(ret); status == windows.STATUS_SUCCESS { - return info.PebBaseAddress, nil - } else { - return 0, windows.NTStatus(ret) - } - } -} - -func readProcessMemory(procHandle syscall.Handle, _ bool, address uint64, size uint) []byte { - var read uint - - buffer := make([]byte, size) - - ret, _, _ := common.ProcNtReadVirtualMemory.Call( - uintptr(procHandle), - uintptr(address), - uintptr(unsafe.Pointer(&buffer[0])), - uintptr(size), - uintptr(unsafe.Pointer(&read)), - ) - if int(ret) >= 0 && read > 0 { - return buffer[:read] - } - return nil -} diff --git a/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_arm64.go b/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_arm64.go deleted file mode 100644 index ddaf19544..000000000 --- a/test/integration/vendor/github.com/shirou/gopsutil/process/process_windows_arm64.go +++ /dev/null @@ -1,104 +0,0 @@ -//go:build windows && arm64 -// +build windows,arm64 - -package process - -import ( - "errors" - "syscall" - "unsafe" - - "github.com/shirou/gopsutil/internal/common" -) - -type PROCESS_MEMORY_COUNTERS struct { - CB uint32 - PageFaultCount uint32 - PeakWorkingSetSize uint32 - WorkingSetSize uint32 - QuotaPeakPagedPoolUsage uint32 - QuotaPagedPoolUsage uint32 - QuotaPeakNonPagedPoolUsage uint32 - QuotaNonPagedPoolUsage uint32 - PagefileUsage uint32 - PeakPagefileUsage uint32 -} - -func queryPebAddress(procHandle syscall.Handle, is32BitProcess bool) (uint64, error) { - if is32BitProcess { - //we are on a 32-bit process reading an external 32-bit process - var info processBasicInformation32 - - ret, _, _ := common.ProcNtQueryInformationProcess.Call( - uintptr(procHandle), - uintptr(common.ProcessBasicInformation), - uintptr(unsafe.Pointer(&info)), - uintptr(unsafe.Sizeof(info)), - uintptr(0), - ) - if int(ret) >= 0 { - return uint64(info.PebBaseAddress), nil - } - } else { - //we are on a 32-bit process reading an external 64-bit process - if common.ProcNtWow64QueryInformationProcess64.Find() == nil { //avoid panic - var info processBasicInformation64 - - ret, _, _ := common.ProcNtWow64QueryInformationProcess64.Call( - uintptr(procHandle), - uintptr(common.ProcessBasicInformation), - uintptr(unsafe.Pointer(&info)), - uintptr(unsafe.Sizeof(info)), - uintptr(0), - ) - if int(ret) >= 0 { - return info.PebBaseAddress, nil - } - } - } - - //return 0 on error - return 0, errors.New("could not query PEB address") -} - -func readProcessMemory(h syscall.Handle, is32BitProcess bool, address uint64, size uint) []byte { - if is32BitProcess { - var read uint - - buffer := make([]byte, size) - - ret, _, _ := common.ProcNtReadVirtualMemory.Call( - uintptr(h), - uintptr(address), - uintptr(unsafe.Pointer(&buffer[0])), - uintptr(size), - uintptr(unsafe.Pointer(&read)), - ) - if int(ret) >= 0 && read > 0 { - return buffer[:read] - } - } else { - //reading a 64-bit process from a 32-bit one - if common.ProcNtWow64ReadVirtualMemory64.Find() == nil { //avoid panic - var read uint64 - - buffer := make([]byte, size) - - ret, _, _ := common.ProcNtWow64ReadVirtualMemory64.Call( - uintptr(h), - uintptr(address&0xFFFFFFFF), //the call expects a 64-bit value - uintptr(address>>32), - uintptr(unsafe.Pointer(&buffer[0])), - uintptr(size), //the call expects a 64-bit value - uintptr(0), //but size is 32-bit so pass zero as the high dword - uintptr(unsafe.Pointer(&read)), - ) - if int(ret) >= 0 && read > 0 { - return buffer[:uint(read)] - } - } - } - - //if we reach here, an error happened - return nil -} diff --git a/test/integration/vendor/github.com/spf13/afero/afero.go b/test/integration/vendor/github.com/spf13/afero/afero.go index 199480cd0..39f658520 100644 --- a/test/integration/vendor/github.com/spf13/afero/afero.go +++ b/test/integration/vendor/github.com/spf13/afero/afero.go @@ -97,7 +97,7 @@ type Fs interface { // Chown changes the uid and gid of the named file. Chown(name string, uid, gid int) error - //Chtimes changes the access and modification times of the named file + // Chtimes changes the access and modification times of the named file Chtimes(name string, atime time.Time, mtime time.Time) error } diff --git a/test/integration/vendor/github.com/spf13/afero/basepath.go b/test/integration/vendor/github.com/spf13/afero/basepath.go index 70a1d9168..2e72793a3 100644 --- a/test/integration/vendor/github.com/spf13/afero/basepath.go +++ b/test/integration/vendor/github.com/spf13/afero/basepath.go @@ -40,7 +40,6 @@ func (f *BasePathFile) Name() string { func (f *BasePathFile) ReadDir(n int) ([]fs.DirEntry, error) { if rdf, ok := f.File.(fs.ReadDirFile); ok { return rdf.ReadDir(n) - } return readDirFile{f.File}.ReadDir(n) } diff --git a/test/integration/vendor/github.com/spf13/afero/copyOnWriteFs.go b/test/integration/vendor/github.com/spf13/afero/copyOnWriteFs.go index 6ff8f3099..184d6dd70 100644 --- a/test/integration/vendor/github.com/spf13/afero/copyOnWriteFs.go +++ b/test/integration/vendor/github.com/spf13/afero/copyOnWriteFs.go @@ -223,7 +223,7 @@ func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, return nil, err } if isaDir { - if err = u.layer.MkdirAll(dir, 0777); err != nil { + if err = u.layer.MkdirAll(dir, 0o777); err != nil { return nil, err } return u.layer.OpenFile(name, flag, perm) @@ -247,8 +247,9 @@ func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, // This function handles the 9 different possibilities caused // by the union which are the intersection of the following... -// layer: doesn't exist, exists as a file, and exists as a directory -// base: doesn't exist, exists as a file, and exists as a directory +// +// layer: doesn't exist, exists as a file, and exists as a directory +// base: doesn't exist, exists as a file, and exists as a directory func (u *CopyOnWriteFs) Open(name string) (File, error) { // Since the overlay overrides the base we check that first b, err := u.isBaseFile(name) @@ -322,5 +323,5 @@ func (u *CopyOnWriteFs) MkdirAll(name string, perm os.FileMode) error { } func (u *CopyOnWriteFs) Create(name string) (File, error) { - return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666) + return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0o666) } diff --git a/test/integration/vendor/github.com/spf13/afero/ioutil.go b/test/integration/vendor/github.com/spf13/afero/ioutil.go index 386c9cdc2..fa6abe1ee 100644 --- a/test/integration/vendor/github.com/spf13/afero/ioutil.go +++ b/test/integration/vendor/github.com/spf13/afero/ioutil.go @@ -141,8 +141,10 @@ func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error { // We generate random temporary file names so that there's a good // chance the file doesn't exist yet - keeps the number of tries in // TempFile to a minimum. -var randNum uint32 -var randmu sync.Mutex +var ( + randNum uint32 + randmu sync.Mutex +) func reseed() uint32 { return uint32(time.Now().UnixNano() + int64(os.Getpid())) @@ -190,7 +192,7 @@ func TempFile(fs Fs, dir, pattern string) (f File, err error) { nconflict := 0 for i := 0; i < 10000; i++ { name := filepath.Join(dir, prefix+nextRandom()+suffix) - f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) + f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() @@ -214,6 +216,7 @@ func TempFile(fs Fs, dir, pattern string) (f File, err error) { func (a Afero) TempDir(dir, prefix string) (name string, err error) { return TempDir(a.Fs, dir, prefix) } + func TempDir(fs Fs, dir, prefix string) (name string, err error) { if dir == "" { dir = os.TempDir() @@ -222,7 +225,7 @@ func TempDir(fs Fs, dir, prefix string) (name string, err error) { nconflict := 0 for i := 0; i < 10000; i++ { try := filepath.Join(dir, prefix+nextRandom()) - err = fs.Mkdir(try, 0700) + err = fs.Mkdir(try, 0o700) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() diff --git a/test/integration/vendor/github.com/spf13/afero/mem/file.go b/test/integration/vendor/github.com/spf13/afero/mem/file.go index 3cf4693b5..62fe4498e 100644 --- a/test/integration/vendor/github.com/spf13/afero/mem/file.go +++ b/test/integration/vendor/github.com/spf13/afero/mem/file.go @@ -245,7 +245,7 @@ func (f *File) Truncate(size int64) error { defer f.fileData.Unlock() if size > int64(len(f.fileData.data)) { diff := size - int64(len(f.fileData.data)) - f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{00}, int(diff))...) + f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{0o0}, int(diff))...) } else { f.fileData.data = f.fileData.data[0:size] } @@ -285,7 +285,7 @@ func (f *File) Write(b []byte) (n int, err error) { tail = f.fileData.data[n+int(cur):] } if diff > 0 { - f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{00}, int(diff)), b...)...) + f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{0o0}, int(diff)), b...)...) f.fileData.data = append(f.fileData.data, tail...) } else { f.fileData.data = append(f.fileData.data[:cur], b...) @@ -321,16 +321,19 @@ func (s *FileInfo) Name() string { s.Unlock() return name } + func (s *FileInfo) Mode() os.FileMode { s.Lock() defer s.Unlock() return s.mode } + func (s *FileInfo) ModTime() time.Time { s.Lock() defer s.Unlock() return s.modtime } + func (s *FileInfo) IsDir() bool { s.Lock() defer s.Unlock() diff --git a/test/integration/vendor/github.com/spf13/afero/memmap.go b/test/integration/vendor/github.com/spf13/afero/memmap.go index d06975e71..e6b7d70b9 100644 --- a/test/integration/vendor/github.com/spf13/afero/memmap.go +++ b/test/integration/vendor/github.com/spf13/afero/memmap.go @@ -15,6 +15,7 @@ package afero import ( "fmt" + "io" "log" "os" "path/filepath" @@ -43,7 +44,7 @@ func (m *MemMapFs) getData() map[string]*mem.FileData { // Root should always exist, right? // TODO: what about windows? root := mem.CreateDir(FilePathSeparator) - mem.SetMode(root, os.ModeDir|0755) + mem.SetMode(root, os.ModeDir|0o755) m.data[FilePathSeparator] = root }) return m.data @@ -96,12 +97,12 @@ func (m *MemMapFs) registerWithParent(f *mem.FileData, perm os.FileMode) { pdir := filepath.Dir(filepath.Clean(f.Name())) err := m.lockfreeMkdir(pdir, perm) if err != nil { - //log.Println("Mkdir error:", err) + // log.Println("Mkdir error:", err) return } parent, err = m.lockfreeOpen(pdir) if err != nil { - //log.Println("Open after Mkdir error:", err) + // log.Println("Open after Mkdir error:", err) return } } @@ -237,7 +238,7 @@ func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, erro file = mem.NewReadOnlyFileHandle(file.(*mem.File).Data()) } if flag&os.O_APPEND > 0 { - _, err = file.Seek(0, os.SEEK_END) + _, err = file.Seek(0, io.SeekEnd) if err != nil { file.Close() return nil, err @@ -319,6 +320,18 @@ func (m *MemMapFs) Rename(oldname, newname string) error { } else { return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound} } + + for p, fileData := range m.getData() { + if strings.HasPrefix(p, oldname+FilePathSeparator) { + m.mu.RUnlock() + m.mu.Lock() + delete(m.getData(), p) + p := strings.Replace(p, oldname, newname, 1) + m.getData()[p] = fileData + m.mu.Unlock() + m.mu.RLock() + } + } return nil } diff --git a/test/integration/vendor/github.com/spf13/afero/regexpfs.go b/test/integration/vendor/github.com/spf13/afero/regexpfs.go index ac359c62a..218f3b235 100644 --- a/test/integration/vendor/github.com/spf13/afero/regexpfs.go +++ b/test/integration/vendor/github.com/spf13/afero/regexpfs.go @@ -10,7 +10,6 @@ import ( // The RegexpFs filters files (not directories) by regular expression. Only // files matching the given regexp will be allowed, all others get a ENOENT error ( // "No such file or directory"). -// type RegexpFs struct { re *regexp.Regexp source Fs diff --git a/test/integration/vendor/github.com/spf13/afero/symlink.go b/test/integration/vendor/github.com/spf13/afero/symlink.go index d1c6ea53d..aa6ae125b 100644 --- a/test/integration/vendor/github.com/spf13/afero/symlink.go +++ b/test/integration/vendor/github.com/spf13/afero/symlink.go @@ -21,9 +21,9 @@ import ( // filesystems saying so. // It indicates support for 3 symlink related interfaces that implement the // behaviors of the os methods: -// - Lstat -// - Symlink, and -// - Readlink +// - Lstat +// - Symlink, and +// - Readlink type Symlinker interface { Lstater Linker diff --git a/test/integration/vendor/github.com/spf13/afero/unionFile.go b/test/integration/vendor/github.com/spf13/afero/unionFile.go index 333d367f4..62dd6c93c 100644 --- a/test/integration/vendor/github.com/spf13/afero/unionFile.go +++ b/test/integration/vendor/github.com/spf13/afero/unionFile.go @@ -47,7 +47,7 @@ func (f *UnionFile) Read(s []byte) (int, error) { if (err == nil || err == io.EOF) && f.Base != nil { // advance the file position also in the base file, the next // call may be a write at this position (or a seek with SEEK_CUR) - if _, seekErr := f.Base.Seek(int64(n), os.SEEK_CUR); seekErr != nil { + if _, seekErr := f.Base.Seek(int64(n), io.SeekCurrent); seekErr != nil { // only overwrite err in case the seek fails: we need to // report an eventual io.EOF to the caller err = seekErr @@ -130,7 +130,7 @@ func (f *UnionFile) Name() string { type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) { - var files = make(map[string]os.FileInfo) + files := make(map[string]os.FileInfo) for _, fi := range lofi { files[fi.Name()] = fi @@ -151,7 +151,6 @@ var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, err } return rfi, nil - } // Readdir will weave the two directories together and @@ -275,7 +274,7 @@ func copyFile(base Fs, layer Fs, name string, bfh File) error { return err } if !exists { - err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME? + err = layer.MkdirAll(filepath.Dir(name), 0o777) // FIXME? if err != nil { return err } diff --git a/test/integration/vendor/github.com/spf13/afero/util.go b/test/integration/vendor/github.com/spf13/afero/util.go index cb7de23f2..9e4cba274 100644 --- a/test/integration/vendor/github.com/spf13/afero/util.go +++ b/test/integration/vendor/github.com/spf13/afero/util.go @@ -43,7 +43,7 @@ func WriteReader(fs Fs, path string, r io.Reader) (err error) { ospath := filepath.FromSlash(dir) if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r + err = fs.MkdirAll(ospath, 0o777) // rwx, rw, r if err != nil { if err != os.ErrExist { return err @@ -71,7 +71,7 @@ func SafeWriteReader(fs Fs, path string, r io.Reader) (err error) { ospath := filepath.FromSlash(dir) if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r + err = fs.MkdirAll(ospath, 0o777) // rwx, rw, r if err != nil { return } @@ -124,7 +124,7 @@ func GetTempDir(fs Fs, subPath string) string { return addSlash(dir) } - err := fs.MkdirAll(dir, 0777) + err := fs.MkdirAll(dir, 0o777) if err != nil { panic(err) } @@ -197,7 +197,6 @@ func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, err // readerContains reports whether any of the subslices is within r. func readerContainsAny(r io.Reader, subslices ...[]byte) bool { - if r == nil || len(subslices) == 0 { return false } diff --git a/test/integration/vendor/modules.txt b/test/integration/vendor/modules.txt index 653ad35ed..e0fd10af2 100644 --- a/test/integration/vendor/modules.txt +++ b/test/integration/vendor/modules.txt @@ -331,7 +331,7 @@ github.com/hashicorp/hcl/hcl/token github.com/hashicorp/hcl/json/parser github.com/hashicorp/hcl/json/scanner github.com/hashicorp/hcl/json/token -# github.com/imdario/mergo v0.3.13 +# github.com/imdario/mergo v0.3.14 ## explicit; go 1.13 github.com/imdario/mergo # github.com/inconshreveable/mousetrap v1.1.0 @@ -345,7 +345,7 @@ github.com/json-iterator/go # github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 ## explicit github.com/kballard/go-shellquote -# github.com/klauspost/compress v1.16.0 +# github.com/klauspost/compress v1.16.3 ## explicit; go 1.18 github.com/klauspost/compress github.com/klauspost/compress/fse @@ -573,13 +573,6 @@ github.com/rivo/uniseg # github.com/serialx/hashring v0.0.0-20190422032157-8b2912629002 ## explicit github.com/serialx/hashring -# github.com/shirou/gopsutil v3.21.11+incompatible -## explicit -github.com/shirou/gopsutil/cpu -github.com/shirou/gopsutil/internal/common -github.com/shirou/gopsutil/mem -github.com/shirou/gopsutil/net -github.com/shirou/gopsutil/process # github.com/shirou/gopsutil/v3 v3.22.7 ## explicit; go 1.15 github.com/shirou/gopsutil/v3/cpu @@ -592,7 +585,7 @@ github.com/shirou/gopsutil/v3/process # github.com/sirupsen/logrus v1.9.0 ## explicit; go 1.13 github.com/sirupsen/logrus -# github.com/spf13/afero v1.9.3 +# github.com/spf13/afero v1.9.5 ## explicit; go 1.16 github.com/spf13/afero github.com/spf13/afero/internal/common diff --git a/test/performance/go.mod b/test/performance/go.mod index d953965c7..fb57ff02f 100644 --- a/test/performance/go.mod +++ b/test/performance/go.mod @@ -31,7 +31,7 @@ require ( github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/klauspost/compress v1.16.0 // indirect + github.com/klauspost/compress v1.16.3 // indirect github.com/klauspost/cpuid/v2 v2.1.0 // indirect github.com/lufia/plan9stats v0.0.0-20220517141722-cf486979b281 // indirect github.com/magiconair/properties v1.8.7 // indirect @@ -55,7 +55,7 @@ require ( github.com/rs/cors v1.8.3 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect github.com/shirou/gopsutil/v3 v3.22.7 // indirect - github.com/spf13/afero v1.9.3 // indirect + github.com/spf13/afero v1.9.5 // indirect github.com/spf13/cast v1.5.0 // indirect github.com/spf13/cobra v1.6.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect diff --git a/test/performance/go.sum b/test/performance/go.sum index 727edc092..4b87a428b 100644 --- a/test/performance/go.sum +++ b/test/performance/go.sum @@ -190,8 +190,8 @@ github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dv github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw1HU4= -github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.3 h1:XuJt9zzcnaz6a16/OU53ZjWp/v7/42WcR5t2a0PcNQY= +github.com/klauspost/compress v1.16.3/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid/v2 v2.1.0 h1:eyi1Ad2aNJMW95zcSbmGg7Cg6cq3ADwLpMAP96d8rF0= github.com/klauspost/cpuid/v2 v2.1.0/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -308,8 +308,8 @@ github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6Mwd github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/spf13/afero v1.9.3 h1:41FoI0fD7OR7mGcKE/aOiLkGreyf8ifIOQmJANWogMk= -github.com/spf13/afero v1.9.3/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y= +github.com/spf13/afero v1.9.5 h1:stMpOSZFs//0Lv29HduCmli3GUfpFoF3Y1Q/aXj/wVM= +github.com/spf13/afero v1.9.5/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= @@ -375,7 +375,7 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -451,6 +451,7 @@ golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= diff --git a/test/performance/vendor/github.com/klauspost/compress/s2/encode_go.go b/test/performance/vendor/github.com/klauspost/compress/s2/encode_go.go index d7749d75c..0d39c7b0e 100644 --- a/test/performance/vendor/github.com/klauspost/compress/s2/encode_go.go +++ b/test/performance/vendor/github.com/klauspost/compress/s2/encode_go.go @@ -717,3 +717,11 @@ func cvtLZ4BlockAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) { func cvtLZ4BlockSnappyAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) { panic("cvtLZ4BlockSnappyAsm should be unreachable") } + +func cvtLZ4sBlockAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) { + panic("cvtLZ4sBlockAsm should be unreachable") +} + +func cvtLZ4sBlockSnappyAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) { + panic("cvtLZ4sBlockSnappyAsm should be unreachable") +} diff --git a/test/performance/vendor/github.com/klauspost/compress/s2/encodeblock_amd64.go b/test/performance/vendor/github.com/klauspost/compress/s2/encodeblock_amd64.go index 9f3dc8c29..297e41501 100644 --- a/test/performance/vendor/github.com/klauspost/compress/s2/encodeblock_amd64.go +++ b/test/performance/vendor/github.com/klauspost/compress/s2/encodeblock_amd64.go @@ -212,7 +212,17 @@ func matchLen(a []byte, b []byte) int //go:noescape func cvtLZ4BlockAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) -// cvtLZ4Block converts an LZ4 block to S2 +// cvtLZ4sBlock converts an LZ4s block to S2 +// +//go:noescape +func cvtLZ4sBlockAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) + +// cvtLZ4Block converts an LZ4 block to Snappy // //go:noescape func cvtLZ4BlockSnappyAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) + +// cvtLZ4sBlock converts an LZ4s block to Snappy +// +//go:noescape +func cvtLZ4sBlockSnappyAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) diff --git a/test/performance/vendor/github.com/klauspost/compress/s2/encodeblock_amd64.s b/test/performance/vendor/github.com/klauspost/compress/s2/encodeblock_amd64.s index 19bd5237b..12a4de3be 100644 --- a/test/performance/vendor/github.com/klauspost/compress/s2/encodeblock_amd64.s +++ b/test/performance/vendor/github.com/klauspost/compress/s2/encodeblock_amd64.s @@ -19271,6 +19271,491 @@ lz4_s2_dstfull: MOVQ SI, uncompressed+48(FP) RET +// func cvtLZ4sBlockAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) +// Requires: SSE2 +TEXT ·cvtLZ4sBlockAsm(SB), NOSPLIT, $0-64 + XORQ SI, SI + MOVQ dst_base+0(FP), AX + MOVQ dst_len+8(FP), CX + MOVQ src_base+24(FP), DX + MOVQ src_len+32(FP), BX + LEAQ (DX)(BX*1), BX + LEAQ -10(AX)(CX*1), CX + XORQ DI, DI + +lz4s_s2_loop: + CMPQ DX, BX + JAE lz4s_s2_corrupt + CMPQ AX, CX + JAE lz4s_s2_dstfull + MOVBQZX (DX), R8 + MOVQ R8, R9 + MOVQ R8, R10 + SHRQ $0x04, R9 + ANDQ $0x0f, R10 + CMPQ R8, $0xf0 + JB lz4s_s2_ll_end + +lz4s_s2_ll_loop: + INCQ DX + CMPQ DX, BX + JAE lz4s_s2_corrupt + MOVBQZX (DX), R8 + ADDQ R8, R9 + CMPQ R8, $0xff + JEQ lz4s_s2_ll_loop + +lz4s_s2_ll_end: + LEAQ (DX)(R9*1), R8 + ADDQ $0x03, R10 + CMPQ R8, BX + JAE lz4s_s2_corrupt + INCQ DX + INCQ R8 + TESTQ R9, R9 + JZ lz4s_s2_lits_done + LEAQ (AX)(R9*1), R11 + CMPQ R11, CX + JAE lz4s_s2_dstfull + ADDQ R9, SI + LEAL -1(R9), R11 + CMPL R11, $0x3c + JLT one_byte_lz4s_s2 + CMPL R11, $0x00000100 + JLT two_bytes_lz4s_s2 + CMPL R11, $0x00010000 + JLT three_bytes_lz4s_s2 + CMPL R11, $0x01000000 + JLT four_bytes_lz4s_s2 + MOVB $0xfc, (AX) + MOVL R11, 1(AX) + ADDQ $0x05, AX + JMP memmove_long_lz4s_s2 + +four_bytes_lz4s_s2: + MOVL R11, R12 + SHRL $0x10, R12 + MOVB $0xf8, (AX) + MOVW R11, 1(AX) + MOVB R12, 3(AX) + ADDQ $0x04, AX + JMP memmove_long_lz4s_s2 + +three_bytes_lz4s_s2: + MOVB $0xf4, (AX) + MOVW R11, 1(AX) + ADDQ $0x03, AX + JMP memmove_long_lz4s_s2 + +two_bytes_lz4s_s2: + MOVB $0xf0, (AX) + MOVB R11, 1(AX) + ADDQ $0x02, AX + CMPL R11, $0x40 + JL memmove_lz4s_s2 + JMP memmove_long_lz4s_s2 + +one_byte_lz4s_s2: + SHLB $0x02, R11 + MOVB R11, (AX) + ADDQ $0x01, AX + +memmove_lz4s_s2: + LEAQ (AX)(R9*1), R11 + + // genMemMoveShort + CMPQ R9, $0x08 + JLE emit_lit_memmove_lz4s_s2_memmove_move_8 + CMPQ R9, $0x10 + JBE emit_lit_memmove_lz4s_s2_memmove_move_8through16 + CMPQ R9, $0x20 + JBE emit_lit_memmove_lz4s_s2_memmove_move_17through32 + JMP emit_lit_memmove_lz4s_s2_memmove_move_33through64 + +emit_lit_memmove_lz4s_s2_memmove_move_8: + MOVQ (DX), R12 + MOVQ R12, (AX) + JMP memmove_end_copy_lz4s_s2 + +emit_lit_memmove_lz4s_s2_memmove_move_8through16: + MOVQ (DX), R12 + MOVQ -8(DX)(R9*1), DX + MOVQ R12, (AX) + MOVQ DX, -8(AX)(R9*1) + JMP memmove_end_copy_lz4s_s2 + +emit_lit_memmove_lz4s_s2_memmove_move_17through32: + MOVOU (DX), X0 + MOVOU -16(DX)(R9*1), X1 + MOVOU X0, (AX) + MOVOU X1, -16(AX)(R9*1) + JMP memmove_end_copy_lz4s_s2 + +emit_lit_memmove_lz4s_s2_memmove_move_33through64: + MOVOU (DX), X0 + MOVOU 16(DX), X1 + MOVOU -32(DX)(R9*1), X2 + MOVOU -16(DX)(R9*1), X3 + MOVOU X0, (AX) + MOVOU X1, 16(AX) + MOVOU X2, -32(AX)(R9*1) + MOVOU X3, -16(AX)(R9*1) + +memmove_end_copy_lz4s_s2: + MOVQ R11, AX + JMP lz4s_s2_lits_emit_done + +memmove_long_lz4s_s2: + LEAQ (AX)(R9*1), R11 + + // genMemMoveLong + MOVOU (DX), X0 + MOVOU 16(DX), X1 + MOVOU -32(DX)(R9*1), X2 + MOVOU -16(DX)(R9*1), X3 + MOVQ R9, R13 + SHRQ $0x05, R13 + MOVQ AX, R12 + ANDL $0x0000001f, R12 + MOVQ $0x00000040, R14 + SUBQ R12, R14 + DECQ R13 + JA emit_lit_memmove_long_lz4s_s2large_forward_sse_loop_32 + LEAQ -32(DX)(R14*1), R12 + LEAQ -32(AX)(R14*1), R15 + +emit_lit_memmove_long_lz4s_s2large_big_loop_back: + MOVOU (R12), X4 + MOVOU 16(R12), X5 + MOVOA X4, (R15) + MOVOA X5, 16(R15) + ADDQ $0x20, R15 + ADDQ $0x20, R12 + ADDQ $0x20, R14 + DECQ R13 + JNA emit_lit_memmove_long_lz4s_s2large_big_loop_back + +emit_lit_memmove_long_lz4s_s2large_forward_sse_loop_32: + MOVOU -32(DX)(R14*1), X4 + MOVOU -16(DX)(R14*1), X5 + MOVOA X4, -32(AX)(R14*1) + MOVOA X5, -16(AX)(R14*1) + ADDQ $0x20, R14 + CMPQ R9, R14 + JAE emit_lit_memmove_long_lz4s_s2large_forward_sse_loop_32 + MOVOU X0, (AX) + MOVOU X1, 16(AX) + MOVOU X2, -32(AX)(R9*1) + MOVOU X3, -16(AX)(R9*1) + MOVQ R11, AX + +lz4s_s2_lits_emit_done: + MOVQ R8, DX + +lz4s_s2_lits_done: + CMPQ DX, BX + JNE lz4s_s2_match + CMPQ R10, $0x03 + JEQ lz4s_s2_done + JMP lz4s_s2_corrupt + +lz4s_s2_match: + CMPQ R10, $0x03 + JEQ lz4s_s2_loop + LEAQ 2(DX), R8 + CMPQ R8, BX + JAE lz4s_s2_corrupt + MOVWQZX (DX), R9 + MOVQ R8, DX + TESTQ R9, R9 + JZ lz4s_s2_corrupt + CMPQ R9, SI + JA lz4s_s2_corrupt + CMPQ R10, $0x12 + JNE lz4s_s2_ml_done + +lz4s_s2_ml_loop: + MOVBQZX (DX), R8 + INCQ DX + ADDQ R8, R10 + CMPQ DX, BX + JAE lz4s_s2_corrupt + CMPQ R8, $0xff + JEQ lz4s_s2_ml_loop + +lz4s_s2_ml_done: + ADDQ R10, SI + CMPQ R9, DI + JNE lz4s_s2_docopy + + // emitRepeat +emit_repeat_again_lz4_s2: + MOVL R10, R8 + LEAL -4(R10), R10 + CMPL R8, $0x08 + JLE repeat_two_lz4_s2 + CMPL R8, $0x0c + JGE cant_repeat_two_offset_lz4_s2 + CMPL R9, $0x00000800 + JLT repeat_two_offset_lz4_s2 + +cant_repeat_two_offset_lz4_s2: + CMPL R10, $0x00000104 + JLT repeat_three_lz4_s2 + CMPL R10, $0x00010100 + JLT repeat_four_lz4_s2 + CMPL R10, $0x0100ffff + JLT repeat_five_lz4_s2 + LEAL -16842747(R10), R10 + MOVL $0xfffb001d, (AX) + MOVB $0xff, 4(AX) + ADDQ $0x05, AX + JMP emit_repeat_again_lz4_s2 + +repeat_five_lz4_s2: + LEAL -65536(R10), R10 + MOVL R10, R9 + MOVW $0x001d, (AX) + MOVW R10, 2(AX) + SARL $0x10, R9 + MOVB R9, 4(AX) + ADDQ $0x05, AX + JMP lz4s_s2_loop + +repeat_four_lz4_s2: + LEAL -256(R10), R10 + MOVW $0x0019, (AX) + MOVW R10, 2(AX) + ADDQ $0x04, AX + JMP lz4s_s2_loop + +repeat_three_lz4_s2: + LEAL -4(R10), R10 + MOVW $0x0015, (AX) + MOVB R10, 2(AX) + ADDQ $0x03, AX + JMP lz4s_s2_loop + +repeat_two_lz4_s2: + SHLL $0x02, R10 + ORL $0x01, R10 + MOVW R10, (AX) + ADDQ $0x02, AX + JMP lz4s_s2_loop + +repeat_two_offset_lz4_s2: + XORQ R8, R8 + LEAL 1(R8)(R10*4), R10 + MOVB R9, 1(AX) + SARL $0x08, R9 + SHLL $0x05, R9 + ORL R9, R10 + MOVB R10, (AX) + ADDQ $0x02, AX + JMP lz4s_s2_loop + +lz4s_s2_docopy: + MOVQ R9, DI + + // emitCopy + CMPL R10, $0x40 + JLE two_byte_offset_short_lz4_s2 + CMPL R9, $0x00000800 + JAE long_offset_short_lz4_s2 + MOVL $0x00000001, R8 + LEAL 16(R8), R8 + MOVB R9, 1(AX) + MOVL R9, R11 + SHRL $0x08, R11 + SHLL $0x05, R11 + ORL R11, R8 + MOVB R8, (AX) + ADDQ $0x02, AX + SUBL $0x08, R10 + + // emitRepeat + LEAL -4(R10), R10 + JMP cant_repeat_two_offset_lz4_s2_emit_copy_short_2b + +emit_repeat_again_lz4_s2_emit_copy_short_2b: + MOVL R10, R8 + LEAL -4(R10), R10 + CMPL R8, $0x08 + JLE repeat_two_lz4_s2_emit_copy_short_2b + CMPL R8, $0x0c + JGE cant_repeat_two_offset_lz4_s2_emit_copy_short_2b + CMPL R9, $0x00000800 + JLT repeat_two_offset_lz4_s2_emit_copy_short_2b + +cant_repeat_two_offset_lz4_s2_emit_copy_short_2b: + CMPL R10, $0x00000104 + JLT repeat_three_lz4_s2_emit_copy_short_2b + CMPL R10, $0x00010100 + JLT repeat_four_lz4_s2_emit_copy_short_2b + CMPL R10, $0x0100ffff + JLT repeat_five_lz4_s2_emit_copy_short_2b + LEAL -16842747(R10), R10 + MOVL $0xfffb001d, (AX) + MOVB $0xff, 4(AX) + ADDQ $0x05, AX + JMP emit_repeat_again_lz4_s2_emit_copy_short_2b + +repeat_five_lz4_s2_emit_copy_short_2b: + LEAL -65536(R10), R10 + MOVL R10, R9 + MOVW $0x001d, (AX) + MOVW R10, 2(AX) + SARL $0x10, R9 + MOVB R9, 4(AX) + ADDQ $0x05, AX + JMP lz4s_s2_loop + +repeat_four_lz4_s2_emit_copy_short_2b: + LEAL -256(R10), R10 + MOVW $0x0019, (AX) + MOVW R10, 2(AX) + ADDQ $0x04, AX + JMP lz4s_s2_loop + +repeat_three_lz4_s2_emit_copy_short_2b: + LEAL -4(R10), R10 + MOVW $0x0015, (AX) + MOVB R10, 2(AX) + ADDQ $0x03, AX + JMP lz4s_s2_loop + +repeat_two_lz4_s2_emit_copy_short_2b: + SHLL $0x02, R10 + ORL $0x01, R10 + MOVW R10, (AX) + ADDQ $0x02, AX + JMP lz4s_s2_loop + +repeat_two_offset_lz4_s2_emit_copy_short_2b: + XORQ R8, R8 + LEAL 1(R8)(R10*4), R10 + MOVB R9, 1(AX) + SARL $0x08, R9 + SHLL $0x05, R9 + ORL R9, R10 + MOVB R10, (AX) + ADDQ $0x02, AX + JMP lz4s_s2_loop + +long_offset_short_lz4_s2: + MOVB $0xee, (AX) + MOVW R9, 1(AX) + LEAL -60(R10), R10 + ADDQ $0x03, AX + + // emitRepeat +emit_repeat_again_lz4_s2_emit_copy_short: + MOVL R10, R8 + LEAL -4(R10), R10 + CMPL R8, $0x08 + JLE repeat_two_lz4_s2_emit_copy_short + CMPL R8, $0x0c + JGE cant_repeat_two_offset_lz4_s2_emit_copy_short + CMPL R9, $0x00000800 + JLT repeat_two_offset_lz4_s2_emit_copy_short + +cant_repeat_two_offset_lz4_s2_emit_copy_short: + CMPL R10, $0x00000104 + JLT repeat_three_lz4_s2_emit_copy_short + CMPL R10, $0x00010100 + JLT repeat_four_lz4_s2_emit_copy_short + CMPL R10, $0x0100ffff + JLT repeat_five_lz4_s2_emit_copy_short + LEAL -16842747(R10), R10 + MOVL $0xfffb001d, (AX) + MOVB $0xff, 4(AX) + ADDQ $0x05, AX + JMP emit_repeat_again_lz4_s2_emit_copy_short + +repeat_five_lz4_s2_emit_copy_short: + LEAL -65536(R10), R10 + MOVL R10, R9 + MOVW $0x001d, (AX) + MOVW R10, 2(AX) + SARL $0x10, R9 + MOVB R9, 4(AX) + ADDQ $0x05, AX + JMP lz4s_s2_loop + +repeat_four_lz4_s2_emit_copy_short: + LEAL -256(R10), R10 + MOVW $0x0019, (AX) + MOVW R10, 2(AX) + ADDQ $0x04, AX + JMP lz4s_s2_loop + +repeat_three_lz4_s2_emit_copy_short: + LEAL -4(R10), R10 + MOVW $0x0015, (AX) + MOVB R10, 2(AX) + ADDQ $0x03, AX + JMP lz4s_s2_loop + +repeat_two_lz4_s2_emit_copy_short: + SHLL $0x02, R10 + ORL $0x01, R10 + MOVW R10, (AX) + ADDQ $0x02, AX + JMP lz4s_s2_loop + +repeat_two_offset_lz4_s2_emit_copy_short: + XORQ R8, R8 + LEAL 1(R8)(R10*4), R10 + MOVB R9, 1(AX) + SARL $0x08, R9 + SHLL $0x05, R9 + ORL R9, R10 + MOVB R10, (AX) + ADDQ $0x02, AX + JMP lz4s_s2_loop + +two_byte_offset_short_lz4_s2: + MOVL R10, R8 + SHLL $0x02, R8 + CMPL R10, $0x0c + JGE emit_copy_three_lz4_s2 + CMPL R9, $0x00000800 + JGE emit_copy_three_lz4_s2 + LEAL -15(R8), R8 + MOVB R9, 1(AX) + SHRL $0x08, R9 + SHLL $0x05, R9 + ORL R9, R8 + MOVB R8, (AX) + ADDQ $0x02, AX + JMP lz4s_s2_loop + +emit_copy_three_lz4_s2: + LEAL -2(R8), R8 + MOVB R8, (AX) + MOVW R9, 1(AX) + ADDQ $0x03, AX + JMP lz4s_s2_loop + +lz4s_s2_done: + MOVQ dst_base+0(FP), CX + SUBQ CX, AX + MOVQ SI, uncompressed+48(FP) + MOVQ AX, dstUsed+56(FP) + RET + +lz4s_s2_corrupt: + XORQ AX, AX + LEAQ -1(AX), SI + MOVQ SI, uncompressed+48(FP) + RET + +lz4s_s2_dstfull: + XORQ AX, AX + LEAQ -2(AX), SI + MOVQ SI, uncompressed+48(FP) + RET + // func cvtLZ4BlockSnappyAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) // Requires: SSE2 TEXT ·cvtLZ4BlockSnappyAsm(SB), NOSPLIT, $0-64 @@ -19536,3 +20021,271 @@ lz4_snappy_dstfull: LEAQ -2(AX), SI MOVQ SI, uncompressed+48(FP) RET + +// func cvtLZ4sBlockSnappyAsm(dst []byte, src []byte) (uncompressed int, dstUsed int) +// Requires: SSE2 +TEXT ·cvtLZ4sBlockSnappyAsm(SB), NOSPLIT, $0-64 + XORQ SI, SI + MOVQ dst_base+0(FP), AX + MOVQ dst_len+8(FP), CX + MOVQ src_base+24(FP), DX + MOVQ src_len+32(FP), BX + LEAQ (DX)(BX*1), BX + LEAQ -10(AX)(CX*1), CX + +lz4s_snappy_loop: + CMPQ DX, BX + JAE lz4s_snappy_corrupt + CMPQ AX, CX + JAE lz4s_snappy_dstfull + MOVBQZX (DX), DI + MOVQ DI, R8 + MOVQ DI, R9 + SHRQ $0x04, R8 + ANDQ $0x0f, R9 + CMPQ DI, $0xf0 + JB lz4s_snappy_ll_end + +lz4s_snappy_ll_loop: + INCQ DX + CMPQ DX, BX + JAE lz4s_snappy_corrupt + MOVBQZX (DX), DI + ADDQ DI, R8 + CMPQ DI, $0xff + JEQ lz4s_snappy_ll_loop + +lz4s_snappy_ll_end: + LEAQ (DX)(R8*1), DI + ADDQ $0x03, R9 + CMPQ DI, BX + JAE lz4s_snappy_corrupt + INCQ DX + INCQ DI + TESTQ R8, R8 + JZ lz4s_snappy_lits_done + LEAQ (AX)(R8*1), R10 + CMPQ R10, CX + JAE lz4s_snappy_dstfull + ADDQ R8, SI + LEAL -1(R8), R10 + CMPL R10, $0x3c + JLT one_byte_lz4s_snappy + CMPL R10, $0x00000100 + JLT two_bytes_lz4s_snappy + CMPL R10, $0x00010000 + JLT three_bytes_lz4s_snappy + CMPL R10, $0x01000000 + JLT four_bytes_lz4s_snappy + MOVB $0xfc, (AX) + MOVL R10, 1(AX) + ADDQ $0x05, AX + JMP memmove_long_lz4s_snappy + +four_bytes_lz4s_snappy: + MOVL R10, R11 + SHRL $0x10, R11 + MOVB $0xf8, (AX) + MOVW R10, 1(AX) + MOVB R11, 3(AX) + ADDQ $0x04, AX + JMP memmove_long_lz4s_snappy + +three_bytes_lz4s_snappy: + MOVB $0xf4, (AX) + MOVW R10, 1(AX) + ADDQ $0x03, AX + JMP memmove_long_lz4s_snappy + +two_bytes_lz4s_snappy: + MOVB $0xf0, (AX) + MOVB R10, 1(AX) + ADDQ $0x02, AX + CMPL R10, $0x40 + JL memmove_lz4s_snappy + JMP memmove_long_lz4s_snappy + +one_byte_lz4s_snappy: + SHLB $0x02, R10 + MOVB R10, (AX) + ADDQ $0x01, AX + +memmove_lz4s_snappy: + LEAQ (AX)(R8*1), R10 + + // genMemMoveShort + CMPQ R8, $0x08 + JLE emit_lit_memmove_lz4s_snappy_memmove_move_8 + CMPQ R8, $0x10 + JBE emit_lit_memmove_lz4s_snappy_memmove_move_8through16 + CMPQ R8, $0x20 + JBE emit_lit_memmove_lz4s_snappy_memmove_move_17through32 + JMP emit_lit_memmove_lz4s_snappy_memmove_move_33through64 + +emit_lit_memmove_lz4s_snappy_memmove_move_8: + MOVQ (DX), R11 + MOVQ R11, (AX) + JMP memmove_end_copy_lz4s_snappy + +emit_lit_memmove_lz4s_snappy_memmove_move_8through16: + MOVQ (DX), R11 + MOVQ -8(DX)(R8*1), DX + MOVQ R11, (AX) + MOVQ DX, -8(AX)(R8*1) + JMP memmove_end_copy_lz4s_snappy + +emit_lit_memmove_lz4s_snappy_memmove_move_17through32: + MOVOU (DX), X0 + MOVOU -16(DX)(R8*1), X1 + MOVOU X0, (AX) + MOVOU X1, -16(AX)(R8*1) + JMP memmove_end_copy_lz4s_snappy + +emit_lit_memmove_lz4s_snappy_memmove_move_33through64: + MOVOU (DX), X0 + MOVOU 16(DX), X1 + MOVOU -32(DX)(R8*1), X2 + MOVOU -16(DX)(R8*1), X3 + MOVOU X0, (AX) + MOVOU X1, 16(AX) + MOVOU X2, -32(AX)(R8*1) + MOVOU X3, -16(AX)(R8*1) + +memmove_end_copy_lz4s_snappy: + MOVQ R10, AX + JMP lz4s_snappy_lits_emit_done + +memmove_long_lz4s_snappy: + LEAQ (AX)(R8*1), R10 + + // genMemMoveLong + MOVOU (DX), X0 + MOVOU 16(DX), X1 + MOVOU -32(DX)(R8*1), X2 + MOVOU -16(DX)(R8*1), X3 + MOVQ R8, R12 + SHRQ $0x05, R12 + MOVQ AX, R11 + ANDL $0x0000001f, R11 + MOVQ $0x00000040, R13 + SUBQ R11, R13 + DECQ R12 + JA emit_lit_memmove_long_lz4s_snappylarge_forward_sse_loop_32 + LEAQ -32(DX)(R13*1), R11 + LEAQ -32(AX)(R13*1), R14 + +emit_lit_memmove_long_lz4s_snappylarge_big_loop_back: + MOVOU (R11), X4 + MOVOU 16(R11), X5 + MOVOA X4, (R14) + MOVOA X5, 16(R14) + ADDQ $0x20, R14 + ADDQ $0x20, R11 + ADDQ $0x20, R13 + DECQ R12 + JNA emit_lit_memmove_long_lz4s_snappylarge_big_loop_back + +emit_lit_memmove_long_lz4s_snappylarge_forward_sse_loop_32: + MOVOU -32(DX)(R13*1), X4 + MOVOU -16(DX)(R13*1), X5 + MOVOA X4, -32(AX)(R13*1) + MOVOA X5, -16(AX)(R13*1) + ADDQ $0x20, R13 + CMPQ R8, R13 + JAE emit_lit_memmove_long_lz4s_snappylarge_forward_sse_loop_32 + MOVOU X0, (AX) + MOVOU X1, 16(AX) + MOVOU X2, -32(AX)(R8*1) + MOVOU X3, -16(AX)(R8*1) + MOVQ R10, AX + +lz4s_snappy_lits_emit_done: + MOVQ DI, DX + +lz4s_snappy_lits_done: + CMPQ DX, BX + JNE lz4s_snappy_match + CMPQ R9, $0x03 + JEQ lz4s_snappy_done + JMP lz4s_snappy_corrupt + +lz4s_snappy_match: + CMPQ R9, $0x03 + JEQ lz4s_snappy_loop + LEAQ 2(DX), DI + CMPQ DI, BX + JAE lz4s_snappy_corrupt + MOVWQZX (DX), R8 + MOVQ DI, DX + TESTQ R8, R8 + JZ lz4s_snappy_corrupt + CMPQ R8, SI + JA lz4s_snappy_corrupt + CMPQ R9, $0x12 + JNE lz4s_snappy_ml_done + +lz4s_snappy_ml_loop: + MOVBQZX (DX), DI + INCQ DX + ADDQ DI, R9 + CMPQ DX, BX + JAE lz4s_snappy_corrupt + CMPQ DI, $0xff + JEQ lz4s_snappy_ml_loop + +lz4s_snappy_ml_done: + ADDQ R9, SI + + // emitCopy +two_byte_offset_lz4_s2: + CMPL R9, $0x40 + JLE two_byte_offset_short_lz4_s2 + MOVB $0xee, (AX) + MOVW R8, 1(AX) + LEAL -60(R9), R9 + ADDQ $0x03, AX + CMPQ AX, CX + JAE lz4s_snappy_loop + JMP two_byte_offset_lz4_s2 + +two_byte_offset_short_lz4_s2: + MOVL R9, DI + SHLL $0x02, DI + CMPL R9, $0x0c + JGE emit_copy_three_lz4_s2 + CMPL R8, $0x00000800 + JGE emit_copy_three_lz4_s2 + LEAL -15(DI), DI + MOVB R8, 1(AX) + SHRL $0x08, R8 + SHLL $0x05, R8 + ORL R8, DI + MOVB DI, (AX) + ADDQ $0x02, AX + JMP lz4s_snappy_loop + +emit_copy_three_lz4_s2: + LEAL -2(DI), DI + MOVB DI, (AX) + MOVW R8, 1(AX) + ADDQ $0x03, AX + JMP lz4s_snappy_loop + +lz4s_snappy_done: + MOVQ dst_base+0(FP), CX + SUBQ CX, AX + MOVQ SI, uncompressed+48(FP) + MOVQ AX, dstUsed+56(FP) + RET + +lz4s_snappy_corrupt: + XORQ AX, AX + LEAQ -1(AX), SI + MOVQ SI, uncompressed+48(FP) + RET + +lz4s_snappy_dstfull: + XORQ AX, AX + LEAQ -2(AX), SI + MOVQ SI, uncompressed+48(FP) + RET diff --git a/test/performance/vendor/github.com/klauspost/compress/s2/lz4sconvert.go b/test/performance/vendor/github.com/klauspost/compress/s2/lz4sconvert.go new file mode 100644 index 000000000..000f39719 --- /dev/null +++ b/test/performance/vendor/github.com/klauspost/compress/s2/lz4sconvert.go @@ -0,0 +1,467 @@ +// Copyright (c) 2022 Klaus Post. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package s2 + +import ( + "encoding/binary" + "fmt" +) + +// LZ4sConverter provides conversion from LZ4s. +// (Intel modified LZ4 Blocks) +// https://cdrdv2-public.intel.com/743912/743912-qat-programmers-guide-v2.0.pdf +// LZ4s is a variant of LZ4 block format. LZ4s should be considered as an intermediate compressed block format. +// The LZ4s format is selected when the application sets the compType to CPA_DC_LZ4S in CpaDcSessionSetupData. +// The LZ4s block returned by the Intel® QAT hardware can be used by an external +// software post-processing to generate other compressed data formats. +// The following table lists the differences between LZ4 and LZ4s block format. LZ4s block format uses +// the same high-level formatting as LZ4 block format with the following encoding changes: +// For Min Match of 4 bytes, Copy length value 1-15 means length 4-18 with 18 bytes adding an extra byte. +// ONLY "Min match of 4 bytes" is supported. +type LZ4sConverter struct { +} + +// ConvertBlock will convert an LZ4s block and append it as an S2 +// block without block length to dst. +// The uncompressed size is returned as well. +// dst must have capacity to contain the entire compressed block. +func (l *LZ4sConverter) ConvertBlock(dst, src []byte) ([]byte, int, error) { + if len(src) == 0 { + return dst, 0, nil + } + const debug = false + const inline = true + const lz4MinMatch = 3 + + s, d := 0, len(dst) + dst = dst[:cap(dst)] + if !debug && hasAmd64Asm { + res, sz := cvtLZ4sBlockAsm(dst[d:], src) + if res < 0 { + const ( + errCorrupt = -1 + errDstTooSmall = -2 + ) + switch res { + case errCorrupt: + return nil, 0, ErrCorrupt + case errDstTooSmall: + return nil, 0, ErrDstTooSmall + default: + return nil, 0, fmt.Errorf("unexpected result: %d", res) + } + } + if d+sz > len(dst) { + return nil, 0, ErrDstTooSmall + } + return dst[:d+sz], res, nil + } + + dLimit := len(dst) - 10 + var lastOffset uint16 + var uncompressed int + if debug { + fmt.Printf("convert block start: len(src): %d, len(dst):%d \n", len(src), len(dst)) + } + + for { + if s >= len(src) { + return dst[:d], 0, ErrCorrupt + } + // Read literal info + token := src[s] + ll := int(token >> 4) + ml := int(lz4MinMatch + (token & 0xf)) + + // If upper nibble is 15, literal length is extended + if token >= 0xf0 { + for { + s++ + if s >= len(src) { + if debug { + fmt.Printf("error reading ll: s (%d) >= len(src) (%d)\n", s, len(src)) + } + return dst[:d], 0, ErrCorrupt + } + val := src[s] + ll += int(val) + if val != 255 { + break + } + } + } + // Skip past token + if s+ll >= len(src) { + if debug { + fmt.Printf("error literals: s+ll (%d+%d) >= len(src) (%d)\n", s, ll, len(src)) + } + return nil, 0, ErrCorrupt + } + s++ + if ll > 0 { + if d+ll > dLimit { + return nil, 0, ErrDstTooSmall + } + if debug { + fmt.Printf("emit %d literals\n", ll) + } + d += emitLiteralGo(dst[d:], src[s:s+ll]) + s += ll + uncompressed += ll + } + + // Check if we are done... + if ml == lz4MinMatch { + if s == len(src) { + break + } + // 0 bytes. + continue + } + // 2 byte offset + if s >= len(src)-2 { + if debug { + fmt.Printf("s (%d) >= len(src)-2 (%d)", s, len(src)-2) + } + return nil, 0, ErrCorrupt + } + offset := binary.LittleEndian.Uint16(src[s:]) + s += 2 + if offset == 0 { + if debug { + fmt.Printf("error: offset 0, ml: %d, len(src)-s: %d\n", ml, len(src)-s) + } + return nil, 0, ErrCorrupt + } + if int(offset) > uncompressed { + if debug { + fmt.Printf("error: offset (%d)> uncompressed (%d)\n", offset, uncompressed) + } + return nil, 0, ErrCorrupt + } + + if ml == lz4MinMatch+15 { + for { + if s >= len(src) { + if debug { + fmt.Printf("error reading ml: s (%d) >= len(src) (%d)\n", s, len(src)) + } + return nil, 0, ErrCorrupt + } + val := src[s] + s++ + ml += int(val) + if val != 255 { + if s >= len(src) { + if debug { + fmt.Printf("error reading ml: s (%d) >= len(src) (%d)\n", s, len(src)) + } + return nil, 0, ErrCorrupt + } + break + } + } + } + if offset == lastOffset { + if debug { + fmt.Printf("emit repeat, length: %d, offset: %d\n", ml, offset) + } + if !inline { + d += emitRepeat16(dst[d:], offset, ml) + } else { + length := ml + dst := dst[d:] + for len(dst) > 5 { + // Repeat offset, make length cheaper + length -= 4 + if length <= 4 { + dst[0] = uint8(length)<<2 | tagCopy1 + dst[1] = 0 + d += 2 + break + } + if length < 8 && offset < 2048 { + // Encode WITH offset + dst[1] = uint8(offset) + dst[0] = uint8(offset>>8)<<5 | uint8(length)<<2 | tagCopy1 + d += 2 + break + } + if length < (1<<8)+4 { + length -= 4 + dst[2] = uint8(length) + dst[1] = 0 + dst[0] = 5<<2 | tagCopy1 + d += 3 + break + } + if length < (1<<16)+(1<<8) { + length -= 1 << 8 + dst[3] = uint8(length >> 8) + dst[2] = uint8(length >> 0) + dst[1] = 0 + dst[0] = 6<<2 | tagCopy1 + d += 4 + break + } + const maxRepeat = (1 << 24) - 1 + length -= 1 << 16 + left := 0 + if length > maxRepeat { + left = length - maxRepeat + 4 + length = maxRepeat - 4 + } + dst[4] = uint8(length >> 16) + dst[3] = uint8(length >> 8) + dst[2] = uint8(length >> 0) + dst[1] = 0 + dst[0] = 7<<2 | tagCopy1 + if left > 0 { + d += 5 + emitRepeat16(dst[5:], offset, left) + break + } + d += 5 + break + } + } + } else { + if debug { + fmt.Printf("emit copy, length: %d, offset: %d\n", ml, offset) + } + if !inline { + d += emitCopy16(dst[d:], offset, ml) + } else { + length := ml + dst := dst[d:] + for len(dst) > 5 { + // Offset no more than 2 bytes. + if length > 64 { + off := 3 + if offset < 2048 { + // emit 8 bytes as tagCopy1, rest as repeats. + dst[1] = uint8(offset) + dst[0] = uint8(offset>>8)<<5 | uint8(8-4)<<2 | tagCopy1 + length -= 8 + off = 2 + } else { + // Emit a length 60 copy, encoded as 3 bytes. + // Emit remaining as repeat value (minimum 4 bytes). + dst[2] = uint8(offset >> 8) + dst[1] = uint8(offset) + dst[0] = 59<<2 | tagCopy2 + length -= 60 + } + // Emit remaining as repeats, at least 4 bytes remain. + d += off + emitRepeat16(dst[off:], offset, length) + break + } + if length >= 12 || offset >= 2048 { + // Emit the remaining copy, encoded as 3 bytes. + dst[2] = uint8(offset >> 8) + dst[1] = uint8(offset) + dst[0] = uint8(length-1)<<2 | tagCopy2 + d += 3 + break + } + // Emit the remaining copy, encoded as 2 bytes. + dst[1] = uint8(offset) + dst[0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1 + d += 2 + break + } + } + lastOffset = offset + } + uncompressed += ml + if d > dLimit { + return nil, 0, ErrDstTooSmall + } + } + + return dst[:d], uncompressed, nil +} + +// ConvertBlockSnappy will convert an LZ4s block and append it +// as a Snappy block without block length to dst. +// The uncompressed size is returned as well. +// dst must have capacity to contain the entire compressed block. +func (l *LZ4sConverter) ConvertBlockSnappy(dst, src []byte) ([]byte, int, error) { + if len(src) == 0 { + return dst, 0, nil + } + const debug = false + const lz4MinMatch = 3 + + s, d := 0, len(dst) + dst = dst[:cap(dst)] + // Use assembly when possible + if !debug && hasAmd64Asm { + res, sz := cvtLZ4sBlockSnappyAsm(dst[d:], src) + if res < 0 { + const ( + errCorrupt = -1 + errDstTooSmall = -2 + ) + switch res { + case errCorrupt: + return nil, 0, ErrCorrupt + case errDstTooSmall: + return nil, 0, ErrDstTooSmall + default: + return nil, 0, fmt.Errorf("unexpected result: %d", res) + } + } + if d+sz > len(dst) { + return nil, 0, ErrDstTooSmall + } + return dst[:d+sz], res, nil + } + + dLimit := len(dst) - 10 + var uncompressed int + if debug { + fmt.Printf("convert block start: len(src): %d, len(dst):%d \n", len(src), len(dst)) + } + + for { + if s >= len(src) { + return nil, 0, ErrCorrupt + } + // Read literal info + token := src[s] + ll := int(token >> 4) + ml := int(lz4MinMatch + (token & 0xf)) + + // If upper nibble is 15, literal length is extended + if token >= 0xf0 { + for { + s++ + if s >= len(src) { + if debug { + fmt.Printf("error reading ll: s (%d) >= len(src) (%d)\n", s, len(src)) + } + return nil, 0, ErrCorrupt + } + val := src[s] + ll += int(val) + if val != 255 { + break + } + } + } + // Skip past token + if s+ll >= len(src) { + if debug { + fmt.Printf("error literals: s+ll (%d+%d) >= len(src) (%d)\n", s, ll, len(src)) + } + return nil, 0, ErrCorrupt + } + s++ + if ll > 0 { + if d+ll > dLimit { + return nil, 0, ErrDstTooSmall + } + if debug { + fmt.Printf("emit %d literals\n", ll) + } + d += emitLiteralGo(dst[d:], src[s:s+ll]) + s += ll + uncompressed += ll + } + + // Check if we are done... + if ml == lz4MinMatch { + if s == len(src) { + break + } + // 0 bytes. + continue + } + // 2 byte offset + if s >= len(src)-2 { + if debug { + fmt.Printf("s (%d) >= len(src)-2 (%d)", s, len(src)-2) + } + return nil, 0, ErrCorrupt + } + offset := binary.LittleEndian.Uint16(src[s:]) + s += 2 + if offset == 0 { + if debug { + fmt.Printf("error: offset 0, ml: %d, len(src)-s: %d\n", ml, len(src)-s) + } + return nil, 0, ErrCorrupt + } + if int(offset) > uncompressed { + if debug { + fmt.Printf("error: offset (%d)> uncompressed (%d)\n", offset, uncompressed) + } + return nil, 0, ErrCorrupt + } + + if ml == lz4MinMatch+15 { + for { + if s >= len(src) { + if debug { + fmt.Printf("error reading ml: s (%d) >= len(src) (%d)\n", s, len(src)) + } + return nil, 0, ErrCorrupt + } + val := src[s] + s++ + ml += int(val) + if val != 255 { + if s >= len(src) { + if debug { + fmt.Printf("error reading ml: s (%d) >= len(src) (%d)\n", s, len(src)) + } + return nil, 0, ErrCorrupt + } + break + } + } + } + if debug { + fmt.Printf("emit copy, length: %d, offset: %d\n", ml, offset) + } + length := ml + // d += emitCopyNoRepeat(dst[d:], int(offset), ml) + for length > 0 { + if d >= dLimit { + return nil, 0, ErrDstTooSmall + } + + // Offset no more than 2 bytes. + if length > 64 { + // Emit a length 64 copy, encoded as 3 bytes. + dst[d+2] = uint8(offset >> 8) + dst[d+1] = uint8(offset) + dst[d+0] = 63<<2 | tagCopy2 + length -= 64 + d += 3 + continue + } + if length >= 12 || offset >= 2048 || length < 4 { + // Emit the remaining copy, encoded as 3 bytes. + dst[d+2] = uint8(offset >> 8) + dst[d+1] = uint8(offset) + dst[d+0] = uint8(length-1)<<2 | tagCopy2 + d += 3 + break + } + // Emit the remaining copy, encoded as 2 bytes. + dst[d+1] = uint8(offset) + dst[d+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1 + d += 2 + break + } + uncompressed += ml + if d > dLimit { + return nil, 0, ErrDstTooSmall + } + } + + return dst[:d], uncompressed, nil +} diff --git a/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/events/event.pb.go b/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/events/event.pb.go index 17f1ab782..a6bba3fd8 100644 --- a/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/events/event.pb.go +++ b/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/events/event.pb.go @@ -1291,208 +1291,9 @@ func (m *SecurityViolationEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) _ = i var l int _ = l -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -======= ->>>>>>> Create dedicated cache and upstream metrics reports -======= ->>>>>>> Create dedicated cache and upstream metrics reports -======= ->>>>>>> Create dedicated cache and upstream metrics reports - if len(m.PolicyName) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.PolicyName))) - i += copy(dAtA[i:], m.PolicyName) -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } -<<<<<<< HEAD - if len(m.DisplayName) > 0 { - i -= len(m.DisplayName) - copy(dAtA[i:], m.DisplayName) - i = encodeVarintEvent(dAtA, i, uint64(len(m.DisplayName))) - i-- - dAtA[i] = 0x2 - i-- - dAtA[i] = 0xb2 -======= - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= if m.XXX_unrecognized != nil { i -= len(m.XXX_unrecognized) copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf -======= ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= - if m.XXX_unrecognized != nil { - i -= len(m.XXX_unrecognized) - copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf -======= ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= - if m.XXX_unrecognized != nil { - i -= len(m.XXX_unrecognized) - copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf -======= ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= - if m.XXX_unrecognized != nil { - i -= len(m.XXX_unrecognized) - copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf } if len(m.ParentHostname) > 0 { i -= len(m.ParentHostname) @@ -1503,15 +1304,6 @@ func (m *SecurityViolationEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) i-- dAtA[i] = 0xc2 } - if len(m.NginxID) > 0 { - i -= len(m.NginxID) - copy(dAtA[i:], m.NginxID) - i = encodeVarintEvent(dAtA, i, uint64(len(m.NginxID))) - i-- - dAtA[i] = 0x2 - i-- - dAtA[i] = 0xba - } if len(m.DisplayName) > 0 { i -= len(m.DisplayName) copy(dAtA[i:], m.DisplayName) diff --git a/test/performance/vendor/github.com/spf13/afero/afero.go b/test/performance/vendor/github.com/spf13/afero/afero.go index 199480cd0..39f658520 100644 --- a/test/performance/vendor/github.com/spf13/afero/afero.go +++ b/test/performance/vendor/github.com/spf13/afero/afero.go @@ -97,7 +97,7 @@ type Fs interface { // Chown changes the uid and gid of the named file. Chown(name string, uid, gid int) error - //Chtimes changes the access and modification times of the named file + // Chtimes changes the access and modification times of the named file Chtimes(name string, atime time.Time, mtime time.Time) error } diff --git a/test/performance/vendor/github.com/spf13/afero/basepath.go b/test/performance/vendor/github.com/spf13/afero/basepath.go index 70a1d9168..2e72793a3 100644 --- a/test/performance/vendor/github.com/spf13/afero/basepath.go +++ b/test/performance/vendor/github.com/spf13/afero/basepath.go @@ -40,7 +40,6 @@ func (f *BasePathFile) Name() string { func (f *BasePathFile) ReadDir(n int) ([]fs.DirEntry, error) { if rdf, ok := f.File.(fs.ReadDirFile); ok { return rdf.ReadDir(n) - } return readDirFile{f.File}.ReadDir(n) } diff --git a/test/performance/vendor/github.com/spf13/afero/copyOnWriteFs.go b/test/performance/vendor/github.com/spf13/afero/copyOnWriteFs.go index 6ff8f3099..184d6dd70 100644 --- a/test/performance/vendor/github.com/spf13/afero/copyOnWriteFs.go +++ b/test/performance/vendor/github.com/spf13/afero/copyOnWriteFs.go @@ -223,7 +223,7 @@ func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, return nil, err } if isaDir { - if err = u.layer.MkdirAll(dir, 0777); err != nil { + if err = u.layer.MkdirAll(dir, 0o777); err != nil { return nil, err } return u.layer.OpenFile(name, flag, perm) @@ -247,8 +247,9 @@ func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, // This function handles the 9 different possibilities caused // by the union which are the intersection of the following... -// layer: doesn't exist, exists as a file, and exists as a directory -// base: doesn't exist, exists as a file, and exists as a directory +// +// layer: doesn't exist, exists as a file, and exists as a directory +// base: doesn't exist, exists as a file, and exists as a directory func (u *CopyOnWriteFs) Open(name string) (File, error) { // Since the overlay overrides the base we check that first b, err := u.isBaseFile(name) @@ -322,5 +323,5 @@ func (u *CopyOnWriteFs) MkdirAll(name string, perm os.FileMode) error { } func (u *CopyOnWriteFs) Create(name string) (File, error) { - return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666) + return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0o666) } diff --git a/test/performance/vendor/github.com/spf13/afero/ioutil.go b/test/performance/vendor/github.com/spf13/afero/ioutil.go index 386c9cdc2..fa6abe1ee 100644 --- a/test/performance/vendor/github.com/spf13/afero/ioutil.go +++ b/test/performance/vendor/github.com/spf13/afero/ioutil.go @@ -141,8 +141,10 @@ func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error { // We generate random temporary file names so that there's a good // chance the file doesn't exist yet - keeps the number of tries in // TempFile to a minimum. -var randNum uint32 -var randmu sync.Mutex +var ( + randNum uint32 + randmu sync.Mutex +) func reseed() uint32 { return uint32(time.Now().UnixNano() + int64(os.Getpid())) @@ -190,7 +192,7 @@ func TempFile(fs Fs, dir, pattern string) (f File, err error) { nconflict := 0 for i := 0; i < 10000; i++ { name := filepath.Join(dir, prefix+nextRandom()+suffix) - f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) + f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() @@ -214,6 +216,7 @@ func TempFile(fs Fs, dir, pattern string) (f File, err error) { func (a Afero) TempDir(dir, prefix string) (name string, err error) { return TempDir(a.Fs, dir, prefix) } + func TempDir(fs Fs, dir, prefix string) (name string, err error) { if dir == "" { dir = os.TempDir() @@ -222,7 +225,7 @@ func TempDir(fs Fs, dir, prefix string) (name string, err error) { nconflict := 0 for i := 0; i < 10000; i++ { try := filepath.Join(dir, prefix+nextRandom()) - err = fs.Mkdir(try, 0700) + err = fs.Mkdir(try, 0o700) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() diff --git a/test/performance/vendor/github.com/spf13/afero/mem/file.go b/test/performance/vendor/github.com/spf13/afero/mem/file.go index 3cf4693b5..62fe4498e 100644 --- a/test/performance/vendor/github.com/spf13/afero/mem/file.go +++ b/test/performance/vendor/github.com/spf13/afero/mem/file.go @@ -245,7 +245,7 @@ func (f *File) Truncate(size int64) error { defer f.fileData.Unlock() if size > int64(len(f.fileData.data)) { diff := size - int64(len(f.fileData.data)) - f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{00}, int(diff))...) + f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{0o0}, int(diff))...) } else { f.fileData.data = f.fileData.data[0:size] } @@ -285,7 +285,7 @@ func (f *File) Write(b []byte) (n int, err error) { tail = f.fileData.data[n+int(cur):] } if diff > 0 { - f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{00}, int(diff)), b...)...) + f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{0o0}, int(diff)), b...)...) f.fileData.data = append(f.fileData.data, tail...) } else { f.fileData.data = append(f.fileData.data[:cur], b...) @@ -321,16 +321,19 @@ func (s *FileInfo) Name() string { s.Unlock() return name } + func (s *FileInfo) Mode() os.FileMode { s.Lock() defer s.Unlock() return s.mode } + func (s *FileInfo) ModTime() time.Time { s.Lock() defer s.Unlock() return s.modtime } + func (s *FileInfo) IsDir() bool { s.Lock() defer s.Unlock() diff --git a/test/performance/vendor/github.com/spf13/afero/memmap.go b/test/performance/vendor/github.com/spf13/afero/memmap.go index d06975e71..e6b7d70b9 100644 --- a/test/performance/vendor/github.com/spf13/afero/memmap.go +++ b/test/performance/vendor/github.com/spf13/afero/memmap.go @@ -15,6 +15,7 @@ package afero import ( "fmt" + "io" "log" "os" "path/filepath" @@ -43,7 +44,7 @@ func (m *MemMapFs) getData() map[string]*mem.FileData { // Root should always exist, right? // TODO: what about windows? root := mem.CreateDir(FilePathSeparator) - mem.SetMode(root, os.ModeDir|0755) + mem.SetMode(root, os.ModeDir|0o755) m.data[FilePathSeparator] = root }) return m.data @@ -96,12 +97,12 @@ func (m *MemMapFs) registerWithParent(f *mem.FileData, perm os.FileMode) { pdir := filepath.Dir(filepath.Clean(f.Name())) err := m.lockfreeMkdir(pdir, perm) if err != nil { - //log.Println("Mkdir error:", err) + // log.Println("Mkdir error:", err) return } parent, err = m.lockfreeOpen(pdir) if err != nil { - //log.Println("Open after Mkdir error:", err) + // log.Println("Open after Mkdir error:", err) return } } @@ -237,7 +238,7 @@ func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, erro file = mem.NewReadOnlyFileHandle(file.(*mem.File).Data()) } if flag&os.O_APPEND > 0 { - _, err = file.Seek(0, os.SEEK_END) + _, err = file.Seek(0, io.SeekEnd) if err != nil { file.Close() return nil, err @@ -319,6 +320,18 @@ func (m *MemMapFs) Rename(oldname, newname string) error { } else { return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound} } + + for p, fileData := range m.getData() { + if strings.HasPrefix(p, oldname+FilePathSeparator) { + m.mu.RUnlock() + m.mu.Lock() + delete(m.getData(), p) + p := strings.Replace(p, oldname, newname, 1) + m.getData()[p] = fileData + m.mu.Unlock() + m.mu.RLock() + } + } return nil } diff --git a/test/performance/vendor/github.com/spf13/afero/regexpfs.go b/test/performance/vendor/github.com/spf13/afero/regexpfs.go index ac359c62a..218f3b235 100644 --- a/test/performance/vendor/github.com/spf13/afero/regexpfs.go +++ b/test/performance/vendor/github.com/spf13/afero/regexpfs.go @@ -10,7 +10,6 @@ import ( // The RegexpFs filters files (not directories) by regular expression. Only // files matching the given regexp will be allowed, all others get a ENOENT error ( // "No such file or directory"). -// type RegexpFs struct { re *regexp.Regexp source Fs diff --git a/test/performance/vendor/github.com/spf13/afero/symlink.go b/test/performance/vendor/github.com/spf13/afero/symlink.go index d1c6ea53d..aa6ae125b 100644 --- a/test/performance/vendor/github.com/spf13/afero/symlink.go +++ b/test/performance/vendor/github.com/spf13/afero/symlink.go @@ -21,9 +21,9 @@ import ( // filesystems saying so. // It indicates support for 3 symlink related interfaces that implement the // behaviors of the os methods: -// - Lstat -// - Symlink, and -// - Readlink +// - Lstat +// - Symlink, and +// - Readlink type Symlinker interface { Lstater Linker diff --git a/test/performance/vendor/github.com/spf13/afero/unionFile.go b/test/performance/vendor/github.com/spf13/afero/unionFile.go index 333d367f4..62dd6c93c 100644 --- a/test/performance/vendor/github.com/spf13/afero/unionFile.go +++ b/test/performance/vendor/github.com/spf13/afero/unionFile.go @@ -47,7 +47,7 @@ func (f *UnionFile) Read(s []byte) (int, error) { if (err == nil || err == io.EOF) && f.Base != nil { // advance the file position also in the base file, the next // call may be a write at this position (or a seek with SEEK_CUR) - if _, seekErr := f.Base.Seek(int64(n), os.SEEK_CUR); seekErr != nil { + if _, seekErr := f.Base.Seek(int64(n), io.SeekCurrent); seekErr != nil { // only overwrite err in case the seek fails: we need to // report an eventual io.EOF to the caller err = seekErr @@ -130,7 +130,7 @@ func (f *UnionFile) Name() string { type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) { - var files = make(map[string]os.FileInfo) + files := make(map[string]os.FileInfo) for _, fi := range lofi { files[fi.Name()] = fi @@ -151,7 +151,6 @@ var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, err } return rfi, nil - } // Readdir will weave the two directories together and @@ -275,7 +274,7 @@ func copyFile(base Fs, layer Fs, name string, bfh File) error { return err } if !exists { - err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME? + err = layer.MkdirAll(filepath.Dir(name), 0o777) // FIXME? if err != nil { return err } diff --git a/test/performance/vendor/github.com/spf13/afero/util.go b/test/performance/vendor/github.com/spf13/afero/util.go index cb7de23f2..9e4cba274 100644 --- a/test/performance/vendor/github.com/spf13/afero/util.go +++ b/test/performance/vendor/github.com/spf13/afero/util.go @@ -43,7 +43,7 @@ func WriteReader(fs Fs, path string, r io.Reader) (err error) { ospath := filepath.FromSlash(dir) if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r + err = fs.MkdirAll(ospath, 0o777) // rwx, rw, r if err != nil { if err != os.ErrExist { return err @@ -71,7 +71,7 @@ func SafeWriteReader(fs Fs, path string, r io.Reader) (err error) { ospath := filepath.FromSlash(dir) if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r + err = fs.MkdirAll(ospath, 0o777) // rwx, rw, r if err != nil { return } @@ -124,7 +124,7 @@ func GetTempDir(fs Fs, subPath string) string { return addSlash(dir) } - err := fs.MkdirAll(dir, 0777) + err := fs.MkdirAll(dir, 0o777) if err != nil { panic(err) } @@ -197,7 +197,6 @@ func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, err // readerContains reports whether any of the subslices is within r. func readerContainsAny(r io.Reader, subslices ...[]byte) bool { - if r == nil || len(subslices) == 0 { return false } diff --git a/test/performance/vendor/modules.txt b/test/performance/vendor/modules.txt index 5f41ac4d8..0a72a03e6 100644 --- a/test/performance/vendor/modules.txt +++ b/test/performance/vendor/modules.txt @@ -69,7 +69,7 @@ github.com/inconshreveable/mousetrap # github.com/kelseyhightower/envconfig v1.4.0 ## explicit github.com/kelseyhightower/envconfig -# github.com/klauspost/compress v1.16.0 +# github.com/klauspost/compress v1.16.3 ## explicit; go 1.18 github.com/klauspost/compress/s2 # github.com/klauspost/cpuid/v2 v2.1.0 @@ -237,7 +237,7 @@ github.com/shirou/gopsutil/v3/process # github.com/sirupsen/logrus v1.9.0 ## explicit; go 1.13 github.com/sirupsen/logrus -# github.com/spf13/afero v1.9.3 +# github.com/spf13/afero v1.9.5 ## explicit; go 1.16 github.com/spf13/afero github.com/spf13/afero/internal/common diff --git a/vendor/github.com/aymanbagabas/go-osc52/v2/LICENSE b/vendor/github.com/aymanbagabas/go-osc52/v2/LICENSE new file mode 100644 index 000000000..25cec1ed4 --- /dev/null +++ b/vendor/github.com/aymanbagabas/go-osc52/v2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Ayman Bagabas + +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/vendor/github.com/aymanbagabas/go-osc52/v2/README.md b/vendor/github.com/aymanbagabas/go-osc52/v2/README.md new file mode 100644 index 000000000..4de3a22d1 --- /dev/null +++ b/vendor/github.com/aymanbagabas/go-osc52/v2/README.md @@ -0,0 +1,83 @@ + +# go-osc52 + +

+ Latest Release + GoDoc +

+ +A Go library to work with the [ANSI OSC52](https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands) terminal sequence. + +## Usage + +You can use this small library to construct an ANSI OSC52 sequence suitable for +your terminal. + + +### Example + +```go +import ( + "os" + "fmt" + + "github.com/aymanbagabas/go-osc52/v2" +) + +func main() { + s := "Hello World!" + + // Copy `s` to system clipboard + osc52.New(s).WriteTo(os.Stderr) + + // Copy `s` to primary clipboard (X11) + osc52.New(s).Primary().WriteTo(os.Stderr) + + // Query the clipboard + osc52.Query().WriteTo(os.Stderr) + + // Clear system clipboard + osc52.Clear().WriteTo(os.Stderr) + + // Use the fmt.Stringer interface to copy `s` to system clipboard + fmt.Fprint(os.Stderr, osc52.New(s)) + + // Or to primary clipboard + fmt.Fprint(os.Stderr, osc52.New(s).Primary()) +} +``` + +## SSH Example + +You can use this over SSH using [gliderlabs/ssh](https://github.com/gliderlabs/ssh) for instance: + +```go +var sshSession ssh.Session +seq := osc52.New("Hello awesome!") +// Check if term is screen or tmux +pty, _, _ := s.Pty() +if pty.Term == "screen" { + seq = seq.Screen() +} else if isTmux { + seq = seq.Tmux() +} +seq.WriteTo(sshSession.Stderr()) +``` + +## Tmux + +Make sure you have `set-clipboard on` in your config, otherwise, tmux won't +allow your application to access the clipboard [^1]. + +Using the tmux option, `osc52.TmuxMode` or `osc52.New(...).Tmux()`, wraps the +OSC52 sequence in a special tmux DCS sequence and pass it to the outer +terminal. This requires `allow-passthrough on` in your config. +`allow-passthrough` is no longer enabled by default +[since tmux 3.3a](https://github.com/tmux/tmux/issues/3218#issuecomment-1153089282) [^2]. + +[^1]: See [tmux clipboard](https://github.com/tmux/tmux/wiki/Clipboard) +[^2]: [What is allow-passthrough](https://github.com/tmux/tmux/wiki/FAQ#what-is-the-passthrough-escape-sequence-and-how-do-i-use-it) + +## Credits + +* [vim-oscyank](https://github.com/ojroques/vim-oscyank) this is heavily inspired by vim-oscyank. diff --git a/vendor/github.com/aymanbagabas/go-osc52/v2/osc52.go b/vendor/github.com/aymanbagabas/go-osc52/v2/osc52.go new file mode 100644 index 000000000..dc758d286 --- /dev/null +++ b/vendor/github.com/aymanbagabas/go-osc52/v2/osc52.go @@ -0,0 +1,305 @@ +// OSC52 is a terminal escape sequence that allows copying text to the clipboard. +// +// The sequence consists of the following: +// +// OSC 52 ; Pc ; Pd BEL +// +// Pc is the clipboard choice: +// +// c: clipboard +// p: primary +// q: secondary (not supported) +// s: select (not supported) +// 0-7: cut-buffers (not supported) +// +// Pd is the data to copy to the clipboard. This string should be encoded in +// base64 (RFC-4648). +// +// If Pd is "?", the terminal replies to the host with the current contents of +// the clipboard. +// +// If Pd is neither a base64 string nor "?", the terminal clears the clipboard. +// +// See https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands +// where Ps = 52 => Manipulate Selection Data. +// +// Examples: +// +// // copy "hello world" to the system clipboard +// fmt.Fprint(os.Stderr, osc52.New("hello world")) +// +// // copy "hello world" to the primary Clipboard +// fmt.Fprint(os.Stderr, osc52.New("hello world").Primary()) +// +// // limit the size of the string to copy 10 bytes +// fmt.Fprint(os.Stderr, osc52.New("0123456789").Limit(10)) +// +// // escape the OSC52 sequence for screen using DCS sequences +// fmt.Fprint(os.Stderr, osc52.New("hello world").Screen()) +// +// // escape the OSC52 sequence for Tmux +// fmt.Fprint(os.Stderr, osc52.New("hello world").Tmux()) +// +// // query the system Clipboard +// fmt.Fprint(os.Stderr, osc52.Query()) +// +// // query the primary clipboard +// fmt.Fprint(os.Stderr, osc52.Query().Primary()) +// +// // clear the system Clipboard +// fmt.Fprint(os.Stderr, osc52.Clear()) +// +// // clear the primary Clipboard +// fmt.Fprint(os.Stderr, osc52.Clear().Primary()) +package osc52 + +import ( + "encoding/base64" + "fmt" + "io" + "strings" +) + +// Clipboard is the clipboard buffer to use. +type Clipboard rune + +const ( + // SystemClipboard is the system clipboard buffer. + SystemClipboard Clipboard = 'c' + // PrimaryClipboard is the primary clipboard buffer (X11). + PrimaryClipboard = 'p' +) + +// Mode is the mode to use for the OSC52 sequence. +type Mode uint + +const ( + // DefaultMode is the default OSC52 sequence mode. + DefaultMode Mode = iota + // ScreenMode escapes the OSC52 sequence for screen using DCS sequences. + ScreenMode + // TmuxMode escapes the OSC52 sequence for tmux. Not needed if tmux + // clipboard is set to `set-clipboard on` + TmuxMode +) + +// Operation is the OSC52 operation. +type Operation uint + +const ( + // SetOperation is the copy operation. + SetOperation Operation = iota + // QueryOperation is the query operation. + QueryOperation + // ClearOperation is the clear operation. + ClearOperation +) + +// Sequence is the OSC52 sequence. +type Sequence struct { + str string + limit int + op Operation + mode Mode + clipboard Clipboard +} + +var _ fmt.Stringer = Sequence{} + +var _ io.WriterTo = Sequence{} + +// String returns the OSC52 sequence. +func (s Sequence) String() string { + var seq strings.Builder + // mode escape sequences start + seq.WriteString(s.seqStart()) + // actual OSC52 sequence start + seq.WriteString(fmt.Sprintf("\x1b]52;%c;", s.clipboard)) + switch s.op { + case SetOperation: + str := s.str + if s.limit > 0 && len(str) > s.limit { + return "" + } + b64 := base64.StdEncoding.EncodeToString([]byte(str)) + switch s.mode { + case ScreenMode: + // Screen doesn't support OSC52 but will pass the contents of a DCS + // sequence to the outer terminal unchanged. + // + // Here, we split the encoded string into 76 bytes chunks and then + // join the chunks with sequences. Finally, + // wrap the whole thing in + // . + // s := strings.SplitN(b64, "", 76) + s := make([]string, 0, len(b64)/76+1) + for i := 0; i < len(b64); i += 76 { + end := i + 76 + if end > len(b64) { + end = len(b64) + } + s = append(s, b64[i:end]) + } + seq.WriteString(strings.Join(s, "\x1b\\\x1bP")) + default: + seq.WriteString(b64) + } + case QueryOperation: + // OSC52 queries the clipboard using "?" + seq.WriteString("?") + case ClearOperation: + // OSC52 clears the clipboard if the data is neither a base64 string nor "?" + // we're using "!" as a default + seq.WriteString("!") + } + // actual OSC52 sequence end + seq.WriteString("\x07") + // mode escape end + seq.WriteString(s.seqEnd()) + return seq.String() +} + +// WriteTo writes the OSC52 sequence to the writer. +func (s Sequence) WriteTo(out io.Writer) (int64, error) { + n, err := out.Write([]byte(s.String())) + return int64(n), err +} + +// Mode sets the mode for the OSC52 sequence. +func (s Sequence) Mode(m Mode) Sequence { + s.mode = m + return s +} + +// Tmux sets the mode to TmuxMode. +// Used to escape the OSC52 sequence for `tmux`. +// +// Note: this is not needed if tmux clipboard is set to `set-clipboard on`. If +// TmuxMode is used, tmux must have `allow-passthrough on` set. +// +// This is a syntactic sugar for s.Mode(TmuxMode). +func (s Sequence) Tmux() Sequence { + return s.Mode(TmuxMode) +} + +// Screen sets the mode to ScreenMode. +// Used to escape the OSC52 sequence for `screen`. +// +// This is a syntactic sugar for s.Mode(ScreenMode). +func (s Sequence) Screen() Sequence { + return s.Mode(ScreenMode) +} + +// Clipboard sets the clipboard buffer for the OSC52 sequence. +func (s Sequence) Clipboard(c Clipboard) Sequence { + s.clipboard = c + return s +} + +// Primary sets the clipboard buffer to PrimaryClipboard. +// This is the X11 primary clipboard. +// +// This is a syntactic sugar for s.Clipboard(PrimaryClipboard). +func (s Sequence) Primary() Sequence { + return s.Clipboard(PrimaryClipboard) +} + +// Limit sets the limit for the OSC52 sequence. +// The default limit is 0 (no limit). +// +// Strings longer than the limit get ignored. Settting the limit to 0 or a +// negative value disables the limit. Each terminal defines its own escapse +// sequence limit. +func (s Sequence) Limit(l int) Sequence { + if l < 0 { + s.limit = 0 + } else { + s.limit = l + } + return s +} + +// Operation sets the operation for the OSC52 sequence. +// The default operation is SetOperation. +func (s Sequence) Operation(o Operation) Sequence { + s.op = o + return s +} + +// Clear sets the operation to ClearOperation. +// This clears the clipboard. +// +// This is a syntactic sugar for s.Operation(ClearOperation). +func (s Sequence) Clear() Sequence { + return s.Operation(ClearOperation) +} + +// Query sets the operation to QueryOperation. +// This queries the clipboard contents. +// +// This is a syntactic sugar for s.Operation(QueryOperation). +func (s Sequence) Query() Sequence { + return s.Operation(QueryOperation) +} + +// SetString sets the string for the OSC52 sequence. Strings are joined with a +// space character. +func (s Sequence) SetString(strs ...string) Sequence { + s.str = strings.Join(strs, " ") + return s +} + +// New creates a new OSC52 sequence with the given string(s). Strings are +// joined with a space character. +func New(strs ...string) Sequence { + s := Sequence{ + str: strings.Join(strs, " "), + limit: 0, + mode: DefaultMode, + clipboard: SystemClipboard, + op: SetOperation, + } + return s +} + +// Query creates a new OSC52 sequence with the QueryOperation. +// This returns a new OSC52 sequence to query the clipboard contents. +// +// This is a syntactic sugar for New().Query(). +func Query() Sequence { + return New().Query() +} + +// Clear creates a new OSC52 sequence with the ClearOperation. +// This returns a new OSC52 sequence to clear the clipboard. +// +// This is a syntactic sugar for New().Clear(). +func Clear() Sequence { + return New().Clear() +} + +func (s Sequence) seqStart() string { + switch s.mode { + case TmuxMode: + // Write the start of a tmux escape sequence. + return "\x1bPtmux;\x1b" + case ScreenMode: + // Write the start of a DCS sequence. + return "\x1bP" + default: + return "" + } +} + +func (s Sequence) seqEnd() string { + switch s.mode { + case TmuxMode: + // Terminate the tmux escape sequence. + return "\x1b\\" + case ScreenMode: + // Write the end of a DCS sequence. + return "\x1b\x5c" + default: + return "" + } +} diff --git a/vendor/github.com/briandowns/spinner/spinner.go b/vendor/github.com/briandowns/spinner/spinner.go index 7b7b081db..97b1a8f74 100644 --- a/vendor/github.com/briandowns/spinner/spinner.go +++ b/vendor/github.com/briandowns/spinner/spinner.go @@ -187,6 +187,7 @@ type Spinner struct { LastOutput string // last character(set) written with colors color func(a ...interface{}) string // default color is white Writer io.Writer // to make testing better, exported so users have access. Use `WithWriter` to update after initialization. + WriterFile *os.File // writer as file to allow terminal check active bool // active holds the state of the spinner enabled bool // indicates whether the spinner is enabled or not stopChan chan struct{} // stopChan is a channel used to stop the indicator @@ -203,6 +204,7 @@ func New(cs []string, d time.Duration, options ...Option) *Spinner { color: color.New(color.FgWhite).SprintFunc(), mu: &sync.RWMutex{}, Writer: color.Output, + WriterFile: os.Stdout, // matches color.Output stopChan: make(chan struct{}, 1), active: false, enabled: true, @@ -261,11 +263,28 @@ func WithHiddenCursor(hideCursor bool) Option { // WithWriter adds the given writer to the spinner. This // function should be favored over directly assigning to -// the struct value. +// the struct value. Assumes it is not working on a terminal +// since it cannot determine from io.Writer. Use WithWriterFile +// to support terminal checks. func WithWriter(w io.Writer) Option { return func(s *Spinner) { s.mu.Lock() s.Writer = w + s.WriterFile = os.Stdout // emulate previous behavior for terminal check + s.mu.Unlock() + } +} + +// WithWriterFile adds the given writer to the spinner. This +// function should be favored over directly assigning to +// the struct value. Unlike WithWriter, this function allows +// us to check if displaying to a terminal (enable spinning) or +// not (disable spinning). Supersedes WithWriter() +func WithWriterFile(f *os.File) Option { + return func(s *Spinner) { + s.mu.Lock() + s.Writer = f // io.Writer for actual writing + s.WriterFile = f // file used only for terminal check s.mu.Unlock() } } @@ -295,7 +314,7 @@ func (s *Spinner) Disable() { // Start will start the indicator. func (s *Spinner) Start() { s.mu.Lock() - if s.active || !s.enabled || !isRunningInTerminal() { + if s.active || !s.enabled || !isRunningInTerminal(s) { s.mu.Unlock() return } @@ -481,9 +500,9 @@ func GenerateNumberSequence(length int) []string { return numSeq } -// isRunningInTerminal check if stdout file descriptor is terminal -func isRunningInTerminal() bool { - return isatty.IsTerminal(os.Stdout.Fd()) +// isRunningInTerminal check if the writer file descriptor is a terminal +func isRunningInTerminal(s *Spinner) bool { + return isatty.IsTerminal(s.WriterFile.Fd()) } func computeNumberOfLinesNeededToPrintString(linePrinted string) int { diff --git a/vendor/github.com/charmbracelet/lipgloss/.gitignore b/vendor/github.com/charmbracelet/lipgloss/.gitignore new file mode 100644 index 000000000..a170af09c --- /dev/null +++ b/vendor/github.com/charmbracelet/lipgloss/.gitignore @@ -0,0 +1 @@ +ssh_example_ed25519* \ No newline at end of file diff --git a/vendor/github.com/charmbracelet/lipgloss/README.md b/vendor/github.com/charmbracelet/lipgloss/README.md index 039e28c7c..a071564ec 100644 --- a/vendor/github.com/charmbracelet/lipgloss/README.md +++ b/vendor/github.com/charmbracelet/lipgloss/README.md @@ -27,10 +27,9 @@ var style = lipgloss.NewStyle(). PaddingLeft(4). Width(22) -fmt.Println(style.Render("Hello, kitty.")) +fmt.Println(style.Render("Hello, kitty")) ``` - ## Colors Lip Gloss supports the following color profiles: @@ -59,7 +58,7 @@ lipgloss.Color("#04B575") // a green lipgloss.Color("#3C3C3C") // a dark gray ``` -...as well as a 1-bit Ascii profile, which is black and white only. +...as well as a 1-bit ASCII profile, which is black and white only. The terminal's color profile will be automatically detected, and colors outside the gamut of the current palette will be automatically coerced to their closest @@ -77,6 +76,29 @@ lipgloss.AdaptiveColor{Light: "236", Dark: "248"} The terminal's background color will automatically be detected and the appropriate color will be chosen at runtime. +### Complete Colors + +CompleteColor specifies exact values for truecolor, ANSI256, and ANSI color +profiles. + +```go +lipgloss.CompleteColor{True: "#0000FF", ANSI256: "86", ANSI: "5"} +``` + +Automatic color degradation will not be performed in this case and it will be +based on the color specified. + +### Complete Adaptive Colors + +You can use CompleteColor with AdaptiveColor to specify the exact values for +light and dark backgrounds without automatic color degradation. + +```go +lipgloss.CompleteAdaptiveColor{ + Light: CompleteColor{TrueColor: "#d7ffae", ANSI256: "193", ANSI: "11"}, + Dark: CompleteColor{TrueColor: "#d75fee", ANSI256: "163", ANSI: "5"}, +} +``` ## Inline Formatting @@ -151,11 +173,11 @@ var style = lipgloss.NewStyle(). Setting a minimum width and height is simple and straightforward. ```go -var str = lipgloss.NewStyle(). +var style = lipgloss.NewStyle(). + SetString("What’s for lunch?"). Width(24). Height(32). - Foreground(lipgloss.Color("63")). - Render("What’s for lunch?") + Foreground(lipgloss.Color("63")) ``` @@ -218,7 +240,7 @@ var wildStyle = style.Copy().Blink(true) ``` `Copy()` performs a copy on the underlying data structure ensuring that you get -a true, dereferenced copy of a style. Without copying it's possible to mutate +a true, dereferenced copy of a style. Without copying, it's possible to mutate styles. @@ -274,20 +296,43 @@ someStyle.MaxWidth(5).MaxHeight(5).Render("yadda yadda") ## Rendering -Generally, you just call the `Render(string)` method on a `lipgloss.Style`: +Generally, you just call the `Render(string...)` method on a `lipgloss.Style`: ```go -fmt.Println(lipgloss.NewStyle().Bold(true).Render("Hello, kitty.")) +style := lipgloss.NewStyle().Bold(true).SetString("Hello,") +fmt.Println(style.Render("kitty.")) // Hello, kitty. +fmt.Println(style.Render("puppy.")) // Hello, puppy. ``` But you could also use the Stringer interface: ```go var style = lipgloss.NewStyle().SetString("你好,猫咪。").Bold(true) +fmt.Println(style) // 你好,猫咪。 +``` + +### Custom Renderers + +Custom renderers allow you to render to a specific outputs. This is +particularly important when you want to render to different outputs and +correctly detect the color profile and dark background status for each, such as +in a server-client situation. + +```go +func myLittleHandler(sess ssh.Session) { + // Create a renderer for the client. + renderer := lipgloss.NewRenderer(sess) + + // Create a new style on the renderer. + style := renderer.NewStyle().Background(lipgloss.AdaptiveColor{Light: "63", Dark: "228"}) -fmt.Printf("%s\n", style) + // Render. The color profile and dark background state will be correctly detected. + io.WriteString(sess, style.Render("Heyyyyyyy")) +} ``` +For an example on using a custom renderer over SSH with [Wish][wish] see the +[SSH example][ssh-example]. ## Utilities @@ -318,10 +363,11 @@ Sometimes you’ll want to know the width and height of text blocks when buildin your layouts. ```go -var block string = lipgloss.NewStyle(). +// Render a block of text. +var style = lipgloss.NewStyle(). Width(40). - Padding(2). - Render(someLongString) + Padding(2) +var block string = style.Render(someLongString) // Get the actual, physical dimensions of the text block. width := lipgloss.Width(block) @@ -386,18 +432,27 @@ the stylesheet-based Markdown renderer. [glamour]: https://github.com/charmbracelet/glamour +## Feedback + +We’d love to hear your thoughts on this project. Feel free to drop us a note! + +* [Twitter](https://twitter.com/charmcli) +* [The Fediverse](https://mastodon.social/@charmcli) +* [Discord](https://charm.sh/chat) + ## License [MIT](https://github.com/charmbracelet/lipgloss/raw/master/LICENSE) - *** Part of [Charm](https://charm.sh). -The Charm logo +The Charm logo Charm热爱开源 • Charm loves open source [docs]: https://pkg.go.dev/github.com/charmbracelet/lipgloss?tab=doc +[wish]: https://github.com/charmbracelet/wish +[ssh-example]: examples/ssh diff --git a/vendor/github.com/charmbracelet/lipgloss/borders.go b/vendor/github.com/charmbracelet/lipgloss/borders.go index a3284ac05..18964221a 100644 --- a/vendor/github.com/charmbracelet/lipgloss/borders.go +++ b/vendor/github.com/charmbracelet/lipgloss/borders.go @@ -84,6 +84,39 @@ var ( BottomRight: "╯", } + blockBorder = Border{ + Top: "█", + Bottom: "█", + Left: "█", + Right: "█", + TopLeft: "█", + TopRight: "█", + BottomLeft: "█", + BottomRight: "█", + } + + outerHalfBlockBorder = Border{ + Top: "▀", + Bottom: "▄", + Left: "▌", + Right: "▐", + TopLeft: "▛", + TopRight: "▜", + BottomLeft: "▙", + BottomRight: "▟", + } + + innerHalfBlockBorder = Border{ + Top: "▄", + Bottom: "▀", + Left: "▐", + Right: "▌", + TopLeft: "▗", + TopRight: "▖", + BottomLeft: "▝", + BottomRight: "▘", + } + thickBorder = Border{ Top: "━", Bottom: "━", @@ -129,6 +162,21 @@ func RoundedBorder() Border { return roundedBorder } +// BlockBorder returns a border that takes the whole block. +func BlockBorder() Border { + return blockBorder +} + +// OuterHalfBlockBorder returns a half-block border that sits outside the frame. +func OuterHalfBlockBorder() Border { + return outerHalfBlockBorder +} + +// InnerHalfBlockBorder returns a half-block border that sits inside the frame. +func InnerHalfBlockBorder() Border { + return innerHalfBlockBorder +} + // ThickBorder returns a border that's thicker than the one returned by // NormalBorder. func ThickBorder() Border { @@ -199,7 +247,7 @@ func (s Style) applyBorder(str string) string { border.Right = " " } - // If corners should be render but are set with the empty string, fill them + // If corners should be rendered but are set with the empty string, fill them // with a single space. if hasTop && hasLeft && border.TopLeft == "" { border.TopLeft = " " @@ -250,7 +298,7 @@ func (s Style) applyBorder(str string) string { // Render top if hasTop { top := renderHorizontalEdge(border.TopLeft, border.Top, border.TopRight, width) - top = styleBorder(top, topFG, topBG) + top = s.styleBorder(top, topFG, topBG) out.WriteString(top) out.WriteRune('\n') } @@ -269,7 +317,7 @@ func (s Style) applyBorder(str string) string { if leftIndex >= len(leftRunes) { leftIndex = 0 } - out.WriteString(styleBorder(r, leftFG, leftBG)) + out.WriteString(s.styleBorder(r, leftFG, leftBG)) } out.WriteString(l) if hasRight { @@ -278,7 +326,7 @@ func (s Style) applyBorder(str string) string { if rightIndex >= len(rightRunes) { rightIndex = 0 } - out.WriteString(styleBorder(r, rightFG, rightBG)) + out.WriteString(s.styleBorder(r, rightFG, rightBG)) } if i < len(lines)-1 { out.WriteRune('\n') @@ -288,7 +336,7 @@ func (s Style) applyBorder(str string) string { // Render bottom if hasBottom { bottom := renderHorizontalEdge(border.BottomLeft, border.Bottom, border.BottomRight, width) - bottom = styleBorder(bottom, bottomFG, bottomBG) + bottom = s.styleBorder(bottom, bottomFG, bottomBG) out.WriteRune('\n') out.WriteString(bottom) } @@ -328,7 +376,7 @@ func renderHorizontalEdge(left, middle, right string, width int) string { } // Apply foreground and background styling to a border. -func styleBorder(border string, fg, bg TerminalColor) string { +func (s Style) styleBorder(border string, fg, bg TerminalColor) string { if fg == noColor && bg == noColor { return border } @@ -336,10 +384,10 @@ func styleBorder(border string, fg, bg TerminalColor) string { var style = termenv.Style{} if fg != noColor { - style = style.Foreground(ColorProfile().Color(fg.value())) + style = style.Foreground(fg.color(s.r)) } if bg != noColor { - style = style.Background(ColorProfile().Color(bg.value())) + style = style.Background(bg.color(s.r)) } return style.Styled(border) diff --git a/vendor/github.com/charmbracelet/lipgloss/color.go b/vendor/github.com/charmbracelet/lipgloss/color.go index 0e7de8903..ef7fd2796 100644 --- a/vendor/github.com/charmbracelet/lipgloss/color.go +++ b/vendor/github.com/charmbracelet/lipgloss/color.go @@ -1,102 +1,19 @@ package lipgloss import ( - "image/color" - "sync" + "strconv" "github.com/muesli/termenv" ) -var ( - colorProfile termenv.Profile - getColorProfile sync.Once - explicitColorProfile bool - - hasDarkBackground bool - getBackgroundColor sync.Once - explicitBackgroundColor bool - - colorProfileMtx sync.RWMutex -) - -// ColorProfile returns the detected termenv color profile. It will perform the -// actual check only once. -func ColorProfile() termenv.Profile { - colorProfileMtx.RLock() - defer colorProfileMtx.RUnlock() - - if !explicitColorProfile { - getColorProfile.Do(func() { - colorProfile = termenv.EnvColorProfile() - }) - } - return colorProfile -} - -// SetColorProfile sets the color profile on a package-wide context. This -// function exists mostly for testing purposes so that you can assure you're -// testing against a specific profile. -// -// Outside of testing you likely won't want to use this function as -// ColorProfile() will detect and cache the terminal's color capabilities -// and choose the best available profile. -// -// Available color profiles are: -// -// termenv.Ascii (no color, 1-bit) -// termenv.ANSI (16 colors, 4-bit) -// termenv.ANSI256 (256 colors, 8-bit) -// termenv.TrueColor (16,777,216 colors, 24-bit) -// -// This function is thread-safe. -func SetColorProfile(p termenv.Profile) { - colorProfileMtx.Lock() - defer colorProfileMtx.Unlock() - - colorProfile = p - explicitColorProfile = true -} - -// HasDarkBackground returns whether or not the terminal has a dark background. -func HasDarkBackground() bool { - colorProfileMtx.RLock() - defer colorProfileMtx.RUnlock() - - if !explicitBackgroundColor { - getBackgroundColor.Do(func() { - hasDarkBackground = termenv.HasDarkBackground() - }) - } - - return hasDarkBackground -} - -// SetHasDarkBackground sets the value of the background color detection on a -// package-wide context. This function exists mostly for testing purposes so -// that you can assure you're testing against a specific background color -// setting. -// -// Outside of testing you likely won't want to use this function as -// HasDarkBackground() will detect and cache the terminal's current background -// color setting. -// -// This function is thread-safe. -func SetHasDarkBackground(b bool) { - colorProfileMtx.Lock() - defer colorProfileMtx.Unlock() - - hasDarkBackground = b - explicitBackgroundColor = true -} - -// TerminalColor is a color intended to be rendered in the terminal. It -// satisfies the Go color.Color interface. +// TerminalColor is a color intended to be rendered in the terminal. type TerminalColor interface { - value() string - color() termenv.Color + color(*Renderer) termenv.Color RGBA() (r, g, b, a uint32) } +var noColor = NoColor{} + // NoColor is used to specify the absence of color styling. When this is active // foreground colors will be rendered with the terminal's default text color, // and background colors will not be drawn at all. @@ -106,12 +23,8 @@ type TerminalColor interface { // var style = someStyle.Copy().Background(lipgloss.NoColor{}) type NoColor struct{} -func (n NoColor) value() string { - return "" -} - -func (n NoColor) color() termenv.Color { - return ColorProfile().Color("") +func (NoColor) color(*Renderer) termenv.Color { + return termenv.NoColor{} } // RGBA returns the RGBA value of this color. Because we have to return @@ -119,32 +32,56 @@ func (n NoColor) color() termenv.Color { // black with 100% opacity. // // Red: 0x0, Green: 0x0, Blue: 0x0, Alpha: 0xFFFF. +// +// Deprecated. func (n NoColor) RGBA() (r, g, b, a uint32) { return 0x0, 0x0, 0x0, 0xFFFF } -var noColor = NoColor{} - // Color specifies a color by hex or ANSI value. For example: // // ansiColor := lipgloss.Color("21") // hexColor := lipgloss.Color("#0000ff") type Color string -func (c Color) value() string { - return string(c) +func (c Color) color(r *Renderer) termenv.Color { + return r.ColorProfile().Color(string(c)) +} + +// RGBA returns the RGBA value of this color. This satisfies the Go Color +// interface. Note that on error we return black with 100% opacity, or: +// +// Red: 0x0, Green: 0x0, Blue: 0x0, Alpha: 0xFFFF. +// +// Deprecated. +func (c Color) RGBA() (r, g, b, a uint32) { + return termenv.ConvertToRGB(c.color(renderer)).RGBA() } -func (c Color) color() termenv.Color { - return ColorProfile().Color(string(c)) +// ANSIColor is a color specified by an ANSI color value. It's merely syntactic +// sugar for the more general Color function. Invalid colors will render as +// black. +// +// Example usage: +// +// // These two statements are equivalent. +// colorA := lipgloss.ANSIColor(21) +// colorB := lipgloss.Color("21") +type ANSIColor uint + +func (ac ANSIColor) color(r *Renderer) termenv.Color { + return Color(strconv.FormatUint(uint64(ac), 10)).color(r) } // RGBA returns the RGBA value of this color. This satisfies the Go Color // interface. Note that on error we return black with 100% opacity, or: // -// Red: 0x0, Green: 0x0, Blue: 0x0, Alpha: 0xFF. -func (c Color) RGBA() (r, g, b, a uint32) { - return hexToColor(c.value()).RGBA() +// Red: 0x0, Green: 0x0, Blue: 0x0, Alpha: 0xFFFF. +// +// Deprecated. +func (ac ANSIColor) RGBA() (r, g, b, a uint32) { + cf := Color(strconv.FormatUint(uint64(ac), 10)) + return cf.RGBA() } // AdaptiveColor provides color options for light and dark backgrounds. The @@ -159,127 +96,77 @@ type AdaptiveColor struct { Dark string } -func (ac AdaptiveColor) value() string { - if HasDarkBackground() { - return ac.Dark +func (ac AdaptiveColor) color(r *Renderer) termenv.Color { + if r.HasDarkBackground() { + return Color(ac.Dark).color(r) } - return ac.Light -} - -func (ac AdaptiveColor) color() termenv.Color { - return ColorProfile().Color(ac.value()) + return Color(ac.Light).color(r) } // RGBA returns the RGBA value of this color. This satisfies the Go Color // interface. Note that on error we return black with 100% opacity, or: // -// Red: 0x0, Green: 0x0, Blue: 0x0, Alpha: 0xFF. +// Red: 0x0, Green: 0x0, Blue: 0x0, Alpha: 0xFFFF. +// +// Deprecated. func (ac AdaptiveColor) RGBA() (r, g, b, a uint32) { - cf := hexToColor(ac.value()) - return cf.RGBA() + return termenv.ConvertToRGB(ac.color(renderer)).RGBA() } // CompleteColor specifies exact values for truecolor, ANSI256, and ANSI color -// profiles. Automatic color degredation will not be performed. +// profiles. Automatic color degradation will not be performed. type CompleteColor struct { TrueColor string ANSI256 string ANSI string } -func (c CompleteColor) value() string { - switch ColorProfile() { +func (c CompleteColor) color(r *Renderer) termenv.Color { + p := r.ColorProfile() + switch p { case termenv.TrueColor: - return c.TrueColor + return p.Color(c.TrueColor) case termenv.ANSI256: - return c.ANSI256 + return p.Color(c.ANSI256) case termenv.ANSI: - return c.ANSI + return p.Color(c.ANSI) default: - return "" + return termenv.NoColor{} } } -func (c CompleteColor) color() termenv.Color { - return colorProfile.Color(c.value()) -} - // RGBA returns the RGBA value of this color. This satisfies the Go Color // interface. Note that on error we return black with 100% opacity, or: // -// Red: 0x0, Green: 0x0, Blue: 0x0, Alpha: 0xFFFF +// Red: 0x0, Green: 0x0, Blue: 0x0, Alpha: 0xFFFF. +// CompleteAdaptiveColor specifies exact values for truecolor, ANSI256, and ANSI color +// +// Deprecated. func (c CompleteColor) RGBA() (r, g, b, a uint32) { - return hexToColor(c.value()).RGBA() + return termenv.ConvertToRGB(c.color(renderer)).RGBA() } // CompleteColor specifies exact values for truecolor, ANSI256, and ANSI color // profiles, with separate options for light and dark backgrounds. Automatic -// color degredation will not be performed. +// color degradation will not be performed. type CompleteAdaptiveColor struct { Light CompleteColor Dark CompleteColor } -func (cac CompleteAdaptiveColor) value() string { - if HasDarkBackground() { - return cac.Dark.value() +func (cac CompleteAdaptiveColor) color(r *Renderer) termenv.Color { + if r.HasDarkBackground() { + return cac.Dark.color(r) } - return cac.Light.value() -} - -func (cac CompleteAdaptiveColor) color() termenv.Color { - return ColorProfile().Color(cac.value()) + return cac.Light.color(r) } // RGBA returns the RGBA value of this color. This satisfies the Go Color // interface. Note that on error we return black with 100% opacity, or: // -// Red: 0x0, Green: 0x0, Blue: 0x0, Alpha: 0xFFFF +// Red: 0x0, Green: 0x0, Blue: 0x0, Alpha: 0xFFFF. +// +// Deprecated. func (cac CompleteAdaptiveColor) RGBA() (r, g, b, a uint32) { - return hexToColor(cac.value()).RGBA() -} - -// hexToColor translates a hex color string (#RRGGBB or #RGB) into a color.RGB, -// which satisfies the color.Color interface. If an invalid string is passed -// black with 100% opacity will be returned: or, in hex format, 0x000000FF. -func hexToColor(hex string) (c color.RGBA) { - c.A = 0xFF - - if hex == "" || hex[0] != '#' { - return c - } - - const ( - fullFormat = 7 // #RRGGBB - shortFormat = 4 // #RGB - ) - - switch len(hex) { - case fullFormat: - const offset = 4 - c.R = hexToByte(hex[1])<= '0' && b <= '9': - return b - '0' - case b >= 'a' && b <= 'f': - return b - 'a' + offset - case b >= 'A' && b <= 'F': - return b - 'A' + offset - } - // Invalid, but just return 0. - return 0 + return termenv.ConvertToRGB(cac.color(renderer)).RGBA() } diff --git a/vendor/github.com/charmbracelet/lipgloss/get.go b/vendor/github.com/charmbracelet/lipgloss/get.go index f01b8f15f..eb24a4ede 100644 --- a/vendor/github.com/charmbracelet/lipgloss/get.go +++ b/vendor/github.com/charmbracelet/lipgloss/get.go @@ -6,42 +6,42 @@ import ( "github.com/muesli/reflow/ansi" ) -// GetBold returns the style's bold value It no value is set false is returned. +// GetBold returns the style's bold value. If no value is set false is returned. func (s Style) GetBold() bool { return s.getAsBool(boldKey, false) } -// GetItalic returns the style's italic value. It no value is set false is +// GetItalic returns the style's italic value. If no value is set false is // returned. func (s Style) GetItalic() bool { return s.getAsBool(italicKey, false) } -// GetUnderline returns the style's underline value. It no value is set false is +// GetUnderline returns the style's underline value. If no value is set false is // returned. func (s Style) GetUnderline() bool { return s.getAsBool(underlineKey, false) } -// GetStrikethrough returns the style's strikethrough value. It no value is set false +// GetStrikethrough returns the style's strikethrough value. If no value is set false // is returned. func (s Style) GetStrikethrough() bool { return s.getAsBool(strikethroughKey, false) } -// GetReverse returns the style's reverse value. It no value is set false is +// GetReverse returns the style's reverse value. If no value is set false is // returned. func (s Style) GetReverse() bool { return s.getAsBool(reverseKey, false) } -// GetBlink returns the style's blink value. It no value is set false is +// GetBlink returns the style's blink value. If no value is set false is // returned. func (s Style) GetBlink() bool { return s.getAsBool(blinkKey, false) } -// GetFaint returns the style's faint value. It no value is set false is +// GetFaint returns the style's faint value. If no value is set false is // returned. func (s Style) GetFaint() bool { return s.getAsBool(faintKey, false) @@ -72,7 +72,7 @@ func (s Style) GetHeight() int { } // GetAlign returns the style's implicit horizontal alignment setting. -// If no alignment is set Position.AlignLeft is returned. +// If no alignment is set Position.Left is returned. func (s Style) GetAlign() Position { v := s.getAsPosition(alignHorizontalKey) if v == Position(0) { @@ -82,7 +82,7 @@ func (s Style) GetAlign() Position { } // GetAlignHorizontal returns the style's implicit horizontal alignment setting. -// If no alignment is set Position.AlignLeft is returned. +// If no alignment is set Position.Left is returned. func (s Style) GetAlignHorizontal() Position { v := s.getAsPosition(alignHorizontalKey) if v == Position(0) { @@ -92,7 +92,7 @@ func (s Style) GetAlignHorizontal() Position { } // GetAlignVertical returns the style's implicit vertical alignment setting. -// If no alignment is set Position.AlignTop is returned. +// If no alignment is set Position.Top is returned. func (s Style) GetAlignVertical() Position { v := s.getAsPosition(alignVerticalKey) if v == Position(0) { @@ -200,7 +200,7 @@ func (s Style) GetVerticalMargins() int { // GetBorder returns the style's border style (type Border) and value for the // top, right, bottom, and left in that order. If no value is set for the // border style, Border{} is returned. For all other unset values false is -// returend. +// returned. func (s Style) GetBorder() (b Border, top, right, bottom, left bool) { return s.getBorderStyle(), s.getAsBool(borderTopKey, false), @@ -290,7 +290,16 @@ func (s Style) GetBorderLeftBackground() TerminalColor { // GetBorderTopWidth returns the width of the top border. If borders contain // runes of varying widths, the widest rune is returned. If no border exists on // the top edge, 0 is returned. +// +// Deprecated: This function simply calls Style.GetBorderTopSize. func (s Style) GetBorderTopWidth() int { + return s.GetBorderTopSize() +} + +// GetBorderTopSize returns the width of the top border. If borders contain +// runes of varying widths, the widest rune is returned. If no border exists on +// the top edge, 0 is returned. +func (s Style) GetBorderTopSize() int { if !s.getAsBool(borderTopKey, false) { return 0 } @@ -415,12 +424,12 @@ func (s Style) getAsBool(k propKey, defaultVal bool) bool { func (s Style) getAsColor(k propKey) TerminalColor { v, ok := s.rules[k] if !ok { - return NoColor{} + return noColor } if c, ok := v.(TerminalColor); ok { return c } - return NoColor{} + return noColor } func (s Style) getAsInt(k propKey) int { diff --git a/vendor/github.com/charmbracelet/lipgloss/position.go b/vendor/github.com/charmbracelet/lipgloss/position.go index 2ecb89790..28f5ccbd6 100644 --- a/vendor/github.com/charmbracelet/lipgloss/position.go +++ b/vendor/github.com/charmbracelet/lipgloss/position.go @@ -34,13 +34,26 @@ const ( // Place places a string or text block vertically in an unstyled box of a given // width or height. func Place(width, height int, hPos, vPos Position, str string, opts ...WhitespaceOption) string { - return PlaceVertical(height, vPos, PlaceHorizontal(width, hPos, str, opts...), opts...) + return renderer.Place(width, height, hPos, vPos, str, opts...) +} + +// Place places a string or text block vertically in an unstyled box of a given +// width or height. +func (r *Renderer) Place(width, height int, hPos, vPos Position, str string, opts ...WhitespaceOption) string { + return r.PlaceVertical(height, vPos, r.PlaceHorizontal(width, hPos, str, opts...), opts...) } // PlaceHorizontal places a string or text block horizontally in an unstyled // block of a given width. If the given width is shorter than the max width of -// the string (measured by it's longest line) this will be a noöp. +// the string (measured by its longest line) this will be a noop. func PlaceHorizontal(width int, pos Position, str string, opts ...WhitespaceOption) string { + return renderer.PlaceHorizontal(width, pos, str, opts...) +} + +// PlaceHorizontal places a string or text block horizontally in an unstyled +// block of a given width. If the given width is shorter than the max width of +// the string (measured by it's longest line) this will be a noöp. +func (r *Renderer) PlaceHorizontal(width int, pos Position, str string, opts ...WhitespaceOption) string { lines, contentWidth := getLines(str) gap := width - contentWidth @@ -48,10 +61,7 @@ func PlaceHorizontal(width int, pos Position, str string, opts ...WhitespaceOpti return str } - ws := &whitespace{} - for _, opt := range opts { - opt(ws) - } + ws := newWhitespace(r, opts...) var b strings.Builder for i, l := range lines { @@ -89,8 +99,15 @@ func PlaceHorizontal(width int, pos Position, str string, opts ...WhitespaceOpti // PlaceVertical places a string or text block vertically in an unstyled block // of a given height. If the given height is shorter than the height of the -// string (measured by it's newlines) then this will be a noöp. +// string (measured by its newlines) then this will be a noop. func PlaceVertical(height int, pos Position, str string, opts ...WhitespaceOption) string { + return renderer.PlaceVertical(height, pos, str, opts...) +} + +// PlaceVertical places a string or text block vertically in an unstyled block +// of a given height. If the given height is shorter than the height of the +// string (measured by it's newlines) then this will be a noöp. +func (r *Renderer) PlaceVertical(height int, pos Position, str string, opts ...WhitespaceOption) string { contentHeight := strings.Count(str, "\n") + 1 gap := height - contentHeight @@ -98,10 +115,7 @@ func PlaceVertical(height int, pos Position, str string, opts ...WhitespaceOptio return str } - ws := &whitespace{} - for _, opt := range opts { - opt(ws) - } + ws := newWhitespace(r, opts...) _, width := getLines(str) emptyLine := ws.render(width) diff --git a/vendor/github.com/charmbracelet/lipgloss/renderer.go b/vendor/github.com/charmbracelet/lipgloss/renderer.go new file mode 100644 index 000000000..4bea8374d --- /dev/null +++ b/vendor/github.com/charmbracelet/lipgloss/renderer.go @@ -0,0 +1,143 @@ +package lipgloss + +import ( + "io" + + "github.com/muesli/termenv" +) + +// We're manually creating the struct here to avoid initializing the output and +// query the terminal multiple times. +var renderer = &Renderer{ + output: termenv.DefaultOutput(), +} + +// Renderer is a lipgloss terminal renderer. +type Renderer struct { + output *termenv.Output + hasDarkBackground *bool +} + +// RendererOption is a function that can be used to configure a [Renderer]. +type RendererOption func(r *Renderer) + +// DefaultRenderer returns the default renderer. +func DefaultRenderer() *Renderer { + return renderer +} + +// SetDefaultRenderer sets the default global renderer. +func SetDefaultRenderer(r *Renderer) { + renderer = r +} + +// NewRenderer creates a new Renderer. +// +// w will be used to determine the terminal's color capabilities. +func NewRenderer(w io.Writer, opts ...termenv.OutputOption) *Renderer { + r := &Renderer{ + output: termenv.NewOutput(w, opts...), + } + return r +} + +// Output returns the termenv output. +func (r *Renderer) Output() *termenv.Output { + return r.output +} + +// SetOutput sets the termenv output. +func (r *Renderer) SetOutput(o *termenv.Output) { + r.output = o +} + +// ColorProfile returns the detected termenv color profile. +func (r *Renderer) ColorProfile() termenv.Profile { + return r.output.Profile +} + +// ColorProfile returns the detected termenv color profile. +func ColorProfile() termenv.Profile { + return renderer.ColorProfile() +} + +// SetColorProfile sets the color profile on the renderer. This function exists +// mostly for testing purposes so that you can assure you're testing against +// a specific profile. +// +// Outside of testing you likely won't want to use this function as the color +// profile will detect and cache the terminal's color capabilities and choose +// the best available profile. +// +// Available color profiles are: +// +// termenv.Ascii // no color, 1-bit +// termenv.ANSI //16 colors, 4-bit +// termenv.ANSI256 // 256 colors, 8-bit +// termenv.TrueColor // 16,777,216 colors, 24-bit +// +// This function is thread-safe. +func (r *Renderer) SetColorProfile(p termenv.Profile) { + r.output.Profile = p +} + +// SetColorProfile sets the color profile on the default renderer. This +// function exists mostly for testing purposes so that you can assure you're +// testing against a specific profile. +// +// Outside of testing you likely won't want to use this function as the color +// profile will detect and cache the terminal's color capabilities and choose +// the best available profile. +// +// Available color profiles are: +// +// termenv.Ascii // no color, 1-bit +// termenv.ANSI //16 colors, 4-bit +// termenv.ANSI256 // 256 colors, 8-bit +// termenv.TrueColor // 16,777,216 colors, 24-bit +// +// This function is thread-safe. +func SetColorProfile(p termenv.Profile) { + renderer.SetColorProfile(p) +} + +// HasDarkBackground returns whether or not the terminal has a dark background. +func HasDarkBackground() bool { + return renderer.HasDarkBackground() +} + +// HasDarkBackground returns whether or not the renderer will render to a dark +// background. A dark background can either be auto-detected, or set explicitly +// on the renderer. +func (r *Renderer) HasDarkBackground() bool { + if r.hasDarkBackground != nil { + return *r.hasDarkBackground + } + return r.output.HasDarkBackground() +} + +// SetHasDarkBackground sets the background color detection value for the +// default renderer. This function exists mostly for testing purposes so that +// you can assure you're testing against a specific background color setting. +// +// Outside of testing you likely won't want to use this function as the +// backgrounds value will be automatically detected and cached against the +// terminal's current background color setting. +// +// This function is thread-safe. +func SetHasDarkBackground(b bool) { + renderer.SetHasDarkBackground(b) +} + +// SetHasDarkBackground sets the background color detection value on the +// renderer. This function exists mostly for testing purposes so that you can +// assure you're testing against a specific background color setting. +// +// Outside of testing you likely won't want to use this function as the +// backgrounds value will be automatically detected and cached against the +// terminal's current background color setting. +// +// This function is thread-safe. +func (r *Renderer) SetHasDarkBackground(b bool) { + r.hasDarkBackground = &b +} diff --git a/vendor/github.com/charmbracelet/lipgloss/runes.go b/vendor/github.com/charmbracelet/lipgloss/runes.go index 723f6dbf7..7a49e326c 100644 --- a/vendor/github.com/charmbracelet/lipgloss/runes.go +++ b/vendor/github.com/charmbracelet/lipgloss/runes.go @@ -4,7 +4,7 @@ import ( "strings" ) -// StyleRunes applys a given style to runes at the given indicesin the string. +// StyleRunes apply a given style to runes at the given indices in the string. // Note that you must provide styling options for both matched and unmatched // runes. Indices out of bounds will be ignored. func StyleRunes(str string, indices []int, matched, unmatched Style) string { diff --git a/vendor/github.com/charmbracelet/lipgloss/set.go b/vendor/github.com/charmbracelet/lipgloss/set.go index 028845433..f8bf9a22d 100644 --- a/vendor/github.com/charmbracelet/lipgloss/set.go +++ b/vendor/github.com/charmbracelet/lipgloss/set.go @@ -1,7 +1,7 @@ package lipgloss // This could (should) probably just be moved into NewStyle(). We've broken it -// out so we can call it in a lazy way. +// out, so we can call it in a lazy way. func (s *Style) init() { if s.rules == nil { s.rules = make(rules) @@ -16,7 +16,7 @@ func (s *Style) set(key propKey, value interface{}) { case int: // We don't allow negative integers on any of our values, so just keep // them at zero or above. We could use uints instead, but the - // conversions are a little tedious so we're sticking with ints for + // conversions are a little tedious, so we're sticking with ints for // sake of usability. s.rules[key] = max(0, v) default: @@ -39,7 +39,7 @@ func (s Style) Italic(v bool) Style { // Underline sets an underline rule. By default, underlines will not be drawn on // whitespace like margins and padding. To change this behavior set -// renderUnderlinesOnSpaces. +// UnderlineSpaces. func (s Style) Underline(v bool) Style { s.set(underlineKey, v) return s @@ -47,7 +47,7 @@ func (s Style) Underline(v bool) Style { // Strikethrough sets a strikethrough rule. By default, strikes will not be // drawn on whitespace like margins and padding. To change this behavior set -// renderStrikethroughOnSpaces. +// StrikethroughSpaces. func (s Style) Strikethrough(v bool) Style { s.set(strikethroughKey, v) return s @@ -120,13 +120,13 @@ func (s Style) Align(p ...Position) Style { return s } -// HorizontalAlign sets a horizontal text alignment rule. +// AlignHorizontal sets a horizontal text alignment rule. func (s Style) AlignHorizontal(p Position) Style { s.set(alignHorizontalKey, p) return s } -// VerticalAlign sets a text alignment rule. +// AlignVertical sets a text alignment rule. func (s Style) AlignVertical(p Position) Style { s.set(alignVerticalKey, p) return s @@ -251,7 +251,7 @@ func (s Style) MarginBackground(c TerminalColor) Style { return s } -// Border is shorthand for setting a the border style and which sides should +// Border is shorthand for setting the border style and which sides should // have a border at once. The variadic argument sides works as follows: // // With one value, the value is applied to all sides. @@ -300,8 +300,9 @@ func (s Style) Border(b Border, sides ...bool) Style { // the border style, the border will be enabled for all sides during rendering. // // You can define border characters as you'd like, though several default -// styles are included: NormalBorder(), RoundedBorder(), ThickBorder(), and -// DoubleBorder(). +// styles are included: NormalBorder(), RoundedBorder(), BlockBorder(), +// OuterHalfBlockBorder(), InnerHalfBlockBorder(), ThickBorder(), +// and DoubleBorder(). // // Example: // @@ -491,8 +492,8 @@ func (s Style) MaxWidth(n int) Style { return o } -// MaxHeight applies a max width to a given style. This is useful in enforcing -// a certain width at render time, particularly with arbitrary strings and +// MaxHeight applies a max height to a given style. This is useful in enforcing +// a certain height at render time, particularly with arbitrary strings and // styles. // // Because this in intended to be used at the time of render, this method will @@ -504,7 +505,7 @@ func (s Style) MaxHeight(n int) Style { } // UnderlineSpaces determines whether to underline spaces between words. By -// default this is true. Spaces can also be underlined without underlining the +// default, this is true. Spaces can also be underlined without underlining the // text itself. func (s Style) UnderlineSpaces(v bool) Style { s.set(underlineSpacesKey, v) @@ -512,13 +513,20 @@ func (s Style) UnderlineSpaces(v bool) Style { } // StrikethroughSpaces determines whether to apply strikethroughs to spaces -// between words. By default this is true. Spaces can also be struck without +// between words. By default, this is true. Spaces can also be struck without // underlining the text itself. func (s Style) StrikethroughSpaces(v bool) Style { s.set(strikethroughSpacesKey, v) return s } +// Renderer sets the renderer for the style. This is useful for changing the +// renderer for a style that is being used in a different context. +func (s Style) Renderer(r *Renderer) Style { + s.r = r + return s +} + // whichSidesInt is a helper method for setting values on sides of a block based // on the number of arguments. It follows the CSS shorthand rules for blocks // like margin, padding. and borders. Here are how the rules work: diff --git a/vendor/github.com/charmbracelet/lipgloss/style.go b/vendor/github.com/charmbracelet/lipgloss/style.go index fb89d06c4..e94b86702 100644 --- a/vendor/github.com/charmbracelet/lipgloss/style.go +++ b/vendor/github.com/charmbracelet/lipgloss/style.go @@ -75,26 +75,43 @@ const ( // A set of properties. type rules map[propKey]interface{} -// NewStyle returns a new, empty Style. While it's syntactic sugar for the +// NewStyle returns a new, empty Style. While it's syntactic sugar for the // Style{} primitive, it's recommended to use this function for creating styles -// incase the underlying implementation changes. +// in case the underlying implementation changes. It takes an optional string +// value to be set as the underlying string value for this style. func NewStyle() Style { - return Style{} + return renderer.NewStyle() +} + +// NewStyle returns a new, empty Style. While it's syntactic sugar for the +// Style{} primitive, it's recommended to use this function for creating styles +// in case the underlying implementation changes. It takes an optional string +// value to be set as the underlying string value for this style. +func (r *Renderer) NewStyle() Style { + s := Style{r: r} + return s } // Style contains a set of rules that comprise a style as a whole. type Style struct { + r *Renderer rules map[propKey]interface{} value string } +// joinString joins a list of strings into a single string separated with a +// space. +func joinString(strs ...string) string { + return strings.Join(strs, " ") +} + // SetString sets the underlying string value for this style. To render once // the underlying string is set, use the Style.String. This method is // a convenience for cases when having a stringer implementation is handy, such // as when using fmt.Sprintf. You can also simply define a style and render out // strings directly with Style.Render. -func (s Style) SetString(str string) Style { - s.value = str +func (s Style) SetString(strs ...string) Style { + s.value = joinString(strs...) return s } @@ -107,7 +124,7 @@ func (s Style) Value() string { // on the rules in this style. An underlying string value must be set with // Style.SetString prior to using this method. func (s Style) String() string { - return s.Render(s.value) + return s.Render() } // Copy returns a copy of this style, including any underlying string values. @@ -117,6 +134,7 @@ func (s Style) Copy() Style { for k, v := range s.rules { o.rules[k] = v } + o.r = s.r o.value = s.value return o } @@ -153,11 +171,20 @@ func (s Style) Inherit(i Style) Style { } // Render applies the defined style formatting to a given string. -func (s Style) Render(str string) string { +func (s Style) Render(strs ...string) string { + if s.r == nil { + s.r = renderer + } + if s.value != "" { + strs = append([]string{s.value}, strs...) + } + var ( - te termenv.Style - teSpace termenv.Style - teWhitespace termenv.Style + str = joinString(strs...) + + te = s.r.ColorProfile().String() + teSpace = s.r.ColorProfile().String() + teWhitespace = s.r.ColorProfile().String() bold = s.getAsBool(boldKey, false) italic = s.getAsBool(italicKey, false) @@ -227,24 +254,22 @@ func (s Style) Render(str string) string { } if fg != noColor { - fgc := fg.color() - te = te.Foreground(fgc) + te = te.Foreground(fg.color(s.r)) if styleWhitespace { - teWhitespace = teWhitespace.Foreground(fgc) + teWhitespace = teWhitespace.Foreground(fg.color(s.r)) } if useSpaceStyler { - teSpace = teSpace.Foreground(fgc) + teSpace = teSpace.Foreground(fg.color(s.r)) } } if bg != noColor { - bgc := bg.color() - te = te.Background(bgc) + te = te.Background(bg.color(s.r)) if colorWhitespace { - teWhitespace = teWhitespace.Background(bgc) + teWhitespace = teWhitespace.Background(bg.color(s.r)) } if useSpaceStyler { - teSpace = teSpace.Background(bgc) + teSpace = teSpace.Background(bg.color(s.r)) } } @@ -384,7 +409,7 @@ func (s Style) applyMargins(str string, inline bool) string { bgc := s.getAsColor(marginBackgroundKey) if bgc != noColor { - styler = styler.Background(bgc.color()) + styler = styler.Background(bgc.color(s.r)) } // Add left and right margin @@ -432,7 +457,7 @@ func padLeft(str string, n int, style *termenv.Style) string { return b.String() } -// Apply right right padding. +// Apply right padding. func padRight(str string, n int, style *termenv.Style) string { if n == 0 || str == "" { return str diff --git a/vendor/github.com/charmbracelet/lipgloss/unset.go b/vendor/github.com/charmbracelet/lipgloss/unset.go index 25f3ac929..a8367898b 100644 --- a/vendor/github.com/charmbracelet/lipgloss/unset.go +++ b/vendor/github.com/charmbracelet/lipgloss/unset.go @@ -79,7 +79,7 @@ func (s Style) UnsetAlignHorizontal() Style { return s } -// UnsetAlignHorizontal removes the vertical text alignment style rule, if set. +// UnsetAlignVertical removes the vertical text alignment style rule, if set. func (s Style) UnsetAlignVertical() Style { delete(s.rules, alignVerticalKey) return s diff --git a/vendor/github.com/charmbracelet/lipgloss/whitespace.go b/vendor/github.com/charmbracelet/lipgloss/whitespace.go index 6c510a78d..b043e5652 100644 --- a/vendor/github.com/charmbracelet/lipgloss/whitespace.go +++ b/vendor/github.com/charmbracelet/lipgloss/whitespace.go @@ -9,10 +9,25 @@ import ( // whitespace is a whitespace renderer. type whitespace struct { + re *Renderer style termenv.Style chars string } +// newWhitespace creates a new whitespace renderer. The order of the options +// matters, it you'r using WithWhitespaceRenderer, make sure it comes first as +// other options might depend on it. +func newWhitespace(r *Renderer, opts ...WhitespaceOption) *whitespace { + w := &whitespace{ + re: r, + style: r.ColorProfile().String(), + } + for _, opt := range opts { + opt(w) + } + return w +} + // Render whitespaces. func (w whitespace) render(width int) string { if w.chars == "" { @@ -49,14 +64,14 @@ type WhitespaceOption func(*whitespace) // WithWhitespaceForeground sets the color of the characters in the whitespace. func WithWhitespaceForeground(c TerminalColor) WhitespaceOption { return func(w *whitespace) { - w.style = w.style.Foreground(c.color()) + w.style = w.style.Foreground(c.color(w.re)) } } // WithWhitespaceBackground sets the background color of the whitespace. func WithWhitespaceBackground(c TerminalColor) WhitespaceOption { return func(w *whitespace) { - w.style = w.style.Background(c.color()) + w.style = w.style.Background(c.color(w.re)) } } diff --git a/vendor/github.com/evilmartians/lefthook/CHANGELOG.md b/vendor/github.com/evilmartians/lefthook/CHANGELOG.md index fcda36318..376619641 100644 --- a/vendor/github.com/evilmartians/lefthook/CHANGELOG.md +++ b/vendor/github.com/evilmartians/lefthook/CHANGELOG.md @@ -2,11 +2,22 @@ ## master (unreleased) -## 1.3.5 (2024-03-15) +## 1.3.7 (2023-03-20) + +- fix: allow globs in skip option ([#457](https://github.com/evilmartians/lefthook/pull/457)) by @mrexox +- deps: dependencies update (March 2023) ([#455](https://github.com/evilmartians/lefthook/pull/455)) by @mrexox +- fix: don't fail on missing config file ([#450](https://github.com/evilmartians/lefthook/pull/450)) by @mrexox + +## 1.3.6 (2023-03-16) + +- fix: stage fixed when root specified ([#449](https://github.com/evilmartians/lefthook/pull/449)) by @mrexox +- feat: implitic skip on missing files for pre-commit and pre-push hooks ([#448](https://github.com/evilmartians/lefthook/pull/448)) by @mrexox + +## 1.3.5 (2023-03-15) - feat: add stage_fixed option ([#445](https://github.com/evilmartians/lefthook/pull/445)) by @mrexox -## 1.3.4 (2024-03-13) +## 1.3.4 (2023-03-13) - fix: don't extra extend config if lefthook-local.yml is missing ([#444](https://github.com/evilmartians/lefthook/pull/444)) by @mrexox diff --git a/vendor/github.com/evilmartians/lefthook/Makefile b/vendor/github.com/evilmartians/lefthook/Makefile index 0fa5a5920..e246c64e2 100644 --- a/vendor/github.com/evilmartians/lefthook/Makefile +++ b/vendor/github.com/evilmartians/lefthook/Makefile @@ -15,3 +15,11 @@ bin/golangci-lint: lint: bin/golangci-lint $$(go env GOPATH)/bin/golangci-lint run + +.ONESHELL: +version: + @read -p "New version: " version + sed -i "s/const version = .*/const version = \"$$version\"/" internal/version/version.go + sed -i "s/VERSION := .*/VERSION := $$version/" packaging/Makefile + make -C packaging clean set-version + git add internal/version/version.go packaging/* diff --git a/vendor/github.com/evilmartians/lefthook/internal/config/available_hooks.go b/vendor/github.com/evilmartians/lefthook/internal/config/available_hooks.go index 6633948fd..cdd46157a 100644 --- a/vendor/github.com/evilmartians/lefthook/internal/config/available_hooks.go +++ b/vendor/github.com/evilmartians/lefthook/internal/config/available_hooks.go @@ -43,6 +43,10 @@ func HookUsesStagedFiles(hook string) bool { return hook == "pre-commit" } +func HookUsesPushFiles(hook string) bool { + return hook == "pre-push" +} + func HookAvailable(hook string) bool { for _, name := range AvailableHooks { if name == hook { diff --git a/vendor/github.com/evilmartians/lefthook/internal/config/load.go b/vendor/github.com/evilmartians/lefthook/internal/config/load.go index 3709f7bc3..451125748 100644 --- a/vendor/github.com/evilmartians/lefthook/internal/config/load.go +++ b/vendor/github.com/evilmartians/lefthook/internal/config/load.go @@ -23,10 +23,25 @@ const ( var hookKeyRegexp = regexp.MustCompile(`^(?P[^.]+)\.(scripts|commands)`) +// NotFoundError wraps viper.ConfigFileNotFoundError for lefthook. +type NotFoundError struct { + message string +} + +// Error returns message of viper.ConfigFileNotFoundError. +func (err NotFoundError) Error() string { + return err.message +} + // Loads configs from the given directory with extensions. func Load(fs afero.Fs, repo *git.Repository) (*Config, error) { global, err := read(fs, repo.RootPath, "lefthook") if err != nil { + var notFoundErr viper.ConfigFileNotFoundError + if ok := errors.As(err, ¬FoundErr); ok { + return nil, NotFoundError{err.Error()} + } + return nil, err } diff --git a/vendor/github.com/evilmartians/lefthook/internal/config/skip.go b/vendor/github.com/evilmartians/lefthook/internal/config/skip.go index 35d2c0647..556cc55d3 100644 --- a/vendor/github.com/evilmartians/lefthook/internal/config/skip.go +++ b/vendor/github.com/evilmartians/lefthook/internal/config/skip.go @@ -1,6 +1,10 @@ package config -import "github.com/evilmartians/lefthook/internal/git" +import ( + "github.com/gobwas/glob" + + "github.com/evilmartians/lefthook/internal/git" +) func isSkip(gitState git.State, value interface{}) bool { switch typedValue := value.(type) { @@ -16,7 +20,13 @@ func isSkip(gitState git.State, value interface{}) bool { return true } case map[string]interface{}: - if typedState["ref"].(string) == gitState.Branch { + ref := typedState["ref"].(string) + if ref == gitState.Branch { + return true + } + + g := glob.MustCompile(ref) + if g.Match(gitState.Branch) { return true } } diff --git a/vendor/github.com/evilmartians/lefthook/internal/lefthook/run.go b/vendor/github.com/evilmartians/lefthook/internal/lefthook/run.go index eb5c180a5..9f8dfb324 100644 --- a/vendor/github.com/evilmartians/lefthook/internal/lefthook/run.go +++ b/vendor/github.com/evilmartians/lefthook/internal/lefthook/run.go @@ -47,6 +47,12 @@ func (l *Lefthook) Run(hookName string, args RunArgs, gitArgs []string) error { // Load config cfg, err := config.Load(l.Fs, l.repo) if err != nil { + var notFoundErr config.NotFoundError + if ok := errors.As(err, ¬FoundErr); ok { + log.Warn(err.Error()) + return nil + } + return err } if err = cfg.Validate(); err != nil { diff --git a/vendor/github.com/evilmartians/lefthook/internal/lefthook/runner/prepare_command.go b/vendor/github.com/evilmartians/lefthook/internal/lefthook/runner/prepare_command.go index e33ce459f..e4bcec376 100644 --- a/vendor/github.com/evilmartians/lefthook/internal/lefthook/runner/prepare_command.go +++ b/vendor/github.com/evilmartians/lefthook/internal/lefthook/runner/prepare_command.go @@ -34,19 +34,19 @@ func (r *Runner) prepareCommand(name string, command *config.Command) (*commandA return nil, errors.New("invalid conig") } - args, err := r.buildCommandArgs(command) + args, err, skipReason := r.buildCommandArgs(command) if err != nil { log.Error(err) return nil, errors.New("error") } - if args == nil || len(args.all) == 0 { - return nil, errors.New("no files for inspection") + if skipReason != nil { + return nil, skipReason } return args, nil } -func (r *Runner) buildCommandArgs(command *config.Command) (*commandArgs, error) { +func (r *Runner) buildCommandArgs(command *config.Command) (*commandArgs, error, error) { filesCommand := r.Hook.Files if command.Files != "" { filesCommand = command.Files @@ -72,21 +72,39 @@ func (r *Runner) buildCommandArgs(command *config.Command) (*commandArgs, error) filesCommand != "" && filesType == config.SubFiles { files, err := filesFn() if err != nil { - return nil, fmt.Errorf("error replacing %s: %w", filesType, err) + return nil, fmt.Errorf("error replacing %s: %w", filesType, err), nil } if len(files) == 0 { - return nil, nil + return nil, nil, errors.New("no files for inspection") } filesPrepared := prepareFiles(command, files) if len(filesPrepared) == 0 { - return nil, nil + return nil, nil, errors.New("no files for inspection") } filteredFiles = append(filteredFiles, filesPrepared...) runString = replaceQuoted(runString, filesType, filesPrepared) } } + if len(filteredFiles) == 0 && config.HookUsesStagedFiles(r.HookName) { + files, err := r.Repo.StagedFiles() + if err == nil { + if len(prepareFiles(command, files)) == 0 { + return nil, nil, errors.New("no matching staged files") + } + } + } + + if len(filteredFiles) == 0 && config.HookUsesPushFiles(r.HookName) { + files, err := r.Repo.PushFiles() + if err == nil { + if len(prepareFiles(command, files)) == 0 { + return nil, nil, errors.New("no matching push files") + } + } + } + runString = strings.ReplaceAll(runString, "{0}", strings.Join(r.GitArgs, " ")) for i, gitArg := range r.GitArgs { runString = strings.ReplaceAll(runString, fmt.Sprintf("{%d}", i+1), gitArg) @@ -97,7 +115,7 @@ func (r *Runner) buildCommandArgs(command *config.Command) (*commandArgs, error) return &commandArgs{ files: filteredFiles, all: strings.Split(runString, " "), - }, nil + }, nil, nil } func prepareFiles(command *config.Command, files []string) []string { diff --git a/vendor/github.com/evilmartians/lefthook/internal/lefthook/runner/runner.go b/vendor/github.com/evilmartians/lefthook/internal/lefthook/runner/runner.go index fc915b517..35fc4840e 100644 --- a/vendor/github.com/evilmartians/lefthook/internal/lefthook/runner/runner.go +++ b/vendor/github.com/evilmartians/lefthook/internal/lefthook/runner/runner.go @@ -203,6 +203,10 @@ func (r *Runner) preHook() { } func (r *Runner) postHook() { + if !config.HookUsesStagedFiles(r.HookName) { + return + } + if err := r.Repo.RestoreUnstaged(); err != nil { log.Warnf("Couldn't restore hidden unstaged files: %s\n", err) return @@ -295,9 +299,7 @@ func (r *Runner) runScript(script *config.Script, path string, file os.FileInfo) return } - if err := r.Repo.AddFiles(files); err != nil { - log.Warn("Couldn't stage fixed files:", err) - } + r.addStagedFiles(files) } } @@ -378,9 +380,19 @@ func (r *Runner) runCommand(name string, command *config.Command) { files = prepareFiles(command, stagedFiles) } - if err := r.Repo.AddFiles(files); err != nil { - log.Warn("Couldn't stage fixed files:", err) + if len(command.Root) > 0 { + for i, file := range files { + files[i] = filepath.Join(command.Root, file) + } } + + r.addStagedFiles(files) + } +} + +func (r *Runner) addStagedFiles(files []string) { + if err := r.Repo.AddFiles(files); err != nil { + log.Warn("Couldn't stage fixed files:", err) } } diff --git a/vendor/github.com/evilmartians/lefthook/internal/version/version.go b/vendor/github.com/evilmartians/lefthook/internal/version/version.go index 8d9f490fc..6c487693a 100644 --- a/vendor/github.com/evilmartians/lefthook/internal/version/version.go +++ b/vendor/github.com/evilmartians/lefthook/internal/version/version.go @@ -6,7 +6,7 @@ import ( "strconv" ) -const version = "1.3.5" +const version = "1.3.7" var ( // Is set via -X github.com/evilmartians/lefthook/internal/version.commit={commit}. diff --git a/vendor/github.com/goreleaser/chglog/.goreleaser.yml b/vendor/github.com/goreleaser/chglog/.goreleaser.yml index b60937b94..b24ed7add 100644 --- a/vendor/github.com/goreleaser/chglog/.goreleaser.yml +++ b/vendor/github.com/goreleaser/chglog/.goreleaser.yml @@ -51,12 +51,13 @@ changelog: order: 9999 archives: - - replacements: - darwin: Darwin - linux: Linux - windows: Windows - 386: i386 - amd64: x86_64 + - name_template: >- + {{ .ProjectName }}_ + {{- title .Os }}_ + {{- if eq .Arch "amd64" }}x86_64 + {{- else if eq .Arch "386" }}i386 + {{- else }}{{ .Arch }}{{ end }} + {{- if .Arm }}v{{ .Arm }}{{ end }} brews: - tap: owner: goreleaser diff --git a/vendor/github.com/goreleaser/nfpm/v2/.golangci.yml b/vendor/github.com/goreleaser/nfpm/v2/.golangci.yml index 538f529c7..0582883fb 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/.golangci.yml +++ b/vendor/github.com/goreleaser/nfpm/v2/.golangci.yml @@ -1,6 +1,31 @@ run: + go: '1.20' timeout: 5m linters: enable: - thelper - gofumpt + - tparallel + - unconvert + - unparam + - wastedassign + - revive + - forbidigo + - tagliatelle + - misspell + - depguard + +linters-settings: + forbidigo: + forbid: + - 'ioutil\.*' + tagliatelle: + case: + use-field-name: false + rules: + yaml: snake + json: snake + depguard: + list-type: 'denylist' + packages-with-error-message: + - 'github.com/pkg/errors': 'use stdlib instead' diff --git a/vendor/github.com/goreleaser/nfpm/v2/.goreleaser.yml b/vendor/github.com/goreleaser/nfpm/v2/.goreleaser.yml index 4333867d1..f4126425e 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/.goreleaser.yml +++ b/vendor/github.com/goreleaser/nfpm/v2/.goreleaser.yml @@ -189,10 +189,9 @@ furies: sboms: - artifacts: archive + signs: - cmd: cosign - env: - - COSIGN_EXPERIMENTAL=1 certificate: '${artifact}.pem' output: true artifacts: checksum @@ -201,15 +200,16 @@ signs: - '--output-certificate=${certificate}' - '--output-signature=${signature}' - '${artifact}' + - --yes + docker_signs: - cmd: cosign - env: - - COSIGN_EXPERIMENTAL=1 artifacts: manifests output: true args: - 'sign' - '${artifact}' + - --yes changelog: sort: asc @@ -249,7 +249,7 @@ milestones: announce: twitter: - enabled: true + enabled: false message_template: "nFPM {{ .Tag }} was just released! See what's new: https://github.com/goreleaser/nfpm/releases/tag/{{ .Tag }}" discord: enabled: true diff --git a/vendor/github.com/goreleaser/nfpm/v2/apk/apk.go b/vendor/github.com/goreleaser/nfpm/v2/apk/apk.go index 9fe97ecb3..e99facc19 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/apk/apk.go +++ b/vendor/github.com/goreleaser/nfpm/v2/apk/apk.go @@ -38,7 +38,6 @@ import ( "io" "net/mail" "os" - "path/filepath" "strings" "sync/atomic" "text/template" @@ -112,7 +111,8 @@ func (*Apk) Package(info *nfpm.Info, apk io.Writer) (err error) { return fmt.Errorf("invalid platform: %s", info.Platform) } info = ensureValidArch(info) - if err = info.Validate(); err != nil { + + if err := nfpm.PrepareForPackager(info, packagerName); err != nil { return err } @@ -394,72 +394,34 @@ func newItemInsideTarGz(out *tar.Writer, content []byte, header *tar.Header) err } func createBuilderData(info *nfpm.Info, sizep *int64) func(tw *tar.Writer) error { - created := map[string]bool{} - return func(tw *tar.Writer) error { - return createFilesInsideTarGz(info, tw, created, sizep) + return createFilesInsideTarGz(info, tw, sizep) } } -func createFilesInsideTarGz(info *nfpm.Info, tw *tar.Writer, created map[string]bool, sizep *int64) (err error) { - // create explicit directories first +func createFilesInsideTarGz(info *nfpm.Info, tw *tar.Writer, sizep *int64) (err error) { for _, file := range info.Contents { - // at this point, we don't care about other types yet - if file.Type != "dir" { - continue - } - - // only consider contents for this packager - if file.Packager != "" && file.Packager != packagerName { - continue - } - - if err := createTree(tw, file.Destination, created); err != nil { - return err - } - - normalizedName := normalizePath(strings.Trim(file.Destination, "/")) + "/" - - if created[normalizedName] { - return fmt.Errorf("duplicate directory: %q", normalizedName) - } - - err = tw.WriteHeader(&tar.Header{ - Name: normalizedName, - Mode: int64(file.FileInfo.Mode), - Typeflag: tar.TypeDir, - Format: tar.FormatGNU, - Uname: file.FileInfo.Owner, - Gname: file.FileInfo.Group, - ModTime: file.FileInfo.MTime, - }) - if err != nil { - return err - } - - created[normalizedName] = true - } - - for _, file := range info.Contents { - // only consider contents for this packager - if file.Packager != "" && file.Packager != packagerName { - continue - } - - // create implicit directory structure below the current content - if err = createTree(tw, file.Destination, created); err != nil { - return err - } + file.Destination = strings.TrimPrefix(file.Destination, "./") switch file.Type { - case "ghost": - // skip ghost files in apk - continue - case "dir": - // already handled above - continue - case "symlink": - err = createSymlinkInsideTarGz(file, tw) + case files.TypeDir, files.TypeImplicitDir: + err = tw.WriteHeader(&tar.Header{ + Name: files.AsRelativePath(file.Destination), + Mode: int64(file.FileInfo.Mode), + Typeflag: tar.TypeDir, + Format: tar.FormatGNU, + Uname: file.FileInfo.Owner, + Gname: file.FileInfo.Group, + ModTime: file.FileInfo.MTime, + }) + case files.TypeSymlink: + err = newItemInsideTarGz(tw, []byte{}, &tar.Header{ + Name: files.AsRelativePath(file.Destination), + Linkname: file.Source, + Typeflag: tar.TypeSymlink, + ModTime: file.FileInfo.MTime, + Format: tar.FormatGNU, + }) default: err = copyToTarAndDigest(file, tw, sizep) } @@ -471,15 +433,6 @@ func createFilesInsideTarGz(info *nfpm.Info, tw *tar.Writer, created map[string] return nil } -func createSymlinkInsideTarGz(file *files.Content, out *tar.Writer) error { - return newItemInsideTarGz(out, []byte{}, &tar.Header{ - Name: strings.TrimLeft(file.Destination, "/"), - Linkname: file.Source, - Typeflag: tar.TypeSymlink, - ModTime: file.FileInfo.MTime, - }) -} - func copyToTarAndDigest(file *files.Content, tw *tar.Writer, sizep *int64) error { contents, err := os.ReadFile(file.Source) if err != nil { @@ -493,7 +446,7 @@ func copyToTarAndDigest(file *files.Content, tw *tar.Writer, sizep *int64) error // tar.FileInfoHeader only uses file.Mode().Perm() which masks the mode with // 0o777 which we don't want because we want to be able to set the suid bit. header.Mode = int64(file.Mode()) - header.Name = normalizePath(file.Destination) + header.Name = files.AsRelativePath(file.Destination) header.Uname = file.FileInfo.Owner header.Gname = file.FileInfo.Group if err = newItemInsideTarGz(tw, contents, header); err != nil { @@ -504,57 +457,6 @@ func copyToTarAndDigest(file *files.Content, tw *tar.Writer, sizep *int64) error return nil } -// normalizePath returns a path separated by slashes without a leading slash. -func normalizePath(src string) string { - return files.ToNixPath(strings.TrimLeft(src, "/")) -} - -// this is needed because the data.tar.gz file should have the empty folders -// as well, so we walk through the dst and create all subfolders. -func createTree(tarw *tar.Writer, dst string, created map[string]bool) error { - for _, path := range pathsToCreate(dst) { - path = normalizePath(path) + "/" - - if created[path] { - // skipping dir that was previously created inside the archive - // (eg: usr/) - continue - } - - if err := tarw.WriteHeader(&tar.Header{ - Name: path, - Mode: 0o755, - Typeflag: tar.TypeDir, - Format: tar.FormatGNU, - Uname: "root", - Gname: "root", - }); err != nil { - return fmt.Errorf("failed to create folder %s: %w", path, err) - } - created[path] = true - } - return nil -} - -func pathsToCreate(dst string) []string { - paths := []string{} - base := strings.Trim(dst, "/") - for { - base = filepath.Dir(base) - if base == "." { - break - } - paths = append(paths, files.ToNixPath(base)) - } - // we don't really need to create those things in order apparently, but, - // it looks really weird if we don't. - result := []string{} - for i := len(paths) - 1; i >= 0; i-- { - result = append(result, paths[i]) - } - return result -} - // reference: https://wiki.adelielinux.org/wiki/APK_internals#.PKGINFO const controlTemplate = ` {{- /* Mandatory fields */ -}} diff --git a/vendor/github.com/goreleaser/nfpm/v2/arch/arch.go b/vendor/github.com/goreleaser/nfpm/v2/arch/arch.go index 0f909fee3..90fad3095 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/arch/arch.go +++ b/vendor/github.com/goreleaser/nfpm/v2/arch/arch.go @@ -9,9 +9,7 @@ import ( "errors" "fmt" "io" - "io/fs" "os" - "path/filepath" "strconv" "strings" "time" @@ -35,6 +33,8 @@ func init() { // nolint: gochecknoglobals var Default = ArchLinux{} +// ArchLinux packager. +// nolint: revive type ArchLinux struct{} // nolint: gochecknoglobals @@ -119,7 +119,9 @@ func (ArchLinux) Package(info *nfpm.Info, w io.Writer) error { return fmt.Errorf("invalid platform: %s", info.Platform) } info = ensureValidArch(info) - if err := info.Validate(); err != nil { + + err := nfpm.PrepareForPackager(info, packagerName) + if err != nil { return err } @@ -138,20 +140,20 @@ func (ArchLinux) Package(info *nfpm.Info, w io.Writer) error { entries, totalSize, err := createFilesInTar(info, tw) if err != nil { - return err + return fmt.Errorf("create files in tar: %w", err) } pkginfoEntry, err := createPkginfo(info, tw, totalSize) if err != nil { - return err + return fmt.Errorf("create pkg info: %w", err) } // .PKGINFO must be the first entry in .MTREE entries = append([]MtreeEntry{*pkginfoEntry}, entries...) - err = createMtree(info, tw, entries) + err = createMtree(tw, entries) if err != nil { - return err + return fmt.Errorf("create mtree: %w", err) } return createScripts(info, tw) @@ -164,103 +166,38 @@ func (ArchLinux) ConventionalExtension() string { // createFilesInTar adds the files described in the given info to the given tar writer func createFilesInTar(info *nfpm.Info, tw *tar.Writer) ([]MtreeEntry, int64, error) { - created := map[string]struct{}{} - var entries []MtreeEntry + entries := make([]MtreeEntry, 0, len(info.Contents)) var totalSize int64 - var contents []*files.Content - for _, content := range info.Contents { - if content.Packager != "" && content.Packager != packagerName { - continue - } - - switch content.Type { - case "dir", "symlink": - contents = append(contents, content) - continue - } - - fi, err := os.Stat(content.Source) - if err != nil { - return nil, 0, err - } - - if fi.IsDir() { - err = filepath.WalkDir(content.Source, func(path string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - - relPath := strings.TrimPrefix(path, content.Source) - - if d.IsDir() { - return nil - } - - c := &files.Content{ - Source: path, - Destination: filepath.Join(content.Destination, relPath), - FileInfo: &files.ContentFileInfo{ - Mode: d.Type(), - }, - } - - if d.Type()&os.ModeSymlink != 0 { - c.Type = "symlink" - } - - contents = append(contents, c) - return nil - }) - if err != nil { - return nil, 0, err - } - } else { - contents = append(contents, content) - } - } - - for _, content := range contents { - path := normalizePath(content.Destination) + content.Destination = files.AsRelativePath(content.Destination) switch content.Type { - case "ghost": - // Ignore ghost files - case "dir": - err := createDirs(content.Destination, tw, created) - if err != nil { - return nil, 0, err - } - - modtime := time.Now() - // If the time is given, use it - if content.FileInfo != nil && !content.ModTime().IsZero() { - modtime = content.ModTime() + case files.TypeDir, files.TypeImplicitDir: + if content.Type == files.TypeDir { + entries = append(entries, MtreeEntry{ + Destination: content.Destination, + Time: content.ModTime().Unix(), + Type: files.TypeDir, + }) } - entries = append(entries, MtreeEntry{ - Destination: path, - Time: modtime.Unix(), - Type: content.Type, + err := tw.WriteHeader(&tar.Header{ + Name: content.Destination, + Mode: int64(content.Mode()), + Typeflag: tar.TypeDir, + ModTime: content.ModTime(), + Uname: content.FileInfo.Owner, + Gname: content.FileInfo.Group, }) - case "symlink": - dir := filepath.Dir(path) - err := createDirs(dir, tw, created) if err != nil { return nil, 0, err } - - modtime := time.Now() - // If the time is given, use it - if content.FileInfo != nil && !content.ModTime().IsZero() { - modtime = content.ModTime() - } - - err = tw.WriteHeader(&tar.Header{ - Name: normalizePath(content.Destination), + case files.TypeSymlink: + err := tw.WriteHeader(&tar.Header{ + Name: content.Destination, Linkname: content.Source, - ModTime: modtime, + ModTime: content.ModTime(), Typeflag: tar.TypeSymlink, }) if err != nil { @@ -269,34 +206,23 @@ func createFilesInTar(info *nfpm.Info, tw *tar.Writer) ([]MtreeEntry, int64, err entries = append(entries, MtreeEntry{ LinkSource: content.Source, - Destination: path, - Time: modtime.Unix(), + Destination: content.Destination, + Time: content.ModTime().Unix(), Mode: 0o777, Type: content.Type, }) default: - dir := filepath.Dir(path) - err := createDirs(dir, tw, created) - if err != nil { - return nil, 0, err - } - src, err := os.Open(content.Source) if err != nil { return nil, 0, err } - srcFi, err := src.Stat() - if err != nil { - return nil, 0, err - } - header := &tar.Header{ - Name: path, - Mode: int64(srcFi.Mode()), + Name: content.Destination, + Mode: int64(content.Mode()), Typeflag: tar.TypeReg, - Size: srcFi.Size(), - ModTime: srcFi.ModTime(), + Size: content.Size(), + ModTime: content.ModTime(), } if content.FileInfo != nil && content.Mode() != 0 { @@ -327,48 +253,22 @@ func createFilesInTar(info *nfpm.Info, tw *tar.Writer) ([]MtreeEntry, int64, err } entries = append(entries, MtreeEntry{ - Destination: path, - Time: srcFi.ModTime().Unix(), - Mode: int64(srcFi.Mode()), - Size: srcFi.Size(), + Destination: content.Destination, + Time: content.ModTime().Unix(), + Mode: int64(content.Mode()), + Size: content.Size(), Type: content.Type, MD5: md5Hash.Sum(nil), SHA256: sha256Hash.Sum(nil), }) - totalSize += srcFi.Size() + totalSize += content.Size() } } return entries, totalSize, nil } -func createDirs(dst string, tw *tar.Writer, created map[string]struct{}) error { - for _, path := range neededPaths(dst) { - path = normalizePath(path) + "/" - - if _, ok := created[path]; ok { - continue - } - - err := tw.WriteHeader(&tar.Header{ - Name: path, - Mode: 0o755, - Typeflag: tar.TypeDir, - ModTime: time.Now(), - Uname: "root", - Gname: "root", - }) - if err != nil { - return fmt.Errorf("failed to create folder: %w", err) - } - - created[path] = struct{}{} - } - - return nil -} - func defaultStr(s, def string) string { if s == "" { return def @@ -376,27 +276,6 @@ func defaultStr(s, def string) string { return s } -func neededPaths(dst string) []string { - dst = files.ToNixPath(dst) - split := strings.Split(strings.Trim(dst, "/."), "/") - - var sb strings.Builder - var paths []string - for index, elem := range split { - if index != 0 { - sb.WriteRune('/') - } - sb.WriteString(elem) - paths = append(paths, sb.String()) - } - - return paths -} - -func normalizePath(src string) string { - return files.ToNixPath(strings.TrimPrefix(src, "/")) -} - func createPkginfo(info *nfpm.Info, tw *tar.Writer, totalSize int64) (*MtreeEntry, error) { if !nameIsValid(info.Name) { return nil, ErrInvalidPkgName @@ -481,9 +360,8 @@ func createPkginfo(info *nfpm.Info, tw *tar.Writer, totalSize int64) (*MtreeEntr } for _, content := range info.Contents { - if content.Type == "config" || content.Type == "config|noreplace" { - path := normalizePath(content.Destination) - path = strings.TrimPrefix(path, "./") + if content.Type == files.TypeConfig || content.Type == files.TypeConfigNoReplace { + path := files.AsRelativePath(content.Destination) err = writeKVPair(buf, "backup", path) if err != nil { @@ -521,7 +399,7 @@ func createPkginfo(info *nfpm.Info, tw *tar.Writer, totalSize int64) (*MtreeEntr Time: time.Now().Unix(), Mode: 0o644, Size: int64(size), - Type: "file", + Type: files.TypeFile, MD5: md5Hash.Sum(nil), SHA256: sha256Hash.Sum(nil), }, nil @@ -574,19 +452,19 @@ type MtreeEntry struct { func (me *MtreeEntry) WriteTo(w io.Writer) (int64, error) { switch me.Type { - case "dir": + case files.TypeDir: n, err := fmt.Fprintf( w, "./%s time=%d.0 type=dir\n", - normalizePath(me.Destination), + me.Destination, me.Time, ) return int64(n), err - case "symlink": + case files.TypeSymlink: n, err := fmt.Fprintf( w, "./%s time=%d.0 mode=%o type=link link=%s\n", - normalizePath(me.Destination), + me.Destination, me.Time, me.Mode, me.LinkSource, @@ -596,7 +474,7 @@ func (me *MtreeEntry) WriteTo(w io.Writer) (int64, error) { n, err := fmt.Fprintf( w, "./%s time=%d.0 mode=%o size=%d type=file md5digest=%x sha256digest=%x\n", - normalizePath(me.Destination), + me.Destination, me.Time, me.Mode, me.Size, @@ -607,29 +485,17 @@ func (me *MtreeEntry) WriteTo(w io.Writer) (int64, error) { } } -func createMtree(info *nfpm.Info, tw *tar.Writer, entries []MtreeEntry) error { +func createMtree(tw *tar.Writer, entries []MtreeEntry) error { buf := &bytes.Buffer{} gw := pgzip.NewWriter(buf) defer gw.Close() - created := map[string]struct{}{} - _, err := io.WriteString(gw, "#mtree\n") if err != nil { return err } for _, entry := range entries { - destDir := filepath.Dir(entry.Destination) - - dirs := createDirsMtree(destDir, created) - for _, dir := range dirs { - _, err = dir.WriteTo(gw) - if err != nil { - return err - } - } - _, err = entry.WriteTo(gw) if err != nil { return err @@ -653,31 +519,6 @@ func createMtree(info *nfpm.Info, tw *tar.Writer, entries []MtreeEntry) error { return err } -func createDirsMtree(dst string, created map[string]struct{}) []MtreeEntry { - var out []MtreeEntry - for _, path := range neededPaths(dst) { - path = normalizePath(path) + "/" - - if path == "./" { - continue - } - - if _, ok := created[path]; ok { - continue - } - - out = append(out, MtreeEntry{ - Destination: path, - Time: time.Now().Unix(), - Mode: 0o755, - Type: "dir", - }) - - created[path] = struct{}{} - } - return out -} - func createScripts(info *nfpm.Info, tw *tar.Writer) error { scripts := map[string]string{} diff --git a/vendor/github.com/goreleaser/nfpm/v2/deb/deb.go b/vendor/github.com/goreleaser/nfpm/v2/deb/deb.go index cf7526b72..565833f64 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/deb/deb.go +++ b/vendor/github.com/goreleaser/nfpm/v2/deb/deb.go @@ -97,7 +97,9 @@ var ErrInvalidSignatureType = errors.New("invalid signature type") // Package writes a new deb package to the given writer using the given info. func (d *Deb) Package(info *nfpm.Info, deb io.Writer) (err error) { // nolint: funlen info = ensureValidArch(info) - if err = info.Validate(); err != nil { + + err = nfpm.PrepareForPackager(withChangelogIfRequested(info), packagerName) + if err != nil { return err } @@ -348,9 +350,7 @@ func fillDataTar(info *nfpm.Info, w io.Writer) (md5sums []byte, instSize int64, // an error in another part of the code. defer out.Close() // nolint: errcheck - created := map[string]bool{} - - md5buf, instSize, err := createFilesInsideDataTar(info, out, created) + md5buf, instSize, err := createFilesInsideDataTar(info, out) if err != nil { return nil, 0, err } @@ -362,78 +362,34 @@ func fillDataTar(info *nfpm.Info, w io.Writer) (md5sums []byte, instSize int64, return md5buf.Bytes(), instSize, nil } -func createSymlinkInsideTar(file *files.Content, out *tar.Writer) error { - return newItemInsideTar(out, []byte{}, &tar.Header{ - Name: normalizePath(file.Destination), - Linkname: file.Source, - Typeflag: tar.TypeSymlink, - ModTime: file.FileInfo.MTime, - Format: tar.FormatGNU, - }) -} - -func createFilesInsideDataTar(info *nfpm.Info, tw *tar.Writer, - created map[string]bool, -) (md5buf bytes.Buffer, instSize int64, err error) { - // create explicit directories first - for _, file := range info.Contents { - // at this point, we don't care about other types yet - if file.Type != "dir" { - continue - } - - // only consider contents for this packager - if file.Packager != "" && file.Packager != packagerName { - continue - } - - if err := createTree(tw, file.Destination, created); err != nil { - return md5buf, 0, err - } - - normalizedName := normalizePath(strings.Trim(file.Destination, "/")) + "/" - - if created[normalizedName] { - return md5buf, 0, fmt.Errorf("duplicate directory: %q", normalizedName) - } - - err = tw.WriteHeader(&tar.Header{ - Name: normalizedName, - Mode: int64(file.FileInfo.Mode), - Typeflag: tar.TypeDir, - Format: tar.FormatGNU, - Uname: file.FileInfo.Owner, - Gname: file.FileInfo.Group, - ModTime: file.FileInfo.MTime, - }) - if err != nil { - return md5buf, 0, err - } - - created[normalizedName] = true - } - +func createFilesInsideDataTar(info *nfpm.Info, tw *tar.Writer) (md5buf bytes.Buffer, instSize int64, err error) { // create files and implicit directories for _, file := range info.Contents { - // only consider contents for this packager - if file.Packager != "" && file.Packager != packagerName { - continue - } - // create implicit directory structure below the current content - if err = createTree(tw, file.Destination, created); err != nil { - return md5buf, 0, err - } - var size int64 // declare early to avoid shadowing err switch file.Type { - case "ghost": + case files.TypeRPMGhost: // skip ghost files in deb continue - case "dir": - // already handled above - continue - case "symlink": - err = createSymlinkInsideTar(file, tw) + case files.TypeDir, files.TypeImplicitDir: + err = tw.WriteHeader(&tar.Header{ + Name: files.AsExplicitRelativePath(file.Destination), + Mode: int64(file.FileInfo.Mode), + Typeflag: tar.TypeDir, + Format: tar.FormatGNU, + Uname: file.FileInfo.Owner, + Gname: file.FileInfo.Group, + ModTime: file.FileInfo.MTime, + }) + case files.TypeSymlink: + err = newItemInsideTar(tw, []byte{}, &tar.Header{ + Name: files.AsExplicitRelativePath(file.Destination), + Linkname: file.Source, + Typeflag: tar.TypeSymlink, + ModTime: file.FileInfo.MTime, + Format: tar.FormatGNU, + }) + case files.TypeDebChangelog: + size, err = createChangelogInsideDataTar(tw, &md5buf, info, file.Destination) default: size, err = copyToTarAndDigest(file, tw, &md5buf) } @@ -443,15 +399,6 @@ func createFilesInsideDataTar(info *nfpm.Info, tw *tar.Writer, instSize += size } - if info.Changelog != "" { - size, err := createChangelogInsideDataTar(tw, &md5buf, created, info) - if err != nil { - return md5buf, 0, err - } - - instSize += size - } - return md5buf, instSize, nil } @@ -472,7 +419,7 @@ func copyToTarAndDigest(file *files.Content, tw *tar.Writer, md5w io.Writer) (in // 0o777 which we don't want because we want to be able to set the suid bit. header.Mode = int64(file.Mode()) header.Format = tar.FormatGNU - header.Name = normalizePath(file.Destination) + header.Name = files.AsExplicitRelativePath(file.Destination) header.Uname = file.FileInfo.Owner header.Gname = file.FileInfo.Group if err := tw.WriteHeader(header); err != nil { @@ -488,8 +435,23 @@ func copyToTarAndDigest(file *files.Content, tw *tar.Writer, md5w io.Writer) (in return file.Size(), nil } -func createChangelogInsideDataTar(tarw *tar.Writer, md5w io.Writer, - created map[string]bool, info *nfpm.Info, +func withChangelogIfRequested(info *nfpm.Info) *nfpm.Info { + if info.Changelog == "" { + return info + } + + // https://www.debian.org/doc/manuals/developers-reference/pkgs.de.html#recording-changes-in-the-package + // https://lintian.debian.org/tags/debian-changelog-file-missing-or-wrong-name + info.Contents = append(info.Contents, &files.Content{ + Destination: fmt.Sprintf("/usr/share/doc/%s/changelog.Debian.gz", info.Name), + Type: files.TypeDebChangelog, // this type is handeled in createDataTarball + }) + + return info +} + +func createChangelogInsideDataTar(tarw *tar.Writer, g io.Writer, info *nfpm.Info, + fileName string, ) (int64, error) { var buf bytes.Buffer out, err := gzip.NewWriterLevel(&buf, gzip.BestCompression) @@ -510,28 +472,21 @@ func createChangelogInsideDataTar(tarw *tar.Writer, md5w io.Writer, } if err = out.Close(); err != nil { - return 0, fmt.Errorf("closing changelog.Debian.gz: %w", err) + return 0, fmt.Errorf("closing %s: %w", filepath.Base(fileName), err) } changelogData := buf.Bytes() - // https://www.debian.org/doc/manuals/developers-reference/pkgs.de.html#recording-changes-in-the-package - // https://lintian.debian.org/tags/debian-changelog-file-missing-or-wrong-name - changelogName := normalizePath(fmt.Sprintf("/usr/share/doc/%s/changelog.Debian.gz", info.Name)) - if err = createTree(tarw, changelogName, created); err != nil { - return 0, err - } - digest := md5.New() // nolint:gas if _, err = digest.Write(changelogData); err != nil { return 0, err } - if _, err = fmt.Fprintf(md5w, "%x %s\n", digest.Sum(nil), changelogName); err != nil { + if _, err = fmt.Fprintf(g, "%x %s\n", digest.Sum(nil), fileName); err != nil { return 0, err } - if err = newFileInsideTar(tarw, changelogName, changelogData); err != nil { + if err = newFileInsideTar(tarw, fileName, changelogData); err != nil { return 0, err } @@ -576,14 +531,14 @@ func createControl(instSize int64, md5sums []byte, info *nfpm.Info) (controlTarG } filesToCreate := map[string][]byte{ - "control": body.Bytes(), - "md5sums": md5sums, - "conffiles": conffiles(info), + "./control": body.Bytes(), + "./md5sums": md5sums, + "./conffiles": conffiles(info), } triggers := createTriggers(info) if len(triggers) > 0 { - filesToCreate["triggers"] = triggers + filesToCreate["./triggers"] = triggers } for name, content := range filesToCreate { @@ -656,7 +611,7 @@ func newItemInsideTar(out *tar.Writer, content []byte, header *tar.Header) error func newFileInsideTar(out *tar.Writer, name string, content []byte) error { return newItemInsideTar(out, content, &tar.Header{ - Name: normalizePath(name), + Name: files.AsExplicitRelativePath(name), Size: int64(len(content)), Mode: 0o644, ModTime: time.Now(), @@ -675,7 +630,7 @@ func newFilePathInsideTar(out *tar.Writer, path, dest string, mode int64) error return err } return newItemInsideTar(out, content, &tar.Header{ - Name: normalizePath(dest), + Name: files.AsExplicitRelativePath(dest), Size: int64(len(content)), Mode: mode, ModTime: time.Now(), @@ -684,69 +639,13 @@ func newFilePathInsideTar(out *tar.Writer, path, dest string, mode int64) error }) } -// normalizePath returns a path separated by slashes, all relative path items -// resolved and relative to the current directory (so it starts with "./"). -func normalizePath(src string) string { - return "." + files.ToNixPath(filepath.Join("/", src)) -} - -// this is needed because the data.tar.gz file should have the empty folders -// as well, so we walk through the dst and create all subfolders. -func createTree(tarw *tar.Writer, dst string, created map[string]bool) error { - for _, path := range pathsToCreate(dst) { - path = normalizePath(path) + "/" - - if created[path] { - // skipping dir that was previously created inside the archive - // (eg: usr/) - continue - } - - if err := tarw.WriteHeader(&tar.Header{ - Name: path, - Mode: 0o755, - Typeflag: tar.TypeDir, - Format: tar.FormatGNU, - ModTime: time.Now(), - Uname: "root", - Gname: "root", - }); err != nil { - return fmt.Errorf("failed to create folder: %w", err) - } - created[path] = true - } - return nil -} - -func pathsToCreate(dst string) []string { - paths := []string{} - base := strings.Trim(dst, "/") - for { - base = filepath.Dir(base) - if base == "." { - break - } - paths = append(paths, files.ToNixPath(base)) - } - // we don't really need to create those things in order apparently, but, - // it looks really weird if we don't. - result := []string{} - for i := len(paths) - 1; i >= 0; i-- { - result = append(result, paths[i]) - } - return result -} - func conffiles(info *nfpm.Info) []byte { // nolint: prealloc var confs []string for _, file := range info.Contents { - if file.Packager != "" && file.Packager != packagerName { - continue - } switch file.Type { - case "config", "config|noreplace": - confs = append(confs, file.Destination) + case files.TypeConfig, files.TypeConfigNoReplace: + confs = append(confs, filepath.Join("/", file.Destination)) } } return []byte(strings.Join(confs, "\n") + "\n") diff --git a/vendor/github.com/goreleaser/nfpm/v2/files/files.go b/vendor/github.com/goreleaser/nfpm/v2/files/files.go index 7b220fea9..7e1b8cc86 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/files/files.go +++ b/vendor/github.com/goreleaser/nfpm/v2/files/files.go @@ -2,21 +2,61 @@ package files import ( "fmt" + "io/fs" "os" "path/filepath" "sort" + "strconv" "strings" "time" "github.com/goreleaser/nfpm/v2/internal/glob" ) +const ( + // TypeFile is the type of a regular file. This is also the type that is + // implied when no type is specified. + TypeFile = "file" + // TypeDir is the type of a directory that is explicitly added in order to + // declare ownership or non-standard permission. + TypeDir = "dir" + /// TypeImplicitDir is the type of a directory that is implicitly added as a + //parent of a file. + TypeImplicitDir = "implicit dir" + // TypeTree is the type of a whole directory tree structure. + TypeTree = "tree" + // TypeSymlink is the type of a symlink that is created at the destination + // path and points to the source path. + TypeSymlink = "symlink" + // TypeConfig is the type of a configuration file that may be changed by the + // user of the package. + TypeConfig = "config" + // TypeConfigNoReplace is like TypeConfig with an added noreplace directive + // that is respected by RPM-based distributions. For all other packages it + // is handled exactly like TypeConfig. + TypeConfigNoReplace = "config|noreplace" + // TypeGhost is the type of an RPM ghost file which is ignored by other packagers. + TypeRPMGhost = "ghost" + // TypeRPMDoc is the type of an RPM doc file which is ignored by other packagers. + TypeRPMDoc = "doc" + // TypeRPMLicence is the type of an RPM licence file which is ignored by other packagers. + TypeRPMLicence = "licence" + // TypeRPMLicense a different spelling of TypeRPMLicence. + TypeRPMLicense = "license" + // TypeRPMReadme is the type of an RPM readme file which is ignored by other packagers. + TypeRPMReadme = "readme" + // TypeDebChangelog is the type of a Debian changelog archive file which is + // ignored by other packagers. This type should never be set for a content + // entry as it is automatically added when a changelog is configred. + TypeDebChangelog = "debian changelog" +) + // Content describes the source and destination // of one file to copy into a package. type Content struct { Source string `yaml:"src,omitempty" json:"src,omitempty"` Destination string `yaml:"dst" json:"dst"` - Type string `yaml:"type,omitempty" json:"type,omitempty" jsonschema:"enum=symlink,enum=ghost,enum=config,enum=config|noreplace,enum=dir,enum=,default="` + Type string `yaml:"type,omitempty" json:"type,omitempty" jsonschema:"enum=symlink,enum=ghost,enum=config,enum=config|noreplace,enum=dir,enum=tree,enum=,default="` Packager string `yaml:"packager,omitempty" json:"packager,omitempty"` FileInfo *ContentFileInfo `yaml:"file_info,omitempty" json:"file_info,omitempty"` } @@ -72,6 +112,9 @@ func (c *Content) WithFileInfoDefaults() *Content { Packager: c.Packager, FileInfo: c.FileInfo, } + if cc.Type == "" { + cc.Type = TypeFile + } if cc.FileInfo == nil { cc.FileInfo = &ContentFileInfo{} } @@ -81,14 +124,17 @@ func (c *Content) WithFileInfoDefaults() *Content { if cc.FileInfo.Group == "" { cc.FileInfo.Group = "root" } - if cc.Type == "dir" && cc.FileInfo.Mode == 0 { + if (cc.Type == TypeDir || cc.Type == TypeImplicitDir) && cc.FileInfo.Mode == 0 { cc.FileInfo.Mode = 0o755 } + if (cc.Type == TypeDir || cc.Type == TypeImplicitDir) && cc.FileInfo.MTime.IsZero() { + cc.FileInfo.MTime = time.Now() + } // determine if we still need info fileInfoAlreadyComplete := (!cc.FileInfo.MTime.IsZero() && cc.FileInfo.Mode != 0 && - (cc.FileInfo.Size != 0 || cc.Type == "dir")) + (cc.FileInfo.Size != 0 || (cc.Type == TypeDir || cc.Type == TypeImplicitDir))) // only stat source when we actually need more information if cc.Source != "" && !fileInfoAlreadyComplete { @@ -140,45 +186,219 @@ func (c *Content) Sys() interface{} { return nil } -// ExpandContentGlobs gathers all of the real files to be copied into the package. -func ExpandContentGlobs(contents Contents, disableGlobbing bool) (files Contents, err error) { - for _, f := range contents { - var globbed map[string]string +func (c *Content) String() string { + var properties []string + if c.Source != "" { + properties = append(properties, "src="+c.Source) + } + if c.Destination != "" { + properties = append(properties, "dst="+c.Destination) + } + if c.Type != "" { + properties = append(properties, "type="+c.Type) + } + if c.Packager != "" { + properties = append(properties, "packager="+c.Packager) + } + if c.FileInfo != nil { + if c.FileInfo.Owner != "" { + properties = append(properties, "owner="+c.FileInfo.Owner) + } + if c.FileInfo.Group != "" { + properties = append(properties, "group="+c.FileInfo.Group) + } + if c.Mode() != 0 { + properties = append(properties, "mode="+c.Mode().String()) + } + if !c.ModTime().IsZero() { + properties = append(properties, "modtime="+c.ModTime().String()) + } + properties = append(properties, "size="+strconv.Itoa(int(c.FileInfo.Size))) + } + + return fmt.Sprintf("Content(%s)", strings.Join(properties, ",")) +} + +// PrepareForPackager performs the following steps to prepare the contents for +// the provided packager: +// +// - It filters out content that is irrelevant for the specified packager +// - It expands globs (if enabled) and file trees +// - It adds implicit directories (parent directories of files) +// - It adds ownership and other file information if not specified directly +// - It normalizes content source paths to be unix style paths +// - It normalizes content destination paths to be absolute paths with a trailing +// slash if the entry is a directory +// +// If no packager is specified, only the files that are relevant for any +// packager are considered. +func PrepareForPackager(rawContents Contents, packager string, disableGlobbing bool) (Contents, error) { + contentMap := make(map[string]*Content) + + for _, content := range rawContents { + if !isRelevantForPackager(packager, content) { + continue + } + + switch content.Type { + case TypeDir: + // implicit directories at the same destination can just be overwritten + presentContent, destinationOccupied := contentMap[NormalizeAbsoluteDirPath(content.Destination)] + if destinationOccupied && presentContent.Type != TypeImplicitDir { + return nil, contentCollisionError(content, presentContent) + } - switch f.Type { - case "ghost", "symlink", "dir": - // Ghost, symlinks and dirs need to be in the list, but dont glob - // them because they do not really exist - files = append(files, f.WithFileInfoDefaults()) - case "config", "config|noreplace", "file", "": - globbed, err = glob.Glob(f.Source, f.Destination, disableGlobbing) + err := addParents(contentMap, content.Destination) if err != nil { return nil, err } - files, err = appendGlobbedFiles(files, globbed, f) + cc := content.WithFileInfoDefaults() + cc.Source = ToNixPath(cc.Source) + cc.Destination = NormalizeAbsoluteDirPath(cc.Destination) + contentMap[cc.Destination] = cc + case TypeImplicitDir: + // if theres an implicit directory, the contents probably already + // have been expanend so we can just ignore it, it will be created + // by another content element again anyway + case TypeRPMGhost, TypeSymlink, TypeRPMDoc, TypeRPMLicence, TypeRPMLicense, TypeRPMReadme, TypeDebChangelog: + presentContent, destinationOccupied := contentMap[NormalizeAbsoluteFilePath(content.Destination)] + if destinationOccupied { + return nil, contentCollisionError(content, presentContent) + } + + err := addParents(contentMap, content.Destination) if err != nil { return nil, err } + + cc := content.WithFileInfoDefaults() + cc.Source = ToNixPath(cc.Source) + cc.Destination = NormalizeAbsoluteFilePath(cc.Destination) + contentMap[cc.Destination] = cc + case TypeTree: + err := addTree(contentMap, content) + if err != nil { + return nil, fmt.Errorf("add tree: %w", err) + } + case TypeConfig, TypeConfigNoReplace, TypeFile, "": + globbed, err := glob.Glob(content.Source, content.Destination, disableGlobbing) + if err != nil { + return nil, err + } + + err = addGlobbedFiles(contentMap, globbed, content) + if err != nil { + return nil, fmt.Errorf("add globbed files from %q: %w", content.Source, err) + } default: - return files, fmt.Errorf("invalid file type: %s", f.Type) + return nil, fmt.Errorf("invalid content type: %s", content.Type) } + } + + res := make(Contents, 0, len(contentMap)) + for _, content := range contentMap { + res = append(res, content) } - err = checkNoCollisions(files) - if err != nil { - return nil, err + sort.Sort(res) + + return res, nil +} + +func isRelevantForPackager(packager string, content *Content) bool { + if packager == "" { + return true + } + + if content.Packager != "" && content.Packager != packager { + return false + } + + if packager != "rpm" && + (content.Type == TypeRPMDoc || content.Type == TypeRPMLicence || + content.Type == TypeRPMLicense || content.Type == TypeRPMReadme || + content.Type == TypeRPMGhost) { + return false + } + + if packager != "deb" && content.Type == TypeDebChangelog { + return false + } + + return true +} + +func addParents(contentMap map[string]*Content, path string) error { + for _, parent := range sortedParents(path) { + parent = NormalizeAbsoluteDirPath(parent) + // check for content collision and just overwrite previously created + // implicit directories + c, ok := contentMap[parent] + if ok { + // either we already created this directory as an explicit directory + // or as an implicit directory of another file + if c.Type == TypeDir || c.Type == TypeImplicitDir { + continue + } + + return contentCollisionError(&Content{ + Type: "parent directory for " + path, + Destination: parent, + }, c) + } + + contentMap[parent] = &Content{ + Destination: parent, + Type: TypeImplicitDir, + FileInfo: &ContentFileInfo{ + Owner: "root", + Group: "root", + Mode: 0o755, + MTime: time.Now(), + }, + } + } + + return nil +} + +func sortedParents(dst string) []string { + paths := []string{} + base := strings.Trim(dst, "/") + for { + base = filepath.Dir(base) + if base == "." { + break + } + paths = append(paths, ToNixPath(base)) } - // sort the files for reproducibility and general cleanliness - sort.Sort(files) + // reverse in place + for i := len(paths)/2 - 1; i >= 0; i-- { + oppositeIndex := len(paths) - 1 - i + paths[i], paths[oppositeIndex] = paths[oppositeIndex], paths[i] + } - return files, nil + return paths } -func appendGlobbedFiles(all Contents, globbed map[string]string, origFile *Content) (Contents, error) { +func addGlobbedFiles(all map[string]*Content, globbed map[string]string, origFile *Content) error { for src, dst := range globbed { + dst = NormalizeAbsoluteFilePath(dst) + presentContent, destinationOccupied := all[dst] + if destinationOccupied { + c := *origFile + c.Destination = dst + return contentCollisionError(&c, presentContent) + } + + err := addParents(all, dst) + if err != nil { + return err + } + // if the file has a FileInfo, we need to copy it but recalculate its size newFileInfo := origFile.FileInfo if newFileInfo != nil { @@ -186,8 +406,9 @@ func appendGlobbedFiles(all Contents, globbed map[string]string, origFile *Conte newFileInfoVal.Size = 0 newFileInfo = &newFileInfoVal } + newFile := (&Content{ - Destination: ToNixPath(dst), + Destination: NormalizeAbsoluteFilePath(dst), Source: ToNixPath(src), Type: origFile.Type, FileInfo: newFileInfo, @@ -195,37 +416,93 @@ func appendGlobbedFiles(all Contents, globbed map[string]string, origFile *Conte }).WithFileInfoDefaults() if dst, err := os.Readlink(src); err == nil { newFile.Source = dst - newFile.Type = "symlink" + newFile.Type = TypeSymlink } - all = append(all, newFile) + all[dst] = newFile } - return all, nil + return nil } -var ErrContentCollision = fmt.Errorf("content collision") +func addTree(all map[string]*Content, tree *Content) error { + if tree.Destination != "/" && tree.Destination != "" { + presentContent, destinationOccupied := all[NormalizeAbsoluteDirPath(tree.Destination)] + if destinationOccupied && presentContent.Type != TypeImplicitDir { + return contentCollisionError(tree, presentContent) + } + } -func checkNoCollisions(contents Contents) error { - alreadyPresent := map[string]*Content{} + err := addParents(all, tree.Destination) + if err != nil { + return err + } + + return filepath.WalkDir(tree.Source, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + + relPath, err := filepath.Rel(tree.Source, path) + if err != nil { + return err + } + + destination := filepath.Join(tree.Destination, relPath) - for _, elem := range contents { - present, ok := alreadyPresent[elem.Destination] - if ok && (present.Packager == "" || elem.Packager == "" || present.Packager == elem.Packager) { - if elem.Type == "dir" { - return fmt.Errorf("cannot add directory %q because it is already present: %w", - elem.Destination, ErrContentCollision) + c := &Content{} + + switch { + case d.IsDir(): + info, err := d.Info() + if err != nil { + return fmt.Errorf("get directory information: %w", err) } - return fmt.Errorf( - "cannot add %q because %q is already present at the same destination (%s): %w", - elem.Source, present.Source, present.Destination, ErrContentCollision) + c.Type = TypeDir + c.Destination = NormalizeAbsoluteDirPath(destination) + c.FileInfo = &ContentFileInfo{ + Owner: "root", + Group: "root", + Mode: info.Mode(), + MTime: info.ModTime(), + } + case d.Type()&os.ModeSymlink != 0: + linkDestination, err := os.Readlink(path) + if err != nil { + return err + } + + c.Source = linkDestination + c.Destination = NormalizeAbsoluteFilePath(destination) + c.Type = TypeSymlink + default: + c.Source = path + c.Destination = NormalizeAbsoluteFilePath(destination) + c.Type = TypeFile + c.FileInfo = &ContentFileInfo{ + Mode: d.Type(), + } } - alreadyPresent[elem.Destination] = elem + all[c.Destination] = c.WithFileInfoDefaults() + + return nil + }) +} + +var ErrContentCollision = fmt.Errorf("content collision") + +func contentCollisionError(new *Content, present *Content) error { + var presentSource string + if present.Source != "" { + presentSource = " with source " + present.Source } - return nil + return fmt.Errorf("adding %s at destination %s: "+ + "%s%s is already present at this destination: %w", + new.Type, new.Destination, present.Type, presentSource, ErrContentCollision, + ) } // ToNixPath converts the given path to a nix-style path. @@ -235,3 +512,53 @@ func checkNoCollisions(contents Contents) error { func ToNixPath(path string) string { return filepath.ToSlash(filepath.Clean(path)) } + +// As relative path converts a path to an explicitly relative path starting with +// a dot (e.g. it converts /foo -> ./foo). +func AsExplicitRelativePath(path string) string { + if path == "/" { + return "./" + } + + cleanedPath := filepath.Clean(path) + + end := "" + if len(cleanedPath) > 1 && strings.HasSuffix(path, "/") { + end = "/" + } + + if !filepath.IsAbs(cleanedPath) { + cleanedPath = filepath.Join("/", cleanedPath) + } + + return "." + cleanedPath + end +} + +// AsRelativePath converts a path to a relative path without a "./" prefix. This +// function leaves trailing slashes to indicate that the path refers to a +// directory. +func AsRelativePath(path string) string { + cleanedPath := filepath.Clean(path) + + end := "" + if len(cleanedPath) > 1 && strings.HasSuffix(path, "/") { + end = "/" + } + + if filepath.IsAbs(cleanedPath) { + return strings.TrimLeft(cleanedPath, "/") + end + } + + return cleanedPath + end +} + +// NormalizeAbsoluteFilePath returns an absolute cleaned path separated by +// slashes. +func NormalizeAbsoluteFilePath(src string) string { + return ToNixPath(filepath.Join("/", src)) +} + +// normalizeFirPath is linke NormalizeAbsoluteFilePath with a trailing slash. +func NormalizeAbsoluteDirPath(path string) string { + return NormalizeAbsoluteFilePath(strings.TrimRight(path, "/")) + "/" +} diff --git a/vendor/github.com/goreleaser/nfpm/v2/internal/cmd/root.go b/vendor/github.com/goreleaser/nfpm/v2/internal/cmd/root.go index b917e02c2..f8f9978d4 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/internal/cmd/root.go +++ b/vendor/github.com/goreleaser/nfpm/v2/internal/cmd/root.go @@ -3,10 +3,10 @@ package cmd import ( "fmt" - _ "github.com/goreleaser/nfpm/v2/apk" - _ "github.com/goreleaser/nfpm/v2/arch" - _ "github.com/goreleaser/nfpm/v2/deb" - _ "github.com/goreleaser/nfpm/v2/rpm" + _ "github.com/goreleaser/nfpm/v2/apk" // apk packager + _ "github.com/goreleaser/nfpm/v2/arch" // archlinux packager + _ "github.com/goreleaser/nfpm/v2/deb" // deb packager + _ "github.com/goreleaser/nfpm/v2/rpm" // rpm packager "github.com/spf13/cobra" ) diff --git a/vendor/github.com/goreleaser/nfpm/v2/internal/rpmpack/header.go b/vendor/github.com/goreleaser/nfpm/v2/internal/rpmpack/header.go index b223672ef..8e95cdbf8 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/internal/rpmpack/header.go +++ b/vendor/github.com/goreleaser/nfpm/v2/internal/rpmpack/header.go @@ -19,8 +19,6 @@ import ( "encoding/binary" "fmt" "sort" - - "github.com/pkg/errors" ) const ( @@ -160,7 +158,7 @@ func (i *index) Bytes() ([]byte, error) { // 4 count and 4 size // We add the pseudo-entry "eigenHeader" to count. if err := binary.Write(w, binary.BigEndian, []int32{int32(len(i.entries)) + 1, int32(entryData.Len())}); err != nil { - return nil, errors.Wrap(err, "failed to write eigenHeader") + return nil, fmt.Errorf("failed to write eigenHeader: %w", err) } // Write the eigenHeader index entry w.Write(i.eigenHeader().indexBytes(i.h, entryData.Len()-0x10)) diff --git a/vendor/github.com/goreleaser/nfpm/v2/internal/rpmpack/rpm.go b/vendor/github.com/goreleaser/nfpm/v2/internal/rpmpack/rpm.go index 2c243e410..76c893d3f 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/internal/rpmpack/rpm.go +++ b/vendor/github.com/goreleaser/nfpm/v2/internal/rpmpack/rpm.go @@ -20,6 +20,7 @@ package rpmpack import ( "bytes" "crypto/sha256" + "errors" "fmt" "io" "path" @@ -31,7 +32,6 @@ import ( "github.com/cavaliergopher/cpio" "github.com/klauspost/compress/zstd" gzip "github.com/klauspost/pgzip" - "github.com/pkg/errors" "github.com/ulikunitz/xz" "github.com/ulikunitz/xz/lzma" ) @@ -243,18 +243,18 @@ func (r *RPM) Write(w io.Writer) error { sort.Strings(fnames) for _, fn := range fnames { if err := r.writeFile(r.files[fn]); err != nil { - return errors.Wrapf(err, "failed to write file %q", fn) + return fmt.Errorf("failed to write file %q: %w", fn, err) } } if err := r.cpio.Close(); err != nil { - return errors.Wrap(err, "failed to close cpio payload") + return fmt.Errorf("failed to close cpio payload: %w", err) } if err := r.compressedPayload.Close(); err != nil { - return errors.Wrap(err, "failed to close gzip payload") + return fmt.Errorf("failed to close gzip payload: %w", err) } if _, err := w.Write(lead(r.Name, r.FullVersion())); err != nil { - return errors.Wrap(err, "failed to write lead") + return fmt.Errorf("failed to write lead: %w", err) } // Write the regular header. h := newIndex(immutable) @@ -273,32 +273,34 @@ func (r *RPM) Write(w io.Writer) error { h.AddEntries(r.customTags) hb, err := h.Bytes() if err != nil { - return errors.Wrap(err, "failed to retrieve header") + return fmt.Errorf("failed to retrieve header: %w", err) } // Write the signatures s := newIndex(signatures) if err := r.writeSignatures(s, hb); err != nil { - return errors.Wrap(err, "failed to create signatures") + return fmt.Errorf("failed to create signatures: %w", err) } s.AddEntries(r.customSigs) sb, err := s.Bytes() if err != nil { - return errors.Wrap(err, "failed to retrieve signatures header") + return fmt.Errorf("failed to retrieve signatures header: %w", err) } if _, err := w.Write(sb); err != nil { - return errors.Wrap(err, "failed to write signature bytes") + return fmt.Errorf("failed to write signature bytes: %w", err) } // Signatures are padded to 8-byte boundaries if _, err := w.Write(make([]byte, (8-len(sb)%8)%8)); err != nil { - return errors.Wrap(err, "failed to write signature padding") + return fmt.Errorf("failed to write signature padding: %w", err) } if _, err := w.Write(hb); err != nil { - return errors.Wrap(err, "failed to write header body") + return fmt.Errorf("failed to write header body: %w", err) } - _, err = w.Write(r.payload.Bytes()) - return errors.Wrap(err, "failed to write payload") + if _, err := w.Write(r.payload.Bytes()); err != nil { + return fmt.Errorf("failed to write payload: %w", err) + } + return nil } // SetPGPSigner registers a function that will accept the header and payload as bytes, @@ -318,14 +320,14 @@ func (r *RPM) writeSignatures(sigHeader *index, regHeader []byte) error { header := append([]byte{}, regHeader...) headerSig, err := r.pgpSigner(header) if err != nil { - return errors.Wrap(err, "call to signer failed") + return fmt.Errorf("call to signer failed: %w", err) } sigHeader.Add(sigRSA, EntryBytes(headerSig)) body := append(header, r.payload.Bytes()...) bodySig, err := r.pgpSigner(body) if err != nil { - return errors.Wrap(err, "call to signer failed") + return fmt.Errorf("call to signer failed: %w", err) } sigHeader.Add(sigPGP, EntryBytes(bodySig)) } @@ -335,22 +337,22 @@ func (r *RPM) writeSignatures(sigHeader *index, regHeader []byte) error { func (r *RPM) writeRelationIndexes(h *index) error { // add all relation categories if err := r.Provides.AddToIndex(h, tagProvides, tagProvideVersion, tagProvideFlags); err != nil { - return errors.Wrap(err, "failed to add provides") + return fmt.Errorf("failed to add provides: %w", err) } if err := r.Obsoletes.AddToIndex(h, tagObsoletes, tagObsoleteVersion, tagObsoleteFlags); err != nil { - return errors.Wrap(err, "failed to add obsoletes") + return fmt.Errorf("failed to add obsoletes: %w", err) } if err := r.Suggests.AddToIndex(h, tagSuggests, tagSuggestVersion, tagSuggestFlags); err != nil { - return errors.Wrap(err, "failed to add suggests") + return fmt.Errorf("failed to add suggests: %w", err) } if err := r.Recommends.AddToIndex(h, tagRecommends, tagRecommendVersion, tagRecommendFlags); err != nil { - return errors.Wrap(err, "failed to add recommends") + return fmt.Errorf("failed to add recommends: %w", err) } if err := r.Requires.AddToIndex(h, tagRequires, tagRequireVersion, tagRequireFlags); err != nil { - return errors.Wrap(err, "failed to add requires") + return fmt.Errorf("failed to add requires: %w", err) } if err := r.Conflicts.AddToIndex(h, tagConflicts, tagConflictVersion, tagConflictFlags); err != nil { - return errors.Wrap(err, "failed to add conflicts") + return fmt.Errorf("failed to add conflicts: %w", err) } return nil @@ -540,10 +542,10 @@ func (r *RPM) writePayload(f RPMFile, links int) error { Links: links, } if err := r.cpio.WriteHeader(hdr); err != nil { - return errors.Wrap(err, "failed to write payload file header") + return fmt.Errorf("failed to write payload file header: %w", err) } if _, err := r.cpio.Write(f.Body); err != nil { - return errors.Wrap(err, "failed to write payload file content") + return fmt.Errorf("failed to write payload file content: %w", err) } r.payloadSize += uint(len(f.Body)) return nil diff --git a/vendor/github.com/goreleaser/nfpm/v2/internal/sign/pgp.go b/vendor/github.com/goreleaser/nfpm/v2/internal/sign/pgp.go index 0f6d7ea28..1c0af4662 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/internal/sign/pgp.go +++ b/vendor/github.com/goreleaser/nfpm/v2/internal/sign/pgp.go @@ -24,11 +24,11 @@ func PGPSigner(keyFile, passphrase string) func([]byte) ([]byte, error) { // PGPSignerWithKeyID returns a PGP signer that creates a detached non-ASCII-armored // signature and is compatible with rpmpack's signature API. -func PGPSignerWithKeyID(keyFile, passphrase string, hexKeyId *string) func([]byte) ([]byte, error) { +func PGPSignerWithKeyID(keyFile, passphrase string, hexKeyID *string) func([]byte) ([]byte, error) { return func(data []byte) ([]byte, error) { - keyId, err := parseKeyID(hexKeyId) + keyID, err := parseKeyID(hexKeyID) if err != nil { - return nil, fmt.Errorf("%v is not a valid key id: %w", hexKeyId, err) + return nil, fmt.Errorf("%v is not a valid key id: %w", hexKeyID, err) } key, err := readSigningKey(keyFile, passphrase) @@ -39,7 +39,7 @@ func PGPSignerWithKeyID(keyFile, passphrase string, hexKeyId *string) func([]byt var signature bytes.Buffer err = openpgp.DetachSign(&signature, key, bytes.NewReader(data), &packet.Config{ - SigningKeyId: keyId, + SigningKeyId: keyID, DefaultHash: crypto.SHA256, }) if err != nil { @@ -56,10 +56,10 @@ func PGPArmoredDetachSign(message io.Reader, keyFile, passphrase string) ([]byte } // PGPArmoredDetachSignWithKeyID creates an ASCII-armored detached signature. -func PGPArmoredDetachSignWithKeyID(message io.Reader, keyFile, passphrase string, hexKeyId *string) ([]byte, error) { - keyId, err := parseKeyID(hexKeyId) +func PGPArmoredDetachSignWithKeyID(message io.Reader, keyFile, passphrase string, hexKeyID *string) ([]byte, error) { + keyID, err := parseKeyID(hexKeyID) if err != nil { - return nil, fmt.Errorf("%v is not a valid key id: %w", hexKeyId, err) + return nil, fmt.Errorf("%v is not a valid key id: %w", hexKeyID, err) } key, err := readSigningKey(keyFile, passphrase) @@ -70,7 +70,7 @@ func PGPArmoredDetachSignWithKeyID(message io.Reader, keyFile, passphrase string var signature bytes.Buffer err = openpgp.ArmoredDetachSign(&signature, key, message, &packet.Config{ - SigningKeyId: keyId, + SigningKeyId: keyID, DefaultHash: crypto.SHA256, }) if err != nil { @@ -80,10 +80,10 @@ func PGPArmoredDetachSignWithKeyID(message io.Reader, keyFile, passphrase string return signature.Bytes(), nil } -func PGPClearSignWithKeyID(message io.Reader, keyFile, passphrase string, hexKeyId *string) ([]byte, error) { - keyId, err := parseKeyID(hexKeyId) +func PGPClearSignWithKeyID(message io.Reader, keyFile, passphrase string, hexKeyID *string) ([]byte, error) { + keyID, err := parseKeyID(hexKeyID) if err != nil { - return nil, fmt.Errorf("%v is not a valid key id: %w", hexKeyId, err) + return nil, fmt.Errorf("%v is not a valid key id: %w", hexKeyID, err) } key, err := readSigningKey(keyFile, passphrase) @@ -94,7 +94,7 @@ func PGPClearSignWithKeyID(message io.Reader, keyFile, passphrase string, hexKey var signature bytes.Buffer writeCloser, err := clearsign.Encode(&signature, key.PrivateKey, &packet.Config{ - SigningKeyId: keyId, + SigningKeyId: keyID, DefaultHash: crypto.SHA256, }) if err != nil { @@ -171,12 +171,12 @@ func PGPReadMessage(message []byte, armoredPubKeyFile string) error { return err } -func parseKeyID(hexKeyId *string) (uint64, error) { - if hexKeyId == nil || *hexKeyId == "" { +func parseKeyID(hexKeyID *string) (uint64, error) { + if hexKeyID == nil || *hexKeyID == "" { return 0, nil } - result, err := strconv.ParseUint(*hexKeyId, 16, 64) + result, err := strconv.ParseUint(*hexKeyID, 16, 64) if err != nil { return 0, err } diff --git a/vendor/github.com/goreleaser/nfpm/v2/nfpm.go b/vendor/github.com/goreleaser/nfpm/v2/nfpm.go index 233141806..702b7f314 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/nfpm.go +++ b/vendor/github.com/goreleaser/nfpm/v2/nfpm.go @@ -134,6 +134,7 @@ func (c *Config) Get(format string) (info *Info, err error) { if err = mergo.Merge(&info.Overridables, override, mergo.WithOverride); err != nil { return nil, fmt.Errorf("failed to merge overrides into info: %w", err) } + var contents []*files.Content for _, f := range info.Contents { if f.Packager == format || f.Packager == "" { @@ -423,7 +424,30 @@ func (e ErrFieldEmpty) Error() string { return fmt.Sprintf("package %s must be provided", e.field) } -// Validate the given Info and returns an error if it is invalid. +// PrepareForPackager validates the configuration for the given packager and +// prepares the contents for said packager. +func PrepareForPackager(info *Info, packager string) (err error) { + if info.Name == "" { + return ErrFieldEmpty{"name"} + } + + if info.Arch == "" && + ((packager == "deb" && info.Deb.Arch == "") || + (packager == "rpm" && info.RPM.Arch == "") || + (packager == "apk" && info.APK.Arch == "")) { + return ErrFieldEmpty{"arch"} + } + if info.Version == "" { + return ErrFieldEmpty{"version"} + } + + info.Contents, err = files.PrepareForPackager(info.Contents, packager, info.DisableGlobbing) + + return err +} + +// Validate the given Info and returns an error if it is invalid. Validate will +// no change the info's contents. func Validate(info *Info) (err error) { if info.Name == "" { return ErrFieldEmpty{"name"} @@ -435,12 +459,13 @@ func Validate(info *Info) (err error) { return ErrFieldEmpty{"version"} } - contents, err := files.ExpandContentGlobs(info.Contents, info.DisableGlobbing) - if err != nil { - return err + for packager := range packagers { + _, err := files.PrepareForPackager(info.Contents, packager, info.DisableGlobbing) + if err != nil { + return err + } } - info.Contents = contents return nil } diff --git a/vendor/github.com/goreleaser/nfpm/v2/rpm/rpm.go b/vendor/github.com/goreleaser/nfpm/v2/rpm/rpm.go index d9559baf8..91cf74967 100644 --- a/vendor/github.com/goreleaser/nfpm/v2/rpm/rpm.go +++ b/vendor/github.com/goreleaser/nfpm/v2/rpm/rpm.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "os" + "path/filepath" "strconv" "strings" "time" @@ -105,7 +106,9 @@ func (*RPM) Package(info *nfpm.Info, w io.Writer) (err error) { rpm *rpmpack.RPM ) info = ensureValidArch(info) - if err = info.Validate(); err != nil { + + err = nfpm.PrepareForPackager(info, packagerName) + if err != nil { return err } @@ -341,26 +344,29 @@ func createFilesInsideRPM(info *nfpm.Info, rpm *rpmpack.RPM) (err error) { var file *rpmpack.RPMFile switch content.Type { - case "config": + case files.TypeConfig: file, err = asRPMFile(content, rpmpack.ConfigFile) - case "config|noreplace": + case files.TypeConfigNoReplace: file, err = asRPMFile(content, rpmpack.ConfigFile|rpmpack.NoReplaceFile) - case "ghost": + case files.TypeRPMGhost: if content.FileInfo.Mode == 0 { content.FileInfo.Mode = os.FileMode(0o644) } file, err = asRPMFile(content, rpmpack.GhostFile) - case "doc": + case files.TypeRPMDoc: file, err = asRPMFile(content, rpmpack.DocFile) - case "licence", "license": + case files.TypeRPMLicence, files.TypeRPMLicense: file, err = asRPMFile(content, rpmpack.LicenceFile) - case "readme": + case files.TypeRPMReadme: file, err = asRPMFile(content, rpmpack.ReadmeFile) - case "symlink": + case files.TypeSymlink: file = asRPMSymlink(content) - case "dir": - file, err = asRPMDirectory(content) + case files.TypeDir: + file = asRPMDirectory(content) + case files.TypeImplicitDir: + // we don't need to add imlicit directories to RPMs + continue default: file, err = asRPMFile(content, rpmpack.GenericFile) } @@ -369,20 +375,23 @@ func createFilesInsideRPM(info *nfpm.Info, rpm *rpmpack.RPM) (err error) { return err } + // clean assures that even folders do not have a trailing slash + file.Name = filepath.Clean(file.Name) rpm.AddFile(*file) + } return nil } -func asRPMDirectory(content *files.Content) (*rpmpack.RPMFile, error) { +func asRPMDirectory(content *files.Content) *rpmpack.RPMFile { return &rpmpack.RPMFile{ Name: content.Destination, Mode: uint(content.Mode()) | tagDirectory, MTime: uint32(time.Now().Unix()), Owner: content.FileInfo.Owner, Group: content.FileInfo.Group, - }, nil + } } func asRPMSymlink(content *files.Content) *rpmpack.RPMFile { @@ -398,7 +407,7 @@ func asRPMSymlink(content *files.Content) *rpmpack.RPMFile { func asRPMFile(content *files.Content, fileType rpmpack.FileType) (*rpmpack.RPMFile, error) { data, err := os.ReadFile(content.Source) - if err != nil && content.Type != "ghost" { + if err != nil && content.Type != files.TypeRPMGhost { return nil, err } diff --git a/vendor/github.com/imdario/mergo/CONTRIBUTING.md b/vendor/github.com/imdario/mergo/CONTRIBUTING.md new file mode 100644 index 000000000..0a1ff9f94 --- /dev/null +++ b/vendor/github.com/imdario/mergo/CONTRIBUTING.md @@ -0,0 +1,112 @@ + +# Contributing to mergo + +First off, thanks for taking the time to contribute! ❤️ + +All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 + +> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: +> - Star the project +> - Tweet about it +> - Refer this project in your project's readme +> - Mention the project at local meetups and tell your friends/colleagues + + +## Table of Contents + +- [Code of Conduct](#code-of-conduct) +- [I Have a Question](#i-have-a-question) +- [I Want To Contribute](#i-want-to-contribute) +- [Reporting Bugs](#reporting-bugs) +- [Suggesting Enhancements](#suggesting-enhancements) + +## Code of Conduct + +This project and everyone participating in it is governed by the +[mergo Code of Conduct](https://github.com/imdario/mergoblob/master/CODE_OF_CONDUCT.md). +By participating, you are expected to uphold this code. Please report unacceptable behavior +to <>. + + +## I Have a Question + +> If you want to ask a question, we assume that you have read the available [Documentation](https://pkg.go.dev/github.com/imdario/mergo). + +Before you ask a question, it is best to search for existing [Issues](https://github.com/imdario/mergo/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. + +If you then still feel the need to ask a question and need clarification, we recommend the following: + +- Open an [Issue](https://github.com/imdario/mergo/issues/new). +- Provide as much context as you can about what you're running into. +- Provide project and platform versions (nodejs, npm, etc), depending on what seems relevant. + +We will then take care of the issue as soon as possible. + +## I Want To Contribute + +> ### Legal Notice +> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license. + +### Reporting Bugs + + +#### Before Submitting a Bug Report + +A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. + +- Make sure that you are using the latest version. +- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](). If you are looking for support, you might want to check [this section](#i-have-a-question)). +- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/imdario/mergoissues?q=label%3Abug). +- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue. +- Collect information about the bug: +- Stack trace (Traceback) +- OS, Platform and Version (Windows, Linux, macOS, x86, ARM) +- Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. +- Possibly your input and the output +- Can you reliably reproduce the issue? And can you also reproduce it with older versions? + + +#### How Do I Submit a Good Bug Report? + +> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to . + + +We use GitHub issues to track bugs and errors. If you run into an issue with the project: + +- Open an [Issue](https://github.com/imdario/mergo/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) +- Explain the behavior you would expect and the actual behavior. +- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. +- Provide the information you collected in the previous section. + +Once it's filed: + +- The project team will label the issue accordingly. +- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced. +- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be implemented by someone. + +### Suggesting Enhancements + +This section guides you through submitting an enhancement suggestion for mergo, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. + + +#### Before Submitting an Enhancement + +- Make sure that you are using the latest version. +- Read the [documentation]() carefully and find out if the functionality is already covered, maybe by an individual configuration. +- Perform a [search](https://github.com/imdario/mergo/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. +- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. + + +#### How Do I Submit a Good Enhancement Suggestion? + +Enhancement suggestions are tracked as [GitHub issues](https://github.com/imdario/mergo/issues). + +- Use a **clear and descriptive title** for the issue to identify the suggestion. +- Provide a **step-by-step description of the suggested enhancement** in as many details as possible. +- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. +- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. +- **Explain why this enhancement would be useful** to most mergo users. You may also want to point out the other projects that solved it better and which could serve as inspiration. + + +## Attribution +This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)! diff --git a/vendor/github.com/imdario/mergo/README.md b/vendor/github.com/imdario/mergo/README.md index 7e6f7aeee..4f0287498 100644 --- a/vendor/github.com/imdario/mergo/README.md +++ b/vendor/github.com/imdario/mergo/README.md @@ -1,6 +1,5 @@ # Mergo - [![GoDoc][3]][4] [![GitHub release][5]][6] [![GoCard][7]][8] @@ -9,6 +8,7 @@ [![Sourcegraph][11]][12] [![FOSSA Status][13]][14] [![Become my sponsor][15]][16] +[![Tidelift][17]][18] [1]: https://travis-ci.org/imdario/mergo.png [2]: https://travis-ci.org/imdario/mergo @@ -26,6 +26,8 @@ [14]: https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_shield [15]: https://img.shields.io/github/sponsors/imdario [16]: https://github.com/sponsors/imdario +[17]: https://tidelift.com/badges/package/go/github.com%2Fimdario%2Fmergo +[18]: https://tidelift.com/subscription/pkg/go-github.com-imdario-mergo A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. @@ -55,7 +57,6 @@ If Mergo is useful to you, consider buying me a coffee, a beer, or making a mont ### Mergo in the wild -- [cli/cli](https://github.com/cli/cli) - [moby/moby](https://github.com/moby/moby) - [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes) - [vmware/dispatch](https://github.com/vmware/dispatch) diff --git a/vendor/github.com/imdario/mergo/SECURITY.md b/vendor/github.com/imdario/mergo/SECURITY.md new file mode 100644 index 000000000..a5de61f77 --- /dev/null +++ b/vendor/github.com/imdario/mergo/SECURITY.md @@ -0,0 +1,14 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.3.x | :white_check_mark: | +| < 0.3 | :x: | + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/vendor/github.com/imdario/mergo/map.go b/vendor/github.com/imdario/mergo/map.go index a13a7ee46..f739255af 100644 --- a/vendor/github.com/imdario/mergo/map.go +++ b/vendor/github.com/imdario/mergo/map.go @@ -44,7 +44,7 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf } } // Remember, remember... - visited[h] = &visit{addr, typ, seen} + visited[h] = &visit{typ, seen, addr} } zeroValue := reflect.Value{} switch dst.Kind() { diff --git a/vendor/github.com/imdario/mergo/merge.go b/vendor/github.com/imdario/mergo/merge.go index 8b4e2f47a..1bf26cfe5 100644 --- a/vendor/github.com/imdario/mergo/merge.go +++ b/vendor/github.com/imdario/mergo/merge.go @@ -38,10 +38,10 @@ func isExportedComponent(field *reflect.StructField) bool { } type Config struct { + Transformers Transformers Overwrite bool AppendSlice bool TypeCheck bool - Transformers Transformers overwriteWithEmptyValue bool overwriteSliceWithEmptyValue bool sliceDeepCopy bool @@ -76,7 +76,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } } // Remember, remember... - visited[h] = &visit{addr, typ, seen} + visited[h] = &visit{typ, seen, addr} } if config.Transformers != nil && !isReflectNil(dst) && dst.IsValid() { @@ -205,6 +205,16 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co dst.SetMapIndex(key, srcElement) } } + + // Ensure that all keys in dst are deleted if they are not in src. + if overwriteWithEmptySrc { + for _, key := range dst.MapKeys() { + srcElement := src.MapIndex(key) + if !srcElement.IsValid() { + dst.SetMapIndex(key, reflect.Value{}) + } + } + } case reflect.Slice: if !dst.CanSet() { break diff --git a/vendor/github.com/imdario/mergo/mergo.go b/vendor/github.com/imdario/mergo/mergo.go index 9fe362d47..d2af2a95f 100644 --- a/vendor/github.com/imdario/mergo/mergo.go +++ b/vendor/github.com/imdario/mergo/mergo.go @@ -28,9 +28,9 @@ var ( // checks in progress are true when it reencounters them. // Visited are stored in a map indexed by 17 * a1 + a2; type visit struct { - ptr uintptr typ reflect.Type next *visit + ptr uintptr } // From src/pkg/encoding/json/encode.go. diff --git a/vendor/github.com/klauspost/compress/README.md b/vendor/github.com/klauspost/compress/README.md index 958666ed8..c2c7252fe 100644 --- a/vendor/github.com/klauspost/compress/README.md +++ b/vendor/github.com/klauspost/compress/README.md @@ -16,6 +16,21 @@ This package provides various compression algorithms. # changelog +* Mar 13, 2023 - [v1.16.1](https://github.com/klauspost/compress/releases/tag/v1.16.1) + * zstd: Speed up + improve best encoder by @greatroar in https://github.com/klauspost/compress/pull/776 + * gzhttp: Add optional [BREACH mitigation](https://github.com/klauspost/compress/tree/master/gzhttp#breach-mitigation). https://github.com/klauspost/compress/pull/762 https://github.com/klauspost/compress/pull/768 https://github.com/klauspost/compress/pull/769 https://github.com/klauspost/compress/pull/770 https://github.com/klauspost/compress/pull/767 + * s2: Add Intel LZ4s converter https://github.com/klauspost/compress/pull/766 + * zstd: Minor bug fixes https://github.com/klauspost/compress/pull/771 https://github.com/klauspost/compress/pull/772 https://github.com/klauspost/compress/pull/773 + * huff0: Speed up compress1xDo by @greatroar in https://github.com/klauspost/compress/pull/774 + +* Feb 26, 2023 - [v1.16.0](https://github.com/klauspost/compress/releases/tag/v1.16.0) + * s2: Add [Dictionary](https://github.com/klauspost/compress/tree/master/s2#dictionaries) support. https://github.com/klauspost/compress/pull/685 + * s2: Add Compression Size Estimate. https://github.com/klauspost/compress/pull/752 + * s2: Add support for custom stream encoder. https://github.com/klauspost/compress/pull/755 + * s2: Add LZ4 block converter. https://github.com/klauspost/compress/pull/748 + * s2: Support io.ReaderAt in ReadSeeker. https://github.com/klauspost/compress/pull/747 + * s2c/s2sx: Use concurrent decoding. https://github.com/klauspost/compress/pull/746 + * Jan 21st, 2023 (v1.15.15) * deflate: Improve level 7-9 by @klauspost in https://github.com/klauspost/compress/pull/739 * zstd: Add delta encoding support by @greatroar in https://github.com/klauspost/compress/pull/728 diff --git a/vendor/github.com/klauspost/compress/fse/decompress.go b/vendor/github.com/klauspost/compress/fse/decompress.go index 926f5f153..cc05d0f7e 100644 --- a/vendor/github.com/klauspost/compress/fse/decompress.go +++ b/vendor/github.com/klauspost/compress/fse/decompress.go @@ -260,7 +260,9 @@ func (s *Scratch) buildDtable() error { // If the buffer is over-read an error is returned. func (s *Scratch) decompress() error { br := &s.bits - br.init(s.br.unread()) + if err := br.init(s.br.unread()); err != nil { + return err + } var s1, s2 decoder // Initialize and decode first state and symbol. diff --git a/vendor/github.com/klauspost/compress/huff0/bitwriter.go b/vendor/github.com/klauspost/compress/huff0/bitwriter.go index ec71f7a34..aed2347ce 100644 --- a/vendor/github.com/klauspost/compress/huff0/bitwriter.go +++ b/vendor/github.com/klauspost/compress/huff0/bitwriter.go @@ -60,6 +60,22 @@ func (b *bitWriter) encTwoSymbols(ct cTable, av, bv byte) { b.nBits += encA.nBits + encB.nBits } +// encFourSymbols adds up to 32 bits from four symbols. +// It will not check if there is space for them, +// so the caller must ensure that b has been flushed recently. +func (b *bitWriter) encFourSymbols(encA, encB, encC, encD cTableEntry) { + bitsA := encA.nBits + bitsB := bitsA + encB.nBits + bitsC := bitsB + encC.nBits + bitsD := bitsC + encD.nBits + combined := uint64(encA.val) | + (uint64(encB.val) << (bitsA & 63)) | + (uint64(encC.val) << (bitsB & 63)) | + (uint64(encD.val) << (bitsC & 63)) + b.bitContainer |= combined << (b.nBits & 63) + b.nBits += bitsD +} + // flush32 will flush out, so there are at least 32 bits available for writing. func (b *bitWriter) flush32() { if b.nBits < 32 { diff --git a/vendor/github.com/klauspost/compress/huff0/compress.go b/vendor/github.com/klauspost/compress/huff0/compress.go index cdc94856f..4ee4fa18d 100644 --- a/vendor/github.com/klauspost/compress/huff0/compress.go +++ b/vendor/github.com/klauspost/compress/huff0/compress.go @@ -248,8 +248,7 @@ func (s *Scratch) compress1xDo(dst, src []byte) ([]byte, error) { tmp := src[n : n+4] // tmp should be len 4 bw.flush32() - bw.encTwoSymbols(cTable, tmp[3], tmp[2]) - bw.encTwoSymbols(cTable, tmp[1], tmp[0]) + bw.encFourSymbols(cTable[tmp[3]], cTable[tmp[2]], cTable[tmp[1]], cTable[tmp[0]]) } } else { for ; n >= 0; n -= 4 { diff --git a/vendor/github.com/klauspost/compress/zstd/blockdec.go b/vendor/github.com/klauspost/compress/zstd/blockdec.go index 2445bb4fe..5f272d87f 100644 --- a/vendor/github.com/klauspost/compress/zstd/blockdec.go +++ b/vendor/github.com/klauspost/compress/zstd/blockdec.go @@ -9,6 +9,7 @@ import ( "encoding/binary" "errors" "fmt" + "hash/crc32" "io" "os" "path/filepath" @@ -442,6 +443,9 @@ func (b *blockDec) decodeLiterals(in []byte, hist *history) (remain []byte, err } } var err error + if debugDecoder { + println("huff table input:", len(literals), "CRC:", crc32.ChecksumIEEE(literals)) + } huff, literals, err = huff0.ReadTable(literals, huff) if err != nil { println("reading huffman table:", err) diff --git a/vendor/github.com/klauspost/compress/zstd/bytebuf.go b/vendor/github.com/klauspost/compress/zstd/bytebuf.go index 176788f25..512ffe5b9 100644 --- a/vendor/github.com/klauspost/compress/zstd/bytebuf.go +++ b/vendor/github.com/klauspost/compress/zstd/bytebuf.go @@ -54,7 +54,7 @@ func (b *byteBuf) readBig(n int, dst []byte) ([]byte, error) { func (b *byteBuf) readByte() (byte, error) { bb := *b if len(bb) < 1 { - return 0, nil + return 0, io.ErrUnexpectedEOF } r := bb[0] *b = bb[1:] diff --git a/vendor/github.com/klauspost/compress/zstd/enc_best.go b/vendor/github.com/klauspost/compress/zstd/enc_best.go index 830f5ba74..07f657d36 100644 --- a/vendor/github.com/klauspost/compress/zstd/enc_best.go +++ b/vendor/github.com/klauspost/compress/zstd/enc_best.go @@ -32,7 +32,6 @@ type match struct { length int32 rep int32 est int32 - _ [12]byte // Aligned size to cache line: 4+4+4+4+4 bytes + 12 bytes padding = 32 bytes } const highScore = 25000 @@ -189,12 +188,6 @@ encodeLoop: panic("offset0 was 0") } - bestOf := func(a, b *match) *match { - if a.est-b.est+(a.s-b.s)*bitsPerByte>>10 < 0 { - return a - } - return b - } const goodEnough = 100 nextHashL := hashLen(cv, bestLongTableBits, bestLongLen) @@ -202,40 +195,41 @@ encodeLoop: candidateL := e.longTable[nextHashL] candidateS := e.table[nextHashS] - matchAt := func(offset int32, s int32, first uint32, rep int32) match { + // Set m to a match at offset if it looks like that will improve compression. + improve := func(m *match, offset int32, s int32, first uint32, rep int32) { if s-offset >= e.maxMatchOff || load3232(src, offset) != first { - return match{s: s, est: highScore} + return } if debugAsserts { if !bytes.Equal(src[s:s+4], src[offset:offset+4]) { panic(fmt.Sprintf("first match mismatch: %v != %v, first: %08x", src[s:s+4], src[offset:offset+4], first)) } } - m := match{offset: offset, s: s, length: 4 + e.matchlen(s+4, offset+4, src), rep: rep} - m.estBits(bitsPerByte) - return m + cand := match{offset: offset, s: s, length: 4 + e.matchlen(s+4, offset+4, src), rep: rep} + cand.estBits(bitsPerByte) + if m.est >= highScore || cand.est-m.est+(cand.s-m.s)*bitsPerByte>>10 < 0 { + *m = cand + } } - m1 := matchAt(candidateL.offset-e.cur, s, uint32(cv), -1) - m2 := matchAt(candidateL.prev-e.cur, s, uint32(cv), -1) - m3 := matchAt(candidateS.offset-e.cur, s, uint32(cv), -1) - m4 := matchAt(candidateS.prev-e.cur, s, uint32(cv), -1) - best := bestOf(bestOf(&m1, &m2), bestOf(&m3, &m4)) + best := match{s: s, est: highScore} + improve(&best, candidateL.offset-e.cur, s, uint32(cv), -1) + improve(&best, candidateL.prev-e.cur, s, uint32(cv), -1) + improve(&best, candidateS.offset-e.cur, s, uint32(cv), -1) + improve(&best, candidateS.prev-e.cur, s, uint32(cv), -1) if canRepeat && best.length < goodEnough { cv32 := uint32(cv >> 8) spp := s + 1 - m1 := matchAt(spp-offset1, spp, cv32, 1) - m2 := matchAt(spp-offset2, spp, cv32, 2) - m3 := matchAt(spp-offset3, spp, cv32, 3) - best = bestOf(bestOf(best, &m1), bestOf(&m2, &m3)) + improve(&best, spp-offset1, spp, cv32, 1) + improve(&best, spp-offset2, spp, cv32, 2) + improve(&best, spp-offset3, spp, cv32, 3) if best.length > 0 { cv32 = uint32(cv >> 24) spp += 2 - m1 := matchAt(spp-offset1, spp, cv32, 1) - m2 := matchAt(spp-offset2, spp, cv32, 2) - m3 := matchAt(spp-offset3, spp, cv32, 3) - best = bestOf(bestOf(best, &m1), bestOf(&m2, &m3)) + improve(&best, spp-offset1, spp, cv32, 1) + improve(&best, spp-offset2, spp, cv32, 2) + improve(&best, spp-offset3, spp, cv32, 3) } } // Load next and check... @@ -262,18 +256,16 @@ encodeLoop: candidateL2 := e.longTable[hashLen(cv2, bestLongTableBits, bestLongLen)] // Short at s+1 - m1 := matchAt(candidateS.offset-e.cur, s, uint32(cv), -1) + improve(&best, candidateS.offset-e.cur, s, uint32(cv), -1) // Long at s+1, s+2 - m2 := matchAt(candidateL.offset-e.cur, s, uint32(cv), -1) - m3 := matchAt(candidateL.prev-e.cur, s, uint32(cv), -1) - m4 := matchAt(candidateL2.offset-e.cur, s+1, uint32(cv2), -1) - m5 := matchAt(candidateL2.prev-e.cur, s+1, uint32(cv2), -1) - best = bestOf(bestOf(bestOf(best, &m1), &m2), bestOf(bestOf(&m3, &m4), &m5)) + improve(&best, candidateL.offset-e.cur, s, uint32(cv), -1) + improve(&best, candidateL.prev-e.cur, s, uint32(cv), -1) + improve(&best, candidateL2.offset-e.cur, s+1, uint32(cv2), -1) + improve(&best, candidateL2.prev-e.cur, s+1, uint32(cv2), -1) if false { // Short at s+3. // Too often worse... - m := matchAt(e.table[hashLen(cv2>>8, bestShortTableBits, bestShortLen)].offset-e.cur, s+2, uint32(cv2>>8), -1) - best = bestOf(best, &m) + improve(&best, e.table[hashLen(cv2>>8, bestShortTableBits, bestShortLen)].offset-e.cur, s+2, uint32(cv2>>8), -1) } // See if we can find a better match by checking where the current best ends. // Use that offset to see if we can find a better full match. @@ -284,13 +276,10 @@ encodeLoop: // For this compression level 2 yields the best results. const skipBeginning = 2 if pos := candidateEnd.offset - e.cur - best.length + skipBeginning; pos >= 0 { - m := matchAt(pos, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) - bestEnd := bestOf(best, &m) + improve(&best, pos, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) if pos := candidateEnd.prev - e.cur - best.length + skipBeginning; pos >= 0 { - m := matchAt(pos, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) - bestEnd = bestOf(bestEnd, &m) + improve(&best, pos, best.s+skipBeginning, load3232(src, best.s+skipBeginning), -1) } - best = bestEnd } } } diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec.go b/vendor/github.com/klauspost/compress/zstd/seqdec.go index f833d1541..27fdf90fb 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec.go @@ -314,9 +314,6 @@ func (s *sequenceDecs) decodeSync(hist []byte) error { } size := ll + ml + len(out) if size-startSize > maxBlockSize { - if size-startSize == 424242 { - panic("here") - } return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) } if size > cap(out) { @@ -427,8 +424,7 @@ func (s *sequenceDecs) decodeSync(hist []byte) error { } } - // Check if space for literals - if size := len(s.literals) + len(s.out) - startSize; size > maxBlockSize { + if size := len(s.literals) + len(out) - startSize; size > maxBlockSize { return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) } diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go index 191384adf..387a30e99 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go @@ -148,7 +148,6 @@ func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { s.seqSize += ctx.litRemain if s.seqSize > maxBlockSize { return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize) - } err := br.close() if err != nil { diff --git a/vendor/github.com/muesli/reflow/truncate/truncate.go b/vendor/github.com/muesli/reflow/truncate/truncate.go index 2f20be965..5aab5f896 100644 --- a/vendor/github.com/muesli/reflow/truncate/truncate.go +++ b/vendor/github.com/muesli/reflow/truncate/truncate.go @@ -80,11 +80,11 @@ func (w *Writer) Write(b []byte) (int, error) { var curWidth uint for _, c := range string(b) { - if c == '\x1B' { + if c == ansi.Marker { // ANSI escape sequence w.ansi = true } else if w.ansi { - if (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) { + if ansi.IsTerminator(c) { // ANSI sequence terminated w.ansi = false } @@ -93,10 +93,11 @@ func (w *Writer) Write(b []byte) (int, error) { } if curWidth > w.width { + n, err := w.buf.WriteString(w.tail) if w.ansiWriter.LastSequence() != "" { w.ansiWriter.ResetAnsi() } - return w.buf.WriteString(w.tail) + return n, err } _, err := w.ansiWriter.Write([]byte(string(c))) diff --git a/vendor/github.com/muesli/termenv/README.md b/vendor/github.com/muesli/termenv/README.md index 90db262bf..29dcf0176 100644 --- a/vendor/github.com/muesli/termenv/README.md +++ b/vendor/github.com/muesli/termenv/README.md @@ -31,61 +31,70 @@ color conversions. go get github.com/muesli/termenv ``` -## Query Terminal Support - -`termenv` can query the terminal it is running in, so you can safely use -advanced features, like RGB colors. `ColorProfile` returns the color profile -supported by the terminal: +## Usage ```go -profile := termenv.ColorProfile() +output := termenv.NewOutput(os.Stdout) ``` -This returns one of the supported color profiles: +`termenv` queries the terminal's capabilities it is running in, so you can +safely use advanced features, like RGB colors or ANSI styles. `output.Profile` +returns the supported profile: - `termenv.Ascii` - no ANSI support detected, ASCII only - `termenv.ANSI` - 16 color ANSI support - `termenv.ANSI256` - Extended 256 color ANSI support - `termenv.TrueColor` - RGB/TrueColor support +Alternatively, you can use `termenv.EnvColorProfile` which evaluates the +terminal like `ColorProfile`, but also respects the `NO_COLOR` and +`CLICOLOR_FORCE` environment variables. + You can also query the terminal for its color scheme, so you know whether your app is running in a light- or dark-themed environment: ```go // Returns terminal's foreground color -color := termenv.ForegroundColor() +color := output.ForegroundColor() // Returns terminal's background color -color := termenv.BackgroundColor() +color := output.BackgroundColor() // Returns whether terminal uses a dark-ish background -darkTheme := termenv.HasDarkBackground() +darkTheme := output.HasDarkBackground() +``` + +### Manual Profile Selection + +If you don't want to rely on the automatic detection, you can manually select +the profile you want to use: + +```go +output := termenv.NewOutput(os.Stdout, termenv.WithProfile(termenv.TrueColor)) ``` ## Colors -`termenv` supports multiple color profiles: ANSI (16 colors), ANSI Extended -(256 colors), and TrueColor (24-bit RGB). Colors will automatically be degraded -to the best matching available color in the desired profile: +`termenv` supports multiple color profiles: Ascii (black & white only), +ANSI (16 colors), ANSI Extended (256 colors), and TrueColor (24-bit RGB). Colors +will automatically be degraded to the best matching available color in the +desired profile: `TrueColor` => `ANSI 256 Colors` => `ANSI 16 Colors` => `Ascii` ```go -s := termenv.String("Hello World") - -// Retrieve color profile supported by terminal -p := termenv.ColorProfile() +s := output.String("Hello World") // Supports hex values // Will automatically degrade colors on terminals not supporting RGB -s.Foreground(p.Color("#abcdef")) +s.Foreground(output.Color("#abcdef")) // but also supports ANSI colors (0-255) -s.Background(p.Color("69")) +s.Background(output.Color("69")) // ...or the color.Color interface -s.Foreground(p.FromColor(color.RGBA{255, 128, 0, 255})) +s.Foreground(output.FromColor(color.RGBA{255, 128, 0, 255})) // Combine fore- & background colors -s.Foreground(p.Color("#ffffff")).Background(p.Color("#0000ff")) +s.Foreground(output.Color("#ffffff")).Background(output.Color("#0000ff")) // Supports the fmt.Stringer interface fmt.Println(s) @@ -96,7 +105,7 @@ fmt.Println(s) You can use a chainable syntax to compose your own styles: ```go -s := termenv.String("foobar") +s := output.String("foobar") // Text styles s.Bold() @@ -118,9 +127,11 @@ s.Bold().Underline() ## Template Helpers +`termenv` provides a set of helper functions to style your Go templates: + ```go // load template helpers -f := termenv.TemplateFuncs(termenv.ColorProfile()) +f := output.TemplateFuncs() tpl := template.New("tpl").Funcs(f) // apply bold style in a template @@ -149,155 +160,150 @@ Other available helper functions are: `Faint`, `Italic`, `CrossOut`, ```go // Move the cursor to a given position -termenv.MoveCursor(row, column) +output.MoveCursor(row, column) // Save the cursor position -termenv.SaveCursorPosition() +output.SaveCursorPosition() // Restore a saved cursor position -termenv.RestoreCursorPosition() +output.RestoreCursorPosition() // Move the cursor up a given number of lines -termenv.CursorUp(n) +output.CursorUp(n) // Move the cursor down a given number of lines -termenv.CursorDown(n) +output.CursorDown(n) // Move the cursor up a given number of lines -termenv.CursorForward(n) +output.CursorForward(n) // Move the cursor backwards a given number of cells -termenv.CursorBack(n) +output.CursorBack(n) // Move the cursor down a given number of lines and place it at the beginning // of the line -termenv.CursorNextLine(n) +output.CursorNextLine(n) // Move the cursor up a given number of lines and place it at the beginning of // the line -termenv.CursorPrevLine(n) +output.CursorPrevLine(n) ``` ## Screen ```go // Reset the terminal to its default style, removing any active styles -termenv.Reset() +output.Reset() // RestoreScreen restores a previously saved screen state -termenv.RestoreScreen() +output.RestoreScreen() // SaveScreen saves the screen state -termenv.SaveScreen() +output.SaveScreen() // Switch to the altscreen. The former view can be restored with ExitAltScreen() -termenv.AltScreen() +output.AltScreen() // Exit the altscreen and return to the former terminal view -termenv.ExitAltScreen() +output.ExitAltScreen() // Clear the visible portion of the terminal -termenv.ClearScreen() +output.ClearScreen() // Clear the current line -termenv.ClearLine() +output.ClearLine() // Clear a given number of lines -termenv.ClearLines(n) +output.ClearLines(n) // Set the scrolling region of the terminal -termenv.ChangeScrollingRegion(top, bottom) +output.ChangeScrollingRegion(top, bottom) // Insert the given number of lines at the top of the scrollable region, pushing // lines below down -termenv.InsertLines(n) +output.InsertLines(n) // Delete the given number of lines, pulling any lines in the scrollable region // below up -termenv.DeleteLines(n) +output.DeleteLines(n) ``` ## Session ```go // SetWindowTitle sets the terminal window title -termenv.SetWindowTitle(title) +output.SetWindowTitle(title) // SetForegroundColor sets the default foreground color -termenv.SetForegroundColor(color) +output.SetForegroundColor(color) // SetBackgroundColor sets the default background color -termenv.SetBackgroundColor(color) +output.SetBackgroundColor(color) // SetCursorColor sets the cursor color -termenv.SetCursorColor(color) +output.SetCursorColor(color) // Hide the cursor -termenv.HideCursor() +output.HideCursor() // Show the cursor -termenv.ShowCursor() +output.ShowCursor() + +// Copy to clipboard +output.Copy(message) + +// Copy to primary clipboard (X11) +output.CopyPrimary(message) + +// Trigger notification +output.Notify(title, body) ``` ## Mouse ```go // Enable X10 mouse mode, only button press events are sent -termenv.EnableMousePress() +output.EnableMousePress() // Disable X10 mouse mode -termenv.DisableMousePress() +output.DisableMousePress() // Enable Mouse Tracking mode -termenv.EnableMouse() +output.EnableMouse() // Disable Mouse Tracking mode -termenv.DisableMouse() +output.DisableMouse() // Enable Hilite Mouse Tracking mode -termenv.EnableMouseHilite() +output.EnableMouseHilite() // Disable Hilite Mouse Tracking mode -termenv.DisableMouseHilite() +output.DisableMouseHilite() // Enable Cell Motion Mouse Tracking mode -termenv.EnableMouseCellMotion() +output.EnableMouseCellMotion() // Disable Cell Motion Mouse Tracking mode -termenv.DisableMouseCellMotion() +output.DisableMouseCellMotion() // Enable All Motion Mouse mode -termenv.EnableMouseAllMotion() +output.EnableMouseAllMotion() // Disable All Motion Mouse mode -termenv.DisableMouseAllMotion() +output.DisableMouseAllMotion() ``` -## Optional Feature Support - -| Terminal | Alt Screen | Query Color Scheme | Query Cursor Position | Set Window Title | Change Cursor Color | Change Default Foreground Setting | Change Default Background Setting | -| ---------------- | :--------: | :----------------: | :-------------------: | :--------------: | :-----------------: | :-------------------------------: | :-------------------------------: | -| alacritty | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| foot | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| kitty | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| Konsole | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | -| rxvt | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | -| screen | ✅ | ⛔[^mux] | ✅ | ✅ | ❌ | ❌ | ✅ | -| st | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| tmux | ✅ | ⛔[^mux] | ✅ | ✅ | ✅ | ✅ | ✅ | -| vte-based[^vte] | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | -| wezterm | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| xterm | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | -| Linux Console | ✅ | ❌ | ✅ | ⛔ | ❌ | ❌ | ❌ | -| Apple Terminal | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | -| iTerm | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | -| Windows cmd | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | -| Windows Terminal | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | +## Bracketed Paste -[^vte]: This covers all vte-based terminals, including Gnome Terminal, guake, Pantheon Terminal, Terminator, Tilix, XFCE Terminal. -[^mux]: Unavailable as multiplexers (like tmux or screen) can be connected to multiple terminals (with different color settings) at the same time. +```go +// Enables bracketed paste mode +termenv.EnableBracketedPaste() -You can help improve this list! Check out [how to](ansi_compat.md) and open an issue or pull request. +// Disables bracketed paste mode +termenv.DisableBracketedPaste() +``` + +## Terminal Feature Support ### Color Support @@ -305,6 +311,73 @@ You can help improve this list! Check out [how to](ansi_compat.md) and open an i - 8-bit (256): rxvt, screen, xterm, Apple Terminal - 4-bit (16): Linux Console +### Control Sequences + +
+Click to show feature matrix + +| Terminal | Query Color Scheme | Query Cursor Position | Set Window Title | Change Cursor Color | Change Default Foreground Setting | Change Default Background Setting | Bracketed Paste | Extended Mouse (SGR) | Pixels Mouse (SGR-Pixels) | +| ---------------- | :----------------: | :-------------------: | :--------------: | :-----------------: | :-------------------------------: | :-------------------------------: | :-------------: | :------------------: | :-----------------------: | +| alacritty | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | +| foot | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| kitty | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| Konsole | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | +| rxvt | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | +| urxvt | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | +| screen | ⛔[^mux] | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | +| st | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | +| tmux | ⛔[^mux] | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | +| vte-based[^vte] | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | +| wezterm | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| xterm | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | +| Linux Console | ❌ | ✅ | ⛔ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | +| Apple Terminal | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | +| iTerm | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | +| Windows cmd | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | +| Windows Terminal | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | + +[^vte]: This covers all vte-based terminals, including Gnome Terminal, guake, Pantheon Terminal, Terminator, Tilix, XFCE Terminal. +[^mux]: Unavailable as multiplexers (like tmux or screen) can be connected to multiple terminals (with different color settings) at the same time. + +You can help improve this list! Check out [how to](ansi_compat.md) and open an issue or pull request. + +
+ +### System Commands + +
+Click to show feature matrix + +| Terminal | Copy to Clipboard (OSC52) | Hyperlinks (OSC8) | Notifications (OSC777) | +| ---------------- | :-----------------------: | :---------------: | :--------------------: | +| alacritty | ✅ | ❌[^alacritty] | ❌ | +| foot | ✅ | ✅ | ✅ | +| kitty | ✅ | ✅ | ✅ | +| Konsole | ❌[^konsole] | ✅ | ❌ | +| rxvt | ❌ | ❌ | ❌ | +| urxvt | ✅[^urxvt] | ❌ | ✅ | +| screen | ✅ | ❌[^screen] | ❌ | +| st | ✅ | ❌ | ❌ | +| tmux | ✅ | ❌[^tmux] | ❌ | +| vte-based[^vte] | ❌[^vte] | ✅ | ❌ | +| wezterm | ✅ | ✅ | ❌ | +| xterm | ✅ | ❌ | ❌ | +| Linux Console | ⛔ | ⛔ | ❌ | +| Apple Terminal | ✅[^apple] | ❌ | ❌ | +| iTerm | ✅ | ✅ | ❌ | +| Windows cmd | ❌ | ❌ | ❌ | +| Windows Terminal | ✅ | ✅ | ❌ | + +[^vte]: This covers all vte-based terminals, including Gnome Terminal, guake, Pantheon Terminal, Terminator, Tilix, XFCE Terminal. OSC52 is not supported, see [issue#2495](https://gitlab.gnome.org/GNOME/vte/-/issues/2495). +[^urxvt]: Workaround for urxvt not supporting OSC52. See [this](https://unix.stackexchange.com/a/629485) for more information. +[^konsole]: OSC52 is not supported, for more info see [bug#372116](https://bugs.kde.org/show_bug.cgi?id=372116). +[^apple]: OSC52 works with a [workaround](https://github.com/roy2220/osc52pty). +[^tmux]: OSC8 is not supported, for more info see [issue#911](https://github.com/tmux/tmux/issues/911). +[^screen]: OSC8 is not supported, for more info see [bug#50952](https://savannah.gnu.org/bugs/index.php?50952). +[^alacritty]: OSC8 is not supported, for more info see [issue#922](https://github.com/alacritty/alacritty/issues/922). + +
+ ## Platform Support `termenv` works on Unix systems (like Linux, macOS, or BSD) and Windows. While @@ -312,13 +385,16 @@ terminal applications on Unix support ANSI styling out-of-the-box, on Windows you need to enable ANSI processing in your application first: ```go - mode, err := termenv.EnableWindowsANSIConsole() + restoreConsole, err := termenv.EnableVirtualTerminalProcessing(termenv.DefaultOutput()) if err != nil { panic(err) } - defer termenv.RestoreWindowsConsole(mode) + defer restoreConsole() ``` +The above code is safe to include on non-Windows systems or when os.Stdout does +not refer to a terminal (e.g. in tests). + ## Color Chart ![ANSI color chart](https://github.com/muesli/termenv/raw/master/examples/color-chart/color-chart.png) @@ -347,8 +423,8 @@ out these projects: Got some feedback or suggestions? Please open an issue or drop me a note! -* [Twitter](https://twitter.com/mueslix) -* [The Fediverse](https://mastodon.social/@fribbledom) +- [Twitter](https://twitter.com/mueslix) +- [The Fediverse](https://mastodon.social/@fribbledom) ## License diff --git a/vendor/github.com/muesli/termenv/ansi_compat.md b/vendor/github.com/muesli/termenv/ansi_compat.md index 67ef4e49c..6b68a3a9a 100644 --- a/vendor/github.com/muesli/termenv/ansi_compat.md +++ b/vendor/github.com/muesli/termenv/ansi_compat.md @@ -46,3 +46,20 @@ This command should set the window title to "Test": ```bash echo -ne "\033]2;Test\007" && sleep 10 ``` + +## Bracketed paste + +Enter this command, then paste a word from the clipboard. The text +displayed on the terminal should contain the codes `200~` and `201~`: + +```bash +echo -ne "\033[?2004h" && sleep 10 +``` + +## Trigger Notification + +This command should trigger a notification: + +```bash +echo -ne "\033]777;notify;Title;Body\033\\" +``` diff --git a/vendor/github.com/muesli/termenv/color.go b/vendor/github.com/muesli/termenv/color.go index 7cf7dae3f..0d11f436b 100644 --- a/vendor/github.com/muesli/termenv/color.go +++ b/vendor/github.com/muesli/termenv/color.go @@ -3,9 +3,7 @@ package termenv import ( "errors" "fmt" - "image/color" "math" - "strconv" "strings" "github.com/lucasb-eyer/go-colorful" @@ -69,72 +67,6 @@ func ConvertToRGB(c Color) colorful.Color { return ch } -// Convert transforms a given Color to a Color supported within the Profile. -func (p Profile) Convert(c Color) Color { - if p == Ascii { - return NoColor{} - } - - switch v := c.(type) { - case ANSIColor: - return v - - case ANSI256Color: - if p == ANSI { - return ansi256ToANSIColor(v) - } - return v - - case RGBColor: - h, err := colorful.Hex(string(v)) - if err != nil { - return nil - } - if p < TrueColor { - ac := hexToANSI256Color(h) - if p == ANSI { - return ansi256ToANSIColor(ac) - } - return ac - } - return v - } - - return c -} - -// Color creates a Color from a string. Valid inputs are hex colors, as well as -// ANSI color codes (0-15, 16-255). -func (p Profile) Color(s string) Color { - if len(s) == 0 { - return nil - } - - var c Color - if strings.HasPrefix(s, "#") { - c = RGBColor(s) - } else { - i, err := strconv.Atoi(s) - if err != nil { - return nil - } - - if i < 16 { - c = ANSIColor(i) - } else { - c = ANSI256Color(i) - } - } - - return p.Convert(c) -} - -// FromColor creates a Color from a color.Color. -func (p Profile) FromColor(c color.Color) Color { - col, _ := colorful.MakeColor(c) - return p.Color(col.Hex()) -} - // Sequence returns the ANSI Sequence for the color. func (c NoColor) Sequence(bg bool) string { return "" @@ -185,12 +117,12 @@ func xTermColor(s string) (RGBColor, error) { } switch { - case strings.HasSuffix(s, "\a"): - s = strings.TrimSuffix(s, "\a") - case strings.HasSuffix(s, "\033"): - s = strings.TrimSuffix(s, "\033") - case strings.HasSuffix(s, "\033\\"): - s = strings.TrimSuffix(s, "\033\\") + case strings.HasSuffix(s, string(BEL)): + s = strings.TrimSuffix(s, string(BEL)) + case strings.HasSuffix(s, string(ESC)): + s = strings.TrimSuffix(s, string(ESC)) + case strings.HasSuffix(s, ST): + s = strings.TrimSuffix(s, ST) default: return RGBColor(""), ErrInvalidColor } diff --git a/vendor/github.com/muesli/termenv/copy.go b/vendor/github.com/muesli/termenv/copy.go new file mode 100644 index 000000000..4bf5c9fea --- /dev/null +++ b/vendor/github.com/muesli/termenv/copy.go @@ -0,0 +1,37 @@ +package termenv + +import ( + "strings" + + "github.com/aymanbagabas/go-osc52/v2" +) + +// Copy copies text to clipboard using OSC 52 escape sequence. +func (o Output) Copy(str string) { + s := osc52.New(str) + if strings.HasPrefix(o.environ.Getenv("TERM"), "screen") { + s = s.Screen() + } + _, _ = s.WriteTo(o) +} + +// CopyPrimary copies text to primary clipboard (X11) using OSC 52 escape +// sequence. +func (o Output) CopyPrimary(str string) { + s := osc52.New(str).Primary() + if strings.HasPrefix(o.environ.Getenv("TERM"), "screen") { + s = s.Screen() + } + _, _ = s.WriteTo(o) +} + +// Copy copies text to clipboard using OSC 52 escape sequence. +func Copy(str string) { + output.Copy(str) +} + +// CopyPrimary copies text to primary clipboard (X11) using OSC 52 escape +// sequence. +func CopyPrimary(str string) { + output.CopyPrimary(str) +} diff --git a/vendor/github.com/muesli/termenv/hyperlink.go b/vendor/github.com/muesli/termenv/hyperlink.go new file mode 100644 index 000000000..97e760a3b --- /dev/null +++ b/vendor/github.com/muesli/termenv/hyperlink.go @@ -0,0 +1,11 @@ +package termenv + +// Hyperlink creates a hyperlink using OSC8. +func Hyperlink(link, name string) string { + return output.Hyperlink(link, name) +} + +// Hyperlink creates a hyperlink using OSC8. +func (o *Output) Hyperlink(link, name string) string { + return OSC + "8;;" + link + ST + name + OSC + "8;;" + ST +} diff --git a/vendor/github.com/muesli/termenv/notification.go b/vendor/github.com/muesli/termenv/notification.go new file mode 100644 index 000000000..2a8cf06a9 --- /dev/null +++ b/vendor/github.com/muesli/termenv/notification.go @@ -0,0 +1,11 @@ +package termenv + +// Notify triggers a notification using OSC777. +func Notify(title, body string) { + output.Notify(title, body) +} + +// Notify triggers a notification using OSC777. +func (o *Output) Notify(title, body string) { + _, _ = o.WriteString(OSC + "777;notify;" + title + ";" + body + ST) +} diff --git a/vendor/github.com/muesli/termenv/output.go b/vendor/github.com/muesli/termenv/output.go new file mode 100644 index 000000000..e22d369c9 --- /dev/null +++ b/vendor/github.com/muesli/termenv/output.go @@ -0,0 +1,197 @@ +package termenv + +import ( + "io" + "os" + "sync" +) + +var ( + // output is the default global output. + output = NewOutput(os.Stdout) +) + +// File represents a file descriptor. +type File interface { + io.ReadWriter + Fd() uintptr +} + +// OutputOption sets an option on Output. +type OutputOption = func(*Output) + +// Output is a terminal output. +type Output struct { + Profile + tty io.Writer + environ Environ + + assumeTTY bool + unsafe bool + cache bool + fgSync *sync.Once + fgColor Color + bgSync *sync.Once + bgColor Color +} + +// Environ is an interface for getting environment variables. +type Environ interface { + Environ() []string + Getenv(string) string +} + +type osEnviron struct{} + +func (oe *osEnviron) Environ() []string { + return os.Environ() +} + +func (oe *osEnviron) Getenv(key string) string { + return os.Getenv(key) +} + +// DefaultOutput returns the default global output. +func DefaultOutput() *Output { + return output +} + +// SetDefaultOutput sets the default global output. +func SetDefaultOutput(o *Output) { + output = o +} + +// NewOutput returns a new Output for the given file descriptor. +func NewOutput(tty io.Writer, opts ...OutputOption) *Output { + o := &Output{ + tty: tty, + environ: &osEnviron{}, + Profile: -1, + fgSync: &sync.Once{}, + fgColor: NoColor{}, + bgSync: &sync.Once{}, + bgColor: NoColor{}, + } + + if o.tty == nil { + o.tty = os.Stdout + } + for _, opt := range opts { + opt(o) + } + if o.Profile < 0 { + o.Profile = o.EnvColorProfile() + } + + return o +} + +// WithEnvironment returns a new OutputOption for the given environment. +func WithEnvironment(environ Environ) OutputOption { + return func(o *Output) { + o.environ = environ + } +} + +// WithProfile returns a new OutputOption for the given profile. +func WithProfile(profile Profile) OutputOption { + return func(o *Output) { + o.Profile = profile + } +} + +// WithColorCache returns a new OutputOption with fore- and background color values +// pre-fetched and cached. +func WithColorCache(v bool) OutputOption { + return func(o *Output) { + o.cache = v + + // cache the values now + _ = o.ForegroundColor() + _ = o.BackgroundColor() + } +} + +// WithTTY returns a new OutputOption to assume whether or not the output is a TTY. +// This is useful when mocking console output. +func WithTTY(v bool) OutputOption { + return func(o *Output) { + o.assumeTTY = v + } +} + +// WithUnsafe returns a new OutputOption with unsafe mode enabled. Unsafe mode doesn't +// check whether or not the terminal is a TTY. +// +// This option supersedes WithTTY. +// +// This is useful when mocking console output and enforcing ANSI escape output +// e.g. on SSH sessions. +func WithUnsafe() OutputOption { + return func(o *Output) { + o.unsafe = true + } +} + +// ForegroundColor returns the terminal's default foreground color. +func (o *Output) ForegroundColor() Color { + f := func() { + if !o.isTTY() { + return + } + + o.fgColor = o.foregroundColor() + } + + if o.cache { + o.fgSync.Do(f) + } else { + f() + } + + return o.fgColor +} + +// BackgroundColor returns the terminal's default background color. +func (o *Output) BackgroundColor() Color { + f := func() { + if !o.isTTY() { + return + } + + o.bgColor = o.backgroundColor() + } + + if o.cache { + o.bgSync.Do(f) + } else { + f() + } + + return o.bgColor +} + +// HasDarkBackground returns whether terminal uses a dark-ish background. +func (o *Output) HasDarkBackground() bool { + c := ConvertToRGB(o.BackgroundColor()) + _, _, l := c.Hsl() + return l < 0.5 +} + +// TTY returns the terminal's file descriptor. This may be nil if the output is +// not a terminal. +func (o Output) TTY() File { + if f, ok := o.tty.(File); ok { + return f + } + return nil +} + +func (o Output) Write(p []byte) (int, error) { + return o.tty.Write(p) +} + +// WriteString writes the given string to the output. +func (o Output) WriteString(s string) (int, error) { + return o.Write([]byte(s)) +} diff --git a/vendor/github.com/muesli/termenv/profile.go b/vendor/github.com/muesli/termenv/profile.go new file mode 100644 index 000000000..fa128e209 --- /dev/null +++ b/vendor/github.com/muesli/termenv/profile.go @@ -0,0 +1,97 @@ +package termenv + +import ( + "image/color" + "strconv" + "strings" + + "github.com/lucasb-eyer/go-colorful" +) + +// Profile is a color profile: Ascii, ANSI, ANSI256, or TrueColor. +type Profile int + +const ( + // TrueColor, 24-bit color profile + TrueColor = Profile(iota) + // ANSI256, 8-bit color profile + ANSI256 + // ANSI, 4-bit color profile + ANSI + // Ascii, uncolored profile + Ascii //nolint:revive +) + +// String returns a new Style. +func (p Profile) String(s ...string) Style { + return Style{ + profile: p, + string: strings.Join(s, " "), + } +} + +// Convert transforms a given Color to a Color supported within the Profile. +func (p Profile) Convert(c Color) Color { + if p == Ascii { + return NoColor{} + } + + switch v := c.(type) { + case ANSIColor: + return v + + case ANSI256Color: + if p == ANSI { + return ansi256ToANSIColor(v) + } + return v + + case RGBColor: + h, err := colorful.Hex(string(v)) + if err != nil { + return nil + } + if p != TrueColor { + ac := hexToANSI256Color(h) + if p == ANSI { + return ansi256ToANSIColor(ac) + } + return ac + } + return v + } + + return c +} + +// Color creates a Color from a string. Valid inputs are hex colors, as well as +// ANSI color codes (0-15, 16-255). +func (p Profile) Color(s string) Color { + if len(s) == 0 { + return nil + } + + var c Color + if strings.HasPrefix(s, "#") { + c = RGBColor(s) + } else { + i, err := strconv.Atoi(s) + if err != nil { + return nil + } + + if i < 16 { + c = ANSIColor(i) + } else { + c = ANSI256Color(i) + } + } + + return p.Convert(c) +} + +// FromColor creates a Color from a color.Color. +func (p Profile) FromColor(c color.Color) Color { + col, _ := colorful.MakeColor(c) + return p.Color(col.Hex()) +} diff --git a/vendor/github.com/muesli/termenv/screen.go b/vendor/github.com/muesli/termenv/screen.go index c62b6d750..a71181b61 100644 --- a/vendor/github.com/muesli/termenv/screen.go +++ b/vendor/github.com/muesli/termenv/screen.go @@ -32,16 +32,20 @@ const ( EraseEntireLineSeq = "2K" // Mouse. - EnableMousePressSeq = "?9h" // press only (X10) - DisableMousePressSeq = "?9l" - EnableMouseSeq = "?1000h" // press, release, wheel - DisableMouseSeq = "?1000l" - EnableMouseHiliteSeq = "?1001h" // highlight - DisableMouseHiliteSeq = "?1001l" - EnableMouseCellMotionSeq = "?1002h" // press, release, move on pressed, wheel - DisableMouseCellMotionSeq = "?1002l" - EnableMouseAllMotionSeq = "?1003h" // press, release, move, wheel - DisableMouseAllMotionSeq = "?1003l" + EnableMousePressSeq = "?9h" // press only (X10) + DisableMousePressSeq = "?9l" + EnableMouseSeq = "?1000h" // press, release, wheel + DisableMouseSeq = "?1000l" + EnableMouseHiliteSeq = "?1001h" // highlight + DisableMouseHiliteSeq = "?1001l" + EnableMouseCellMotionSeq = "?1002h" // press, release, move on pressed, wheel + DisableMouseCellMotionSeq = "?1002l" + EnableMouseAllMotionSeq = "?1003h" // press, release, move, wheel + DisableMouseAllMotionSeq = "?1003l" + EnableMouseExtendedModeSeq = "?1006h" // press, release, move, wheel, extended coordinates + DisableMouseExtendedModeSeq = "?1006l" + EnableMousePixelsModeSeq = "?1016h" // press, release, move, wheel, extended pixel coordinates + DisableMousePixelsModeSeq = "?1016l" // Screen. RestoreScreenSeq = "?47l" @@ -49,210 +53,538 @@ const ( AltScreenSeq = "?1049h" ExitAltScreenSeq = "?1049l" + // Bracketed paste. + // https://en.wikipedia.org/wiki/Bracketed-paste + EnableBracketedPasteSeq = "?2004h" + DisableBracketedPasteSeq = "?2004l" + StartBracketedPasteSeq = "200~" + EndBracketedPasteSeq = "201~" + // Session. - SetWindowTitleSeq = "2;%s\007" - SetForegroundColorSeq = "10;%s\007" - SetBackgroundColorSeq = "11;%s\007" - SetCursorColorSeq = "12;%s\007" + SetWindowTitleSeq = "2;%s" + string(BEL) + SetForegroundColorSeq = "10;%s" + string(BEL) + SetBackgroundColorSeq = "11;%s" + string(BEL) + SetCursorColorSeq = "12;%s" + string(BEL) ShowCursorSeq = "?25h" HideCursorSeq = "?25l" ) // Reset the terminal to its default style, removing any active styles. +func (o Output) Reset() { + fmt.Fprint(o.tty, CSI+ResetSeq+"m") +} + +// SetForegroundColor sets the default foreground color. +func (o Output) SetForegroundColor(color Color) { + fmt.Fprintf(o.tty, OSC+SetForegroundColorSeq, color) +} + +// SetBackgroundColor sets the default background color. +func (o Output) SetBackgroundColor(color Color) { + fmt.Fprintf(o.tty, OSC+SetBackgroundColorSeq, color) +} + +// SetCursorColor sets the cursor color. +func (o Output) SetCursorColor(color Color) { + fmt.Fprintf(o.tty, OSC+SetCursorColorSeq, color) +} + +// RestoreScreen restores a previously saved screen state. +func (o Output) RestoreScreen() { + fmt.Fprint(o.tty, CSI+RestoreScreenSeq) +} + +// SaveScreen saves the screen state. +func (o Output) SaveScreen() { + fmt.Fprint(o.tty, CSI+SaveScreenSeq) +} + +// AltScreen switches to the alternate screen buffer. The former view can be +// restored with ExitAltScreen(). +func (o Output) AltScreen() { + fmt.Fprint(o.tty, CSI+AltScreenSeq) +} + +// ExitAltScreen exits the alternate screen buffer and returns to the former +// terminal view. +func (o Output) ExitAltScreen() { + fmt.Fprint(o.tty, CSI+ExitAltScreenSeq) +} + +// ClearScreen clears the visible portion of the terminal. +func (o Output) ClearScreen() { + fmt.Fprintf(o.tty, CSI+EraseDisplaySeq, 2) + o.MoveCursor(1, 1) +} + +// MoveCursor moves the cursor to a given position. +func (o Output) MoveCursor(row int, column int) { + fmt.Fprintf(o.tty, CSI+CursorPositionSeq, row, column) +} + +// HideCursor hides the cursor. +func (o Output) HideCursor() { + fmt.Fprint(o.tty, CSI+HideCursorSeq) +} + +// ShowCursor shows the cursor. +func (o Output) ShowCursor() { + fmt.Fprint(o.tty, CSI+ShowCursorSeq) +} + +// SaveCursorPosition saves the cursor position. +func (o Output) SaveCursorPosition() { + fmt.Fprint(o.tty, CSI+SaveCursorPositionSeq) +} + +// RestoreCursorPosition restores a saved cursor position. +func (o Output) RestoreCursorPosition() { + fmt.Fprint(o.tty, CSI+RestoreCursorPositionSeq) +} + +// CursorUp moves the cursor up a given number of lines. +func (o Output) CursorUp(n int) { + fmt.Fprintf(o.tty, CSI+CursorUpSeq, n) +} + +// CursorDown moves the cursor down a given number of lines. +func (o Output) CursorDown(n int) { + fmt.Fprintf(o.tty, CSI+CursorDownSeq, n) +} + +// CursorForward moves the cursor up a given number of lines. +func (o Output) CursorForward(n int) { + fmt.Fprintf(o.tty, CSI+CursorForwardSeq, n) +} + +// CursorBack moves the cursor backwards a given number of cells. +func (o Output) CursorBack(n int) { + fmt.Fprintf(o.tty, CSI+CursorBackSeq, n) +} + +// CursorNextLine moves the cursor down a given number of lines and places it at +// the beginning of the line. +func (o Output) CursorNextLine(n int) { + fmt.Fprintf(o.tty, CSI+CursorNextLineSeq, n) +} + +// CursorPrevLine moves the cursor up a given number of lines and places it at +// the beginning of the line. +func (o Output) CursorPrevLine(n int) { + fmt.Fprintf(o.tty, CSI+CursorPreviousLineSeq, n) +} + +// ClearLine clears the current line. +func (o Output) ClearLine() { + fmt.Fprint(o.tty, CSI+EraseEntireLineSeq) +} + +// ClearLineLeft clears the line to the left of the cursor. +func (o Output) ClearLineLeft() { + fmt.Fprint(o.tty, CSI+EraseLineLeftSeq) +} + +// ClearLineRight clears the line to the right of the cursor. +func (o Output) ClearLineRight() { + fmt.Fprint(o.tty, CSI+EraseLineRightSeq) +} + +// ClearLines clears a given number of lines. +func (o Output) ClearLines(n int) { + clearLine := fmt.Sprintf(CSI+EraseLineSeq, 2) + cursorUp := fmt.Sprintf(CSI+CursorUpSeq, 1) + fmt.Fprint(o.tty, clearLine+strings.Repeat(cursorUp+clearLine, n)) +} + +// ChangeScrollingRegion sets the scrolling region of the terminal. +func (o Output) ChangeScrollingRegion(top, bottom int) { + fmt.Fprintf(o.tty, CSI+ChangeScrollingRegionSeq, top, bottom) +} + +// InsertLines inserts the given number of lines at the top of the scrollable +// region, pushing lines below down. +func (o Output) InsertLines(n int) { + fmt.Fprintf(o.tty, CSI+InsertLineSeq, n) +} + +// DeleteLines deletes the given number of lines, pulling any lines in +// the scrollable region below up. +func (o Output) DeleteLines(n int) { + fmt.Fprintf(o.tty, CSI+DeleteLineSeq, n) +} + +// EnableMousePress enables X10 mouse mode. Button press events are sent only. +func (o Output) EnableMousePress() { + fmt.Fprint(o.tty, CSI+EnableMousePressSeq) +} + +// DisableMousePress disables X10 mouse mode. +func (o Output) DisableMousePress() { + fmt.Fprint(o.tty, CSI+DisableMousePressSeq) +} + +// EnableMouse enables Mouse Tracking mode. +func (o Output) EnableMouse() { + fmt.Fprint(o.tty, CSI+EnableMouseSeq) +} + +// DisableMouse disables Mouse Tracking mode. +func (o Output) DisableMouse() { + fmt.Fprint(o.tty, CSI+DisableMouseSeq) +} + +// EnableMouseHilite enables Hilite Mouse Tracking mode. +func (o Output) EnableMouseHilite() { + fmt.Fprint(o.tty, CSI+EnableMouseHiliteSeq) +} + +// DisableMouseHilite disables Hilite Mouse Tracking mode. +func (o Output) DisableMouseHilite() { + fmt.Fprint(o.tty, CSI+DisableMouseHiliteSeq) +} + +// EnableMouseCellMotion enables Cell Motion Mouse Tracking mode. +func (o Output) EnableMouseCellMotion() { + fmt.Fprint(o.tty, CSI+EnableMouseCellMotionSeq) +} + +// DisableMouseCellMotion disables Cell Motion Mouse Tracking mode. +func (o Output) DisableMouseCellMotion() { + fmt.Fprint(o.tty, CSI+DisableMouseCellMotionSeq) +} + +// EnableMouseAllMotion enables All Motion Mouse mode. +func (o Output) EnableMouseAllMotion() { + fmt.Fprint(o.tty, CSI+EnableMouseAllMotionSeq) +} + +// DisableMouseAllMotion disables All Motion Mouse mode. +func (o Output) DisableMouseAllMotion() { + fmt.Fprint(o.tty, CSI+DisableMouseAllMotionSeq) +} + +// EnableMouseExtendedMotion enables Extended Mouse mode (SGR). This should be +// enabled in conjunction with EnableMouseCellMotion, and EnableMouseAllMotion. +func (o Output) EnableMouseExtendedMode() { + fmt.Fprint(o.tty, CSI+EnableMouseExtendedModeSeq) +} + +// DisableMouseExtendedMotion disables Extended Mouse mode (SGR). +func (o Output) DisableMouseExtendedMode() { + fmt.Fprint(o.tty, CSI+DisableMouseExtendedModeSeq) +} + +// EnableMousePixelsMotion enables Pixel Motion Mouse mode (SGR-Pixels). This +// should be enabled in conjunction with EnableMouseCellMotion, and +// EnableMouseAllMotion. +func (o Output) EnableMousePixelsMode() { + fmt.Fprint(o.tty, CSI+EnableMousePixelsModeSeq) +} + +// DisableMousePixelsMotion disables Pixel Motion Mouse mode (SGR-Pixels). +func (o Output) DisableMousePixelsMode() { + fmt.Fprint(o.tty, CSI+DisableMousePixelsModeSeq) +} + +// SetWindowTitle sets the terminal window title. +func (o Output) SetWindowTitle(title string) { + fmt.Fprintf(o.tty, OSC+SetWindowTitleSeq, title) +} + +// EnableBracketedPaste enables bracketed paste. +func (o Output) EnableBracketedPaste() { + fmt.Fprintf(o.tty, CSI+EnableBracketedPasteSeq) +} + +// DisableBracketedPaste disables bracketed paste. +func (o Output) DisableBracketedPaste() { + fmt.Fprintf(o.tty, CSI+DisableBracketedPasteSeq) +} + +// Legacy functions. + +// Reset the terminal to its default style, removing any active styles. +// +// Deprecated: please use termenv.Output instead. func Reset() { - fmt.Print(CSI + ResetSeq + "m") + output.Reset() } // SetForegroundColor sets the default foreground color. +// +// Deprecated: please use termenv.Output instead. func SetForegroundColor(color Color) { - fmt.Printf(OSC+SetForegroundColorSeq, color) + output.SetForegroundColor(color) } // SetBackgroundColor sets the default background color. +// +// Deprecated: please use termenv.Output instead. func SetBackgroundColor(color Color) { - fmt.Printf(OSC+SetBackgroundColorSeq, color) + output.SetBackgroundColor(color) } // SetCursorColor sets the cursor color. +// +// Deprecated: please use termenv.Output instead. func SetCursorColor(color Color) { - fmt.Printf(OSC+SetCursorColorSeq, color) + output.SetCursorColor(color) } // RestoreScreen restores a previously saved screen state. +// +// Deprecated: please use termenv.Output instead. func RestoreScreen() { - fmt.Print(CSI + RestoreScreenSeq) + output.RestoreScreen() } // SaveScreen saves the screen state. +// +// Deprecated: please use termenv.Output instead. func SaveScreen() { - fmt.Print(CSI + SaveScreenSeq) + output.SaveScreen() } // AltScreen switches to the alternate screen buffer. The former view can be // restored with ExitAltScreen(). +// +// Deprecated: please use termenv.Output instead. func AltScreen() { - fmt.Print(CSI + AltScreenSeq) + output.AltScreen() } // ExitAltScreen exits the alternate screen buffer and returns to the former // terminal view. +// +// Deprecated: please use termenv.Output instead. func ExitAltScreen() { - fmt.Print(CSI + ExitAltScreenSeq) + output.ExitAltScreen() } // ClearScreen clears the visible portion of the terminal. +// +// Deprecated: please use termenv.Output instead. func ClearScreen() { - fmt.Printf(CSI+EraseDisplaySeq, 2) - MoveCursor(1, 1) + output.ClearScreen() } // MoveCursor moves the cursor to a given position. +// +// Deprecated: please use termenv.Output instead. func MoveCursor(row int, column int) { - fmt.Printf(CSI+CursorPositionSeq, row, column) + output.MoveCursor(row, column) } // HideCursor hides the cursor. +// +// Deprecated: please use termenv.Output instead. func HideCursor() { - fmt.Printf(CSI + HideCursorSeq) + output.HideCursor() } // ShowCursor shows the cursor. +// +// Deprecated: please use termenv.Output instead. func ShowCursor() { - fmt.Printf(CSI + ShowCursorSeq) + output.ShowCursor() } // SaveCursorPosition saves the cursor position. +// +// Deprecated: please use termenv.Output instead. func SaveCursorPosition() { - fmt.Print(CSI + SaveCursorPositionSeq) + output.SaveCursorPosition() } // RestoreCursorPosition restores a saved cursor position. +// +// Deprecated: please use termenv.Output instead. func RestoreCursorPosition() { - fmt.Print(CSI + RestoreCursorPositionSeq) + output.RestoreCursorPosition() } // CursorUp moves the cursor up a given number of lines. +// +// Deprecated: please use termenv.Output instead. func CursorUp(n int) { - fmt.Printf(CSI+CursorUpSeq, n) + output.CursorUp(n) } // CursorDown moves the cursor down a given number of lines. +// +// Deprecated: please use termenv.Output instead. func CursorDown(n int) { - fmt.Printf(CSI+CursorDownSeq, n) + output.CursorDown(n) } // CursorForward moves the cursor up a given number of lines. +// +// Deprecated: please use termenv.Output instead. func CursorForward(n int) { - fmt.Printf(CSI+CursorForwardSeq, n) + output.CursorForward(n) } // CursorBack moves the cursor backwards a given number of cells. +// +// Deprecated: please use termenv.Output instead. func CursorBack(n int) { - fmt.Printf(CSI+CursorBackSeq, n) + output.CursorBack(n) } // CursorNextLine moves the cursor down a given number of lines and places it at // the beginning of the line. +// +// Deprecated: please use termenv.Output instead. func CursorNextLine(n int) { - fmt.Printf(CSI+CursorNextLineSeq, n) + output.CursorNextLine(n) } // CursorPrevLine moves the cursor up a given number of lines and places it at // the beginning of the line. +// +// Deprecated: please use termenv.Output instead. func CursorPrevLine(n int) { - fmt.Printf(CSI+CursorPreviousLineSeq, n) + output.CursorPrevLine(n) } // ClearLine clears the current line. +// +// Deprecated: please use termenv.Output instead. func ClearLine() { - fmt.Print(CSI + EraseEntireLineSeq) + output.ClearLine() } // ClearLineLeft clears the line to the left of the cursor. +// +// Deprecated: please use termenv.Output instead. func ClearLineLeft() { - fmt.Print(CSI + EraseLineLeftSeq) + output.ClearLineLeft() } // ClearLineRight clears the line to the right of the cursor. +// +// Deprecated: please use termenv.Output instead. func ClearLineRight() { - fmt.Print(CSI + EraseLineRightSeq) + output.ClearLineRight() } // ClearLines clears a given number of lines. +// +// Deprecated: please use termenv.Output instead. func ClearLines(n int) { - clearLine := fmt.Sprintf(CSI+EraseLineSeq, 2) - cursorUp := fmt.Sprintf(CSI+CursorUpSeq, 1) - fmt.Print(clearLine + strings.Repeat(cursorUp+clearLine, n)) + output.ClearLines(n) } // ChangeScrollingRegion sets the scrolling region of the terminal. +// +// Deprecated: please use termenv.Output instead. func ChangeScrollingRegion(top, bottom int) { - fmt.Printf(CSI+ChangeScrollingRegionSeq, top, bottom) + output.ChangeScrollingRegion(top, bottom) } // InsertLines inserts the given number of lines at the top of the scrollable // region, pushing lines below down. +// +// Deprecated: please use termenv.Output instead. func InsertLines(n int) { - fmt.Printf(CSI+InsertLineSeq, n) + output.InsertLines(n) } // DeleteLines deletes the given number of lines, pulling any lines in // the scrollable region below up. +// +// Deprecated: please use termenv.Output instead. func DeleteLines(n int) { - fmt.Printf(CSI+DeleteLineSeq, n) + output.DeleteLines(n) } // EnableMousePress enables X10 mouse mode. Button press events are sent only. +// +// Deprecated: please use termenv.Output instead. func EnableMousePress() { - fmt.Print(CSI + EnableMousePressSeq) + output.EnableMousePress() } // DisableMousePress disables X10 mouse mode. +// +// Deprecated: please use termenv.Output instead. func DisableMousePress() { - fmt.Print(CSI + EnableMousePressSeq) + output.DisableMousePress() } // EnableMouse enables Mouse Tracking mode. +// +// Deprecated: please use termenv.Output instead. func EnableMouse() { - fmt.Print(CSI + EnableMouseSeq) + output.EnableMouse() } // DisableMouse disables Mouse Tracking mode. +// +// Deprecated: please use termenv.Output instead. func DisableMouse() { - fmt.Print(CSI + DisableMouseSeq) + output.DisableMouse() } // EnableMouseHilite enables Hilite Mouse Tracking mode. +// +// Deprecated: please use termenv.Output instead. func EnableMouseHilite() { - fmt.Print(CSI + EnableMouseHiliteSeq) + output.EnableMouseHilite() } // DisableMouseHilite disables Hilite Mouse Tracking mode. +// +// Deprecated: please use termenv.Output instead. func DisableMouseHilite() { - fmt.Print(CSI + DisableMouseHiliteSeq) + output.DisableMouseHilite() } // EnableMouseCellMotion enables Cell Motion Mouse Tracking mode. +// +// Deprecated: please use termenv.Output instead. func EnableMouseCellMotion() { - fmt.Print(CSI + EnableMouseCellMotionSeq) + output.EnableMouseCellMotion() } // DisableMouseCellMotion disables Cell Motion Mouse Tracking mode. +// +// Deprecated: please use termenv.Output instead. func DisableMouseCellMotion() { - fmt.Print(CSI + DisableMouseCellMotionSeq) + output.DisableMouseCellMotion() } // EnableMouseAllMotion enables All Motion Mouse mode. +// +// Deprecated: please use termenv.Output instead. func EnableMouseAllMotion() { - fmt.Print(CSI + EnableMouseAllMotionSeq) + output.EnableMouseAllMotion() } // DisableMouseAllMotion disables All Motion Mouse mode. +// +// Deprecated: please use termenv.Output instead. func DisableMouseAllMotion() { - fmt.Print(CSI + DisableMouseAllMotionSeq) + output.DisableMouseAllMotion() } // SetWindowTitle sets the terminal window title. +// +// Deprecated: please use termenv.Output instead. func SetWindowTitle(title string) { - fmt.Printf(OSC+SetWindowTitleSeq, title) + output.SetWindowTitle(title) +} + +// EnableBracketedPaste enables bracketed paste. +// +// Deprecated: please use termenv.Output instead. +func EnableBracketedPaste() { + output.EnableBracketedPaste() +} + +// DisableBracketedPaste disables bracketed paste. +// +// Deprecated: please use termenv.Output instead. +func DisableBracketedPaste() { + output.DisableBracketedPaste() } diff --git a/vendor/github.com/muesli/termenv/style.go b/vendor/github.com/muesli/termenv/style.go index 577aa29e3..83b0b4d7a 100644 --- a/vendor/github.com/muesli/termenv/style.go +++ b/vendor/github.com/muesli/termenv/style.go @@ -22,6 +22,7 @@ const ( // Style is a string that various rendering styles can be applied to. type Style struct { + profile Profile string styles []string } @@ -29,7 +30,8 @@ type Style struct { // String returns a new Style. func String(s ...string) Style { return Style{ - string: strings.Join(s, " "), + profile: ANSI, + string: strings.Join(s, " "), } } @@ -39,6 +41,9 @@ func (t Style) String() string { // Styled renders s with all applied styles. func (t Style) Styled(s string) string { + if t.profile == Ascii { + return s + } if len(t.styles) == 0 { return s } diff --git a/vendor/github.com/muesli/termenv/templatehelper.go b/vendor/github.com/muesli/termenv/templatehelper.go index 4c716e2ea..d75b0796c 100644 --- a/vendor/github.com/muesli/termenv/templatehelper.go +++ b/vendor/github.com/muesli/termenv/templatehelper.go @@ -4,11 +4,20 @@ import ( "text/template" ) +// TemplateFuncs returns template helpers for the given output. +func (o Output) TemplateFuncs() template.FuncMap { + return TemplateFuncs(o.Profile) +} + // TemplateFuncs contains a few useful template helpers. func TemplateFuncs(p Profile) template.FuncMap { + if p == Ascii { + return noopTemplateFuncs + } + return template.FuncMap{ "Color": func(values ...interface{}) string { - s := String(values[len(values)-1].(string)) + s := p.String(values[len(values)-1].(string)) switch len(values) { case 2: s = s.Foreground(p.Color(values[0].(string))) @@ -21,7 +30,7 @@ func TemplateFuncs(p Profile) template.FuncMap { return s.String() }, "Foreground": func(values ...interface{}) string { - s := String(values[len(values)-1].(string)) + s := p.String(values[len(values)-1].(string)) if len(values) == 2 { s = s.Foreground(p.Color(values[0].(string))) } @@ -29,27 +38,49 @@ func TemplateFuncs(p Profile) template.FuncMap { return s.String() }, "Background": func(values ...interface{}) string { - s := String(values[len(values)-1].(string)) + s := p.String(values[len(values)-1].(string)) if len(values) == 2 { s = s.Background(p.Color(values[0].(string))) } return s.String() }, - "Bold": styleFunc(Style.Bold), - "Faint": styleFunc(Style.Faint), - "Italic": styleFunc(Style.Italic), - "Underline": styleFunc(Style.Underline), - "Overline": styleFunc(Style.Overline), - "Blink": styleFunc(Style.Blink), - "Reverse": styleFunc(Style.Reverse), - "CrossOut": styleFunc(Style.CrossOut), + "Bold": styleFunc(p, Style.Bold), + "Faint": styleFunc(p, Style.Faint), + "Italic": styleFunc(p, Style.Italic), + "Underline": styleFunc(p, Style.Underline), + "Overline": styleFunc(p, Style.Overline), + "Blink": styleFunc(p, Style.Blink), + "Reverse": styleFunc(p, Style.Reverse), + "CrossOut": styleFunc(p, Style.CrossOut), } } -func styleFunc(f func(Style) Style) func(...interface{}) string { +func styleFunc(p Profile, f func(Style) Style) func(...interface{}) string { return func(values ...interface{}) string { - s := String(values[0].(string)) + s := p.String(values[0].(string)) return f(s).String() } } + +var noopTemplateFuncs = template.FuncMap{ + "Color": noColorFunc, + "Foreground": noColorFunc, + "Background": noColorFunc, + "Bold": noStyleFunc, + "Faint": noStyleFunc, + "Italic": noStyleFunc, + "Underline": noStyleFunc, + "Overline": noStyleFunc, + "Blink": noStyleFunc, + "Reverse": noStyleFunc, + "CrossOut": noStyleFunc, +} + +func noColorFunc(values ...interface{}) string { + return values[len(values)-1].(string) +} + +func noStyleFunc(values ...interface{}) string { + return values[0].(string) +} diff --git a/vendor/github.com/muesli/termenv/termenv.go b/vendor/github.com/muesli/termenv/termenv.go index 9161d9920..4ceb27177 100644 --- a/vendor/github.com/muesli/termenv/termenv.go +++ b/vendor/github.com/muesli/termenv/termenv.go @@ -2,7 +2,6 @@ package termenv import ( "errors" - "os" "github.com/mattn/go-isatty" ) @@ -12,66 +11,61 @@ var ( ErrStatusReport = errors.New("unable to retrieve status report") ) -// Profile is a color profile: Ascii, ANSI, ANSI256, or TrueColor. -type Profile int - const ( + // Escape character + ESC = '\x1b' + // Bell + BEL = '\a' // Control Sequence Introducer - CSI = "\x1b[" + CSI = string(ESC) + "[" // Operating System Command - OSC = "\x1b]" - - // Ascii, uncolored profile. - Ascii = Profile(iota) //nolint:revive - // ANSI, 4-bit color profile - ANSI - // ANSI256, 8-bit color profile - ANSI256 - // TrueColor, 24-bit color profile - TrueColor + OSC = string(ESC) + "]" + // String Terminator + ST = string(ESC) + `\` ) -func isTTY(fd uintptr) bool { - if len(os.Getenv("CI")) > 0 { +func (o *Output) isTTY() bool { + if o.assumeTTY || o.unsafe { + return true + } + if len(o.environ.Getenv("CI")) > 0 { + return false + } + if o.TTY() == nil { return false } - return isatty.IsTerminal(fd) + return isatty.IsTerminal(o.TTY().Fd()) } // ColorProfile returns the supported color profile: // Ascii, ANSI, ANSI256, or TrueColor. func ColorProfile() Profile { - if !isTTY(os.Stdout.Fd()) { - return Ascii - } - - return colorProfile() + return output.ColorProfile() } // ForegroundColor returns the terminal's default foreground color. func ForegroundColor() Color { - if !isTTY(os.Stdout.Fd()) { - return NoColor{} - } - - return foregroundColor() + return output.ForegroundColor() } // BackgroundColor returns the terminal's default background color. func BackgroundColor() Color { - if !isTTY(os.Stdout.Fd()) { - return NoColor{} - } - - return backgroundColor() + return output.BackgroundColor() } // HasDarkBackground returns whether terminal uses a dark-ish background. func HasDarkBackground() bool { - c := ConvertToRGB(BackgroundColor()) - _, _, l := c.Hsl() - return l < 0.5 + return output.HasDarkBackground() +} + +// EnvNoColor returns true if the environment variables explicitly disable color output +// by setting NO_COLOR (https://no-color.org/) +// or CLICOLOR/CLICOLOR_FORCE (https://bixense.com/clicolors/) +// If NO_COLOR is set, this will return true, ignoring CLICOLOR/CLICOLOR_FORCE +// If CLICOLOR=="0", it will be true only if CLICOLOR_FORCE is also "0" or is unset. +func (o *Output) EnvNoColor() bool { + return o.environ.Getenv("NO_COLOR") != "" || (o.environ.Getenv("CLICOLOR") == "0" && !o.cliColorForced()) } // EnvNoColor returns true if the environment variables explicitly disable color output @@ -80,7 +74,7 @@ func HasDarkBackground() bool { // If NO_COLOR is set, this will return true, ignoring CLICOLOR/CLICOLOR_FORCE // If CLICOLOR=="0", it will be true only if CLICOLOR_FORCE is also "0" or is unset. func EnvNoColor() bool { - return os.Getenv("NO_COLOR") != "" || (os.Getenv("CLICOLOR") == "0" && !cliColorForced()) + return output.EnvNoColor() } // EnvColorProfile returns the color profile based on environment variables set @@ -91,18 +85,29 @@ func EnvNoColor() bool { // If the terminal does not support any colors, but CLICOLOR_FORCE is set and not "0" // then the ANSI color profile will be returned. func EnvColorProfile() Profile { - if EnvNoColor() { + return output.EnvColorProfile() +} + +// EnvColorProfile returns the color profile based on environment variables set +// Supports NO_COLOR (https://no-color.org/) +// and CLICOLOR/CLICOLOR_FORCE (https://bixense.com/clicolors/) +// If none of these environment variables are set, this behaves the same as ColorProfile() +// It will return the Ascii color profile if EnvNoColor() returns true +// If the terminal does not support any colors, but CLICOLOR_FORCE is set and not "0" +// then the ANSI color profile will be returned. +func (o *Output) EnvColorProfile() Profile { + if o.EnvNoColor() { return Ascii } - p := ColorProfile() - if cliColorForced() && p == Ascii { + p := o.ColorProfile() + if o.cliColorForced() && p == Ascii { return ANSI } return p } -func cliColorForced() bool { - if forced := os.Getenv("CLICOLOR_FORCE"); forced != "" { +func (o *Output) cliColorForced() bool { + if forced := o.environ.Getenv("CLICOLOR_FORCE"); forced != "" { return forced != "0" } return false diff --git a/vendor/github.com/muesli/termenv/termenv_js.go b/vendor/github.com/muesli/termenv/termenv_js.go deleted file mode 100644 index ef7bb5c7d..000000000 --- a/vendor/github.com/muesli/termenv/termenv_js.go +++ /dev/null @@ -1,18 +0,0 @@ -//go:build js -// +build js - -package termenv - -func colorProfile() Profile { - return ANSI256 -} - -func foregroundColor() Color { - // default gray - return ANSIColor(7) -} - -func backgroundColor() Color { - // default black - return ANSIColor(0) -} diff --git a/vendor/github.com/muesli/termenv/termenv_other.go b/vendor/github.com/muesli/termenv/termenv_other.go new file mode 100644 index 000000000..93a43b6ac --- /dev/null +++ b/vendor/github.com/muesli/termenv/termenv_other.go @@ -0,0 +1,30 @@ +//go:build js || plan9 || aix +// +build js plan9 aix + +package termenv + +import "io" + +// ColorProfile returns the supported color profile: +// ANSI256 +func (o Output) ColorProfile() Profile { + return ANSI256 +} + +func (o Output) foregroundColor() Color { + // default gray + return ANSIColor(7) +} + +func (o Output) backgroundColor() Color { + // default black + return ANSIColor(0) +} + +// EnableVirtualTerminalProcessing enables virtual terminal processing on +// Windows for w and returns a function that restores w to its previous state. +// On non-Windows platforms, or if w does not refer to a terminal, then it +// returns a non-nil no-op function and no error. +func EnableVirtualTerminalProcessing(w io.Writer) (func() error, error) { + return func() error { return nil }, nil +} diff --git a/vendor/github.com/muesli/termenv/termenv_posix.go b/vendor/github.com/muesli/termenv/termenv_posix.go new file mode 100644 index 000000000..b2109b749 --- /dev/null +++ b/vendor/github.com/muesli/termenv/termenv_posix.go @@ -0,0 +1,17 @@ +//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd +// +build darwin dragonfly freebsd linux netbsd openbsd + +package termenv + +import ( + "golang.org/x/sys/unix" +) + +func isForeground(fd int) bool { + pgrp, err := unix.IoctlGetInt(fd, unix.TIOCGPGRP) + if err != nil { + return false + } + + return pgrp == unix.Getpgrp() +} diff --git a/vendor/github.com/muesli/termenv/termenv_solaris.go b/vendor/github.com/muesli/termenv/termenv_solaris.go new file mode 100644 index 000000000..27a95a93e --- /dev/null +++ b/vendor/github.com/muesli/termenv/termenv_solaris.go @@ -0,0 +1,22 @@ +//go:build solaris || illumos +// +build solaris illumos + +package termenv + +import ( + "golang.org/x/sys/unix" +) + +func isForeground(fd int) bool { + pgrp, err := unix.IoctlGetInt(fd, unix.TIOCGPGRP) + if err != nil { + return false + } + + g, err := unix.Getpgrp() + if err != nil { + return false + } + + return pgrp == g +} diff --git a/vendor/github.com/muesli/termenv/termenv_unix.go b/vendor/github.com/muesli/termenv/termenv_unix.go index 35211da80..11746d2b4 100644 --- a/vendor/github.com/muesli/termenv/termenv_unix.go +++ b/vendor/github.com/muesli/termenv/termenv_unix.go @@ -5,7 +5,7 @@ package termenv import ( "fmt" - "os" + "io" "strconv" "strings" "time" @@ -18,27 +18,27 @@ const ( OSCTimeout = 5 * time.Second ) -func isForeground(fd int) bool { - pgrp, err := unix.IoctlGetInt(fd, unix.TIOCGPGRP) - if err != nil { - return false +// ColorProfile returns the supported color profile: +// Ascii, ANSI, ANSI256, or TrueColor. +func (o *Output) ColorProfile() Profile { + if !o.isTTY() { + return Ascii } - return pgrp == unix.Getpgrp() -} - -func colorProfile() Profile { - term := os.Getenv("TERM") - colorTerm := os.Getenv("COLORTERM") + term := o.environ.Getenv("TERM") + colorTerm := o.environ.Getenv("COLORTERM") switch strings.ToLower(colorTerm) { case "24bit": fallthrough case "truecolor": - if term == "screen" || !strings.HasPrefix(term, "screen") { - // enable TrueColor in tmux, but not for old-school screen - return TrueColor + if strings.HasPrefix(term, "screen") { + // tmux supports TrueColor, screen only ANSI256 + if o.environ.Getenv("TERM_PROGRAM") != "tmux" { + return ANSI256 + } } + return TrueColor case "yes": fallthrough case "true": @@ -65,8 +65,8 @@ func colorProfile() Profile { return Ascii } -func foregroundColor() Color { - s, err := termStatusReport(10) +func (o Output) foregroundColor() Color { + s, err := o.termStatusReport(10) if err == nil { c, err := xTermColor(s) if err == nil { @@ -74,7 +74,7 @@ func foregroundColor() Color { } } - colorFGBG := os.Getenv("COLORFGBG") + colorFGBG := o.environ.Getenv("COLORFGBG") if strings.Contains(colorFGBG, ";") { c := strings.Split(colorFGBG, ";") i, err := strconv.Atoi(c[0]) @@ -87,8 +87,8 @@ func foregroundColor() Color { return ANSIColor(7) } -func backgroundColor() Color { - s, err := termStatusReport(11) +func (o Output) backgroundColor() Color { + s, err := o.termStatusReport(11) if err == nil { c, err := xTermColor(s) if err == nil { @@ -96,7 +96,7 @@ func backgroundColor() Color { } } - colorFGBG := os.Getenv("COLORFGBG") + colorFGBG := o.environ.Getenv("COLORFGBG") if strings.Contains(colorFGBG, ";") { c := strings.Split(colorFGBG, ";") i, err := strconv.Atoi(c[len(c)-1]) @@ -109,7 +109,8 @@ func backgroundColor() Color { return ANSIColor(0) } -func waitForData(fd uintptr, timeout time.Duration) error { +func (o *Output) waitForData(timeout time.Duration) error { + fd := o.TTY().Fd() tv := unix.NsecToTimeval(int64(timeout)) var readfds unix.FdSet readfds.Set(int(fd)) @@ -132,13 +133,15 @@ func waitForData(fd uintptr, timeout time.Duration) error { return nil } -func readNextByte(f *os.File) (byte, error) { - if err := waitForData(f.Fd(), OSCTimeout); err != nil { - return 0, err +func (o *Output) readNextByte() (byte, error) { + if !o.unsafe { + if err := o.waitForData(OSCTimeout); err != nil { + return 0, err + } } var b [1]byte - n, err := f.Read(b[:]) + n, err := o.TTY().Read(b[:]) if err != nil { return 0, err } @@ -151,17 +154,17 @@ func readNextByte(f *os.File) (byte, error) { } // readNextResponse reads either an OSC response or a cursor position response: -// * OSC response: "\x1b]11;rgb:1111/1111/1111\x1b\\" -// * cursor position response: "\x1b[42;1R" -func readNextResponse(fd *os.File) (response string, isOSC bool, err error) { - start, err := readNextByte(fd) +// - OSC response: "\x1b]11;rgb:1111/1111/1111\x1b\\" +// - cursor position response: "\x1b[42;1R" +func (o *Output) readNextResponse() (response string, isOSC bool, err error) { + start, err := o.readNextByte() if err != nil { return "", false, err } // first byte must be ESC - for start != '\033' { - start, err = readNextByte(fd) + for start != ESC { + start, err = o.readNextByte() if err != nil { return "", false, err } @@ -170,7 +173,7 @@ func readNextResponse(fd *os.File) (response string, isOSC bool, err error) { response += string(start) // next byte is either '[' (cursor position response) or ']' (OSC response) - tpe, err := readNextByte(fd) + tpe, err := o.readNextByte() if err != nil { return "", false, err } @@ -188,7 +191,7 @@ func readNextResponse(fd *os.File) (response string, isOSC bool, err error) { } for { - b, err := readNextByte(os.Stdout) + b, err := o.readNextByte() if err != nil { return "", false, err } @@ -197,7 +200,7 @@ func readNextResponse(fd *os.File) (response string, isOSC bool, err error) { if oscResponse { // OSC can be terminated by BEL (\a) or ST (ESC) - if b == '\a' || strings.HasSuffix(response, "\033") { + if b == BEL || strings.HasSuffix(response, string(ESC)) { return response, true, nil } } else { @@ -216,42 +219,50 @@ func readNextResponse(fd *os.File) (response string, isOSC bool, err error) { return "", false, ErrStatusReport } -func termStatusReport(sequence int) (string, error) { +func (o Output) termStatusReport(sequence int) (string, error) { // screen/tmux can't support OSC, because they can be connected to multiple // terminals concurrently. - term := os.Getenv("TERM") - if strings.HasPrefix(term, "screen") { + term := o.environ.Getenv("TERM") + if strings.HasPrefix(term, "screen") || strings.HasPrefix(term, "tmux") { return "", ErrStatusReport } - // if in background, we can't control the terminal - if !isForeground(unix.Stdout) { + tty := o.TTY() + if tty == nil { return "", ErrStatusReport } - t, err := unix.IoctlGetTermios(unix.Stdout, tcgetattr) - if err != nil { - return "", ErrStatusReport - } - defer unix.IoctlSetTermios(unix.Stdout, tcsetattr, t) //nolint:errcheck + if !o.unsafe { + fd := int(tty.Fd()) + // if in background, we can't control the terminal + if !isForeground(fd) { + return "", ErrStatusReport + } - noecho := *t - noecho.Lflag = noecho.Lflag &^ unix.ECHO - noecho.Lflag = noecho.Lflag &^ unix.ICANON - if err := unix.IoctlSetTermios(unix.Stdout, tcsetattr, &noecho); err != nil { - return "", ErrStatusReport + t, err := unix.IoctlGetTermios(fd, tcgetattr) + if err != nil { + return "", fmt.Errorf("%s: %s", ErrStatusReport, err) + } + defer unix.IoctlSetTermios(fd, tcsetattr, t) //nolint:errcheck + + noecho := *t + noecho.Lflag = noecho.Lflag &^ unix.ECHO + noecho.Lflag = noecho.Lflag &^ unix.ICANON + if err := unix.IoctlSetTermios(fd, tcsetattr, &noecho); err != nil { + return "", fmt.Errorf("%s: %s", ErrStatusReport, err) + } } // first, send OSC query, which is ignored by terminal which do not support it - fmt.Printf("\033]%d;?\033\\", sequence) + fmt.Fprintf(tty, OSC+"%d;?"+ST, sequence) // then, query cursor position, should be supported by all terminals - fmt.Printf("\033[6n") + fmt.Fprintf(tty, CSI+"6n") // read the next response - res, isOSC, err := readNextResponse(os.Stdout) + res, isOSC, err := o.readNextResponse() if err != nil { - return "", err + return "", fmt.Errorf("%s: %s", ErrStatusReport, err) } // if this is not OSC response, then the terminal does not support it @@ -260,7 +271,7 @@ func termStatusReport(sequence int) (string, error) { } // read the cursor query response next and discard the result - _, _, err = readNextResponse(os.Stdout) + _, _, err = o.readNextResponse() if err != nil { return "", err } @@ -268,3 +279,11 @@ func termStatusReport(sequence int) (string, error) { // fmt.Println("Rcvd", res[1:]) return res, nil } + +// EnableVirtualTerminalProcessing enables virtual terminal processing on +// Windows for w and returns a function that restores w to its previous state. +// On non-Windows platforms, or if w does not refer to a terminal, then it +// returns a non-nil no-op function and no error. +func EnableVirtualTerminalProcessing(w io.Writer) (func() error, error) { + return func() error { return nil }, nil +} diff --git a/vendor/github.com/muesli/termenv/termenv_windows.go b/vendor/github.com/muesli/termenv/termenv_windows.go index 7f5b1ece2..1d9c61871 100644 --- a/vendor/github.com/muesli/termenv/termenv_windows.go +++ b/vendor/github.com/muesli/termenv/termenv_windows.go @@ -4,22 +4,26 @@ package termenv import ( - "os" + "fmt" "strconv" "golang.org/x/sys/windows" ) -func colorProfile() Profile { - if os.Getenv("ConEmuANSI") == "ON" { +func (o *Output) ColorProfile() Profile { + if !o.isTTY() { + return Ascii + } + + if o.environ.Getenv("ConEmuANSI") == "ON" { return TrueColor } winVersion, _, buildNumber := windows.RtlGetNtVersionNumbers() if buildNumber < 10586 || winVersion < 10 { // No ANSI support before Windows 10 build 10586. - if os.Getenv("ANSICON") != "" { - conVersion := os.Getenv("ANSICON_VER") + if o.environ.Getenv("ANSICON") != "" { + conVersion := o.environ.Getenv("ANSICON_VER") cv, err := strconv.ParseInt(conVersion, 10, 64) if err != nil || cv < 181 { // No 8 bit color support before v1.81 release. @@ -39,19 +43,19 @@ func colorProfile() Profile { return TrueColor } -func foregroundColor() Color { +func (o Output) foregroundColor() Color { // default gray return ANSIColor(7) } -func backgroundColor() Color { +func (o Output) backgroundColor() Color { // default black return ANSIColor(0) } // EnableWindowsANSIConsole enables virtual terminal processing on Windows // platforms. This allows the use of ANSI escape sequences in Windows console -// applications. Ensure this gets called before anything gets rendered with +// applications. Ensure this gets called before anything gets rendered with // termenv. // // Returns the original console mode and an error if one occurred. @@ -87,3 +91,49 @@ func RestoreWindowsConsole(mode uint32) error { return windows.SetConsoleMode(handle, mode) } + +// EnableVirtualTerminalProcessing enables virtual terminal processing on +// Windows for o and returns a function that restores o to its previous state. +// On non-Windows platforms, or if o does not refer to a terminal, then it +// returns a non-nil no-op function and no error. +func EnableVirtualTerminalProcessing(o *Output) (restoreFunc func() error, err error) { + // There is nothing to restore until we set the console mode. + restoreFunc = func() error { + return nil + } + + // If o is not a tty, then there is nothing to do. + tty := o.TTY() + if tty == nil { + return + } + + // Get the current console mode. If there is an error, assume that o is not + // a terminal, discard the error, and return. + var mode uint32 + if err2 := windows.GetConsoleMode(windows.Handle(tty.Fd()), &mode); err2 != nil { + return + } + + // If virtual terminal processing is already set, then there is nothing to + // do and nothing to restore. + if mode&windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING == windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING { + return + } + + // Enable virtual terminal processing. See + // https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences + if err2 := windows.SetConsoleMode(windows.Handle(tty.Fd()), mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING); err2 != nil { + err = fmt.Errorf("windows.SetConsoleMode: %w", err2) + return + } + + // Set the restore function. We maintain a reference to the tty in the + // closure (rather than just its handle) to ensure that the tty is not + // closed by a finalizer. + restoreFunc = func() error { + return windows.SetConsoleMode(windows.Handle(tty.Fd()), mode) + } + + return +} diff --git a/vendor/github.com/nginx/agent/sdk/v2/proto/events/event.pb.go b/vendor/github.com/nginx/agent/sdk/v2/proto/events/event.pb.go index 17f1ab782..a6bba3fd8 100644 --- a/vendor/github.com/nginx/agent/sdk/v2/proto/events/event.pb.go +++ b/vendor/github.com/nginx/agent/sdk/v2/proto/events/event.pb.go @@ -1291,208 +1291,9 @@ func (m *SecurityViolationEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) _ = i var l int _ = l -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD -======= ->>>>>>> Create dedicated cache and upstream metrics reports -======= ->>>>>>> Create dedicated cache and upstream metrics reports -======= ->>>>>>> Create dedicated cache and upstream metrics reports - if len(m.PolicyName) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.PolicyName))) - i += copy(dAtA[i:], m.PolicyName) -<<<<<<< HEAD -<<<<<<< HEAD -<<<<<<< HEAD - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } -<<<<<<< HEAD - if len(m.DisplayName) > 0 { - i -= len(m.DisplayName) - copy(dAtA[i:], m.DisplayName) - i = encodeVarintEvent(dAtA, i, uint64(len(m.DisplayName))) - i-- - dAtA[i] = 0x2 - i-- - dAtA[i] = 0xb2 -======= - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= if m.XXX_unrecognized != nil { i -= len(m.XXX_unrecognized) copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf -======= ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= - if m.XXX_unrecognized != nil { - i -= len(m.XXX_unrecognized) - copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf -======= ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= - if m.XXX_unrecognized != nil { - i -= len(m.XXX_unrecognized) - copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf -======= ->>>>>>> Create dedicated cache and upstream metrics reports - } - if len(m.SupportID) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.SupportID))) - i += copy(dAtA[i:], m.SupportID) - } - if len(m.Outcome) > 0 { - dAtA[i] = 0x1a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Outcome))) - i += copy(dAtA[i:], m.Outcome) - } - if len(m.OutcomeReason) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.OutcomeReason))) - i += copy(dAtA[i:], m.OutcomeReason) - } - if len(m.BlockingExceptionReason) > 0 { - dAtA[i] = 0x2a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.BlockingExceptionReason))) - i += copy(dAtA[i:], m.BlockingExceptionReason) - } - if len(m.Method) > 0 { - dAtA[i] = 0x32 - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Method))) - i += copy(dAtA[i:], m.Method) - } - if len(m.Protocol) > 0 { - dAtA[i] = 0x3a - i++ - i = encodeVarintEvent(dAtA, i, uint64(len(m.Protocol))) - i += copy(dAtA[i:], m.Protocol) -======= - if m.XXX_unrecognized != nil { - i -= len(m.XXX_unrecognized) - copy(dAtA[i:], m.XXX_unrecognized) ->>>>>>> adds updated generated files from protobuf } if len(m.ParentHostname) > 0 { i -= len(m.ParentHostname) @@ -1503,15 +1304,6 @@ func (m *SecurityViolationEvent) MarshalToSizedBuffer(dAtA []byte) (int, error) i-- dAtA[i] = 0xc2 } - if len(m.NginxID) > 0 { - i -= len(m.NginxID) - copy(dAtA[i:], m.NginxID) - i = encodeVarintEvent(dAtA, i, uint64(len(m.NginxID))) - i-- - dAtA[i] = 0x2 - i-- - dAtA[i] = 0xba - } if len(m.DisplayName) > 0 { i -= len(m.DisplayName) copy(dAtA[i:], m.DisplayName) diff --git a/vendor/github.com/spf13/afero/afero.go b/vendor/github.com/spf13/afero/afero.go index 199480cd0..39f658520 100644 --- a/vendor/github.com/spf13/afero/afero.go +++ b/vendor/github.com/spf13/afero/afero.go @@ -97,7 +97,7 @@ type Fs interface { // Chown changes the uid and gid of the named file. Chown(name string, uid, gid int) error - //Chtimes changes the access and modification times of the named file + // Chtimes changes the access and modification times of the named file Chtimes(name string, atime time.Time, mtime time.Time) error } diff --git a/vendor/github.com/spf13/afero/basepath.go b/vendor/github.com/spf13/afero/basepath.go index 70a1d9168..2e72793a3 100644 --- a/vendor/github.com/spf13/afero/basepath.go +++ b/vendor/github.com/spf13/afero/basepath.go @@ -40,7 +40,6 @@ func (f *BasePathFile) Name() string { func (f *BasePathFile) ReadDir(n int) ([]fs.DirEntry, error) { if rdf, ok := f.File.(fs.ReadDirFile); ok { return rdf.ReadDir(n) - } return readDirFile{f.File}.ReadDir(n) } diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs.go b/vendor/github.com/spf13/afero/copyOnWriteFs.go index 6ff8f3099..184d6dd70 100644 --- a/vendor/github.com/spf13/afero/copyOnWriteFs.go +++ b/vendor/github.com/spf13/afero/copyOnWriteFs.go @@ -223,7 +223,7 @@ func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, return nil, err } if isaDir { - if err = u.layer.MkdirAll(dir, 0777); err != nil { + if err = u.layer.MkdirAll(dir, 0o777); err != nil { return nil, err } return u.layer.OpenFile(name, flag, perm) @@ -247,8 +247,9 @@ func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, // This function handles the 9 different possibilities caused // by the union which are the intersection of the following... -// layer: doesn't exist, exists as a file, and exists as a directory -// base: doesn't exist, exists as a file, and exists as a directory +// +// layer: doesn't exist, exists as a file, and exists as a directory +// base: doesn't exist, exists as a file, and exists as a directory func (u *CopyOnWriteFs) Open(name string) (File, error) { // Since the overlay overrides the base we check that first b, err := u.isBaseFile(name) @@ -322,5 +323,5 @@ func (u *CopyOnWriteFs) MkdirAll(name string, perm os.FileMode) error { } func (u *CopyOnWriteFs) Create(name string) (File, error) { - return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666) + return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0o666) } diff --git a/vendor/github.com/spf13/afero/ioutil.go b/vendor/github.com/spf13/afero/ioutil.go index 386c9cdc2..fa6abe1ee 100644 --- a/vendor/github.com/spf13/afero/ioutil.go +++ b/vendor/github.com/spf13/afero/ioutil.go @@ -141,8 +141,10 @@ func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error { // We generate random temporary file names so that there's a good // chance the file doesn't exist yet - keeps the number of tries in // TempFile to a minimum. -var randNum uint32 -var randmu sync.Mutex +var ( + randNum uint32 + randmu sync.Mutex +) func reseed() uint32 { return uint32(time.Now().UnixNano() + int64(os.Getpid())) @@ -190,7 +192,7 @@ func TempFile(fs Fs, dir, pattern string) (f File, err error) { nconflict := 0 for i := 0; i < 10000; i++ { name := filepath.Join(dir, prefix+nextRandom()+suffix) - f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) + f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() @@ -214,6 +216,7 @@ func TempFile(fs Fs, dir, pattern string) (f File, err error) { func (a Afero) TempDir(dir, prefix string) (name string, err error) { return TempDir(a.Fs, dir, prefix) } + func TempDir(fs Fs, dir, prefix string) (name string, err error) { if dir == "" { dir = os.TempDir() @@ -222,7 +225,7 @@ func TempDir(fs Fs, dir, prefix string) (name string, err error) { nconflict := 0 for i := 0; i < 10000; i++ { try := filepath.Join(dir, prefix+nextRandom()) - err = fs.Mkdir(try, 0700) + err = fs.Mkdir(try, 0o700) if os.IsExist(err) { if nconflict++; nconflict > 10 { randmu.Lock() diff --git a/vendor/github.com/spf13/afero/mem/file.go b/vendor/github.com/spf13/afero/mem/file.go index 3cf4693b5..62fe4498e 100644 --- a/vendor/github.com/spf13/afero/mem/file.go +++ b/vendor/github.com/spf13/afero/mem/file.go @@ -245,7 +245,7 @@ func (f *File) Truncate(size int64) error { defer f.fileData.Unlock() if size > int64(len(f.fileData.data)) { diff := size - int64(len(f.fileData.data)) - f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{00}, int(diff))...) + f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{0o0}, int(diff))...) } else { f.fileData.data = f.fileData.data[0:size] } @@ -285,7 +285,7 @@ func (f *File) Write(b []byte) (n int, err error) { tail = f.fileData.data[n+int(cur):] } if diff > 0 { - f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{00}, int(diff)), b...)...) + f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{0o0}, int(diff)), b...)...) f.fileData.data = append(f.fileData.data, tail...) } else { f.fileData.data = append(f.fileData.data[:cur], b...) @@ -321,16 +321,19 @@ func (s *FileInfo) Name() string { s.Unlock() return name } + func (s *FileInfo) Mode() os.FileMode { s.Lock() defer s.Unlock() return s.mode } + func (s *FileInfo) ModTime() time.Time { s.Lock() defer s.Unlock() return s.modtime } + func (s *FileInfo) IsDir() bool { s.Lock() defer s.Unlock() diff --git a/vendor/github.com/spf13/afero/memmap.go b/vendor/github.com/spf13/afero/memmap.go index d06975e71..e6b7d70b9 100644 --- a/vendor/github.com/spf13/afero/memmap.go +++ b/vendor/github.com/spf13/afero/memmap.go @@ -15,6 +15,7 @@ package afero import ( "fmt" + "io" "log" "os" "path/filepath" @@ -43,7 +44,7 @@ func (m *MemMapFs) getData() map[string]*mem.FileData { // Root should always exist, right? // TODO: what about windows? root := mem.CreateDir(FilePathSeparator) - mem.SetMode(root, os.ModeDir|0755) + mem.SetMode(root, os.ModeDir|0o755) m.data[FilePathSeparator] = root }) return m.data @@ -96,12 +97,12 @@ func (m *MemMapFs) registerWithParent(f *mem.FileData, perm os.FileMode) { pdir := filepath.Dir(filepath.Clean(f.Name())) err := m.lockfreeMkdir(pdir, perm) if err != nil { - //log.Println("Mkdir error:", err) + // log.Println("Mkdir error:", err) return } parent, err = m.lockfreeOpen(pdir) if err != nil { - //log.Println("Open after Mkdir error:", err) + // log.Println("Open after Mkdir error:", err) return } } @@ -237,7 +238,7 @@ func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, erro file = mem.NewReadOnlyFileHandle(file.(*mem.File).Data()) } if flag&os.O_APPEND > 0 { - _, err = file.Seek(0, os.SEEK_END) + _, err = file.Seek(0, io.SeekEnd) if err != nil { file.Close() return nil, err @@ -319,6 +320,18 @@ func (m *MemMapFs) Rename(oldname, newname string) error { } else { return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound} } + + for p, fileData := range m.getData() { + if strings.HasPrefix(p, oldname+FilePathSeparator) { + m.mu.RUnlock() + m.mu.Lock() + delete(m.getData(), p) + p := strings.Replace(p, oldname, newname, 1) + m.getData()[p] = fileData + m.mu.Unlock() + m.mu.RLock() + } + } return nil } diff --git a/vendor/github.com/spf13/afero/regexpfs.go b/vendor/github.com/spf13/afero/regexpfs.go index ac359c62a..218f3b235 100644 --- a/vendor/github.com/spf13/afero/regexpfs.go +++ b/vendor/github.com/spf13/afero/regexpfs.go @@ -10,7 +10,6 @@ import ( // The RegexpFs filters files (not directories) by regular expression. Only // files matching the given regexp will be allowed, all others get a ENOENT error ( // "No such file or directory"). -// type RegexpFs struct { re *regexp.Regexp source Fs diff --git a/vendor/github.com/spf13/afero/symlink.go b/vendor/github.com/spf13/afero/symlink.go index d1c6ea53d..aa6ae125b 100644 --- a/vendor/github.com/spf13/afero/symlink.go +++ b/vendor/github.com/spf13/afero/symlink.go @@ -21,9 +21,9 @@ import ( // filesystems saying so. // It indicates support for 3 symlink related interfaces that implement the // behaviors of the os methods: -// - Lstat -// - Symlink, and -// - Readlink +// - Lstat +// - Symlink, and +// - Readlink type Symlinker interface { Lstater Linker diff --git a/vendor/github.com/spf13/afero/unionFile.go b/vendor/github.com/spf13/afero/unionFile.go index 333d367f4..62dd6c93c 100644 --- a/vendor/github.com/spf13/afero/unionFile.go +++ b/vendor/github.com/spf13/afero/unionFile.go @@ -47,7 +47,7 @@ func (f *UnionFile) Read(s []byte) (int, error) { if (err == nil || err == io.EOF) && f.Base != nil { // advance the file position also in the base file, the next // call may be a write at this position (or a seek with SEEK_CUR) - if _, seekErr := f.Base.Seek(int64(n), os.SEEK_CUR); seekErr != nil { + if _, seekErr := f.Base.Seek(int64(n), io.SeekCurrent); seekErr != nil { // only overwrite err in case the seek fails: we need to // report an eventual io.EOF to the caller err = seekErr @@ -130,7 +130,7 @@ func (f *UnionFile) Name() string { type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) { - var files = make(map[string]os.FileInfo) + files := make(map[string]os.FileInfo) for _, fi := range lofi { files[fi.Name()] = fi @@ -151,7 +151,6 @@ var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, err } return rfi, nil - } // Readdir will weave the two directories together and @@ -275,7 +274,7 @@ func copyFile(base Fs, layer Fs, name string, bfh File) error { return err } if !exists { - err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME? + err = layer.MkdirAll(filepath.Dir(name), 0o777) // FIXME? if err != nil { return err } diff --git a/vendor/github.com/spf13/afero/util.go b/vendor/github.com/spf13/afero/util.go index cb7de23f2..9e4cba274 100644 --- a/vendor/github.com/spf13/afero/util.go +++ b/vendor/github.com/spf13/afero/util.go @@ -43,7 +43,7 @@ func WriteReader(fs Fs, path string, r io.Reader) (err error) { ospath := filepath.FromSlash(dir) if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r + err = fs.MkdirAll(ospath, 0o777) // rwx, rw, r if err != nil { if err != os.ErrExist { return err @@ -71,7 +71,7 @@ func SafeWriteReader(fs Fs, path string, r io.Reader) (err error) { ospath := filepath.FromSlash(dir) if ospath != "" { - err = fs.MkdirAll(ospath, 0777) // rwx, rw, r + err = fs.MkdirAll(ospath, 0o777) // rwx, rw, r if err != nil { return } @@ -124,7 +124,7 @@ func GetTempDir(fs Fs, subPath string) string { return addSlash(dir) } - err := fs.MkdirAll(dir, 0777) + err := fs.MkdirAll(dir, 0o777) if err != nil { panic(err) } @@ -197,7 +197,6 @@ func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, err // readerContains reports whether any of the subslices is within r. func readerContainsAny(r io.Reader, subslices ...[]byte) bool { - if r == nil || len(subslices) == 0 { return false } diff --git a/vendor/modules.txt b/vendor/modules.txt index 4d0a77f02..7590944ef 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -53,14 +53,17 @@ github.com/alvaroloes/enumer # github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d ## explicit; go 1.13 github.com/asaskevich/govalidator +# github.com/aymanbagabas/go-osc52/v2 v2.0.1 +## explicit; go 1.16 +github.com/aymanbagabas/go-osc52/v2 # github.com/beorn7/perks v1.0.1 ## explicit; go 1.11 github.com/beorn7/perks/quantile # github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb ## explicit github.com/blakesmith/ar -# github.com/briandowns/spinner v1.21.0 -## explicit; go 1.14 +# github.com/briandowns/spinner v1.23.0 +## explicit; go 1.17 github.com/briandowns/spinner # github.com/bufbuild/buf v1.15.1 ## explicit; go 1.19 @@ -264,8 +267,8 @@ github.com/cenkalti/backoff/v4 # github.com/cespare/xxhash/v2 v2.1.2 ## explicit; go 1.11 github.com/cespare/xxhash/v2 -# github.com/charmbracelet/lipgloss v0.6.0 -## explicit; go 1.15 +# github.com/charmbracelet/lipgloss v0.7.1 +## explicit; go 1.17 github.com/charmbracelet/lipgloss # github.com/cpuguy83/go-md2man/v2 v2.0.2 ## explicit; go 1.11 @@ -333,7 +336,7 @@ github.com/emirpasic/gods/utils # github.com/envoyproxy/protoc-gen-validate v0.3.0-java ## explicit github.com/envoyproxy/protoc-gen-validate/validate -# github.com/evilmartians/lefthook v1.3.5 +# github.com/evilmartians/lefthook v1.3.7 ## explicit; go 1.19 github.com/evilmartians/lefthook github.com/evilmartians/lefthook/cmd @@ -584,13 +587,13 @@ github.com/google/pprof/profile # github.com/google/uuid v1.3.0 ## explicit github.com/google/uuid -# github.com/goreleaser/chglog v0.4.1 -## explicit; go 1.19 +# github.com/goreleaser/chglog v0.4.2 +## explicit; go 1.20 github.com/goreleaser/chglog # github.com/goreleaser/fileglob v1.3.0 ## explicit; go 1.16 github.com/goreleaser/fileglob -# github.com/goreleaser/nfpm/v2 v2.26.0 +# github.com/goreleaser/nfpm/v2 v2.27.1 ## explicit; go 1.19 github.com/goreleaser/nfpm/v2 github.com/goreleaser/nfpm/v2/apk @@ -631,7 +634,7 @@ github.com/huandu/xstrings # github.com/iancoleman/orderedmap v0.0.0-20190318233801-ac98e3ecb4b0 ## explicit github.com/iancoleman/orderedmap -# github.com/imdario/mergo v0.3.13 +# github.com/imdario/mergo v0.3.14 ## explicit; go 1.13 github.com/imdario/mergo # github.com/inconshreveable/mousetrap v1.1.0 @@ -655,7 +658,7 @@ github.com/josharian/intern # github.com/kevinburke/ssh_config v1.1.0 ## explicit github.com/kevinburke/ssh_config -# github.com/klauspost/compress v1.16.0 +# github.com/klauspost/compress v1.16.3 ## explicit; go 1.18 github.com/klauspost/compress github.com/klauspost/compress/flate @@ -738,7 +741,7 @@ github.com/muesli/mango-cobra # github.com/muesli/mango-pflag v0.1.0 ## explicit; go 1.17 github.com/muesli/mango-pflag -# github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68 +# github.com/muesli/reflow v0.3.0 ## explicit; go 1.13 github.com/muesli/reflow/ansi github.com/muesli/reflow/truncate @@ -747,8 +750,8 @@ github.com/muesli/reflow/wrap # github.com/muesli/roff v0.1.0 ## explicit; go 1.17 github.com/muesli/roff -# github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0 -## explicit; go 1.13 +# github.com/muesli/termenv v0.15.1 +## explicit; go 1.17 github.com/muesli/termenv # github.com/mwitkow/go-proto-validators v0.3.2 ## explicit; go 1.13 @@ -891,7 +894,7 @@ github.com/shopspring/decimal # github.com/sirupsen/logrus v1.9.0 ## explicit; go 1.13 github.com/sirupsen/logrus -# github.com/spf13/afero v1.9.3 +# github.com/spf13/afero v1.9.5 ## explicit; go 1.16 github.com/spf13/afero github.com/spf13/afero/internal/common