From 5857741b28523b9732271bc5741e3384d5870751 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=AA=20de=20Souza=20Pinto?= Date: Thu, 5 Nov 2026 09:09:55 +0100 Subject: [PATCH] Bump eve/pkg/pillar in all subprojects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is also needed to fix SBOM generation, broken by commit 2cb4f793478d3176dc4f99390fb95876a01abb26. Signed-off-by: RenĂª de Souza Pinto --- evetest/go.mod | 20 +- evetest/go.sum | 56 +- evetest/sdn/vm/go.mod | 6 +- evetest/sdn/vm/go.sum | 12 +- pkg/installer/src/go.mod | 20 +- pkg/installer/src/go.sum | 50 +- .../github.com/go-logr/logr/context_noslog.go | 1 - .../github.com/go-logr/logr/context_slog.go | 1 - .../github.com/go-logr/logr/sloghandler.go | 1 - .../vendor/github.com/go-logr/logr/slogr.go | 1 - .../github.com/go-logr/logr/slogsink.go | 1 - .../pkg/v1/types/types.go | 17 + .../lf-edge/eve/pkg/kube/cnirpc/LICENSE | 2 +- .../lf-edge/eve/pkg/kube/cnirpc/cnirpc.go | 12 + .../eve/pkg/pillar/base/execwrapper.go | 37 +- .../lf-edge/eve/pkg/pillar/base/kubevirt.go | 64 ++- .../eve/pkg/pillar/base/logobjecttypes.go | 8 +- .../lf-edge/eve/pkg/pillar/base/round.go | 9 +- .../lf-edge/eve/pkg/pillar/evetpm/evetpm.md | 338 ++++++++++++ .../evetpm/faultinjection_keypresence.go | 61 +++ .../faultinjection_keypresence_disabled.go | 14 + .../lf-edge/eve/pkg/pillar/evetpm/tpm.go | 121 ++++- .../eve/pkg/pillar/pubsub/allocstats.go | 66 +++ .../lf-edge/eve/pkg/pillar/pubsub/driver.go | 6 - .../eve/pkg/pillar/pubsub/emptydriver.go | 10 - .../lf-edge/eve/pkg/pillar/pubsub/large.go | 282 ---------- .../eve/pkg/pillar/pubsub/memdriver.go | 10 - .../lf-edge/eve/pkg/pillar/pubsub/publish.go | 57 +- .../lf-edge/eve/pkg/pillar/pubsub/stats.go | 157 ++++++ .../eve/pkg/pillar/pubsub/subscribe.go | 8 - .../lf-edge/eve/pkg/pillar/pubsub/util.go | 37 +- .../lf-edge/eve/pkg/pillar/sriov/sriov.go | 320 +++++++++--- .../pkg/pillar/types/assignableadapters.go | 486 +++++++++++++----- .../eve/pkg/pillar/types/cachedresolvedip.go | 79 --- .../eve/pkg/pillar/types/clustertypes.go | 196 ++++++- .../eve/pkg/pillar/types/contenttreetypes.go | 6 + .../types/deferredcontentdeletetypes.go | 72 +++ .../eve/pkg/pillar/types/diskmetrics.go | 15 +- .../lf-edge/eve/pkg/pillar/types/dns.go | 43 +- .../eve/pkg/pillar/types/domainmgrtypes.go | 101 +++- .../lf-edge/eve/pkg/pillar/types/dpc.go | 27 + .../eve/pkg/pillar/types/errorbound.go | 103 ++++ .../lf-edge/eve/pkg/pillar/types/errortime.go | 1 + .../eve/pkg/pillar/types/evaluation.go | 306 ----------- .../lf-edge/eve/pkg/pillar/types/global.go | 319 +++++++++++- .../eve/pkg/pillar/types/ifnametopci.go | 57 +- .../eve/pkg/pillar/types/locationconsts.go | 39 +- .../lf-edge/eve/pkg/pillar/types/memory.go | 46 +- .../eve/pkg/pillar/types/mgmtproxytypes.go | 48 ++ .../eve/pkg/pillar/types/vaultmgrtypes.go | 124 +++++ .../eve/pkg/pillar/types/volumetypes.go | 51 +- .../eve/pkg/pillar/types/zedagenttypes.go | 34 +- .../eve/pkg/pillar/types/zedcloudmetrics.go | 37 ++ .../eve/pkg/pillar/types/zedkubetypes.go | 74 +++ .../eve/pkg/pillar/types/zedmanagertypes.go | 22 + .../eve/pkg/pillar/types/zedroutertypes.go | 70 ++- .../lf-edge/eve/pkg/pillar/types/zfs.go | 16 + .../eve/pkg/pillar/utils/cgroup/cgroup.go | 88 ++++ .../eve/pkg/pillar/utils/cgroup/notify.go | 110 ++++ .../pillar/utils/cloudconfig/cloudconfig.go | 49 +- .../pillar/utils/cloudconfig/rootedwrite.go | 425 +++++++++++++++ .../lf-edge/eve/pkg/pillar/utils/file/file.go | 42 +- .../github.com/sirupsen/logrus/.golangci.yml | 95 ++-- .../github.com/sirupsen/logrus/CHANGELOG.md | 4 +- .../github.com/sirupsen/logrus/README.md | 126 ++--- .../github.com/sirupsen/logrus/appveyor.yml | 16 +- .../github.com/sirupsen/logrus/entry.go | 25 +- .../github.com/sirupsen/logrus/hooks.go | 8 +- .../github.com/sirupsen/logrus/logger.go | 34 +- .../github.com/sirupsen/logrus/logrus.go | 20 +- .../sirupsen/logrus/terminal_check_bsd.go | 2 +- .../sirupsen/logrus/terminal_check_unix.go | 2 + .../sirupsen/logrus/terminal_check_wasi.go | 8 + .../sirupsen/logrus/terminal_check_wasip1.go | 8 + .../sirupsen/logrus/text_formatter.go | 3 +- .../vendor/golang.org/x/net/html/entity.go | 5 +- .../vendor/golang.org/x/net/html/escape.go | 140 +++-- .../vendor/golang.org/x/net/html/foreign.go | 2 +- .../src/vendor/golang.org/x/net/html/parse.go | 249 +++------ .../src/vendor/golang.org/x/net/html/token.go | 41 +- .../golang.org/x/net/http2/hpack/encode.go | 1 - .../golang.org/x/net/http2/hpack/hpack.go | 1 - .../golang.org/x/net/http2/hpack/tables.go | 51 +- .../golang.org/x/net/http2/server_wrap.go | 16 + .../golang.org/x/net/http2/transport_wrap.go | 88 ++-- .../src/vendor/golang.org/x/net/idna/idna.go | 6 +- .../src/vendor/golang.org/x/sys/cpu/parse.go | 62 ++- .../golang.org/x/sys/unix/syscall_linux.go | 1 + .../x/sys/unix/syscall_linux_386.go | 1 - .../x/sys/unix/syscall_linux_amd64.go | 1 - .../x/sys/unix/syscall_linux_arm.go | 1 - .../x/sys/unix/syscall_linux_arm64.go | 1 - .../x/sys/unix/syscall_linux_loong64.go | 1 - .../x/sys/unix/syscall_linux_mips64x.go | 1 - .../x/sys/unix/syscall_linux_mipsx.go | 1 - .../x/sys/unix/syscall_linux_ppc.go | 1 - .../x/sys/unix/syscall_linux_ppc64x.go | 1 - .../x/sys/unix/syscall_linux_riscv64.go | 1 - .../x/sys/unix/syscall_linux_s390x.go | 1 - .../x/sys/unix/syscall_linux_sparc64.go | 1 - .../golang.org/x/sys/unix/zerrors_linux.go | 8 +- .../golang.org/x/sys/unix/zsyscall_linux.go | 17 + .../x/sys/unix/zsyscall_linux_386.go | 17 - .../x/sys/unix/zsyscall_linux_amd64.go | 17 - .../x/sys/unix/zsyscall_linux_arm.go | 17 - .../x/sys/unix/zsyscall_linux_arm64.go | 17 - .../x/sys/unix/zsyscall_linux_loong64.go | 17 - .../x/sys/unix/zsyscall_linux_mips.go | 17 - .../x/sys/unix/zsyscall_linux_mips64.go | 17 - .../x/sys/unix/zsyscall_linux_mips64le.go | 17 - .../x/sys/unix/zsyscall_linux_mipsle.go | 17 - .../x/sys/unix/zsyscall_linux_ppc.go | 17 - .../x/sys/unix/zsyscall_linux_ppc64.go | 17 - .../x/sys/unix/zsyscall_linux_ppc64le.go | 17 - .../x/sys/unix/zsyscall_linux_riscv64.go | 17 - .../x/sys/unix/zsyscall_linux_s390x.go | 17 - .../x/sys/unix/zsyscall_linux_sparc64.go | 17 - .../golang.org/x/sys/unix/ztypes_linux.go | 76 +++ .../golang.org/x/sys/unix/ztypes_linux_386.go | 4 + .../x/sys/unix/ztypes_linux_amd64.go | 4 + .../golang.org/x/sys/unix/ztypes_linux_arm.go | 4 + .../x/sys/unix/ztypes_linux_arm64.go | 4 + .../x/sys/unix/ztypes_linux_loong64.go | 4 + .../x/sys/unix/ztypes_linux_mips.go | 4 + .../x/sys/unix/ztypes_linux_mips64.go | 4 + .../x/sys/unix/ztypes_linux_mips64le.go | 4 + .../x/sys/unix/ztypes_linux_mipsle.go | 4 + .../golang.org/x/sys/unix/ztypes_linux_ppc.go | 4 + .../x/sys/unix/ztypes_linux_ppc64.go | 4 + .../x/sys/unix/ztypes_linux_ppc64le.go | 4 + .../x/sys/unix/ztypes_linux_riscv64.go | 4 + .../x/sys/unix/ztypes_linux_s390x.go | 4 + .../x/sys/unix/ztypes_linux_sparc64.go | 4 + .../x/sys/windows/security_windows.go | 36 ++ .../x/sys/windows/syscall_windows.go | 8 +- .../golang.org/x/sys/windows/types_windows.go | 1 + .../x/text/unicode/norm/forminfo.go | 9 +- .../golang.org/x/text/unicode/norm/iter.go | 8 +- .../x/text/unicode/norm/normalize.go | 20 +- .../protobuf/internal/encoding/tag/tag.go | 11 +- .../protobuf/internal/encoding/text/decode.go | 115 +++-- .../protobuf/internal/filedesc/desc.go | 1 + .../protobuf/internal/filedesc/desc_lazy.go | 22 - .../protobuf/internal/genid/descriptor_gen.go | 1 + .../protobuf/internal/impl/codec_map.go | 6 + .../protobuf/internal/impl/decode.go | 3 +- .../protobuf/internal/impl/validate.go | 26 + .../protobuf/internal/version/version.go | 2 +- .../protobuf/proto/decode.go | 10 +- .../types/known/timestamppb/timestamp.pb.go | 13 +- pkg/installer/src/vendor/modules.txt | 29 +- pkg/recovertpm/src/go.mod | 22 +- pkg/recovertpm/src/go.sum | 54 +- .../github.com/go-logr/logr/context_noslog.go | 1 - .../github.com/go-logr/logr/context_slog.go | 1 - .../github.com/go-logr/logr/sloghandler.go | 1 - .../vendor/github.com/go-logr/logr/slogr.go | 1 - .../github.com/go-logr/logr/slogsink.go | 1 - .../pkg/v1/types/types.go | 17 + .../lf-edge/eve/pkg/kube/cnirpc/LICENSE | 2 +- .../lf-edge/eve/pkg/kube/cnirpc/cnirpc.go | 12 + .../eve/pkg/pillar/base/execwrapper.go | 37 +- .../lf-edge/eve/pkg/pillar/base/kubevirt.go | 64 ++- .../eve/pkg/pillar/base/logobjecttypes.go | 8 +- .../lf-edge/eve/pkg/pillar/base/round.go | 9 +- .../lf-edge/eve/pkg/pillar/evetpm/evetpm.md | 338 ++++++++++++ .../evetpm/faultinjection_keypresence.go | 61 +++ .../faultinjection_keypresence_disabled.go | 14 + .../lf-edge/eve/pkg/pillar/evetpm/tpm.go | 121 ++++- .../eve/pkg/pillar/pubsub/allocstats.go | 66 +++ .../lf-edge/eve/pkg/pillar/pubsub/driver.go | 6 - .../eve/pkg/pillar/pubsub/emptydriver.go | 10 - .../lf-edge/eve/pkg/pillar/pubsub/large.go | 282 ---------- .../eve/pkg/pillar/pubsub/memdriver.go | 10 - .../lf-edge/eve/pkg/pillar/pubsub/publish.go | 57 +- .../lf-edge/eve/pkg/pillar/pubsub/stats.go | 157 ++++++ .../eve/pkg/pillar/pubsub/subscribe.go | 8 - .../lf-edge/eve/pkg/pillar/pubsub/util.go | 37 +- .../lf-edge/eve/pkg/pillar/sriov/sriov.go | 320 +++++++++--- .../pkg/pillar/types/assignableadapters.go | 486 +++++++++++++----- .../eve/pkg/pillar/types/cachedresolvedip.go | 79 --- .../eve/pkg/pillar/types/clustertypes.go | 196 ++++++- .../eve/pkg/pillar/types/contenttreetypes.go | 6 + .../types/deferredcontentdeletetypes.go | 72 +++ .../eve/pkg/pillar/types/diskmetrics.go | 15 +- .../lf-edge/eve/pkg/pillar/types/dns.go | 43 +- .../eve/pkg/pillar/types/domainmgrtypes.go | 101 +++- .../lf-edge/eve/pkg/pillar/types/dpc.go | 27 + .../eve/pkg/pillar/types/errorbound.go | 103 ++++ .../lf-edge/eve/pkg/pillar/types/errortime.go | 1 + .../eve/pkg/pillar/types/evaluation.go | 306 ----------- .../lf-edge/eve/pkg/pillar/types/global.go | 319 +++++++++++- .../eve/pkg/pillar/types/ifnametopci.go | 57 +- .../eve/pkg/pillar/types/locationconsts.go | 39 +- .../lf-edge/eve/pkg/pillar/types/memory.go | 46 +- .../eve/pkg/pillar/types/mgmtproxytypes.go | 48 ++ .../eve/pkg/pillar/types/vaultmgrtypes.go | 124 +++++ .../eve/pkg/pillar/types/volumetypes.go | 51 +- .../eve/pkg/pillar/types/zedagenttypes.go | 34 +- .../eve/pkg/pillar/types/zedcloudmetrics.go | 37 ++ .../eve/pkg/pillar/types/zedkubetypes.go | 74 +++ .../eve/pkg/pillar/types/zedmanagertypes.go | 22 + .../eve/pkg/pillar/types/zedroutertypes.go | 70 ++- .../lf-edge/eve/pkg/pillar/types/zfs.go | 16 + .../eve/pkg/pillar/utils/cgroup/cgroup.go | 88 ++++ .../eve/pkg/pillar/utils/cgroup/notify.go | 110 ++++ .../pillar/utils/cloudconfig/cloudconfig.go | 49 +- .../pillar/utils/cloudconfig/rootedwrite.go | 425 +++++++++++++++ .../lf-edge/eve/pkg/pillar/utils/file/file.go | 42 +- .../github.com/sirupsen/logrus/.golangci.yml | 95 ++-- .../github.com/sirupsen/logrus/CHANGELOG.md | 4 +- .../github.com/sirupsen/logrus/README.md | 126 ++--- .../github.com/sirupsen/logrus/appveyor.yml | 16 +- .../github.com/sirupsen/logrus/entry.go | 25 +- .../github.com/sirupsen/logrus/hooks.go | 8 +- .../github.com/sirupsen/logrus/logger.go | 34 +- .../github.com/sirupsen/logrus/logrus.go | 20 +- .../sirupsen/logrus/terminal_check_bsd.go | 2 +- .../sirupsen/logrus/terminal_check_unix.go | 2 + .../sirupsen/logrus/terminal_check_wasi.go | 8 + .../sirupsen/logrus/terminal_check_wasip1.go | 8 + .../sirupsen/logrus/text_formatter.go | 3 +- .../vendor/golang.org/x/net/html/entity.go | 5 +- .../vendor/golang.org/x/net/html/escape.go | 140 +++-- .../vendor/golang.org/x/net/html/foreign.go | 2 +- .../src/vendor/golang.org/x/net/html/parse.go | 249 +++------ .../src/vendor/golang.org/x/net/html/token.go | 41 +- .../golang.org/x/net/http2/hpack/encode.go | 1 - .../golang.org/x/net/http2/hpack/hpack.go | 1 - .../golang.org/x/net/http2/hpack/tables.go | 51 +- .../golang.org/x/net/http2/server_wrap.go | 16 + .../golang.org/x/net/http2/transport_wrap.go | 88 ++-- .../src/vendor/golang.org/x/net/idna/idna.go | 6 +- .../src/vendor/golang.org/x/sys/cpu/parse.go | 62 ++- .../golang.org/x/sys/unix/syscall_linux.go | 1 + .../x/sys/unix/syscall_linux_386.go | 1 - .../x/sys/unix/syscall_linux_amd64.go | 1 - .../x/sys/unix/syscall_linux_arm.go | 1 - .../x/sys/unix/syscall_linux_arm64.go | 1 - .../x/sys/unix/syscall_linux_loong64.go | 1 - .../x/sys/unix/syscall_linux_mips64x.go | 1 - .../x/sys/unix/syscall_linux_mipsx.go | 1 - .../x/sys/unix/syscall_linux_ppc.go | 1 - .../x/sys/unix/syscall_linux_ppc64x.go | 1 - .../x/sys/unix/syscall_linux_riscv64.go | 1 - .../x/sys/unix/syscall_linux_s390x.go | 1 - .../x/sys/unix/syscall_linux_sparc64.go | 1 - .../golang.org/x/sys/unix/zerrors_linux.go | 8 +- .../golang.org/x/sys/unix/zsyscall_linux.go | 17 + .../x/sys/unix/zsyscall_linux_386.go | 17 - .../x/sys/unix/zsyscall_linux_amd64.go | 17 - .../x/sys/unix/zsyscall_linux_arm.go | 17 - .../x/sys/unix/zsyscall_linux_arm64.go | 17 - .../x/sys/unix/zsyscall_linux_loong64.go | 17 - .../x/sys/unix/zsyscall_linux_mips.go | 17 - .../x/sys/unix/zsyscall_linux_mips64.go | 17 - .../x/sys/unix/zsyscall_linux_mips64le.go | 17 - .../x/sys/unix/zsyscall_linux_mipsle.go | 17 - .../x/sys/unix/zsyscall_linux_ppc.go | 17 - .../x/sys/unix/zsyscall_linux_ppc64.go | 17 - .../x/sys/unix/zsyscall_linux_ppc64le.go | 17 - .../x/sys/unix/zsyscall_linux_riscv64.go | 17 - .../x/sys/unix/zsyscall_linux_s390x.go | 17 - .../x/sys/unix/zsyscall_linux_sparc64.go | 17 - .../golang.org/x/sys/unix/ztypes_linux.go | 76 +++ .../golang.org/x/sys/unix/ztypes_linux_386.go | 4 + .../x/sys/unix/ztypes_linux_amd64.go | 4 + .../golang.org/x/sys/unix/ztypes_linux_arm.go | 4 + .../x/sys/unix/ztypes_linux_arm64.go | 4 + .../x/sys/unix/ztypes_linux_loong64.go | 4 + .../x/sys/unix/ztypes_linux_mips.go | 4 + .../x/sys/unix/ztypes_linux_mips64.go | 4 + .../x/sys/unix/ztypes_linux_mips64le.go | 4 + .../x/sys/unix/ztypes_linux_mipsle.go | 4 + .../golang.org/x/sys/unix/ztypes_linux_ppc.go | 4 + .../x/sys/unix/ztypes_linux_ppc64.go | 4 + .../x/sys/unix/ztypes_linux_ppc64le.go | 4 + .../x/sys/unix/ztypes_linux_riscv64.go | 4 + .../x/sys/unix/ztypes_linux_s390x.go | 4 + .../x/sys/unix/ztypes_linux_sparc64.go | 4 + .../x/sys/windows/security_windows.go | 36 ++ .../x/sys/windows/syscall_windows.go | 8 +- .../golang.org/x/sys/windows/types_windows.go | 1 + .../x/text/unicode/norm/forminfo.go | 9 +- .../golang.org/x/text/unicode/norm/iter.go | 8 +- .../x/text/unicode/norm/normalize.go | 20 +- .../protobuf/internal/encoding/tag/tag.go | 11 +- .../protobuf/internal/encoding/text/decode.go | 115 +++-- .../protobuf/internal/filedesc/desc.go | 1 + .../protobuf/internal/filedesc/desc_lazy.go | 22 - .../protobuf/internal/genid/descriptor_gen.go | 1 + .../protobuf/internal/impl/codec_map.go | 6 + .../protobuf/internal/impl/decode.go | 3 +- .../protobuf/internal/impl/validate.go | 26 + .../protobuf/internal/version/version.go | 2 +- .../protobuf/proto/decode.go | 10 +- .../types/known/timestamppb/timestamp.pb.go | 13 +- pkg/recovertpm/src/vendor/modules.txt | 31 +- pkg/vtpm/swtpm-vtpm/go.mod | 20 +- pkg/vtpm/swtpm-vtpm/go.sum | 50 +- .../github.com/go-logr/logr/context_noslog.go | 1 - .../github.com/go-logr/logr/context_slog.go | 1 - .../github.com/go-logr/logr/sloghandler.go | 1 - .../vendor/github.com/go-logr/logr/slogr.go | 1 - .../github.com/go-logr/logr/slogsink.go | 1 - .../pkg/v1/types/types.go | 17 + .../lf-edge/eve/pkg/kube/cnirpc/LICENSE | 2 +- .../lf-edge/eve/pkg/kube/cnirpc/cnirpc.go | 12 + .../eve/pkg/pillar/base/execwrapper.go | 37 +- .../lf-edge/eve/pkg/pillar/base/kubevirt.go | 64 ++- .../eve/pkg/pillar/base/logobjecttypes.go | 8 +- .../lf-edge/eve/pkg/pillar/base/round.go | 9 +- .../lf-edge/eve/pkg/pillar/evetpm/evetpm.md | 338 ++++++++++++ .../evetpm/faultinjection_keypresence.go | 61 +++ .../faultinjection_keypresence_disabled.go | 14 + .../lf-edge/eve/pkg/pillar/evetpm/tpm.go | 121 ++++- .../eve/pkg/pillar/pubsub/allocstats.go | 66 +++ .../lf-edge/eve/pkg/pillar/pubsub/driver.go | 6 - .../eve/pkg/pillar/pubsub/emptydriver.go | 10 - .../lf-edge/eve/pkg/pillar/pubsub/large.go | 282 ---------- .../eve/pkg/pillar/pubsub/memdriver.go | 10 - .../lf-edge/eve/pkg/pillar/pubsub/publish.go | 57 +- .../lf-edge/eve/pkg/pillar/pubsub/stats.go | 157 ++++++ .../eve/pkg/pillar/pubsub/subscribe.go | 8 - .../lf-edge/eve/pkg/pillar/pubsub/util.go | 37 +- .../lf-edge/eve/pkg/pillar/sriov/sriov.go | 320 +++++++++--- .../pkg/pillar/types/assignableadapters.go | 486 +++++++++++++----- .../eve/pkg/pillar/types/cachedresolvedip.go | 79 --- .../eve/pkg/pillar/types/clustertypes.go | 196 ++++++- .../eve/pkg/pillar/types/contenttreetypes.go | 6 + .../types/deferredcontentdeletetypes.go | 72 +++ .../eve/pkg/pillar/types/diskmetrics.go | 15 +- .../lf-edge/eve/pkg/pillar/types/dns.go | 43 +- .../eve/pkg/pillar/types/domainmgrtypes.go | 101 +++- .../lf-edge/eve/pkg/pillar/types/dpc.go | 27 + .../eve/pkg/pillar/types/errorbound.go | 103 ++++ .../lf-edge/eve/pkg/pillar/types/errortime.go | 1 + .../eve/pkg/pillar/types/evaluation.go | 306 ----------- .../lf-edge/eve/pkg/pillar/types/global.go | 319 +++++++++++- .../eve/pkg/pillar/types/ifnametopci.go | 57 +- .../eve/pkg/pillar/types/locationconsts.go | 39 +- .../lf-edge/eve/pkg/pillar/types/memory.go | 46 +- .../eve/pkg/pillar/types/mgmtproxytypes.go | 48 ++ .../eve/pkg/pillar/types/vaultmgrtypes.go | 124 +++++ .../eve/pkg/pillar/types/volumetypes.go | 51 +- .../eve/pkg/pillar/types/zedagenttypes.go | 34 +- .../eve/pkg/pillar/types/zedcloudmetrics.go | 37 ++ .../eve/pkg/pillar/types/zedkubetypes.go | 74 +++ .../eve/pkg/pillar/types/zedmanagertypes.go | 22 + .../eve/pkg/pillar/types/zedroutertypes.go | 70 ++- .../lf-edge/eve/pkg/pillar/types/zfs.go | 16 + .../eve/pkg/pillar/utils/cgroup/cgroup.go | 88 ++++ .../eve/pkg/pillar/utils/cgroup/notify.go | 110 ++++ .../pillar/utils/cloudconfig/cloudconfig.go | 49 +- .../pillar/utils/cloudconfig/rootedwrite.go | 425 +++++++++++++++ .../lf-edge/eve/pkg/pillar/utils/file/file.go | 42 +- .../github.com/sirupsen/logrus/.golangci.yml | 95 ++-- .../github.com/sirupsen/logrus/CHANGELOG.md | 4 +- .../github.com/sirupsen/logrus/README.md | 126 ++--- .../github.com/sirupsen/logrus/appveyor.yml | 16 +- .../github.com/sirupsen/logrus/entry.go | 25 +- .../github.com/sirupsen/logrus/hooks.go | 8 +- .../github.com/sirupsen/logrus/logger.go | 34 +- .../github.com/sirupsen/logrus/logrus.go | 20 +- .../sirupsen/logrus/terminal_check_bsd.go | 2 +- .../sirupsen/logrus/terminal_check_unix.go | 2 + .../sirupsen/logrus/terminal_check_wasi.go | 8 + .../sirupsen/logrus/terminal_check_wasip1.go | 8 + .../sirupsen/logrus/text_formatter.go | 3 +- .../vendor/golang.org/x/net/html/entity.go | 5 +- .../vendor/golang.org/x/net/html/escape.go | 140 +++-- .../vendor/golang.org/x/net/html/foreign.go | 2 +- .../vendor/golang.org/x/net/html/parse.go | 249 +++------ .../vendor/golang.org/x/net/html/token.go | 41 +- .../golang.org/x/net/http2/hpack/encode.go | 1 - .../golang.org/x/net/http2/hpack/hpack.go | 1 - .../golang.org/x/net/http2/hpack/tables.go | 51 +- .../golang.org/x/net/http2/server_wrap.go | 16 + .../golang.org/x/net/http2/transport_wrap.go | 88 ++-- .../vendor/golang.org/x/net/idna/idna.go | 6 +- .../vendor/golang.org/x/sys/cpu/parse.go | 62 ++- .../golang.org/x/sys/unix/syscall_linux.go | 1 + .../x/sys/unix/syscall_linux_386.go | 1 - .../x/sys/unix/syscall_linux_amd64.go | 1 - .../x/sys/unix/syscall_linux_arm.go | 1 - .../x/sys/unix/syscall_linux_arm64.go | 1 - .../x/sys/unix/syscall_linux_loong64.go | 1 - .../x/sys/unix/syscall_linux_mips64x.go | 1 - .../x/sys/unix/syscall_linux_mipsx.go | 1 - .../x/sys/unix/syscall_linux_ppc.go | 1 - .../x/sys/unix/syscall_linux_ppc64x.go | 1 - .../x/sys/unix/syscall_linux_riscv64.go | 1 - .../x/sys/unix/syscall_linux_s390x.go | 1 - .../x/sys/unix/syscall_linux_sparc64.go | 1 - .../golang.org/x/sys/unix/zerrors_linux.go | 8 +- .../golang.org/x/sys/unix/zsyscall_linux.go | 17 + .../x/sys/unix/zsyscall_linux_386.go | 17 - .../x/sys/unix/zsyscall_linux_amd64.go | 17 - .../x/sys/unix/zsyscall_linux_arm.go | 17 - .../x/sys/unix/zsyscall_linux_arm64.go | 17 - .../x/sys/unix/zsyscall_linux_loong64.go | 17 - .../x/sys/unix/zsyscall_linux_mips.go | 17 - .../x/sys/unix/zsyscall_linux_mips64.go | 17 - .../x/sys/unix/zsyscall_linux_mips64le.go | 17 - .../x/sys/unix/zsyscall_linux_mipsle.go | 17 - .../x/sys/unix/zsyscall_linux_ppc.go | 17 - .../x/sys/unix/zsyscall_linux_ppc64.go | 17 - .../x/sys/unix/zsyscall_linux_ppc64le.go | 17 - .../x/sys/unix/zsyscall_linux_riscv64.go | 17 - .../x/sys/unix/zsyscall_linux_s390x.go | 17 - .../x/sys/unix/zsyscall_linux_sparc64.go | 17 - .../golang.org/x/sys/unix/ztypes_linux.go | 76 +++ .../golang.org/x/sys/unix/ztypes_linux_386.go | 4 + .../x/sys/unix/ztypes_linux_amd64.go | 4 + .../golang.org/x/sys/unix/ztypes_linux_arm.go | 4 + .../x/sys/unix/ztypes_linux_arm64.go | 4 + .../x/sys/unix/ztypes_linux_loong64.go | 4 + .../x/sys/unix/ztypes_linux_mips.go | 4 + .../x/sys/unix/ztypes_linux_mips64.go | 4 + .../x/sys/unix/ztypes_linux_mips64le.go | 4 + .../x/sys/unix/ztypes_linux_mipsle.go | 4 + .../golang.org/x/sys/unix/ztypes_linux_ppc.go | 4 + .../x/sys/unix/ztypes_linux_ppc64.go | 4 + .../x/sys/unix/ztypes_linux_ppc64le.go | 4 + .../x/sys/unix/ztypes_linux_riscv64.go | 4 + .../x/sys/unix/ztypes_linux_s390x.go | 4 + .../x/sys/unix/ztypes_linux_sparc64.go | 4 + .../x/sys/windows/security_windows.go | 36 ++ .../x/sys/windows/syscall_windows.go | 8 +- .../golang.org/x/sys/windows/types_windows.go | 1 + .../x/text/unicode/norm/forminfo.go | 9 +- .../golang.org/x/text/unicode/norm/iter.go | 8 +- .../x/text/unicode/norm/normalize.go | 20 +- .../protobuf/internal/encoding/tag/tag.go | 11 +- .../protobuf/internal/encoding/text/decode.go | 115 +++-- .../protobuf/internal/filedesc/desc.go | 1 + .../protobuf/internal/filedesc/desc_lazy.go | 22 - .../protobuf/internal/genid/descriptor_gen.go | 1 + .../protobuf/internal/impl/codec_map.go | 6 + .../protobuf/internal/impl/decode.go | 3 +- .../protobuf/internal/impl/validate.go | 26 + .../protobuf/internal/version/version.go | 2 +- .../protobuf/proto/decode.go | 10 +- .../types/known/timestamppb/timestamp.pb.go | 13 +- pkg/vtpm/swtpm-vtpm/vendor/modules.txt | 29 +- 445 files changed, 13797 insertions(+), 5985 deletions(-) create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/evetpm.md create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence.go create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence_disabled.go create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/allocstats.go delete mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/large.go create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/stats.go delete mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/cachedresolvedip.go create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/deferredcontentdeletetypes.go create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/errorbound.go delete mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/evaluation.go create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/mgmtproxytypes.go create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/cgroup.go create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/notify.go create mode 100644 pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cloudconfig/rootedwrite.go create mode 100644 pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_wasi.go create mode 100644 pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_wasip1.go create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/evetpm.md create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence.go create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence_disabled.go create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/allocstats.go delete mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/large.go create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/stats.go delete mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/cachedresolvedip.go create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/deferredcontentdeletetypes.go create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/errorbound.go delete mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/evaluation.go create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/mgmtproxytypes.go create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/cgroup.go create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/notify.go create mode 100644 pkg/recovertpm/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cloudconfig/rootedwrite.go create mode 100644 pkg/recovertpm/src/vendor/github.com/sirupsen/logrus/terminal_check_wasi.go create mode 100644 pkg/recovertpm/src/vendor/github.com/sirupsen/logrus/terminal_check_wasip1.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/evetpm.md create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence_disabled.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/allocstats.go delete mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/large.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/stats.go delete mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/types/cachedresolvedip.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/types/deferredcontentdeletetypes.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/types/errorbound.go delete mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/types/evaluation.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/types/mgmtproxytypes.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/cgroup.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/notify.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cloudconfig/rootedwrite.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/sirupsen/logrus/terminal_check_wasi.go create mode 100644 pkg/vtpm/swtpm-vtpm/vendor/github.com/sirupsen/logrus/terminal_check_wasip1.go diff --git a/evetest/go.mod b/evetest/go.mod index ca8a980c183..0ab7cfc62f2 100644 --- a/evetest/go.mod +++ b/evetest/go.mod @@ -11,13 +11,13 @@ require ( github.com/charmbracelet/x/ansi v0.8.0 github.com/containerd/errdefs v1.0.0 github.com/distribution/reference v0.6.0 - github.com/docker/cli v29.6.2+incompatible + github.com/docker/cli v29.7.2+incompatible github.com/google/go-cmp v0.7.0 - github.com/google/go-containerregistry v0.21.9 + github.com/google/go-containerregistry v0.22.1 github.com/google/uuid v1.6.0 github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 github.com/lf-edge/eve-api/go v0.0.0-20261015104443-e46e4c3a39ce - github.com/lf-edge/eve/pkg/pillar v0.0.0-20260908064046-68014620df6f + github.com/lf-edge/eve/pkg/pillar v0.0.0-20261104204650-27a85cc06c69 github.com/luthermonson/go-proxmox v0.8.0 github.com/moby/moby/api v1.55.0 github.com/moby/moby/client v0.5.1 @@ -61,7 +61,7 @@ require ( github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/gabriel-vasile/mimetype v1.4.2 // indirect - github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect @@ -71,10 +71,10 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jinzhu/copier v0.4.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.19.1 // indirect + github.com/klauspost/compress v1.19.2 // indirect github.com/kr/fs v0.1.0 // indirect github.com/leodido/go-urn v1.2.4 // indirect - github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20240315102754-0f6d1f182e0d // indirect + github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20261015084011-20eade920485 // indirect github.com/lucasb-eyer/go-colorful v1.4.1 // indirect github.com/magefile/mage v1.14.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect @@ -100,14 +100,14 @@ require ( github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect - go.opentelemetry.io/otel v1.44.0 // indirect - go.opentelemetry.io/otel/metric v1.44.0 // indirect - go.opentelemetry.io/otel/trace v1.44.0 // indirect + go.opentelemetry.io/otel v1.45.0 // indirect + go.opentelemetry.io/otel/metric v1.45.0 // indirect + go.opentelemetry.io/otel/trace v1.45.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/net v0.58.0 // indirect golang.org/x/sync v0.22.0 // indirect golang.org/x/text v0.41.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa + google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/api v0.33.5 // indirect diff --git a/evetest/go.sum b/evetest/go.sum index 8dbec61adeb..97a7a044496 100644 --- a/evetest/go.sum +++ b/evetest/go.sum @@ -43,8 +43,8 @@ github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5Qvfr github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c= github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0= -github.com/docker/cli v29.6.2+incompatible h1:/bjePvcbbFTnRrMfWJBY7AjfICdsiLVgHn6LwTVOcqw= -github.com/docker/cli v29.6.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/cli v29.7.2+incompatible h1:dlkwallR8XqfeVnA2ELEhdwvb4lsSwuB4IgsG8Q9cLY= +github.com/docker/cli v29.7.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/docker-credential-helpers v0.9.3 h1:gAm/VtF9wgqJMoxzT3Gj5p4AqIjCBS4wrsOh9yRqcz8= github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo= github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= @@ -68,8 +68,8 @@ github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXE github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= @@ -94,8 +94,8 @@ github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-containerregistry v0.21.9 h1:F+D4uZ3iA3DLMJLfhaqMdHJbzeqm/216WGQq2dokuLs= -github.com/google/go-containerregistry v0.21.9/go.mod h1:dP5XNKcL7kMFF/TB3LfvWmVhAcv7iqkHb3oDK8aauTo= +github.com/google/go-containerregistry v0.22.1 h1:RZuuSYhTvlDvtsK+NkutoCZ//C0X2ebLK8X8l3ULs84= +github.com/google/go-containerregistry v0.22.1/go.mod h1:bJR35SK8XgisYmhg/FMQ/5RK0S/XrOAqLBV5/LR2XE0= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/vP9vJGqPwcdqsWjOt+V8J7+bTc= github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= @@ -115,8 +115,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 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.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= -github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= +github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -127,10 +127,10 @@ github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= github.com/lf-edge/eve-api/go v0.0.0-20261015104443-e46e4c3a39ce h1:rmKaUyMA4frXWagYo1WN5Zt6/5iV0W26OnTpQ87+ueE= github.com/lf-edge/eve-api/go v0.0.0-20261015104443-e46e4c3a39ce/go.mod h1:6HxNA/qKJVEqwpuOFkcQ0h3QyotvAs/cjHLC961FPOY= -github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20240315102754-0f6d1f182e0d h1:tUBb9M6u42LXwHAYHyh22wJeUUQlTpDkXwRXalpRqbo= -github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20240315102754-0f6d1f182e0d/go.mod h1:Nn3juMJJ1G8dyHOebdZyS4jOB/fuxAd5fIajBaWjHr8= -github.com/lf-edge/eve/pkg/pillar v0.0.0-20260908064046-68014620df6f h1:7sdKscHejbA7ivGq3cFyB0MBRGTa7J776XxHmrcISMY= -github.com/lf-edge/eve/pkg/pillar v0.0.0-20260908064046-68014620df6f/go.mod h1:d5oL5xkNtDg9z0s0MqsjSi+Bza+W+6dkuEkD2VBYFug= +github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20261015084011-20eade920485 h1:UI1G5IeecS+6wwO9LVEwstKkgZ9y9WvdSvwS44Qed6M= +github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20261015084011-20eade920485/go.mod h1:Vq745ozk94M81lIQlQIQv88kvgYAWvO7/5OnCrRiCQc= +github.com/lf-edge/eve/pkg/pillar v0.0.0-20261104204650-27a85cc06c69 h1:KXs5Zcmh/iftWVmBRxZAGJjvHxxpRI4f7uTJ7XYRL7o= +github.com/lf-edge/eve/pkg/pillar v0.0.0-20261104204650-27a85cc06c69/go.mod h1:zT+D/+vZZET6RrTQmDNYbCUcGnXntvvEMem2tySWs9w= github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/luthermonson/go-proxmox v0.8.0 h1:KwrgeLrTXTlAezj7zt/tU4bm70VFQiJfej/5sL8rqO8= @@ -233,16 +233,16 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= -go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= -go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= -go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= -go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= -go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= -go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= -go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= -go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= -go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= -go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= +go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= +go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= +go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= +go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= +go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= +go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= +go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= +go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= +go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -264,8 +264,8 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= -golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= +golang.org/x/mod v0.39.0 h1:UF5zwQdCRRUpHfyPwr7d4UrGiVeldIsogtzWVnczL74= +golang.org/x/mod v0.39.0/go.mod h1:bvIbwjQ0HUFFf5AKukeeYQG4ZBUG9yxQbR9aEweIwYY= golang.org/x/net v0.0.0-20181129055619-fae4c4e3ad76/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -342,16 +342,16 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= -golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= -golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= +golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= +golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= diff --git a/evetest/sdn/vm/go.mod b/evetest/sdn/vm/go.mod index bc40ee30d9a..8ffd71cafd2 100644 --- a/evetest/sdn/vm/go.mod +++ b/evetest/sdn/vm/go.mod @@ -10,7 +10,7 @@ require ( github.com/inconshreveable/go-vhost v1.0.0 github.com/lf-edge/eve-libs v0.0.0-20260928172040-a59ba20797d0 github.com/lf-edge/eve/evetest v0.0.0-20260820145609-63ab025d6185 - github.com/lf-edge/eve/pkg/pillar v0.0.0-20260421125048-8d3825045e4e + github.com/lf-edge/eve/pkg/pillar v0.0.0-20261104204650-27a85cc06c69 github.com/sirupsen/logrus v1.9.4 github.com/vishvananda/netlink v1.3.1 github.com/vishvananda/netns v0.0.5 @@ -25,7 +25,7 @@ require ( github.com/containerd/errdefs v1.0.0 // indirect github.com/containerd/errdefs/pkg v0.3.0 // indirect github.com/distribution/reference v0.6.0 // indirect - github.com/docker/cli v29.6.2+incompatible // indirect + github.com/docker/cli v29.7.2+incompatible // indirect github.com/docker/docker-credential-helpers v0.9.3 // indirect github.com/docker/go-connections v0.7.0 // indirect github.com/docker/go-units v0.5.0 // indirect @@ -57,5 +57,5 @@ require ( go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/net v0.58.0 // indirect golang.org/x/text v0.41.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260720211330-0afa2a65878a // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect ) diff --git a/evetest/sdn/vm/go.sum b/evetest/sdn/vm/go.sum index 9ae03a51c23..ec2d9910344 100644 --- a/evetest/sdn/vm/go.sum +++ b/evetest/sdn/vm/go.sum @@ -10,8 +10,8 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1 github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/docker/cli v29.6.2+incompatible h1:/bjePvcbbFTnRrMfWJBY7AjfICdsiLVgHn6LwTVOcqw= -github.com/docker/cli v29.6.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/cli v29.7.2+incompatible h1:dlkwallR8XqfeVnA2ELEhdwvb4lsSwuB4IgsG8Q9cLY= +github.com/docker/cli v29.7.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/docker-credential-helpers v0.9.3 h1:gAm/VtF9wgqJMoxzT3Gj5p4AqIjCBS4wrsOh9yRqcz8= github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo= github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= @@ -53,8 +53,8 @@ github.com/lf-edge/eve-libs v0.0.0-20260928172040-a59ba20797d0 h1:u7tFrmeaqkuIc0 github.com/lf-edge/eve-libs v0.0.0-20260928172040-a59ba20797d0/go.mod h1:TXOpIgx9kwsunYgGcyTAAJvI+faOAd+PWk7p8mt0I8Y= github.com/lf-edge/eve/evetest v0.0.0-20260820145609-63ab025d6185 h1:agtPP9iMc5xt+dOiQuCLILIs0MfzNiVfWB1H63xOudg= github.com/lf-edge/eve/evetest v0.0.0-20260820145609-63ab025d6185/go.mod h1:0rjyNSuw/de5os1UZon3oguCZbVmi0m1s1KxQWS678M= -github.com/lf-edge/eve/pkg/pillar v0.0.0-20260421125048-8d3825045e4e h1:MGhvM4TrXHYyssTTcEkpc79zatoZ1oJRrrbjTU++ps0= -github.com/lf-edge/eve/pkg/pillar v0.0.0-20260421125048-8d3825045e4e/go.mod h1:Zx1ZEowId6xn7o9qGVNymtxc87muRObab6SofXZCXUk= +github.com/lf-edge/eve/pkg/pillar v0.0.0-20261104204650-27a85cc06c69 h1:KXs5Zcmh/iftWVmBRxZAGJjvHxxpRI4f7uTJ7XYRL7o= +github.com/lf-edge/eve/pkg/pillar v0.0.0-20261104204650-27a85cc06c69/go.mod h1:zT+D/+vZZET6RrTQmDNYbCUcGnXntvvEMem2tySWs9w= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc= @@ -121,8 +121,8 @@ golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260720211330-0afa2a65878a h1:qI/YMH1ep2qQtqcp00gMQyoU7mjvbhg88GJKCvfoLj0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260720211330-0afa2a65878a/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= diff --git a/pkg/installer/src/go.mod b/pkg/installer/src/go.mod index 4ad833f6674..ba95a5c933a 100644 --- a/pkg/installer/src/go.mod +++ b/pkg/installer/src/go.mod @@ -6,9 +6,9 @@ toolchain go1.25.11 require ( github.com/google/go-tpm v0.9.1 - github.com/lf-edge/eve/pkg/pillar v0.0.0-20260521051436-614efc1c3bb7 + github.com/lf-edge/eve/pkg/pillar v0.0.0-20261104204650-27a85cc06c69 github.com/satori/go.uuid v1.2.1-0.20180404165556-75cca531ea76 - github.com/sirupsen/logrus v1.9.3 + github.com/sirupsen/logrus v1.9.4 ) require ( @@ -16,28 +16,28 @@ require ( github.com/eriknordmark/ipinfo v0.0.0-20230728132417-2d8f4da903d7 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/gabriel-vasile/mimetype v1.4.2 // indirect - github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/logr v1.4.4 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.15.5 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/go-cmp v0.7.0 // indirect - github.com/google/go-containerregistry v0.14.0 // indirect + github.com/google/go-containerregistry v0.22.1 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.2.4 // indirect github.com/lf-edge/eve-api/go v0.0.0-20261015104443-e46e4c3a39ce // indirect - github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20240315102754-0f6d1f182e0d // indirect + github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20261015084011-20eade920485 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/vishvananda/netlink v1.3.1 // indirect github.com/vishvananda/netns v0.0.5 // indirect github.com/x448/float16 v0.8.4 // indirect - golang.org/x/crypto v0.52.0 // indirect - golang.org/x/net v0.55.0 // indirect - golang.org/x/sys v0.45.0 // indirect - golang.org/x/text v0.37.0 // indirect - google.golang.org/protobuf v1.36.10 // indirect + golang.org/x/crypto v0.55.0 // indirect + golang.org/x/net v0.58.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect k8s.io/api v0.33.5 // indirect diff --git a/pkg/installer/src/go.sum b/pkg/installer/src/go.sum index d0579f5c719..2aa176a7ab4 100644 --- a/pkg/installer/src/go.sum +++ b/pkg/installer/src/go.sum @@ -5,6 +5,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/eriknordmark/ipinfo v0.0.0-20230728132417-2d8f4da903d7 h1:25R+h8+75+zyY0+/6TfUsz/arhEltIwNMgDH6IGJ/tc= github.com/eriknordmark/ipinfo v0.0.0-20230728132417-2d8f4da903d7/go.mod h1:m5kR+NOoKCuA5r6T+9f7q7VfPjPhHskhmxRAebb7avM= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= @@ -13,8 +15,8 @@ github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= @@ -28,8 +30,8 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69 github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-containerregistry v0.14.0 h1:z58vMqHxuwvAsVwvKEkmVBz2TlgBgH5k6koEXBtlYkw= -github.com/google/go-containerregistry v0.14.0/go.mod h1:aiJ2fp/SXvkWgmYHioXnbMdlgB8eXiiYOY55gfN91Wk= +github.com/google/go-containerregistry v0.22.1 h1:RZuuSYhTvlDvtsK+NkutoCZ//C0X2ebLK8X8l3ULs84= +github.com/google/go-containerregistry v0.22.1/go.mod h1:bJR35SK8XgisYmhg/FMQ/5RK0S/XrOAqLBV5/LR2XE0= github.com/google/go-tpm v0.9.1 h1:0pGc4X//bAlmZzMKf8iz6IsDo1nYTbYJ6FZN/rg4zdM= github.com/google/go-tpm v0.9.1/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -37,6 +39,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 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.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= +github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -45,10 +49,10 @@ github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= github.com/lf-edge/eve-api/go v0.0.0-20261015104443-e46e4c3a39ce h1:rmKaUyMA4frXWagYo1WN5Zt6/5iV0W26OnTpQ87+ueE= github.com/lf-edge/eve-api/go v0.0.0-20261015104443-e46e4c3a39ce/go.mod h1:6HxNA/qKJVEqwpuOFkcQ0h3QyotvAs/cjHLC961FPOY= -github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20240315102754-0f6d1f182e0d h1:tUBb9M6u42LXwHAYHyh22wJeUUQlTpDkXwRXalpRqbo= -github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20240315102754-0f6d1f182e0d/go.mod h1:Nn3juMJJ1G8dyHOebdZyS4jOB/fuxAd5fIajBaWjHr8= -github.com/lf-edge/eve/pkg/pillar v0.0.0-20260521051436-614efc1c3bb7 h1:hnrzxv2c6O6UZDicBmsd6dNEDdblH8KE3dlOoSy4EGM= -github.com/lf-edge/eve/pkg/pillar v0.0.0-20260521051436-614efc1c3bb7/go.mod h1:HFvZLjsD+i+yizWd5uPqCfKD9CTBXR1LkMIOGUba3JQ= +github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20261015084011-20eade920485 h1:UI1G5IeecS+6wwO9LVEwstKkgZ9y9WvdSvwS44Qed6M= +github.com/lf-edge/eve/pkg/kube/cnirpc v0.0.0-20261015084011-20eade920485/go.mod h1:Vq745ozk94M81lIQlQIQv88kvgYAWvO7/5OnCrRiCQc= +github.com/lf-edge/eve/pkg/pillar v0.0.0-20261104204650-27a85cc06c69 h1:KXs5Zcmh/iftWVmBRxZAGJjvHxxpRI4f7uTJ7XYRL7o= +github.com/lf-edge/eve/pkg/pillar v0.0.0-20261104204650-27a85cc06c69/go.mod h1:zT+D/+vZZET6RrTQmDNYbCUcGnXntvvEMem2tySWs9w= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -63,15 +67,14 @@ github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/satori/go.uuid v1.2.1-0.20180404165556-75cca531ea76 h1:ofyVTM1w4iyKwaQIlRR6Ip06mXXx5Cnz7a4mTGYq1hE= github.com/satori/go.uuid v1.2.1-0.20180404165556-75cca531ea76/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= -github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= @@ -88,31 +91,30 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= -golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= +golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= +golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= -golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= +golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= -golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= -golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -121,8 +123,8 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= -google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= diff --git a/pkg/installer/src/vendor/github.com/go-logr/logr/context_noslog.go b/pkg/installer/src/vendor/github.com/go-logr/logr/context_noslog.go index f012f9a18e8..0a3d1a125e0 100644 --- a/pkg/installer/src/vendor/github.com/go-logr/logr/context_noslog.go +++ b/pkg/installer/src/vendor/github.com/go-logr/logr/context_noslog.go @@ -1,5 +1,4 @@ //go:build !go1.21 -// +build !go1.21 /* Copyright 2019 The logr Authors. diff --git a/pkg/installer/src/vendor/github.com/go-logr/logr/context_slog.go b/pkg/installer/src/vendor/github.com/go-logr/logr/context_slog.go index 065ef0b8280..c69eb01ba1b 100644 --- a/pkg/installer/src/vendor/github.com/go-logr/logr/context_slog.go +++ b/pkg/installer/src/vendor/github.com/go-logr/logr/context_slog.go @@ -1,5 +1,4 @@ //go:build go1.21 -// +build go1.21 /* Copyright 2019 The logr Authors. diff --git a/pkg/installer/src/vendor/github.com/go-logr/logr/sloghandler.go b/pkg/installer/src/vendor/github.com/go-logr/logr/sloghandler.go index 82d1ba49481..befaf5510fa 100644 --- a/pkg/installer/src/vendor/github.com/go-logr/logr/sloghandler.go +++ b/pkg/installer/src/vendor/github.com/go-logr/logr/sloghandler.go @@ -1,5 +1,4 @@ //go:build go1.21 -// +build go1.21 /* Copyright 2023 The logr Authors. diff --git a/pkg/installer/src/vendor/github.com/go-logr/logr/slogr.go b/pkg/installer/src/vendor/github.com/go-logr/logr/slogr.go index 28a83d02439..bfe80eb8d68 100644 --- a/pkg/installer/src/vendor/github.com/go-logr/logr/slogr.go +++ b/pkg/installer/src/vendor/github.com/go-logr/logr/slogr.go @@ -1,5 +1,4 @@ //go:build go1.21 -// +build go1.21 /* Copyright 2023 The logr Authors. diff --git a/pkg/installer/src/vendor/github.com/go-logr/logr/slogsink.go b/pkg/installer/src/vendor/github.com/go-logr/logr/slogsink.go index 4060fcbc2b0..ab76ea99fe6 100644 --- a/pkg/installer/src/vendor/github.com/go-logr/logr/slogsink.go +++ b/pkg/installer/src/vendor/github.com/go-logr/logr/slogsink.go @@ -1,5 +1,4 @@ //go:build go1.21 -// +build go1.21 /* Copyright 2023 The logr Authors. diff --git a/pkg/installer/src/vendor/github.com/google/go-containerregistry/pkg/v1/types/types.go b/pkg/installer/src/vendor/github.com/google/go-containerregistry/pkg/v1/types/types.go index efc6bd6b933..69878980b56 100644 --- a/pkg/installer/src/vendor/github.com/google/go-containerregistry/pkg/v1/types/types.go +++ b/pkg/installer/src/vendor/github.com/google/go-containerregistry/pkg/v1/types/types.go @@ -29,6 +29,7 @@ const ( OCIRestrictedLayer MediaType = "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip" OCIUncompressedLayer MediaType = "application/vnd.oci.image.layer.v1.tar" OCIUncompressedRestrictedLayer MediaType = "application/vnd.oci.image.layer.nondistributable.v1.tar" + OCIEmptyJSON MediaType = "application/vnd.oci.empty.v1+json" DockerManifestSchema1 MediaType = "application/vnd.docker.distribution.manifest.v1+json" DockerManifestSchema1Signed MediaType = "application/vnd.docker.distribution.manifest.v1+prettyjws" @@ -80,3 +81,19 @@ func (m MediaType) IsConfig() bool { } return false } + +func (m MediaType) IsSchema1() bool { + switch m { + case DockerManifestSchema1, DockerManifestSchema1Signed: + return true + } + return false +} + +func (m MediaType) IsLayer() bool { + switch m { + case DockerLayer, DockerUncompressedLayer, OCILayer, OCILayerZStd, OCIUncompressedLayer, DockerForeignLayer, OCIRestrictedLayer, OCIUncompressedRestrictedLayer: + return true + } + return false +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/kube/cnirpc/LICENSE b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/kube/cnirpc/LICENSE index 2c484691582..5be3f9bdae4 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/kube/cnirpc/LICENSE +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/kube/cnirpc/LICENSE @@ -204,4 +204,4 @@ This product bundles portions of the go net package, which is available under the BSD-style license. For details, see the netclone/README This product bundles portions of the go httpproxy package, which is -available under the BSD-style license. For details, see the zedcloud/proxy.go +available under the BSD-style license. For details, see pkg/pillar/controllerconn/proxy.go diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/kube/cnirpc/cnirpc.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/kube/cnirpc/cnirpc.go index cf73dd8de19..c54ebec69de 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/kube/cnirpc/cnirpc.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/kube/cnirpc/cnirpc.go @@ -18,6 +18,13 @@ type CommonCNIRPCArgs struct { Pod AppPod // Interface inside the pod. PodInterface NetInterfaceWithNs + // NetworkInstance : UUID of the EVE Network Instance that this interface attaches to, + // read by eve-bridge from the per-NI NAD CNI config ("networkInstance" field). + // Used for directly-deployed Kubernetes workloads, which carry no controller-assigned + // AppNetworkConfig: zedrouter has no pre-allocated adapter to match the inbound MAC against, + // so the NI identity must arrive explicitly. Empty for the controller-managed path, which + // continues to resolve the NI via the MAC-matched adapter. + NetworkInstance string } // CommonCNIRPCRetval : a set of values returned by every CNI RPC method. @@ -76,6 +83,11 @@ type CheckPodConnectionRetval struct { // It describes Kubernetes Pod under which a given app is running. type AppPod struct { Name string + // Namespace of the Kubernetes pod. Forwarded from K8S_POD_NAMESPACE. + // Needed for directly-deployed Kubernetes workloads so zedrouter can key on + // (Namespace, Name) — pod names are not unique across namespaces. Empty for the + // controller-managed path (which keys on the pod name only). + Namespace string // NetNsPath references network namespace of the Kubernetes pod // inside which the application is running. NetNsPath string diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/execwrapper.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/execwrapper.go index b84a0949bd3..93487de42b7 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/execwrapper.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/execwrapper.go @@ -18,10 +18,10 @@ import ( const ( /* - * execution timeout is supposed to be less than the watchdog timeout, - * as otherwise the watchdog might fire and reboot the system before - * the timeout fires - * exceptions are when an executable is started from a different goroutine + * timeoutLimit caps the timeout WithLimitedTimeout accepts: a command that + * hangs is then reported as an error rather than left to trip the + * watchdog. WithUnlimitedTimeout lifts the cap and instead relies on the + * touch-file refresh execCommand performs while waiting. * source of the error timeout and the watchdog timeout: * error timeout: $ grep -r errorTime pkg/pillar/cmd/ | grep time * watchdog timeout: $ grep hv_watchdog_timer pkg/grub/rootfs.cfg @@ -67,6 +67,21 @@ func (c *Command) CombinedOutput() ([]byte, error) { return c.execCommand() } +// ErrorOutput runs the command and returns only its standard error. Standard +// output is left unset, so os/exec connects it to the null device: use this +// for commands whose stdout is noise (progress bars, chatter) and whose +// failure reason is printed on stderr. +// Waits for the exec call to finish for `defaultTimeout` after which timeout error is returned +func (c *Command) ErrorOutput() ([]byte, error) { + var buf bytes.Buffer + c.command.Stderr = &buf + c.buffer = &buf + if c.timeout == 0 { + c.timeout = defaultTimeout + } + return c.execCommand() +} + func (c *Command) execCommand() ([]byte, error) { if c.errorMonad != nil { return nil, c.errorMonad @@ -79,8 +94,10 @@ func (c *Command) execCommand() ([]byte, error) { return nil, fmt.Errorf("execCommand(%v): error while starting command: %s", c.command.Args, err.Error()) } - // Use a channel to signal completion so we can use a select statement - done := make(chan error) + // Use a channel to signal completion so we can use a select statement. + // Buffered so the Wait() goroutine can always deliver its result and exit, + // even if execCommand already returned via the ctx-cancel or timeout branch. + done := make(chan error, 1) go func() { done <- c.command.Wait() }() stillRunning := time.NewTicker(25 * time.Second) defer stillRunning.Stop() @@ -121,7 +138,13 @@ func (c *Command) WithLimitedTimeout(timeout time.Duration) *Command { return c } -// WithUnlimitedTimeout set custom timeout for command not bound to any limits for when run in a separate goroutine +// WithUnlimitedTimeout sets a timeout for the command that is not capped by +// timeoutLimit. While waiting, execCommand refreshes the calling agent's +// watchdog touch file every 25 seconds, so a timeout longer than the watchdog +// interval is safe on an agent's main goroutine as well. That refresh requires +// getAgentName to resolve an agent from the calling goroutine's stack, which +// only holds when a pkg/pillar/cmd/ frame is on it: a command issued +// from a goroutine started inside a library package gets no refresh. func (c *Command) WithUnlimitedTimeout(timeout time.Duration) *Command { c.timeout = timeout diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/kubevirt.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/kubevirt.go index 3ca17106602..6933adafb65 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/kubevirt.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/kubevirt.go @@ -14,7 +14,7 @@ import ( ) const ( - // EveVirtTypeFile contains the virtualization type, i.e., kvm, xen or k + // EveVirtTypeFile contains the virtualization type, i.e., kvm or k EveVirtTypeFile = "/run/eve-hv-type" // KubeAppNameMaxLen limits the length of the app name for Kubernetes. // This also includes the appended UUID prefix. @@ -31,6 +31,12 @@ const ( DefaultEtcdSizeGB uint32 = 10 // EtcdVolBlockSizeBytes is the block size for the etcd volume EtcdVolBlockSizeBytes = uint64(4 * 1024) + // InstallOptionWitnessZvol grub option at install time. Reserves a + // zvol for the 2-node-HA witness, sized from InstallOptionEtcdSizeGB. + // Presence enables it; there is no value. Only meaningful on ZFS, + // where the vault zvol otherwise claims the whole remaining pool and + // leaves nothing to carve out later. + InstallOptionWitnessZvol = "eve_install_k3s_witness" // KubevirtHypervisorName is the name of the imaginary EVE 'k' hypervisor KubevirtHypervisorName = "k" ) @@ -72,16 +78,21 @@ var ( kubeNameSeparators = regexp.MustCompile("[.-]+") ) +// SanitizeKubeName converts an arbitrary display name into a DNS-1123-compatible +// fragment usable inside a Kubernetes object name: underscores become dashes, +// other forbidden characters are dropped, runs of '.'/'-' collapse to a single +// dash, and the result is lowercased. It does NOT guarantee uniqueness - callers +// that need a unique object name must append a discriminator (e.g. a UUID suffix). +func SanitizeKubeName(displayName string) string { + name := strings.ReplaceAll(displayName, "_", "-") + name = kubeNameForbiddenChars.ReplaceAllString(name, "") + name = kubeNameSeparators.ReplaceAllString(name, "-") + return strings.ToLower(name) +} + // GetAppKubeName returns name of the application used inside Kubernetes (for Pod or VMI). func GetAppKubeName(displayName string, uuid uuid.UUID) string { - appKubeName := displayName - // Replace underscores with dashes for Kubernetes - appKubeName = strings.ReplaceAll(appKubeName, "_", "-") - // Remove special characters using regular expressions - appKubeName = kubeNameForbiddenChars.ReplaceAllString(appKubeName, "") - // Reduce combinations like '-.-' or '.-.' to a single dash - appKubeName = kubeNameSeparators.ReplaceAllString(appKubeName, "-") - appKubeName = strings.ToLower(appKubeName) + appKubeName := SanitizeKubeName(displayName) const maxLen = KubeAppNameMaxLen - 1 - KubeAppNameUUIDSuffixLen if len(appKubeName) > maxLen { appKubeName = appKubeName[:maxLen] @@ -97,6 +108,41 @@ func GetAppKubeNameWithPurge(displayName string, id uuid.UUID, purgeCounter uint return GetAppKubeName(displayName, id) + "-" + strconv.FormatUint(uint64(purgeCounter), 10) } +// kubeAppUUIDSeed seeds the v5 UUID derivation for directly-deployed Kubernetes workloads. +// It is a fixed constant so the derivation is stable across reboots, nodes, and EVE versions. +var kubeAppUUIDSeed = uuid.NewV5(uuid.NamespaceOID, "eve-kube-app-network-id") + +// rsPodSuffix matches the 5-character lowercase-alphanumeric suffix that the ReplicaSet +// controller appends to pod names ("-"). +var rsPodSuffix = regexp.MustCompile(`^[a-z0-9]{5}$`) + +// KubeAppUUID derives a stable, cluster-consistent synthetic appUUID for a directly-deployed +// Kubernetes workload (helm/raw yaml) that has no EVE controller-assigned UUID. It is a pure +// function of (namespace, ownerName) so every cluster node derives the identical value — +// which keeps the ClusterDeterministic MAC stable across reboot and migration. +func KubeAppUUID(namespace, ownerName string) uuid.UUID { + return uuid.NewV5(kubeAppUUIDSeed, namespace+"/"+ownerName) +} + +// KubePodMatchesOwner reports whether podName is either an ownerless bare Pod (whose synthesized +// ownerName is the pod name itself) or a pod of the bare ReplicaSet ownerName, with the form +// "-<5 lowercase-alnum chars>". Validating the suffix shape (rather than a plain +// prefix check) disambiguates nested owner names such as "app" vs "app-foo": +// "app-foo-x2k4p" matches only "app-foo", since "foo-x2k4p" is not a valid suffix. +func KubePodMatchesOwner(podName, ownerName string) bool { + if ownerName == "" { + return false + } + if podName == ownerName { + return true + } + prefix := ownerName + "-" + if !strings.HasPrefix(podName, prefix) { + return false + } + return rsPodSuffix.MatchString(podName[len(prefix):]) +} + // GetVMINameFromVirtLauncher extracts VMI name and ReplicaSet name from a Kubevirt // launcher pod name. // Pod name format: virt-launcher--<5-char-pod-suffix> diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/logobjecttypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/logobjecttypes.go index d873241bd5c..709fedf616a 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/logobjecttypes.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/logobjecttypes.go @@ -77,6 +77,8 @@ const ( ContentTreeConfigLogType LogObjectType = "contenttree_config" // ContentTreeStatusLogType : ContentTreeStatusLogType LogObjectType = "contenttree_status" + // DeferredContentDeleteStatusLogType : + DeferredContentDeleteStatusLogType LogObjectType = "deferred_content_delete_status" // DevicePortConfig : object being logged DevicePortConfigLogType LogObjectType = "deviceport_config" // DevicePortConfigList : @@ -161,6 +163,8 @@ const ( SigUSR1StacksType LogObjectType = "sigusr1_stacks" // FatalStacksType: FatalStacksType LogObjectType = "fatal_stacks" + // KernelPanicStacksType: Linux kernel log of a panic, read from pstore + KernelPanicStacksType LogObjectType = "kernel_panic_stacks" // MemoryNotificationType MemoryNotificationType = "memory_notification" // DiskNotificationType @@ -171,14 +175,10 @@ const ( EncryptedVaultKeyFromDeviceLogType LogObjectType = "encrypted_vault_key_from_device" // EncryptedVaultKeyFromControllerLogType: EncryptedVaultKeyFromControllerLogType LogObjectType = "encrypted_vault_key_from_controller" - // CachedResolvedIPsLogType: - CachedResolvedIPsLogType LogObjectType = "cached_resolved_ips" // AppMACGeneratorLogType : type for AppMACGenerator log entries AppMACGeneratorLogType LogObjectType = "app_mac_generator" // KubeAppFailover KubeAppFailover LogObjectType = "kube_app_failover" - // EvalStatusLogType : type for EvalStatus log entries - EvalStatusLogType LogObjectType = "eval_status" ) // RelationObjectType : diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/round.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/round.go index d8c1c350f75..3b56c8ea921 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/round.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/base/round.go @@ -14,11 +14,16 @@ func RoundToMbytes(byteCount uint64) uint64 { return (byteCount + mbyte/2) / mbyte } -// RoundUpToMbytes - Bytes converted to Mbytes with round-up +// RoundUpToMbytes - Bytes converted to Mbytes with round-up; cannot overflow, +// even for math.MaxUint64 (cgroup.Unlimited) func RoundUpToMbytes(byteCount uint64) uint64 { const mbyte = 1 << 20 - return (byteCount + mbyte - 1) / mbyte + mb := byteCount / mbyte + if byteCount%mbyte != 0 { + mb++ + } + return mb } // ClampToUint32 - ensure it doesn't exceed MaxUint32 diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/evetpm.md b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/evetpm.md new file mode 100644 index 00000000000..356d12cdae2 --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/evetpm.md @@ -0,0 +1,338 @@ +# evetpm: Shared TPM 2.0 Primitive Layer + +## Overview + +`pkg/pillar/evetpm` is the Go library that every pillar component +which touches the TPM goes through. It owns the +on-TPM data layout for EVE (well-known persistent handles, NV +indices, PCR selections, disk-key seal blobs, policy-PCR bookkeeping) +and exposes the primitives — probe, sign, encrypt/decrypt, seal/unseal, +PCR policy — that the microservices above it compose into product +behaviour. It is not itself a microservice; it has no `Run()`, no +pubsub, and no long-lived state of its own beyond what it stores in +the TPM or on disk on behalf of its callers. + +The boundary against the microservices is intentionally narrow: + +* **`evetpm`** decides *what* the on-TPM layout looks like (which + handles, which NV indices, which PCRs go into a disk-key policy, + how the policy digest is computed) and provides the operations + (`SealDiskKey`, `UnsealDiskKey`, `EncryptDecryptUsingTpm`, + `TpmSign`, …) that mutate or read it. It opens `/dev/tpmrm0` on + every call and closes it again; it holds no TPM session across + calls. +* **`tpmmgr`** drives provisioning and attestation against that + layout — see [`pkg/pillar/docs/tpmmgr.md`](../docs/tpmmgr.md). +* **`vaultmgr`** drives disk-key seal/unseal on top of + `SealDiskKey` / `UnsealDiskKey` / `FetchSealedVaultKey`. +* **`zedagent`** and **`controllerconn`** use the encrypt/decrypt + and signing primitives for cert hashing, the attestation FSM, and + the device-key-signed authentication to the controller. + +EVE targets the TPM 2.0 revision. A TPM 1.0 device or a TPM 2.0 that +fails the runtime check in `IsTpmEnabled` is treated as "no usable +TPM"; callers branch into their soft (on-disk key) paths and the +TPM-rooted operations in this package are skipped. + +## On-TPM Data Layout + +The package owns the global EVE convention for what lives where on +the TPM. Other pillar code references these constants rather than +hard-coding handle values. The microservice doc +[`pkg/pillar/docs/tpmmgr.md`](../docs/tpmmgr.md#key-inputoutput) +summarises the same table from the operator's perspective; this +section is the canonical statement. + +### Persistent key handles + +| Constant | Handle | Purpose | +|---|---|---| +| `TpmEKHdl` | `0x81000001` | Endorsement Key (RSA-2048, restricted decrypt). Created from the TCG standard EK template (`DefaultEkTemplate`). | +| `TpmSRKHdl` | `0x81000002` | Storage Root Key (RSA-2048, restricted decrypt). Parent for sealed objects. | +| `TpmAIKHdl` | `0x81000003` | Attestation Key (AK; RSA-2048, restricted signing). Used in the vTPM credential-activation flow. The constant identifier retains the TPM 1.2 "AIK" name; the TPM 2.0 spec calls it AK. | +| `TpmQuoteKeyHdl` | `0x81000004` | PCR Quote signing key (ECC P-256, restricted signing). | +| `TpmEcdhKeyHdl` | `0x81000005` | ECDH key (ECC P-256). Used both for ECDH key derivation in `EncryptDecryptUsingTpm` / `DecryptSecretWithEcdhKey` and by `vaultmgr` for vault-key wrap/unwrap. | +| `TpmDeviceKeyHdl` | `0x817FFFFF` | Long-lived ECDSA device-identity key. The certificate at `/config/device.cert.pem` chains to this. | + +### NV indices + +| Constant | Handle | Contents | +|---|---|---| +| `TpmDeviceCertHdl` | `0x1500000` | Backup copy of `/config/device.cert.pem`. `tpmmgr` mirrors the device cert into NV at first boot so the cert survives a wipe of `/config`. | +| `TpmPasswdHdl` | `0x1600000` | TPM credentials (a UUID generated on first boot, truncated to `MaxPasswdLength` = 7 bytes by `ReadOwnerCrdl`). Mirrored at `/config/tpm_credential`. **Not** the owner-hierarchy password — every owner-hierarchy operation in `evetpm`/`tpmmgr` passes `EmptyPassword`. The credential is instead bound as the `userAuth` of the **device key** at creation time (`CreatePrimary`'s `inSensitive.userAuth` in `createDeviceKey`), and must subsequently be supplied to authorize that key in `TpmSign` and `ECDHZGen`. `vcomlink` also passes it as the auth value for caller-supplied NV / signing / certify operations. | +| `TpmDiskKeyHdl` | `0x1700000` | Legacy (un-sealed) disk key — random 32-byte raw key written via `writeDiskKey`. Pre-dates PCR-sealed vaults; carried forward for upgrade compatibility (see `FetchSealedVaultKey`). | +| `TpmSealedDiskPubHdl` | `0x1900000` | TPM2B_PUBLIC of the sealed disk-key object. Both the encrypted (`enc_seal.go`) and legacy (`tpm.go`) seal paths write here. | +| `TpmSealedDiskPrivHdl` | `0x1800000` | TPM2B_PRIVATE of the sealed disk-key object. | + +The legacy disk key at `TpmDiskKeyHdl` and the sealed pair at +`TpmSealedDiskPubHdl` / `TpmSealedDiskPrivHdl` can coexist on the +same device — see [Disk-key seal / unseal](#disk-key-seal--unseal) for +the migration logic. + +### PCR selections + +All PCR operations are in the SHA256 bank. The package exposes three +distinct selections, used for different things; conflating them is a +common source of bugs. + +| Variable | PCRs | Used for | +|---|---|---| +| `PcrSelection` | `{7}` | "Entropy" PCR selection passed to `CreatePrimary` when generating non-policy keys. The contents don't matter for the resulting key, but PCR 7 is stable across boots. | +| `PcrListForQuote` | `{0..15}` | Selection signed in `tpm2.Quote` for attestation. PCRs 16–23 are deliberately excluded. | +| `DefaultDiskKeySealingPCRs` | `{0,1,2,3,4,6,7,8,9,10,11,12,13,14}` | Default selection sealing the vault key. PCR 5 is excluded (`PCRIndexGPT`, which measures the GPT partition table — volatile across A/B image updates because EVE flips the IMGA/IMGB "active" vs "updating" attribute bits in the GPT header on every base-OS upgrade); PCR 15 is excluded (`PCRIndexOS`, reserved for OS / user use). | + +`ValidatePolicyPcr` enforces the constraints on any controller-supplied +selection: PCR 0 (`PCRIndexSRTM`) must be present, PCR 5 must not be +present, no duplicates, all indexes in `[0..15]`, total count ≤ 15 +(`PCRIndexMaxCount`). + +### Disk-key policy persistence + +The PCR selection actually used to seal the on-disk vault key is +persisted at `types.PolicyPcrFile` (`/persist/status/policy-pcr.json`), +serialised as `types.VaultKeyPolicyPCR{PolicyPresent, Indexes, ID}`. +The file is owned by this package — `GetDiskKeyPolicyPcrOrDefault`, +`SaveDiskKeyPolicyPcr`, `RecoverDiskKeyPolicyPcr`, and +`ValidatePolicyPcr` all read or write it under a file lock. + +The `ID` field distinguishes how the policy got there: + +* `> 0` — controller-supplied (the integer is the controller's policy + ID). +* `0` (`PolicyPCRRecoveredDefault`) — recovery succeeded with the + default PCR set. +* `-1` (`PolicyPCRRecovered`) — recovery searched the candidate space + and found a non-default subset that produces the digest baked into + the sealed object's `AuthPolicy`. + +`RecoverDiskKeyPolicyPcr` is the read-back path used when unseal +fails with the saved selection. It reads the `AuthPolicy` digest out +of the sealed object's public area +(`tpm2.NVReadEx(TpmSealedDiskPubHdl)` → +`tpm2.DecodePublic` → `pubData.AuthPolicy`) and brute-forces all +subsets of `PcrListForQuote.PCRs` against the current PCR values, +computing each candidate digest with `computePolicyPCRAuthDigest`. +With 16 candidate PCRs that is at most 2^16 trials — sub-millisecond +in practice. The recovered selection is persisted back to +`policy-pcr.json` so subsequent unseals can skip the search. + +`computePolicyPCRAuthDigest` reproduces the TPM's policy-digest +formula in software: + +```text +newPolicyDigest = SHA256( + oldPolicyDigest // 32 bytes of zero, since PolicyPCR + // is the first and only policy + || TPM_CC_PolicyPCR // 0x0000017F, big-endian + || TPML_PCR_SELECTION // Count | HashAlg | SizeOfSelect | bitmap + || SHA256(PCR_i ‖ PCR_j ‖ …) // digestTPM, PCRs concatenated in + // ascending index order +) +``` + +The bitmap is 3 bytes wide (sufficient for PCRs 0–23, matching the +`PcrListForQuote` range), MSB-first within each byte. + +### Other persistent state on disk + +| Path | Written by | Purpose | +|---|---|---| +| `/persist/status/sealingpcrs` (`savedSealingPcrsFile`) | `saveDiskKeySealingPCRs` after a successful seal | gob-encoded `map[int][]byte` of PCR values at seal time. Read by `FindMismatchingPCRs` to diagnose unseal failure. | +| `/persist/status/tpm_measurement_seal_success` (`measurementLogSealSuccess`) | `SealDiskKey` (and `-backup` rotation on re-seal) | Concatenation of `types.TpmMeasurementLogFile` + `types.TpmMeasurefsEventLog` at seal time. | +| `/persist/status/tpm_measurement_unseal_fail` (`measurementLogUnsealFail`) | `UnsealDiskKey` on failure | Same shape, captured at the failing unseal. Diffing this against `…_seal_success` is the operator's tool for "why did unseal fail?" | +| `/persist/status/boot_vars/success`, `…/fail` | `saveBootVariables` from the same call sites | EFI BootOrder + BootXXXX variables copied from `/hostfs/sys/firmware/efi/efivars/`, with the GUID suffix stripped. | + +`GetTpmLogFileNames`, `GetTpmLogBackupFileNames`, and +`GetBootVariablesDirNames` are the public accessors `monitor` and +similar tools use to reach the log paths without hard-coding them. + +## Public API Surface + +### Capability / probe + +| Function | What it returns | +|---|---| +| `IsTpmEnabled() bool` | `true` iff `/config/device.cert.pem` exists and `/config/device.key.pem` does not. The presence of the soft key file is the canonical "TPM path failed at provisioning time" marker. Before `tpmmgr createDeviceCert` has run (no cert file yet) it returns `false`, which is correct: a not-yet-provisioned device has no TPM-rooted identity. | +| `PCRBankSHA256Enabled() bool` | Cached probe: reads PCR 0 in the SHA256 bank once and remembers the result in `pcrBank256Status`. False on no-TPM platforms or TPMs without a SHA256 bank. | +| `FetchTpmSwStatus() info.HwSecurityModuleStatus` | `NOTFOUND` / `DISABLED` / `ENABLED` for the controller report. | +| `FetchTpmHwInfo() / FetchTpmHwInfoDescription() (string, error)` | "`-, FW Version `" string for the controller report. Returns `ErrNoTPM` on no-TPM platforms (or `""` from `…Description`). Cached after the first call. | +| `GetSpecVersion() (string, error)` | TPM family indicator (e.g. `"2.0"`). | +| `GetTpmProperty(tpm2.TPMProp) (uint32, error)` | Raw `GetCapability` wrapper used by the helpers above. | +| `GetModelName(v1, v2 uint32) string` / `GetFirmwareVersion(v1, v2 uint32) string` | Decode the four-byte ASCII vendor strings and packed firmware-version words returned by the TPM. | +| `GetRandom(uint16) ([]byte, error)` | `tpm2.GetRandom` wrapper. Used as the entropy source for vault-key seed generation (`FetchVaultKey`, `FetchSealedVaultKey`) — TPM RNG is preferred over `/dev/urandom` to match the recommendation in the TPM 2.0 architecture spec. | + +### Key + cert primitives + +| Function | Purpose | +|---|---| +| `TpmPrivateKey` | `crypto.Signer` whose `Sign` routes through the TPM device key. Used as the private-key argument to `x509.CreateCertificate` so that certs are signed by the in-TPM device key without ever materialising the private value. `Public()` returns either the cached value set by `SetDevicePublicKey` (used during the bootstrap before `device.cert.pem` is on disk) or the public key parsed from the cert file. | +| `SetDevicePublicKey(crypto.PublicKey)` | Seed the cached public key for `TpmPrivateKey.Public()` during the self-signed bootstrap. | +| `TpmSign(digest []byte) (*big.Int, *big.Int, error)` | Low-level: sign a 32-byte SHA-256 digest with the device key (`TpmDeviceKeyHdl`), returning the raw ECDSA `R, S`. `controllerconn/authen.go` calls this for the device-authenticated handshake. `TpmPrivateKey.Sign` wraps it with `asn1.Marshal`. | +| `CreateKey(log, tpmPath, keyHandle, ownerHandle, template, overwrite)` | Generate a primary key under the owner hierarchy and `EvictControl` it into a persistent slot. The `overwrite=false` path is idempotent: an existing key with matching attributes is left in place; only attribute mismatches trigger a recreate. Called by `tpmmgr` for EK / SRK / AK / quote / ECDH and for the device key itself. | +| `ReadOwnerCrdl() (string, error)` | Read `/config/tpm_credential` and truncate to `MaxPasswdLength` (7 bytes). This is the auth value bound to the device key on creation (see `TpmPasswdHdl` row above); device-key operations (`TpmSign`, `ECDHZGen`, and vcomlink's `tpmSign` / `tpmReadNV` / `tpmCertifyKeyWithAik`) must pass it. | +| `GetDevicePrivateKey()` / `GetPrivateKeyFromFile(path)` / `GetPublicKeyFromCert(path)` | PEM helpers in `keys.go` for the soft-key path. `GetDevicePrivateKey` reads `/config/device.key.pem` and returns an `*ecdsa.PrivateKey`; `GetPublicKeyFromCert` parses any X.509 cert PEM. | +| `EccIntToBytes(curve, *big.Int) []byte` | Left-pad an ECC scalar to the curve's byte width. Works around the "missing leading zero" issue in pre-v1.38 TPMs that reject ECPoints whose `XRaw`/`YRaw` are shorter than the curve size. | + +`DefaultKeyParams`, `DefaultEkTemplate`, `DefaultSrkTemplate`, +`DefaultAikTemplate`, `DefaultQuoteKeyTemplate`, +`DefaultEcdhKeyTemplate` are the `tpm2.Public` templates used with +`CreateKey`. The EK template is the TCG standard EK template +(verbatim AuthPolicy from +[Credential_Profile_EK_V2.0](https://trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf)); +the others are bespoke to EVE. + +### Encrypt / decrypt + +`encryptdecypt.go` implements the two operations that funnel almost +every "secret crossing the TPM boundary" path in pillar: + +| Function | Used by | +|---|---| +| `EncryptDecryptUsingTpm(in []byte, encrypt bool) ([]byte, error)` | `vaultmgr` for vault-key wrap/unwrap; `tpmmgr testEncryptDecrypt` and the periodic TPM sanity check; `cipher` for `EdgeNodeCert` body roundtrips. Derives an AES-256 key from the ECDH shared secret between the device's own ECDH key (`TpmEcdhKeyHdl`) and the device cert public key, then AES-CFB encrypts or decrypts with an all-zero IV. Same call on both sides → reversible. | +| `DecryptSecretWithEcdhKey(log, X, Y, edgeNodeCert, iv, ciphertext, plaintext)` | `cipher` for controller-to-device secret exchange. The controller has performed the other half of an ECDH against the published `ecdh.cert.pem`; this function reconstructs the shared secret (`tpm2.ECDHZGen(TpmEcdhKeyHdl, …)` if TPM, scalar mult if soft), KDFs it (SHA256 over the X/Y points padded to curve width), and AES-CFB-decrypts. | +| `AESEncrypt` / `AESDecrypt` | The AES-CFB primitive used by both of the above. Also exported for direct use by `cipher`. | +| `Sha256FromECPoint(X, Y, pubKey)` | KDF: pad X and Y to curve width, concatenate, SHA-256. | + +The soft-fallback path inside `getDecryptKey` triggers when either +`IsTpmEnabled()` is false or `edgeNodeCert.IsTpm` is false — the +latter handles the case where the device has a TPM in general but +the ECDH cert was created via the soft path. In that case the +private key is read from `EcdhKeyFile` (`/persist/certs/ecdh.key.pem`) +and the scalar multiplication happens in Go rather than in hardware. + +### Disk-key seal / unseal + +`SealDiskKey` and `UnsealDiskKey` are the public entry points. Both +branch on `tpmSupportsAES128CFB()`: + +* If the TPM supports AES-128-CFB as a symmetric cipher (queried via + `tpm2.TestParms`), the encrypted variants in `enc_seal.go` are used. + These wrap the seal/unseal in a salted HMAC session + (`tpm2.Salted(TpmEKHdl, ekPub)`) with `tpm2.AESEncryption(128, + Encrypt{In,Out})` parameter encryption. The session salt is + encrypted to the EK public key by the kernel-side + `transport.TPM`; the plaintext disk key is therefore encrypted on + the CPU↔TPM bus and protected from a passive bus snooper. +* Otherwise, the legacy variants `sealDiskKeyLegacy` / + `unsealDiskKeyLegacy` are used. These use the older `legacy/tpm2` + API with a plain `PolicyPCR` session — correct, but the key value + is in cleartext on the bus. + +Both paths store the sealed object in the same two NV indices +(`TpmSealedDiskPubHdl` / `TpmSealedDiskPrivHdl`) in the same wire +format. The encrypted variant strips the leading 2-byte size prefix +from the v2 `tpm2.Marshal(TPMTPublic)` output before storing, so an +encrypted-path seal can be unsealed by the legacy path on a +subsequent boot (and vice versa) — both paths read the same on-TPM +bytes. + +The two reasons `enc_seal.go` uses the newer `tpm2` package while +the rest of the file uses `legacy/tpm2`: + +1. Parameter encryption (`AESEncryption(128, Encrypt{In,Out})`) on + salted HMAC sessions is only available on the v2 API. +2. `TPMLPCRSelection` / `TPMSPCRSelection` carry the + PC-Client-compatible bitmap helpers (`PCClientCompatible.PCRs(...)`) + needed to build the policy session correctly for the v2 ABI. + +Migrating the rest of the package to v2 is tracked separately — see +[TSS 2.0 Backend](#tss-20-backend) below. + +#### Wrapper / high-level entry points + +| Function | What it does | +|---|---| +| `FetchVaultKey(log)` | Legacy (un-sealed) path. Reads `TpmDiskKeyHdl` from NV; on miss generates 32 random bytes via `GetRandom` and writes them. Used on TPMs without a usable SHA256 PCR bank. | +| `FetchSealedVaultKey(log)` | Modern path. Branches on `(sealedKeyPresent, legacyKeyPresent)`: fresh install → generate + seal; legacy only → "clone-then-seal" migration so a failed upgrade can still fall back; sealed present → unseal. Falls back to `FetchVaultKey` if the SHA256 PCR bank is absent. | +| `SealDiskKey(log, key, pcrSel)` | Seal + write success-side measurement log + boot variables + sealing-PCR snapshot. | +| `UnsealDiskKey(pcrSel)` | Unseal; on failure also copy the current measurement log and boot variables into the `…_unseal_fail` slots, and call `FindMismatchingPCRs` to enrich the returned error with the list of PCR indexes whose values have changed since seal time. | +| `UnsealDiskKeyWithRecovery(log, pcrSel)` | Try `UnsealDiskKey(pcrSel)`; on failure call `RecoverDiskKeyPolicyPcr` and try again with the recovered selection. Called from inside `FetchSealedVaultKey`. | +| `WipeOutStaleSealedKeyIfAny()` | NV-undefine both seal handles. Used by `vaultmgr` before re-sealing with a new policy. | +| `PolicyPCRSession(rw, pcrSel)` | Build a `tpm2.SessionPolicy` with a single `PolicyPCR` step and return the session handle + computed policy digest. Used by the legacy seal/unseal path. | +| `CompareLegacyandSealedKey(log)` | Returns a `SealedKeyType` (`Unknown` / `Reused` / `New` / `Unprotected`) describing the relationship between the legacy and sealed keys for the controller report. | + +`SealedKeyType` is the user-facing label set published in +`EncryptedVaultKeyFromDevice`; its `String()` is what the controller +sees. + +### PCR policy bookkeeping + +| Function | What it does | +|---|---| +| `GetDiskKeyPolicyPcrOrDefault(path) tpm2.PCRSelection` | Read `policy-pcr.json` under a file lock, validate, return the selection. Fall back to `DefaultDiskKeySealingPCRs` on missing / corrupt / invalid file. | +| `SaveDiskKeyPolicyPcr(sp, path) (changed, err)` | Sort indexes, compare to existing file under lock, write atomically only if different. **Crashes the service via `log.Fatalf` on write failure** — the rationale is to let the boot loop retry rather than continue with a stale policy. | +| `ValidatePolicyPcr(sp) error` | Constraint check (see [PCR selections](#pcr-selections)). | +| `RecoverDiskKeyPolicyPcr() (tpm2.PCRSelection, error)` | Read the sealed object's `AuthPolicy` digest, try the default selection first, then brute-force subsets of `PcrListForQuote.PCRs`. Saves the recovered selection back to `policy-pcr.json` with `ID = PolicyPCRRecoveredDefault` or `PolicyPCRRecovered`. | +| `FindMismatchingPCRs() ([]int, error)` | Read the saved sealing-time PCR map (`sealingpcrs`) and compare against current PCR values; return the indexes that differ. Used to enrich unseal-failure errors with operator-actionable detail (e.g. "PCR 7 changed → secure-boot policy update"). | + +## Callers + +`evetpm` has no main package; the dependency arrows all point inward. +Major callers in pillar: + +| Caller | What it uses `evetpm` for | +|---|---| +| `pkg/pillar/cmd/tpmmgr` | Everything provisioning-related: `CreateKey` against every template, `IsTpmEnabled`, `TpmPrivateKey`, `FetchTpmHwInfoDescription`, `EncryptDecryptUsingTpm` (sanity check), `GetTpmLogFileNames` / `GetBootVariablesDirNames` (debug bundles). See [`pkg/pillar/docs/tpmmgr.md`](../docs/tpmmgr.md). | +| `pkg/pillar/cmd/vaultmgr` | `FetchSealedVaultKey`, `SealDiskKey`, `EncryptDecryptUsingTpm` (wrap/unwrap of the controller-supplied vault key), `CompareLegacyandSealedKey`, `ValidatePolicyPcr` / `SaveDiskKeyPolicyPcr`. The vault key seal/unseal flow is the principal consumer of this package; `UnsealDiskKeyWithRecovery`, `WipeOutStaleSealedKeyIfAny`, and `FindMismatchingPCRs` are reached transitively through `FetchSealedVaultKey` and the `pkg/pillar/vault` handlers. | +| `pkg/pillar/vault/{handler_ext4,handler_zfs,key}.go` | Wrappers that pick `FetchSealedVaultKey` vs. `FetchVaultKey` based on `PCRBankSHA256Enabled()`. | +| `pkg/pillar/cipher/handlecipher.go` | `DecryptSecretWithEcdhKey`, `EncryptDecryptUsingTpm` for the controller-to-device secret exchange (`EdgeNodeCert`-keyed cipher blocks). | +| `pkg/pillar/controllerconn/{authen,tls}.go` | `TpmPrivateKey`, `TpmSign` for the device-key-signed authentication handshake; `IsTpmEnabled` to pick the soft vs. TPM-rooted code path. | +| `pkg/pillar/cmd/zedagent/reportinfo.go` | `FetchTpmSwStatus`, `FetchTpmHwInfoDescription`, `GetSpecVersion`, `CompareLegacyandSealedKey` for the controller info report (`HSMStatus`, `HSMInfo`). | +| `pkg/pillar/cmd/vcomlink` | `TpmEKHdl`, `TpmAIKHdl` and the read primitives — the guest-VM TPM service exposed over vsock proxies a subset of TPM ops back into this package. | +| `pkg/pillar/cmd/msrv` | Credential-activation flow (`ActivateCredentialReq`) goes through the same handles. | +| `pkg/pillar/cmd/monitor/messages.go` | `GetTpmLogFileNames`, `GetTpmLogBackupFileNames`, `GetBootVariablesDirNames` to ship the latest seal/unseal artefacts off the device for diagnostics. | +| `pkg/pillar/hardware/inventory.go` | `FetchTpmHwInfo` for the hardware inventory. | + +`nodeagent` is an indirect consumer: it watches `TpmSanityStatus` +published by `tpmmgr`, which `tpmmgr` derives from the result of +`EncryptDecryptUsingTpm` + `tpm2.Quote` here. + +## TSS 2.0 Backend + +TPM2 commands go through Google's +[`go-tpm`](https://github.com/google/go-tpm) (Apache 2.0). The +package pulls in **both** the `legacy/tpm2` package and the newer +top-level `tpm2` (plus `tpm2/transport`). The split is by file: + +| File | API | Why | +|---|---|---| +| `tpm.go`, `encryptdecypt.go` | `legacy/tpm2` | These predate the v2 package upstream. The legacy API is still supported and the migration cost has not justified the rewrite. | +| `enc_seal.go` | `tpm2` + `tpm2/transport` | Salted HMAC sessions with AES-128-CFB parameter encryption are only exposed on the v2 API. The bitmap helpers (`PCClientCompatible.PCRs(...)`) and `TPMLPCRSelection` types also live there. | +| `keys.go` | none (pure Go `crypto/*` / PEM) | Soft-key helpers. | + +Most of `tpmmgr` and `evetpm` predate the v2 package and the legacy +API has remained adequate; `enc_seal.go` was written against the v2 +package because parameter encryption and `TPMLPCRSelection` are only +exposed there. A full v2 migration is **TBD** — a tracking issue will +be filed separately. + +## Test Hooks + +`testhelper.go` exposes two helpers (`SimTpmWaitForTpmReadyState`, +`SimTpmAvailable`) for unit tests that run against a `swtpm` +simulator. Several package globals are deliberately `var` rather +than `const` so tests can redirect them: + +* `TpmDevicePath` (`/dev/tpmrm0`) — set to the swtpm socket. +* `EcdhKeyFile` (`/persist/certs/ecdh.key.pem`) — set to a tempdir + path; `SetECDHPrivateKeyFile` is the public setter. +* `savedSealingPcrsFile`, `measurementLogSealSuccess`, + `measurementLogUnsealFail` — redirected so a test seal/unseal does + not stomp the on-device persistent state. + +These are not part of the runtime API surface — production callers +should treat them as constants. + +## Further Reading + +* [`pkg/pillar/docs/tpmmgr.md`](../docs/tpmmgr.md) — the microservice + that drives provisioning and attestation through this package. +* [`docs/SECURITY-ARCHITECTURE.md`](../../../docs/SECURITY-ARCHITECTURE.md) + — EVE's top-level security design: device identity, onboarding, + vault-key sealing, attestation. +* [Trusted Computing Group](https://trustedcomputinggroup.org/) — + TPM 2.0 specifications. The policy-digest formula reproduced in + `computePolicyPCRAuthDigest` is in Part 1 ("Architecture"), the + EK template is from the EK Credential Profile. +* [`go-tpm`](https://github.com/google/go-tpm) — both `legacy/tpm2` + and the top-level `tpm2` packages used here. diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence.go new file mode 100644 index 00000000000..d49ce7cc22f --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence.go @@ -0,0 +1,61 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +//go:build faultinjection + +package evetpm + +import ( + "errors" + "fmt" + "os" + "strconv" + "strings" + + "github.com/google/go-tpm/tpmutil" + "github.com/lf-edge/eve/pkg/pillar/types" + fileutils "github.com/lf-edge/eve/pkg/pillar/utils/file" +) + +// Fault injection for the disk-key presence check, compiled in only under the +// faultinjection build tag (FAULT_INJECTION=y). Production images get the +// pass-through in faultinjection_keypresence_disabled.go instead. +// +// It stands in for a TPM that cannot say whether a disk key exists while the +// rest of it works: the state in which taking the error for an absent key +// seals a fresh key over the one the vault is encrypted with. The marker holds +// the number of presence checks to fail, or "always". It lives on /persist +// because the checks it targets run during boot, before the vault is unlocked, +// and anything under /config is measured into the PCRs the key is sealed to. +var keyPresenceFaultFile = types.PersistStatusDir + "/tpm-key-presence-fault" + +var errInjectedKeyPresenceFault = errors.New("injected TPM fault") + +func checkDiskKeyPresence(handle tpmutil.Handle) (bool, error) { + if takeKeyPresenceFault() { + return false, fmt.Errorf("NVReadPublic(%#x): %w", handle, errInjectedKeyPresenceFault) + } + return nvIndexWritten(handle) +} + +// takeKeyPresenceFault reports whether this check is to fail. A count is +// decremented durably before the failure is returned, so a reboot neither +// repeats an injected failure nor loses one. +func takeKeyPresenceFault() bool { + data, err := os.ReadFile(keyPresenceFaultFile) + if err != nil { + return false + } + armed := strings.TrimSpace(string(data)) + if armed == "always" { + return true + } + n, err := strconv.Atoi(armed) + if err != nil || n <= 0 { + return false + } + if err := fileutils.WriteRename(keyPresenceFaultFile, []byte(strconv.Itoa(n-1))); err != nil { + return false + } + return true +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence_disabled.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence_disabled.go new file mode 100644 index 00000000000..d9a9ada8b79 --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/faultinjection_keypresence_disabled.go @@ -0,0 +1,14 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +//go:build !faultinjection + +package evetpm + +import "github.com/google/go-tpm/tpmutil" + +// checkDiskKeyPresence is the production variant: the TPM is asked directly. +// The fault-injecting one lives in faultinjection_keypresence.go. +func checkDiskKeyPresence(handle tpmutil.Handle) (bool, error) { + return nvIndexWritten(handle) +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/tpm.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/tpm.go index e8cccf11257..1ca3ace97d6 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/tpm.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/evetpm/tpm.go @@ -26,6 +26,7 @@ import ( "slices" "sort" "strings" + "time" "unsafe" "github.com/google/go-tpm/legacy/tpm2" @@ -89,6 +90,9 @@ const ( PCRIndexMax = 15 // PCRIndexSRTM is the PCR index for Static Root of Trust for Measurement PCRIndexSRTM = 0 + // PCRIndexBootManagerCode is the PCR index for the boot manager/OS loader + // binary (EVE's GRUB), measured by firmware per the TCG PC Client profile. + PCRIndexBootManagerCode = 4 // PCRIndexGPT is the PCR index for GPT partition table and boot manager configuration PCRIndexGPT = 5 // PCRIndexOS is the PCR index for defined by the OS or user. @@ -135,6 +139,14 @@ var ( return tpm2.PCRSelection{Hash: tpm2.AlgSHA256, PCRs: pcrs} }() + // criticalFirmwarePCRs are the firmware-owned SHA-256 PCRs that must carry a + // genuine measurement for the measured-boot chain to be anchored: PCR 0 (firmware + // / S-CRTM version) and PCR 4 (the boot manager measurement of the launched + // bootloader, EVE's GRUB). If either is left at its all-zero reset value, firmware + // did no SHA-256 measured boot, so the value is forgeable by any code that runs + // after ExitBootServices, defeating the seal. + criticalFirmwarePCRs = []int{PCRIndexSRTM, PCRIndexBootManagerCode} + // TpmDevicePath is the TPM device file path, it is not a constant due to // test usage. TpmDevicePath = "/dev/tpmrm0" @@ -1007,9 +1019,16 @@ func FetchSealedVaultKey(log *base.LogObject) ([]byte, error) { return FetchVaultKey(log) } - //gain some knowledge about existing environment - sealedKeyPresent := isSealedKeyPresent() - legacyKeyPresent := isLegacyKeyPresent() + sealedKeyPresent, err := diskKeyPresent(log, TpmSealedDiskPrivHdl, "sealed") + if err != nil { + return nil, err + } + legacyKeyPresent := false + if !sealedKeyPresent { + if legacyKeyPresent, err = diskKeyPresent(log, TpmDiskKeyHdl, "legacy"); err != nil { + return nil, err + } + } // Determine the PCR selection to use pcrSelection := GetDiskKeyPolicyPcrOrDefault(types.PolicyPcrFile) @@ -1165,21 +1184,53 @@ func sealDiskKeyLegacy(log *base.LogObject, key []byte, pcrSel tpm2.PCRSelection return nil } -func isSealedKeyPresent() bool { +// diskKeyPresenceAttempts and diskKeyPresenceRetryDelay bound the retries of a +// TPM error while deciding whether a disk key exists. The TPM can answer a +// command with a transient warning such as RC_RETRY. +const ( + diskKeyPresenceAttempts = 3 + diskKeyPresenceRetryDelay = 500 * time.Millisecond +) + +// diskKeyPresent reports whether the disk key NV index at handle holds a key, +// retrying a TPM error. It returns an error when the TPM keeps failing, which +// the caller must not read as an absent key: that would seal a fresh key over +// the one the vault is encrypted with. +func diskKeyPresent(log *base.LogObject, handle tpmutil.Handle, kind string) (bool, error) { + for attempt := 1; ; attempt++ { + present, err := checkDiskKeyPresence(handle) + if err == nil { + return present, nil + } + log.Warnf("checking for the %s disk key (attempt %d/%d): %v", + kind, attempt, diskKeyPresenceAttempts, err) + if attempt == diskKeyPresenceAttempts { + return false, fmt.Errorf("cannot tell whether a %s disk key exists: %w", kind, err) + } + time.Sleep(diskKeyPresenceRetryDelay) + } +} + +// nvIndexWritten reports whether the NV index at handle is defined and has +// been written. Only the TPM reporting the index undefined, or defined and +// never written (a seal cut between define and write), yields false; every +// other failure is returned. +func nvIndexWritten(handle tpmutil.Handle) (bool, error) { rw, err := tpm2.OpenTPM(TpmDevicePath) if err != nil { - return false + return false, fmt.Errorf("OpenTPM failed: %w", err) } defer rw.Close() - _, err = tpm2.NVReadEx(rw, TpmSealedDiskPrivHdl, - tpm2.HandleOwner, EmptyPassword, 0) - return err == nil -} - -func isLegacyKeyPresent() bool { - _, err := readDiskKey() - return err == nil + pub, err := tpm2.NVReadPublic(rw, handle) + var handleErr tpm2.HandleError + if errors.As(err, &handleErr) && handleErr.Code == tpm2.RCHandle { + return false, nil + } + if err != nil { + return false, fmt.Errorf("NVReadPublic(%#x) failed: %w", handle, err) + } + return pub.Attributes&tpm2.AttrWritten != 0, nil } // unsealDiskKeyLegacy unseals key from TPM using the legacy go-tpm API without @@ -1228,6 +1279,17 @@ func unsealDiskKeyLegacy(pcrSel tpm2.PCRSelection) ([]byte, error) { // protect the key on the CPU-TPM bus. Otherwise, it falls back to the // legacy unencrypted seal path. func SealDiskKey(log *base.LogObject, key []byte, pcrSel tpm2.PCRSelection) error { + // Never seal to firmware anchor PCRs that were left at their all-zero + // reset value. An all-zero PCR 0 or 4 means firmware did not extend the + // SHA-256 bank, so the value is forgeable by any code running after + // ExitBootServices (EVE's GRUB is unsigned) and the seal would provide + // no tamper protection. + if zeroed, err := unextendedCriticalPCRs(); err != nil { + return fmt.Errorf("checking firmware PCRs before sealing: %w", err) + } else if len(zeroed) > 0 { + return fmt.Errorf("refusing to seal disk key: firmware anchor PCR(s) %v are all-zero in the SHA-256 bank, measured-boot chain is not anchored (TPM Carte Blanche attack)", zeroed) + } + if tpmSupportsAES128CFB() { log.Noticef("TPM supports AES-128-CFB, sealing with parameter encryption") if err := sealDiskKeyEncrypted(log, key, pcrSel); err != nil { @@ -1372,7 +1434,11 @@ func PolicyPCRSession(rw io.ReadWriteCloser, pcrSel tpm2.PCRSelection) (tpmutil. // CompareLegacyandSealedKey compares legacy and sealed keys // to record if we are using a new key for sealed vault func CompareLegacyandSealedKey(log *base.LogObject) SealedKeyType { - if !isSealedKeyPresent() { + present, err := nvIndexWritten(TpmSealedDiskPrivHdl) + if err != nil { + log.Warnf("CompareLegacyandSealedKey: %v", err) + } + if !present { return SealedKeyTypeUnprotected } legacyKey, err := readDiskKey() @@ -1445,6 +1511,33 @@ func pcrBankSHA256EnabledHelper() bool { return err == nil } +// unextendedCriticalPCRs reads the critical firmware PCRs (criticalFirmwarePCRs) +// from the SHA-256 bank and returns those still at their all-zero reset value. +// An all-zero firmware PCR means firmware never extended the SHA-256 bank for it, +// so the value can be reproduced (forged) by any code that runs after +// ExitBootServices. Sealing to such a PCR provides no tamper protection +// (TPM Carte Blanche attack). +func unextendedCriticalPCRs() ([]int, error) { + rw, err := tpm2.OpenTPM(TpmDevicePath) + if err != nil { + return nil, err + } + defer rw.Close() + + zero := make([]byte, sha256.Size) + zeroed := make([]int, 0, len(criticalFirmwarePCRs)) + for _, idx := range criticalFirmwarePCRs { + val, err := tpm2.ReadPCR(rw, idx, tpm2.AlgSHA256) + if err != nil { + return nil, fmt.Errorf("reading PCR %d from SHA-256 bank: %w", idx, err) + } + if bytes.Equal(val, zero) { + zeroed = append(zeroed, idx) + } + } + return zeroed, nil +} + func backupCopiedMeasurementLogs() error { sealSuccessBackupPath, unsealFailBackupPath := GetTpmLogBackupFileNames() diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/allocstats.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/allocstats.go new file mode 100644 index 00000000000..9ac25a77dae --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/allocstats.go @@ -0,0 +1,66 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package pubsub + +import ( + "sort" + "sync/atomic" +) + +// Alloc counts heap allocations pubsub makes at one kind of call site: how +// many, the bytes asked for, and the bytes the Go allocator reserves for +// them, which is the request rounded up to its size class. +type Alloc struct { + Count atomic.Int64 + Bytes atomic.Int64 + Reserved atomic.Int64 +} + +// Add counts one allocation of n bytes. +func (a *Alloc) Add(n int) { + if a == nil || n <= 0 { + return + } + a.Count.Add(1) + a.Bytes.Add(int64(n)) + a.Reserved.Add(int64(AllocSize(n))) +} + +// AddTemp counts a []byte(s) or string(b) conversion of n bytes passed to +// a function which does not keep it: Go converts up to 32 bytes on the +// stack. +func (a *Alloc) AddTemp(n int) { + if n > 32 { + a.Add(n) + } +} + +func (a *Alloc) snapshot(kind string, m map[string]int64) { + m["alloc_"+kind+"_count"] = a.Count.Load() + m["alloc_"+kind+"_bytes"] = a.Bytes.Load() + m["alloc_"+kind+"_reserved"] = a.Reserved.Load() +} + +// sizeClasses are the object sizes of the Go allocator up to 32 KiB +// (class_to_size in runtime/sizeclasses.go); larger objects take whole +// 8 KiB pages. +var sizeClasses = [...]int{8, 16, 24, 32, 48, 64, 80, 96, 112, 128, 144, 160, + 176, 192, 208, 224, 240, 256, 288, 320, 352, 384, 416, 448, 480, 512, 576, + 640, 704, 768, 896, 1024, 1152, 1280, 1408, 1536, 1792, 2048, 2304, 2688, + 3072, 3200, 3456, 4096, 4864, 5376, 6144, 6528, 6784, 6912, 8192, 9472, + 9728, 10240, 10880, 12288, 13568, 14336, 16384, 18432, 19072, 20480, + 21760, 24576, 27264, 28672, 32768} + +// AllocSize returns the bytes the Go allocator reserves for n bytes. +func AllocSize(n int) int { + if n > sizeClasses[len(sizeClasses)-1] { + const page = 8 << 10 + return (n + page - 1) &^ (page - 1) + } + return sizeClasses[sort.SearchInts(sizeClasses[:], n)] +} + +// deepCopyAlloc counts the JSON DeepCopy goes through; DeepCopy does not +// know the topic. +var deepCopyAlloc Alloc diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/driver.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/driver.go index 82863aacffa..735ffed5b11 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/driver.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/driver.go @@ -42,9 +42,6 @@ type DriverSubscriber interface { // Stop subscribing to a name and topic // This is expected to return immediately. Stop() error - - // LargeDirName returns the directory to be used for large fields - LargeDirName() string } // DriverPublisher interface that a driver for publishing must implement @@ -74,9 +71,6 @@ type DriverPublisher interface { // CheckMaxSize to see if it will fit CheckMaxSize(key string, val []byte) error - - // LargeDirName returns the directory to be used for large fields - LargeDirName() string } // Restarted interface that lets you determine if a Publication has been restarted diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/emptydriver.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/emptydriver.go index 32225f79b36..3cba8b239d8 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/emptydriver.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/emptydriver.go @@ -61,11 +61,6 @@ func (e *EmptyDriverPublisher) Stop() error { return nil } -// LargeDirName where to put large fields -func (e *EmptyDriverPublisher) LargeDirName() string { - return "/tmp" -} - // EmptyDriverSubscriber struct type EmptyDriverSubscriber struct{} @@ -84,8 +79,3 @@ func (e *EmptyDriverSubscriber) Load() (map[string][]byte, int, error) { func (e *EmptyDriverSubscriber) Stop() error { return nil } - -// LargeDirName where to put large fields -func (e *EmptyDriverSubscriber) LargeDirName() string { - return "/tmp" -} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/large.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/large.go deleted file mode 100644 index ec915eba46e..00000000000 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/large.go +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright (c) 2021 Zededa, Inc. -// SPDX-License-Identifier: Apache-2.0 - -package pubsub - -import ( - "encoding/json" - "fmt" - "io" - "os" - "strings" - - "github.com/lf-edge/eve/pkg/pillar/base" - fileutils "github.com/lf-edge/eve/pkg/pillar/utils/file" -) - -const ( - // maxLargeLen is the largest single file we support - maxLargeLen = 1024 * 1024 - // tagLarge is the prefix in the json tag which directs us to use files - tagLarge = "pubsub-large-" - // tagFile is the internal prefix we use for the filename - tagFile = "pubsub-file-" -) - -// The generic type for a json decode -type jsonTree map[string]interface{} - -// removeLarge removes all json with the tagLarge prefix -func removeLarge(log *base.LogObject, b []byte, rootDir string) ([]byte, error) { - return writeLargeImpl(log, b, "", rootDir) -} - -// writeAndRemoveLarge looks for the tagLarge prefix, saves the content of those -// fields to uniquely-named files under dirname, and inserts tagFile prefixed -// fields in the json to specify the fileaname -func writeAndRemoveLarge(log *base.LogObject, b []byte, dirname string) ([]byte, error) { - return writeLargeImpl(log, b, dirname, "") -} - -// If dirname is set we write files there. -// Otherwise we use rootDir to estimate the size of the fileTag entries -func writeLargeImpl(log *base.LogObject, b []byte, dirname string, rootDir string) ([]byte, error) { - var tree jsonTree - - err := json.Unmarshal(b, &tree) - if err != nil { - err := fmt.Errorf("writeLargeImpl: json.Unmarshal failed for %s: %v", - dirname, err) - return nil, err - } - tree, err = writeRemoveTree(log, tree, dirname, rootDir) - if err != nil { - return nil, err - } - log.Tracef("New tree: %+v", tree) - b, err = json.Marshal(tree) - if err != nil { - err := fmt.Errorf("writeLargeImpl: json.Marshal failed for %s: %v", - dirname, err) - return nil, err - } - return b, nil -} - -func writeRemoveTree(log *base.LogObject, - tree jsonTree, dirname string, rootDir string) (jsonTree, error) { - - // function to recursively descend into a subtree - descend := func(k string, v interface{}) (interface{}, error) { - subtree, ok := v.(map[string]interface{}) - if !ok { - return v, nil - } - log.Tracef("Descending into %s", k) - return writeRemoveTree(log, subtree, dirname, rootDir) - } - - out := make(jsonTree) - for k, v := range tree { - if !strings.HasPrefix(k, tagLarge) { - list, ok := v.([]interface{}) - if ok { - var subtrees []interface{} - // descend into each entry of a list - for _, entry := range list { - subtree, err := descend(k, entry) - if err != nil { - return out, err - } - subtrees = append(subtrees, subtree) - } - out[k] = subtrees - continue - } - // map or a scalar type - subtree, err := descend(k, v) - if err != nil { - return out, err - } - out[k] = subtree - continue - } - oldTagLen := len(tagLarge) - nk := tagFile + k[oldTagLen:] - - log.Tracef("tag %s type %T val %v\n", k, v, v) - - // We need to have a map to marshal (with a dummy tag - - // we use k as the dummy), so that atoms and other values can be - // consistently unmarshalled in readAddLarge() - val := make(jsonTree) - val[k] = v - b, err := json.Marshal(val) - if err != nil { - err := fmt.Errorf("writeRemoveTree: Marshal failed for %s: %v", - nk, err) - return out, err - } - length := len(b) - if length >= maxLargeLen { - err := fmt.Errorf("too large string %d bytes for %s", - length, k) - return out, err - } - if dirname == "" { - // Guess how much space a filename would take - filename := rootDir + "0123456789012345678901234567890123456789012345678901234567890123456789" - b, err := json.Marshal(filename) - if err != nil { - err := fmt.Errorf("writeRemoveTree: filename Marshal failed for %s: %v", - filename, err) - return out, err - } - out[nk] = string(b) - continue - } - err = fileutils.EnsureDir(dirname) - if err != nil { - err := fmt.Errorf("writeRemoveTree: EnsureDir failed for %s %s: %v", - dirname, nk, err) - return out, err - } - tmpfile, err := os.CreateTemp(dirname, nk) - if err != nil { - err := fmt.Errorf("writeRemoveTree: TempFile failed for %s %s: %v", - dirname, nk, err) - return out, err - } - defer tmpfile.Close() - filename := tmpfile.Name() - - _, err = tmpfile.Write(b) - if err != nil { - err := fmt.Errorf("writeRemoveTree: Write failed for %s %s: %v", - dirname, nk, err) - return out, err - } - tmpfile.Close() - - b, err = json.Marshal(filename) - if err != nil { - err := fmt.Errorf("writeRemoveTree: filename Marshal failed for %s: %v", - filename, err) - return out, err - } - out[nk] = string(b) - } - return out, nil -} - -// readAddLarge walks the json and uses readfile to fill in those fields which -// have a tagFile prefix. -// If there is an error it returns the input -func readAddLarge(log *base.LogObject, b []byte) ([]byte, error) { - var tree jsonTree - - err := json.Unmarshal(b, &tree) - if err != nil { - err := fmt.Errorf("readAddLarge: json.Unmarshal failed: %v", - err) - return b, err - } - tree, err = readAddTree(log, tree) - if err != nil { - return b, err - } - log.Tracef("New tree: %+v", tree) - out, err := json.Marshal(tree) - if err != nil { - err := fmt.Errorf("readAddLarge: json.Marshal failed: %v", - err) - return b, err - } - return out, nil -} - -func readAddTree(log *base.LogObject, tree jsonTree) (jsonTree, error) { - // function to recursively descend into a subtree - descend := func(k string, v interface{}) (interface{}, error) { - subtree, ok := v.(map[string]interface{}) - if !ok { - return v, nil - } - log.Tracef("Descending into %s", k) - return readAddTree(log, subtree) - } - - out := make(jsonTree) - for k, v := range tree { - if !strings.HasPrefix(k, tagFile) { - list, ok := v.([]interface{}) - if ok { - var subtrees []interface{} - // descend into each entry of a list - for _, entry := range list { - subtree, err := descend(k, entry) - if err != nil { - return out, err - } - subtrees = append(subtrees, subtree) - } - out[k] = subtrees - continue - } - // map or a scalar type - subtree, err := descend(k, v) - if err != nil { - return out, err - } - out[k] = subtree - continue - } - oldTagLen := len(tagFile) - nk := tagLarge + k[oldTagLen:] - - str, ok := v.(string) - if !ok { - err := fmt.Errorf("readAddLarge: value not a string but %T for %s", - v, k) - return nil, err - } - log.Tracef("tag %s value: %s", k, str) - var filename string - err := json.Unmarshal([]byte(str), &filename) - if err != nil { - err := fmt.Errorf("readAddLarge: filename Unmarshal failed for %s: %v", - k, err) - return nil, err - } - b, err := fileutils.ReadWithMaxSize(log, filename, maxLargeLen+1) - if err != nil { - // XXX we handle not exists. - if !os.IsNotExist(err) && err != io.EOF { - err := fmt.Errorf("readAddLarge: failed for %s: %v", - k, err) - return nil, err - } - } - os.Remove(filename) - if len(b) == 0 { - continue - } - log.Tracef("tag %s read %s content: %s", k, filename, str) - var val jsonTree - err = json.Unmarshal(b, &val) - if err != nil { - err := fmt.Errorf("readAddLarge: file content Unmarshal failed for %s: %v", - filename, err) - return nil, err - } - if len(val) != 1 { - err := fmt.Errorf("readAddLarge: map read from file %s has %d keys for %s", - filename, len(val), k) - return nil, err - } - for _, v1 := range val { - out[nk] = v1 - } - } - return out, nil -} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/memdriver.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/memdriver.go index 07151711737..5bd57558c15 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/memdriver.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/memdriver.go @@ -160,11 +160,6 @@ func (e *MemoryDriverPublisher) Stop() error { return nil } -// LargeDirName where to put large fields -func (e *MemoryDriverPublisher) LargeDirName() string { - return tmpDir -} - // MemoryDriverSubscriber struct type MemoryDriverSubscriber struct { topic string @@ -199,8 +194,3 @@ func (e *MemoryDriverSubscriber) Stop() error { e.subscribers.Delete(e.topic) return nil } - -// LargeDirName where to put large fields -func (e *MemoryDriverSubscriber) LargeDirName() string { - return tmpDir -} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/publish.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/publish.go index b4676718f7e..92b736a4949 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/publish.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/publish.go @@ -88,11 +88,7 @@ func (pub *PublicationImpl) CheckMaxSize(key string, item interface{}) error { if err != nil { pub.log.Fatal("json Marshal in CheckMaxSize", err) } - // Remove the large items which would use files - b, err = removeLarge(pub.log, b, pub.driver.LargeDirName()) - if err != nil { - return err - } + PublicationStats(name).AllocMarshal.Add(len(b)) return pub.driver.CheckMaxSize(key, b) } @@ -111,11 +107,26 @@ func (pub *PublicationImpl) Publish(key string, item interface{}) error { } // Perform a deepCopy in case the caller might change a map etc newItem := DeepCopy(pub.log, item) - if m, ok := pub.km.key.Load(key); ok { - if cmp.Equal(m, newItem) { - pub.log.Tracef("Publish(%s/%s) unchanged\n", name, key) - return nil - } + m, ok := pub.km.key.Load(key) + if ok && cmp.Equal(m, newItem) { + pub.log.Tracef("Publish(%s/%s) unchanged\n", name, key) + return nil + } + // marshal to json bytes to send to the driver + b, err := json.Marshal(item) + if err != nil { + pub.log.Fatal("json Marshal in Publish", err) + } + PublicationStats(name).AllocMarshal.Add(len(b)) + // Refuse a value which does not fit in a message before it is stored or + // checkpointed: sending it would fail on every connection, and after + // every reboot if checkpointed. + if err := pub.driver.CheckMaxSize(key, b); err != nil { + PublicationStats(name).Refused.Add(1) + pub.log.Errorf("Publish(%s/%s) refused: %v", name, key, err) + return err + } + if ok { // DO NOT log Values. They may contain sensitive information. pub.log.Tracef("Publish(%s/%s) replacing due to diff\n", name, key) @@ -138,14 +149,6 @@ func (pub *PublicationImpl) Publish(key string, item interface{}) error { pub.dump("after Publish") } pub.updatersNotify(name) - // marshal to json bytes to send to the driver - b, err := json.Marshal(item) - if err != nil { - pub.log.Fatal("json Marshal in Publish", err) - } - - // We pass the full json to the driver including any pubsub-large - // items to have a complete checkpoint. return pub.driver.Publish(key, b) } @@ -267,12 +270,6 @@ func (pub *PublicationImpl) populate() { return } for key, itemB := range pairs { - // Just in case large items were stored separately - itemB, err = readAddLarge(pub.log, itemB) - if err != nil { - // Handle missing files?? - pub.log.Error(err) - } item, err := parseTemplate(pub.log, itemB, pub.topicType) if err != nil { // Handle bad files such as those of size zero @@ -296,7 +293,6 @@ func (pub *PublicationImpl) DetermineDiffs(localCollection LocalCollection) []st var keys []string name := pub.nameString() items := pub.GetAll() - dirname := fmt.Sprintf("%s/%s", pub.driver.LargeDirName(), pub.nameString()) // Look for deleted for localKey := range localCollection { _, ok := items[localKey] @@ -313,26 +309,17 @@ func (pub *PublicationImpl) DetermineDiffs(localCollection LocalCollection) []st if err != nil { pub.log.Fatalf("json Marshal in DetermineDiffs for origin key %s: %v", originKey, err) } + PublicationStats(name).AllocMarshal.Add(len(originb)) local := lookupLocal(localCollection, originKey) if local == nil { pub.log.Tracef("determineDiffs(%s): key %s added\n", name, originKey) - // Extract large fields and save to file - originb, err = writeAndRemoveLarge(pub.log, originb, dirname) - if err != nil { - pub.log.Fatal(err) - } localCollection[originKey] = originb keys = append(keys, originKey) } else if bytes.Compare(originb, local) != 0 { pub.log.Tracef("determineDiffs(%s): key %s replacing due to diff\n", name, originKey) - // Extract large fields and save to file - originb, err = writeAndRemoveLarge(pub.log, originb, dirname) - if err != nil { - pub.log.Fatal(err) - } localCollection[originKey] = originb keys = append(keys, originKey) } else { diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/stats.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/stats.go new file mode 100644 index 00000000000..77094e7deed --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/stats.go @@ -0,0 +1,157 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package pubsub + +import ( + "encoding/json" + "net/http" + "sync" + "sync/atomic" +) + +// PubStats counts what a publication sent, over all its subscribers. +type PubStats struct { + Connections atomic.Int64 // subscriber connections being served + Messages atomic.Int64 + Bytes atomic.Int64 + MaxMessage atomic.Int64 + LargeWarnings atomic.Int64 // messages above the warning size + + CompressedMessages atomic.Int64 // messages above the frame size, sent compressed + CompressedBytes atomic.Int64 // their size on the wire + Refused atomic.Int64 // values too large even compressed + + AllocMarshal Alloc // JSON of published items + AllocMessage Alloc // wire messages built for subscribers + AllocLarge Alloc // fields tagged pubsub-large moved out to files +} + +// SubStats counts what the subscriptions to a publication received, over +// all subscriptions in this process. +type SubStats struct { + Subscribers atomic.Int64 // connected subscriptions + Frames atomic.Int64 + Bytes atomic.Int64 + MaxFrame atomic.Int64 + RetainedBufBytes atomic.Int64 // read buffers held while frames are read + OversizedFrames atomic.Int64 // frames read into a one-off buffer + BufTakenBytes atomic.Int64 // read buffer bytes handed out, over all reads + + CompressedFrames atomic.Int64 // compressed frames received + DecompressedBytes atomic.Int64 // the size of their messages + + AllocReadBuf Alloc // read buffers: pool misses, one-off and decompressed buffers + AllocDecode Alloc // copies and decoding of received messages + AllocLarge Alloc // fields tagged pubsub-large read back from files +} + +var ( + pubStats sync.Map // publication name -> *PubStats + subStats sync.Map // publication name -> *SubStats +) + +// PublicationStats returns the counters of the named publication. +func PublicationStats(name string) *PubStats { + s, _ := pubStats.LoadOrStore(name, &PubStats{}) + return s.(*PubStats) +} + +// SubscriptionStats returns the counters of the subscriptions to the named +// publication. +func SubscriptionStats(name string) *SubStats { + s, _ := subStats.LoadOrStore(name, &SubStats{}) + return s.(*SubStats) +} + +// AddMessage counts a sent message of the given size. +func (s *PubStats) AddMessage(size int) { + s.Messages.Add(1) + s.Bytes.Add(int64(size)) + storeMax(&s.MaxMessage, int64(size)) +} + +// AddFrame counts a received frame of the given size. +func (s *SubStats) AddFrame(size int) { + s.Frames.Add(1) + s.Bytes.Add(int64(size)) + storeMax(&s.MaxFrame, int64(size)) +} + +func storeMax(largest *atomic.Int64, v int64) { + for { + cur := largest.Load() + if v <= cur || largest.CompareAndSwap(cur, v) { + return + } + } +} + +func (s *PubStats) snapshot() map[string]int64 { + m := map[string]int64{ + "connections": s.Connections.Load(), + "messages": s.Messages.Load(), + "bytes": s.Bytes.Load(), + "max_message": s.MaxMessage.Load(), + "large_warnings": s.LargeWarnings.Load(), + + "compressed_messages": s.CompressedMessages.Load(), + "compressed_bytes": s.CompressedBytes.Load(), + "refused": s.Refused.Load(), + } + s.AllocMarshal.snapshot("marshal", m) + s.AllocMessage.snapshot("message", m) + s.AllocLarge.snapshot("large", m) + return m +} + +func (s *SubStats) snapshot() map[string]int64 { + m := map[string]int64{ + "subscribers": s.Subscribers.Load(), + "frames": s.Frames.Load(), + "bytes": s.Bytes.Load(), + "max_frame": s.MaxFrame.Load(), + "retained_buf_bytes": s.RetainedBufBytes.Load(), + "oversized_frames": s.OversizedFrames.Load(), + "compressed_frames": s.CompressedFrames.Load(), + "decompressed_bytes": s.DecompressedBytes.Load(), + "buf_taken_bytes": s.BufTakenBytes.Load(), + } + s.AllocReadBuf.snapshot("readbuf", m) + s.AllocDecode.snapshot("decode", m) + s.AllocLarge.snapshot("large", m) + return m +} + +// StatsJSON returns all counters as one line of JSON: +// {"publications": {name: {counter: n}}, "subscriptions": {...}}. +func StatsJSON() []byte { + collect := func(m *sync.Map) map[string]map[string]int64 { + out := make(map[string]map[string]int64) + m.Range(func(k, v any) bool { + switch s := v.(type) { + case *PubStats: + out[k.(string)] = s.snapshot() + case *SubStats: + out[k.(string)] = s.snapshot() + } + return true + }) + return out + } + pubs := collect(&pubStats) + deepCopy := make(map[string]int64) + deepCopyAlloc.snapshot("deepcopy", deepCopy) + pubs["(DeepCopy)"] = deepCopy + b, _ := json.Marshal(map[string]map[string]map[string]int64{ + "publications": pubs, + "subscriptions": collect(&subStats), + }) + return b +} + +// StatsHandler serves StatsJSON. +func StatsHandler(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(append(StatsJSON(), '\n')) +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/subscribe.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/subscribe.go index 680ad284cae..30a200c8957 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/subscribe.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/subscribe.go @@ -219,14 +219,6 @@ func handleModify(ctxArg interface{}, key string, itemcb []byte) { sub := ctxArg.(*SubscriptionImpl) name := sub.nameString() sub.log.Tracef("pubsub.handleModify(%s) key %s\n", name, key) - // Any large items which were stored separately? - itemcb, err := readAddLarge(sub.log, itemcb) - if err != nil { - errStr := fmt.Sprintf("handleModify(%s): readAddLarge failed %s", - name, err) - sub.log.Errorln(errStr) - return - } item, err := parseTemplate(sub.log, itemcb, sub.topicType) if err != nil { errStr := fmt.Sprintf("handleModify(%s): json failed %s", diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/util.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/util.go index 34606c96e0c..3efcf03d588 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/util.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/pubsub/util.go @@ -5,11 +5,8 @@ package pubsub import ( "encoding/json" - "fmt" - "net" "reflect" "strings" - "syscall" "github.com/lf-edge/eve/pkg/pillar/base" ) @@ -29,6 +26,7 @@ func DeepCopy(log *base.LogObject, in interface{}) interface{} { if err != nil { log.Fatal("json Marshal in deepCopy", err) } + deepCopyAlloc.Add(len(b)) p := reflect.New(reflect.TypeOf(in)) output := p.Interface() if err := json.Unmarshal(b, output); err != nil { @@ -74,39 +72,6 @@ func TypeToName(something interface{}) string { return out[len(out)-1] } -// ConnReadCheck waits till conn's fd is readable -func ConnReadCheck(conn net.Conn) error { - var sysErr error - - sysConn, ok := conn.(syscall.Conn) - if !ok { - return fmt.Errorf("Not syscall.Conn") - } - rawConn, err := sysConn.SyscallConn() - if err != nil { - return fmt.Errorf("Exception while getting rawConn: %s", - err) - } - - err = rawConn.Read(func(fd uintptr) bool { - _, _, err := syscall.Recvfrom(int(fd), []byte{}, syscall.MSG_PEEK) - if err != nil { - if err == syscall.EAGAIN { - return false - } - //assign unknown error to syserr which will be handled later. - sysErr = fmt.Errorf("Unknown error from syscall.Recvfrom: %s", - err) - } - return true - }) - if err != nil { - return fmt.Errorf("Exception from rawConn.Read: %s", - err) - } - return sysErr -} - // ChannelWatch describe a channel to watch and the callback to call type ChannelWatch struct { // Chan is the channel to watch for incoming data diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/sriov/sriov.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/sriov/sriov.go index 83ad612c39e..8e0260164a9 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/sriov/sriov.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/sriov/sriov.go @@ -4,7 +4,6 @@ package sriov import ( - "context" "fmt" "net" "os" @@ -18,9 +17,13 @@ import ( "github.com/vishvananda/netlink" ) +// NicLinuxPath is the sysfs root for network devices. It is a var rather than +// a const so tests can repoint GetVf at a fake sysfs tree. +var NicLinuxPath = "/sys/class/net/" + // constants for Linux paths for devices const ( - NicLinuxPath = "/sys/class/net/" + PciDevicesPath = "/sys/bus/pci/devices/" NumVfsDevicePath = "/device/sriov_numvfs" TotalVfsPath = "/device/sriov_totalvfs" AutoprobePath = "/device/sriov_drivers_autoprobe" @@ -29,11 +32,21 @@ const ( VfCreationTimeout = 150 * time.Second ) -// CreateVF creates Virtual Functions of given count for given Physical Function -func CreateVF(device string, vfCount uint8, log *base.LogObject) error { - numVfsPath := filepath.Join(NicLinuxPath, device, NumVfsDevicePath) - autoprobePath := filepath.Join(NicLinuxPath, device, AutoprobePath) - totalVfsPath := filepath.Join(NicLinuxPath, device, TotalVfsPath) +// CreateVF creates Virtual Functions of given count for the Physical Function +// at the given PCI BDF. +// +// The sysfs writes go through /sys/bus/pci/devices//sriov_* rather than +// /sys/class/net//device/sriov_* because the latter is sensitive to the +// kernel netdev name. In the EVE-K path NIM renames a PF netdev (e.g. +// eth2 -> keth2) when it bridges it; if that rename overlaps with our sysfs +// poll, the /sys/class/net/ path disappears mid-call and the whole +// operation fails. The PCI BDF is stable across renames, so anchoring on it +// makes CreateVF robust against this race. +func CreateVF(pciBDF string, vfCount uint8, log *base.LogObject) error { + devBase := filepath.Join(PciDevicesPath, pciBDF) + numVfsPath := filepath.Join(devBase, "sriov_numvfs") + autoprobePath := filepath.Join(devBase, "sriov_drivers_autoprobe") + totalVfsPath := filepath.Join(devBase, "sriov_totalvfs") totalBuf, err := os.ReadFile(totalVfsPath) if err != nil { @@ -46,7 +59,7 @@ func CreateVF(device string, vfCount uint8, log *base.LogObject) error { if _, err := os.Stat(autoprobePath); err == nil { if err := os.WriteFile(autoprobePath, []byte("0"), 0); err != nil { - log.Warnf("Warning: could not disable autoprobe on %s: %s", device, err) + log.Warnf("Warning: could not disable autoprobe on %s: %s", pciBDF, err) } } else if !os.IsNotExist(err) { return fmt.Errorf("error checking autoprobe: %w", err) @@ -59,6 +72,12 @@ func CreateVF(device string, vfCount uint8, log *base.LogObject) error { currentVal := strings.TrimSpace(string(currentBuf)) if currentVal == strconv.Itoa(int(vfCount)) { + // numvfs already at target — still ensure the PF is up before + // returning, in case a prior CreateVF aborted between the kernel + // allocating VFs and the link recovery step. + if err := ensurePFAdminUp(pciBDF); err != nil { + return fmt.Errorf("PF admin-up recovery failed for %s: %w", pciBDF, err) + } return nil } @@ -82,14 +101,32 @@ func CreateVF(device string, vfCount uint8, log *base.LogObject) error { } } - // After VF manipulation the PF can go operstate=down; detect and recover. - if err := ensurePFLinkUp(device); err != nil { - return fmt.Errorf("PF link recovery failed for %s: %w", device, err) + // Bumping sriov_numvfs can clear IFF_UP on some drivers; restore it. + // Do not wait for carrier — cable-less passthrough PFs are valid. + if err := ensurePFAdminUp(pciBDF); err != nil { + return fmt.Errorf("PF admin-up recovery failed for %s: %w", pciBDF, err) } return nil } +// resolvePFIfnameFromBDF returns the current netdev name of the PF at the +// given PCI BDF. Reading /sys/bus/pci/devices//net/ is BDF-anchored and +// always reflects the current kernel name, so a rename (e.g. eth2 -> keth2) +// that races with our caller is observed on the next call rather than +// blowing up an already-cached name. +func resolvePFIfnameFromBDF(pciBDF string) (string, error) { + netDir := filepath.Join(PciDevicesPath, pciBDF, "net") + entries, err := os.ReadDir(netDir) + if err != nil { + return "", fmt.Errorf("readdir %s: %w", netDir, err) + } + if len(entries) == 0 { + return "", fmt.Errorf("no netdev under %s", netDir) + } + return entries[0].Name(), nil +} + func pollNumVfs(path, expected string, timeout, interval time.Duration) error { deadline := time.Now().Add(timeout) for { @@ -108,61 +145,175 @@ func pollNumVfs(path, expected string, timeout, interval time.Duration) error { } } -// ensurePFLinkUp checks if the PF interface is down and brings it up if needed. -// device is the interface name directly (e.g. "enp3s0f0"). -func ensurePFLinkUp(device string) error { - link, err := netlink.LinkByName(device) +// ensurePFAdminUp makes sure the PF netdev has the IFF_UP admin flag set. +// +// Bumping sriov_numvfs causes some drivers (ixgbe, i40e) to reset the PF and +// clear IFF_UP; VF creation itself succeeds but downstream operations that +// expect an admin-up PF (per-VF MAC/VLAN via netlink) will fail until we +// restore the flag. +// +// IMPORTANT: this checks IFF_UP only, NOT OperState. Many SR-IOV PFs are +// intentionally cable-less — used purely as a VF source for app passthrough, +// with no host traffic ever flowing on them. Waiting for OperState=OperUp +// would block forever (or until the cable poll timeout) on those PFs. The +// kernel allows VF allocation and per-VF config on an IFF_UP / no-carrier PF +// just fine, so that's all we need to guarantee here. +// +// pciBDF (not the netdev name) is the input because NIM may rename the PF +// (e.g. eth2 -> keth2 when bridging) concurrently with this call; the BDF is +// stable and lets us look up the current netdev name at the moment of use. +func ensurePFAdminUp(pciBDF string) error { + ifname, err := resolvePFIfnameFromBDF(pciBDF) if err != nil { - return fmt.Errorf("netlink: could not find interface %s: %w", device, err) + return fmt.Errorf("resolve PF ifname for %s: %w", pciBDF, err) } + link, err := netlink.LinkByName(ifname) + if err != nil { + return fmt.Errorf("netlink: could not find interface %s (pci %s): %w", + ifname, pciBDF, err) + } + if link.Attrs().Flags&net.FlagUp != 0 { + return nil + } + if err := netlink.LinkSetUp(link); err != nil { + return fmt.Errorf("netlink: failed to bring %s (pci %s) admin-up: %w", + ifname, pciBDF, err) + } + return nil +} - if link.Attrs().OperState == netlink.OperUp { +// GetVfIfaceName returns formatted VF name +func GetVfIfaceName(index uint8, ifname string) string { + return fmt.Sprintf("%svf%d", ifname, index) +} + +// BindVFToVfioPCI binds the VF at the given PCI BDF to the vfio-pci driver. +// +// EVE sets sriov_drivers_autoprobe=0 on the PF before bumping sriov_numvfs so +// freshly created VFs arrive driverless. But this is not guaranteed in every +// path: a previous boot may have left numvfs already at the target (in which +// case CreateVF's early-return skips the autoprobe write) and the resident PF +// VF driver (ixgbevf / iavf / igbvf) will have grabbed the VFs the first time +// they appeared. The upstream sriov-network-device-plugin's `drivers: vfio-pci` +// selector won't match anything bound to those host drivers, so we have to +// actively rebind here — driver_override + drivers_probe alone is a no-op on +// an already-bound device. +// +// Sequence (mirrors what hypervisor.PCIReserveGeneric does for PF passthrough): +// 1. If /driver already points at vfio-pci, return — nothing to do. +// 2. Write "vfio-pci" to /driver_override so the next probe pins the +// driver match to vfio-pci, regardless of vendor:device tables. +// 3. If /driver exists (bound to host driver), write the BDF to +// /driver/unbind to detach it. +// 4. Write the BDF to /sys/bus/pci/drivers_probe to trigger probing. +// 5. Verify /driver now resolves to .../drivers/vfio-pci. drivers_probe +// does NOT return an error if the override driver is missing or no driver +// ends up bound, so a post-bind check is the only way to catch a kernel +// that doesn't have vfio-pci registered (or a probe race that failed). +func BindVFToVfioPCI(vfBDF string) error { + devDir := filepath.Join("/sys/bus/pci/devices", vfBDF) + driverLink := filepath.Join(devDir, "driver") + overridePath := filepath.Join(devDir, "driver_override") + + if isVfioPCIBound(driverLink) { return nil } - if err := netlink.LinkSetUp(link); err != nil { - return fmt.Errorf("netlink: failed to bring %s up: %w", device, err) + if err := os.WriteFile(overridePath, []byte("vfio-pci"), 0); err != nil { + return fmt.Errorf("write driver_override for %s: %w", vfBDF, err) } - if err := pollLinkUp(device, 3*time.Minute, 100*time.Millisecond); err != nil { - return fmt.Errorf("PF %s did not come up after LinkSetUp: %w", device, err) + // Unbind whatever host driver is currently attached. The driver symlink + // only exists when a driver is bound, so Stat tells us whether to skip. + if _, err := os.Stat(driverLink); err == nil { + unbindPath := filepath.Join(driverLink, "unbind") + if err := os.WriteFile(unbindPath, []byte(vfBDF), 0); err != nil { + return fmt.Errorf("unbind %s from current driver: %w", vfBDF, err) + } + } else if !os.IsNotExist(err) { + return fmt.Errorf("stat %s: %w", driverLink, err) } + if err := os.WriteFile("/sys/bus/pci/drivers_probe", []byte(vfBDF), 0); err != nil { + return fmt.Errorf("write drivers_probe for %s: %w", vfBDF, err) + } + + if !isVfioPCIBound(driverLink) { + // Look at what (if anything) ended up bound so the operator can tell + // "vfio-pci not in this kernel" from "some other driver re-grabbed it". + actual, _ := os.Readlink(driverLink) + return fmt.Errorf("VF %s did not bind to vfio-pci after probe "+ + "(current driver: %q) — check that the kernel has CONFIG_VFIO_PCI "+ + "and that no other driver re-grabbed the device", + vfBDF, filepath.Base(actual)) + } return nil } -func pollLinkUp(device string, timeout, interval time.Duration) error { - deadline := time.Now().Add(timeout) - for { - link, err := netlink.LinkByName(device) - if err != nil { - return fmt.Errorf("netlink: lookup %s: %w", device, err) - } - if link.Attrs().OperState == netlink.OperUp { - return nil - } - if time.Now().After(deadline) { - return fmt.Errorf("timed out waiting for %s operstate to become up (current: %s)", - device, link.Attrs().OperState) - } - time.Sleep(interval) +// isVfioPCIBound returns true iff the device's "driver" symlink resolves to +// the vfio-pci driver directory. Reading the link target is more reliable +// than Stat: SameFile would also work but adds a second Stat for nothing. +func isVfioPCIBound(driverLink string) bool { + target, err := os.Readlink(driverLink) + if err != nil { + return false } + return filepath.Base(target) == "vfio-pci" } -// GetVfIfaceName returns formatted VF name -func GetVfIfaceName(index uint8, ifname string) string { - return fmt.Sprintf("%svf%d", ifname, index) +// GetPFIfaceFromVFBDF returns the kernel netdev name of the Physical Function +// that owns the given Virtual Function PCI BDF. +// +// Path: /sys/bus/pci/devices//physfn/net/ +// - "physfn" is a symlink the kernel maintains on every VF, pointing back +// to its parent PF. +// - "net/" lists the netdev(s) attached to the PF. A normal SR-IOV +// PF has exactly one netdev so picking the first entry is unambiguous. +func GetPFIfaceFromVFBDF(vfBDF string) (string, error) { + netDir := filepath.Join("/sys/bus/pci/devices", vfBDF, "physfn", "net") + entries, err := os.ReadDir(netDir) + if err != nil { + return "", fmt.Errorf("readdir %s: %w", netDir, err) + } + if len(entries) == 0 { + return "", fmt.Errorf("no netdev under %s", netDir) + } + return entries[0].Name(), nil } -// ParseVfIfaceName returns index of VF and its PF from name +// ParseVfIfaceName splits a VF iface/phylabel like "eth2vf5" into its PF name +// ("eth2") and VF index (5). Mirrors the inverse of GetVfIfaceName. +// +// Implementation note: the previous version used fmt.Sscanf with format +// "%svf%d", which is broken — Go's %s verb is greedy and consumes the entire +// input, leaving nothing for the literal "vf" or the trailing %d to match. +// Sscanf returns an error and zero values for both fields. Use a manual +// split on the LAST "vf" occurrence instead, so "eth2vf5" parses correctly +// and the (extremely unusual) case of a PF named "...vf..." is handled by +// only treating the final "vf" as the suffix. func ParseVfIfaceName(ifname string) (uint8, string, error) { - var iface string - var index uint8 - n, err := fmt.Sscanf(ifname, "%svf%d", &iface, &index) - if n != 2 { - err = fmt.Errorf("ParseVfIfaceName: could not parse all arguments for %s expected 2, got %d", ifname, n) + // Scan backwards for the last "vf" that's followed by a valid uint8. + // i is the position where the digit suffix begins; we need at least + // two characters before it (for "vf") and at least one char after. + for i := len(ifname) - 1; i >= 2; i-- { + if ifname[i-2:i] != "vf" { + continue + } + suffix := ifname[i:] + if suffix == "" { + continue + } + idx, err := strconv.ParseUint(suffix, 10, 8) + if err != nil { + continue + } + pf := ifname[:i-2] + if pf == "" { + return 0, "", fmt.Errorf("ParseVfIfaceName: empty PF in %q", ifname) + } + return uint8(idx), pf, nil } - return index, iface, err + return 0, "", fmt.Errorf("ParseVfIfaceName: no 'vf' suffix in %q", ifname) } // GetVf retrieve information about VFs for NIC given @@ -216,50 +367,31 @@ func GetVf(device string) (*VFList, error) { //nolint:gocyclo // GetVfByTimeout returns Vf for given PF by timeout func GetVfByTimeout(timeout time.Duration, device string, expectedVfCount uint8) (*VFList, error) { - toCtx, cancel := context.WithTimeout(context.Background(), timeout) - defer cancel() - c := AsyncGetVF(toCtx, device, expectedVfCount) + deadline := time.Now().Add(timeout) for { - select { - case answer := <-c: - return answer, nil - case <-toCtx.Done(): + vfs, err := GetVf(device) + if err == nil && vfs != nil && len(vfs.Data) == int(expectedVfCount) { + return vfs, nil + } + if time.Now().After(deadline) { return nil, fmt.Errorf("getVfByTimeout reached timeout %v", timeout) } + time.Sleep(1 * time.Second) } } -// AsyncGetVF returns Vf for given PF asynchronously -func AsyncGetVF(ctx context.Context, device string, expectedVfCount uint8) chan *VFList { - ch := make(chan *VFList) - go func() { - select { - default: - time.Sleep(1 * time.Second) - vfs, _ := GetVf(device) - if len(vfs.Data) == int(expectedVfCount) { - ch <- vfs - break - } - case <-ctx.Done(): - return - } - }() - return ch -} - // EthVF must match EthVF structure in devcommon.proto type EthVF struct { - Index uint8 - PciLong string // BFD notation - Mac string - VlanID uint16 + Index uint8 `json:",omitempty"` + PciLong string `json:",omitempty"` // BFD notation + Mac string `json:",omitempty"` + VlanID uint16 `json:",omitempty"` } // VFList is list of VF for given PF (Eth device) type VFList struct { - Count uint8 - Data []EthVF + Count uint8 `json:",omitempty"` + Data []EthVF `json:",omitempty"` } // GetInfo get information on VF for given VF @@ -272,6 +404,38 @@ func (vfl *VFList) GetInfo(idx uint8) *EthVF { return nil } +// ClearVFAdminMAC zeroes the per-VF admin MAC programmed on the PF's VF +// table. Called on VM stop/delete/cleanup so the next tenant of this VF +// doesn't inherit the previous VM's admin MAC. +// +// Background: sriov-cni programs the admin MAC on the PF via netlink on pod +// ADD, and is supposed to clear it on pod DEL. In practice — when the VF is +// pre-bound to vfio-pci (EVE's model) — sriov-cni's DEL path doesn't always +// reach the admin-MAC clear because the VF has no kernel netdev to operate +// on. Without an explicit clear here, the admin MAC entry on the PF +// persists across VM stops and the next VM that lands on this VF sees the +// previous tenant's MAC programmed on the host side. +// +// Uses the PF ifname (not VF) because LinkSetVfHardwareAddr operates on the +// PF link with a VF index. Caller passes both because the VF ifname is +// usually torn down once the VF is bound to vfio-pci. +// +// All-zeros MAC is what `ip link set vf mac 00:00:00:00:00:00` +// writes; the kernel interprets it as "no admin MAC, let the VF use its +// default" — which is exactly the post-cleanup state we want. +func ClearVFAdminMAC(pfIface string, index uint8) error { + pf, err := netlink.LinkByName(pfIface) + if err != nil { + return fmt.Errorf("ClearVFAdminMAC: find PF %s: %w", pfIface, err) + } + zero := net.HardwareAddr{0, 0, 0, 0, 0, 0} + if err := netlink.LinkSetVfHardwareAddr(pf, int(index), zero); err != nil { + return fmt.Errorf("ClearVFAdminMAC: clear PF %s VF %d: %w", + pfIface, index, err) + } + return nil +} + // SetupVfHardwareAddr sets up MAC address for the given VF // of the given PF func SetupVfHardwareAddr(iface string, mac string, index uint8) error { diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/assignableadapters.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/assignableadapters.go index a3b99528c08..df96f22b217 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/assignableadapters.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/assignableadapters.go @@ -25,13 +25,19 @@ import ( ) type AssignableAdapters struct { - Initialized bool - IoBundleList []IoBundle + Initialized bool `json:",omitempty"` + IoBundleList []IoBundle `json:",omitempty"` } type ioBundleErrorBase struct { - ErrStr string - TypeStr string + ErrStr string `json:",omitempty"` + TypeStr string `json:",omitempty"` + // Warning marks an advisory entry: a model inconsistency EVE worked around. + // Reported to the controller as a warning, not an error. + Warning bool `json:",omitempty"` + // GroupScoped marks an entry describing the whole assignment group (e.g. a + // collision). Stored on every member but reported once, without attribution. + GroupScoped bool `json:",omitempty"` } func (i ioBundleErrorBase) Error() string { @@ -40,8 +46,8 @@ func (i ioBundleErrorBase) Error() string { // IOBundleError is an error stored in IoBundles that can be marshalled type IOBundleError struct { - Errors []ioBundleErrorBase - TimeOfError time.Time + Errors []ioBundleErrorBase `json:",omitempty"` + TimeOfError time.Time `json:",omitempty"` } // ErrorTime returns the time of the last error added @@ -60,21 +66,122 @@ func (iobe *IOBundleError) String() string { return strings.Join(errorStrings, "; ") } -// Append converts an error to ioBundleErrorBase and adds it -func (iobe *IOBundleError) Append(err error) { +// appendEntry adds entry unless an identical one exists, refreshing the +// timestamp. Dedup keeps the list bounded when a condition is re-detected. +func (iobe *IOBundleError) appendEntry(entry ioBundleErrorBase) { if iobe.Errors == nil { iobe.Errors = make([]ioBundleErrorBase, 0, 1) } + for _, e := range iobe.Errors { + if e.ErrStr == entry.ErrStr && e.TypeStr == entry.TypeStr && + e.Warning == entry.Warning && e.GroupScoped == entry.GroupScoped { + // Already present; leave the timestamp so a persistent error + // keeps its original time. + return + } + } + iobe.Errors = append(iobe.Errors, entry) + iobe.TimeOfError = time.Now() +} - typeStr := reflect.TypeOf(err).String() - baseErr := ioBundleErrorBase{ - ErrStr: err.Error(), - TypeStr: typeStr, +// SetSourceErrors reconciles the entries owned by owner's type to exactly the +// desired strings (all classified alike by warning/groupScoped). Unchanged +// entries are left in place; TimeOfError advances only when an entry is added, +// and resets when the last entry is removed. An empty desired clears the source. +// This lets each source refresh its own errors every reconciliation pass without +// churning the timestamp of a persistent error or touching other sources. +// Returns true if the entry set changed. +func (iobe *IOBundleError) SetSourceErrors(owner error, warning, groupScoped bool, desired []string) bool { + typeStr := reflect.TypeOf(owner).String() + want := make(map[string]bool, len(desired)) + for _, s := range desired { + want[s] = true } + have := make(map[string]bool) + changed := false + kept := iobe.Errors[:0] + for _, e := range iobe.Errors { + if e.TypeStr == typeStr && !want[e.ErrStr] { + changed = true // stale entry of this source: drop + continue + } + if e.TypeStr == typeStr { + have[e.ErrStr] = true + } + kept = append(kept, e) + } + iobe.Errors = kept + added := false + for _, s := range desired { + if !have[s] { + iobe.Errors = append(iobe.Errors, ioBundleErrorBase{ + ErrStr: s, TypeStr: typeStr, Warning: warning, GroupScoped: groupScoped, + }) + added = true + } + } + if len(iobe.Errors) == 0 { + iobe.TimeOfError = time.Time{} + } else if added { + iobe.TimeOfError = time.Now() + } + return changed || added +} - iobe.Errors = append(iobe.Errors, baseErr) +// Append adds a member-scoped hard error. +func (iobe *IOBundleError) Append(err error) { + iobe.appendEntry(ioBundleErrorBase{ + ErrStr: err.Error(), + TypeStr: reflect.TypeOf(err).String(), + }) +} - iobe.TimeOfError = time.Now() +// AppendWarning adds a member-scoped advisory warning (see Warning). +func (iobe *IOBundleError) AppendWarning(err error) { + iobe.appendEntry(ioBundleErrorBase{ + ErrStr: err.Error(), + TypeStr: reflect.TypeOf(err).String(), + Warning: true, + }) +} + +// AppendGroupError adds a group-scoped hard error (see GroupScoped). +func (iobe *IOBundleError) AppendGroupError(err error) { + iobe.appendEntry(ioBundleErrorBase{ + ErrStr: err.Error(), + TypeStr: reflect.TypeOf(err).String(), + GroupScoped: true, + }) +} + +// IsOnlyWarnings returns true if there is at least one entry and every entry is +// an advisory warning (no hard errors). Used to pick the reported severity. +func (iobe *IOBundleError) IsOnlyWarnings() bool { + if len(iobe.Errors) == 0 { + return false + } + for _, err := range iobe.Errors { + if !err.Warning { + return false + } + } + return true +} + +// HardErrorString returns the combined text of the entries that are not +// advisory warnings, and "" when the bundle carries only warnings or nothing. +// Callers deciding whether an adapter is usable must key on this rather than on +// Empty(): a warning records a model inconsistency EVE worked around and +// carried on from, so it must not by itself make the adapter unusable. +func (iobe *IOBundleError) HardErrorString() string { + errorStrings := make([]string, 0, len(iobe.Errors)) + for _, err := range iobe.Errors { + if err.Warning { + continue + } + errorStrings = append(errorStrings, err.Error()) + } + return strings.Join(errorStrings, "; ") } // Empty returns true if no error has been added @@ -117,10 +224,81 @@ func (iobe *IOBundleError) removeByType(e error) { } } -// Clear clears all errors -func (iobe *IOBundleError) Clear() { - iobe.Errors = make([]ioBundleErrorBase, 0) - iobe.TimeOfError = time.Time{} +// RemoveByType clears entries of type e, leaving other errors and warnings. +func (iobe *IOBundleError) RemoveByType(e error) { + iobe.removeByType(e) +} + +// AggregatedIoBundleError is the combined error state of an assignment group, +// ready for reporting in a single ZioBundle. +type AggregatedIoBundleError struct { + Description string // combined text + OnlyWarnings bool // every entry is a warning (picks WARNING vs ERROR) + Empty bool // no member carries an entry + ErrorTime time.Time // most recent error time across members +} + +// AggregateIoBundleGroupErrors combines a group's members' entries for reporting: +// group-scoped entries once and unattributed, member-scoped entries prefixed with +// their member's label. Duplicates are suppressed; nil members ignored. +func AggregateIoBundleGroupErrors(members []*IoBundle) AggregatedIoBundleError { + var parts []string + seenGroup := map[string]bool{} + onlyWarnings := true + anyEntry := false + var latest time.Time + // Group-scoped entries first, deduplicated across members. + for _, m := range members { + if m == nil { + continue + } + if m.Error.TimeOfError.After(latest) { + latest = m.Error.TimeOfError + } + for _, e := range m.Error.Errors { + if !e.GroupScoped { + continue + } + key := e.TypeStr + "\x00" + e.ErrStr + if seenGroup[key] { + continue + } + seenGroup[key] = true + anyEntry = true + if !e.Warning { + onlyWarnings = false + } + parts = append(parts, e.ErrStr) + } + } + // Member-scoped entries, attributed to the owning member. + for _, m := range members { + if m == nil { + continue + } + seenMember := map[string]bool{} + for _, e := range m.Error.Errors { + if e.GroupScoped { + continue + } + key := e.TypeStr + "\x00" + e.ErrStr + if seenMember[key] { + continue + } + seenMember[key] = true + anyEntry = true + if !e.Warning { + onlyWarnings = false + } + parts = append(parts, fmt.Sprintf("%s: %s", m.Logicallabel, e.ErrStr)) + } + } + return AggregatedIoBundleError{ + Description: strings.Join(parts, "; "), + OnlyWarnings: anyEntry && onlyWarnings, + Empty: !anyEntry, + ErrorTime: latest, + } } // IoBundle has one entry per individual receptacle with a reference @@ -129,82 +307,82 @@ func (iobe *IOBundleError) Clear() { type IoBundle struct { // Type // Type of the IoBundle - Type IoType + Type IoType `json:",omitempty"` // Phylabel // Label on the outside of the enclosure - Phylabel string + Phylabel string `json:",omitempty"` // Logical Label assigned to the Adapter. Could match Phylabel // or could be a user-chosen string like "shopfloor" - Logicallabel string + Logicallabel string `json:",omitempty"` // Assignment Group, is unique label that is applied across PhysicalIOs // Entire group can be assigned to application or nothing at all // If this is an empty string it means the IoBundle can not be assigned. - AssignmentGroup string + AssignmentGroup string `json:",omitempty"` // Parent Assignment Group is there to reference the parent assignment group in order to make the device // dependent on a different device. // Currently the concrete reason to do this is to make a usb device dependent on the PCI address the USB // controller is using to prevent passthrough of the USB controller in one application while trying to passthrough // a USB device on this controller to another application. - ParentAssignmentGroup string + ParentAssignmentGroup string `json:",omitempty"` - Usage zcommon.PhyIoMemberUsage + Usage zcommon.PhyIoMemberUsage `json:",omitempty"` // Cost is zero for the free ports; less desirable ports have higher numbers - Cost uint8 + Cost uint8 `json:",omitempty"` // The following set of I/O addresses and info/aliases are used to find // a device, and also to configure it. // XXX TBD: Add PciClass, PciVendor and PciDevice strings as well // for matching - Ifname string // Matching for network PCI devices e.g., "eth1" + Ifname string `json:",omitempty"` // Matching for network PCI devices e.g., "eth1" // Attributes from controller but can also be set locally. - PciLong string // Specific PCI bus address in Domain:Bus:Device.Function syntax + PciLong string `json:",omitempty"` // Specific PCI bus address in Domain:Bus:Device.Function syntax // For non-PCI devices such as the ISA serial ports we have: // XXX: Why is IRQ a string?? Should convert it into Int. - Irq string // E.g., "5" - Ioports string // E.g., "2f8-2ff" - Serial string // E.g., "/dev/ttyS1" - UsbAddr string // E.g., "1:2.3" - UsbProduct string // E.g., "0951:1666" + Irq string `json:",omitempty"` // E.g., "5" + Ioports string `json:",omitempty"` // E.g., "2f8-2ff" + Serial string `json:",omitempty"` // E.g., "/dev/ttyS1" + UsbAddr string `json:",omitempty"` // E.g., "1:2.3"; "1:2.*" for everything below port 2, "1:*" for the whole bus + UsbProduct string `json:",omitempty"` // E.g., "0951:1666" // Attributes Derived and assigned locally ( not from controller) - Unique string // From firmware_node symlink; used for debug checks - MacAddr string // Set for networking adapters. XXX Note used for match. + Unique string `json:",omitempty"` // From firmware_node symlink; used for debug checks + MacAddr string `json:",omitempty"` // Set for networking adapters. XXX Note used for match. // UsedByUUID // Application UUID ( Can be Dom0 too ) that owns the Bundle. // For unassigned adapters, this is not set. - UsedByUUID uuid.UUID + UsedByUUID uuid.UUID `json:",omitempty"` // IsPciBack // Is the IoBundle assigned to pciBack; means other bundles in the same group are also assigned // If the device is managed by dom0, this is False. // If the device is ( or to be ) managed by DomU, this is True - IsPCIBack bool // Assigned to pciback - IsPort bool // Whole or part of the bundle is a zedrouter port + IsPCIBack bool `json:",omitempty"` // Assigned to pciback + IsPort bool `json:",omitempty"` // Whole or part of the bundle is a zedrouter port // Do not put device under pciBack, instead keep it in dom0 as long as it is not assigned to any application. // In other words, this does not prevent assignments but keeps unassigned devices visible to EVE. - KeepInHost bool - Error IOBundleError + KeepInHost bool `json:",omitempty"` + Error IOBundleError `json:",omitempty"` // Only used in PhyIoNetEthPF - Vfs sriov.VFList + Vfs sriov.VFList `json:",omitempty"` // Only used in PhyIoNetEthVF - VfParams VfInfo + VfParams VfInfo `json:",omitempty"` // Used for additional attributes - Cbattr map[string]string + Cbattr map[string]string `json:",omitempty"` } // VfInfo Stores information about Virtual Function (VF) type VfInfo struct { - Index uint8 - VlanID uint16 - PFIface string + Index uint8 `json:",omitempty"` + VlanID uint16 `json:",omitempty"` + PFIface string `json:",omitempty"` } // Really a constant @@ -365,6 +543,16 @@ func (ioType IoType) IsNet() bool { } } +// IsNetEthVF returns true when the adapter is an SR-IOV Virtual Function. +// VFs are intentionally excluded from IsNet() because: +// - They must be bound to vfio-pci (pciback) regardless of testing mode. +// - They are never EVE network ports (keepInHost logic must not apply). +// +// Use this predicate wherever VF-specific behaviour is required. +func (ioType IoType) IsNetEthVF() bool { + return ioType == IoNetEthVF +} + // Key is used with pubsub func (aa AssignableAdapters) Key() string { return "global" @@ -594,76 +782,103 @@ func (ErrCycleDetected) Error() string { return "Cycle detected, please check provided parentassigngrp/assigngrp" } -// CheckParentAssigngrp finds dependency loops between ioBundles and sets/clears the error +// The following empty types are owner markers for SetSourceErrors: they identify +// which source produced an entry so each source clears only its own. + +// ErrIoBundleAssignmentGroupConflict owns CheckBadAssignmentGroups errors. +type ErrIoBundleAssignmentGroupConflict struct{} + +func (ErrIoBundleAssignmentGroupConflict) Error() string { return "assignment-group conflict" } + +// ErrIoBundleModelInconsistency owns updatePortAndPciBackIoBundle warnings. +type ErrIoBundleModelInconsistency struct{} + +func (ErrIoBundleModelInconsistency) Error() string { return "device-model inconsistency" } + +// ErrIoBundleRename owns the interface-rename warning from IoBundleToPci. +type ErrIoBundleRename struct{} + +func (ErrIoBundleRename) Error() string { return "interface renamed to match model" } + +// ErrIoBundlePcibackOp owns errors from moving a device in/out of pciback. +type ErrIoBundlePcibackOp struct{} + +func (ErrIoBundlePcibackOp) Error() string { return "pciback operation failed" } + +// ErrIoBundleMissingDevice means the device backing an IoBundle was not found. +// Typed so callers can clear it (RemoveByType) once resolvable, keeping warnings. +type ErrIoBundleMissingDevice struct { + msg string +} + +func (e ErrIoBundleMissingDevice) Error() string { + return e.msg +} + +// CheckParentAssigngrp validates the parentassigngrp/assigngrp graph and records +// the applicable per-bundle error (self-parent, parent mismatch, empty-group with +// parent, or a dependency cycle). Errors are reconciled through SetSourceErrors so +// a persistent error keeps a stable timestamp across reconciliation passes instead +// of being churned by a remove-then-re-add; a churning timestamp republishes +// AssignableAdapters every pass and spins nim's DPC verification. Returns true if +// the error set changed. func (aa *AssignableAdapters) CheckParentAssigngrp() bool { assigngrp2parent := make(map[string]string) + ownParent := make(map[int]bool) + mismatch := make(map[int]bool) + emptyWithParent := make(map[int]bool) for i := range aa.IoBundleList { - ioBundle := &aa.IoBundleList[i] - for _, parentAssigngrpErr := range []error{ - ErrOwnParent{}, - ErrParentAssigngrpMismatch{}, - ErrEmptyAssigngrpWithParent{}, - ErrCycleDetected{}, - } { - ioBundle.Error.removeByType(parentAssigngrpErr) - } - } - - var cycleDetectedAssigngrp string - for i := range aa.IoBundleList { - ioBundle := &aa.IoBundleList[i] - - if ioBundle.AssignmentGroup == ioBundle.ParentAssignmentGroup && ioBundle.AssignmentGroup != "" { - ioBundle.Error.Append(ErrOwnParent{}) - return true + ib := &aa.IoBundleList[i] + if ib.AssignmentGroup == ib.ParentAssignmentGroup && ib.AssignmentGroup != "" { + ownParent[i] = true + continue } - parentassigngrp, ok := assigngrp2parent[ioBundle.AssignmentGroup] - if ok && parentassigngrp != ioBundle.ParentAssignmentGroup { - ioBundle.Error.Append(ErrParentAssigngrpMismatch{}) - return true + if parent, ok := assigngrp2parent[ib.AssignmentGroup]; ok && parent != ib.ParentAssignmentGroup { + mismatch[i] = true + continue } - - if ioBundle.AssignmentGroup == "" && ioBundle.ParentAssignmentGroup != "" { - ioBundle.Error.Append(ErrEmptyAssigngrpWithParent{}) - return true + if ib.AssignmentGroup == "" && ib.ParentAssignmentGroup != "" { + emptyWithParent[i] = true + continue } - assigngrp2parent[ioBundle.AssignmentGroup] = ioBundle.ParentAssignmentGroup + assigngrp2parent[ib.AssignmentGroup] = ib.ParentAssignmentGroup } + // A group is in a cycle if following parent links from it returns to an + // already-visited group. Self-parents are excluded above, so they are + // reported as ErrOwnParent rather than ErrCycleDetected. + cycleGroups := make(map[string]bool) for assigngrp := range assigngrp2parent { - visitedAssigngrp := make(map[string]struct{}) - visitedAssigngrp[assigngrp] = struct{}{} - - for { - if assigngrp == "" { + visited := map[string]struct{}{assigngrp: {}} + for g := assigngrp; g != ""; { + g = assigngrp2parent[g] + if _, seen := visited[g]; seen { + cycleGroups[g] = true break } - - assigngrp = assigngrp2parent[assigngrp] - _, visitedBefore := visitedAssigngrp[assigngrp] - if visitedBefore { - // cycle detected - cycleDetectedAssigngrp = assigngrp - break - } - - visitedAssigngrp[assigngrp] = struct{}{} + visited[g] = struct{}{} } } - if cycleDetectedAssigngrp == "" { - return false + changed := false + setErr := func(ib *IoBundle, owner error, want bool) { + var desired []string + if want { + desired = []string{owner.Error()} + } + if ib.Error.SetSourceErrors(owner, false, false, desired) { + changed = true + } } - for i := range aa.IoBundleList { - ioBundle := &aa.IoBundleList[i] - if ioBundle.AssignmentGroup == cycleDetectedAssigngrp { - ioBundle.Error.Append(ErrCycleDetected{}) - } + ib := &aa.IoBundleList[i] + setErr(ib, ErrOwnParent{}, ownParent[i]) + setErr(ib, ErrParentAssigngrpMismatch{}, mismatch[i]) + setErr(ib, ErrEmptyAssigngrpWithParent{}, emptyWithParent[i]) + setErr(ib, ErrCycleDetected{}, cycleGroups[ib.AssignmentGroup]) } - - return true + return changed } // IOBundleCollision has the members IoBundles can collide on @@ -676,7 +891,23 @@ type IOBundleCollision struct { } func (i IOBundleCollision) String() string { - return fmt.Sprintf("phylabel %s - usbaddr: %s usbproduct: %s pcilong: %s assigngrp: %s", i.Phylabel, i.USBAddr, i.USBProduct, i.PCILong, i.Assigngrp) + var parts []string + if i.USBAddr != "" { + parts = append(parts, "usbaddr "+i.USBAddr) + } + if i.USBProduct != "" { + parts = append(parts, "usbproduct "+i.USBProduct) + } + if i.PCILong != "" { + parts = append(parts, "pcilong "+i.PCILong) + } + if i.Assigngrp != "" { + parts = append(parts, "assigngrp "+i.Assigngrp) + } + if len(parts) == 0 { + return i.Phylabel + } + return fmt.Sprintf("%s (%s)", i.Phylabel, strings.Join(parts, ", ")) } // ErrIOBundleCollision describes an error where an IoBundle collides with another IoBundle @@ -685,15 +916,11 @@ type ErrIOBundleCollision struct { } func (i ErrIOBundleCollision) Error() string { - collisionErrStrPrefix := "ioBundle collision:" - collisionStrs := make([]string, 0, len(i.Collisions)) for _, collision := range i.Collisions { collisionStrs = append(collisionStrs, collision.String()) } - collisionErrStrBody := strings.Join(collisionStrs, "||") - - return fmt.Sprintf("%s||%s||", collisionErrStrPrefix, collisionErrStrBody) + return "ioBundle collision: " + strings.Join(collisionStrs, "; ") } func newIoBundleCollisionErr() ErrIOBundleCollision { @@ -702,34 +929,33 @@ func newIoBundleCollisionErr() ErrIOBundleCollision { } } -// CheckBadUSBBundles sets and clears ib.Error/ErrorTime if bundle collides in regards of USB +// CheckBadUSBBundles sets and clears ib.Error/ErrorTime when several bundles +// describe the same USB device, i.e. share a USB address and/or USB product +// (plus PCI address and assignment group). Only bundles identifying a USB +// device take part: a model may legitimately list several receptacles of one +// USB controller as separate bundles of a single assignment group, which share +// a PCI address without describing the same device. Bundles sharing a PCI +// address across assignment groups are CheckBadAssignmentGroups' concern. func (aa *AssignableAdapters) CheckBadUSBBundles() { usbProductsAddressMap := make(map[[4]string][]*IoBundle) for i := range aa.IoBundleList { ioBundle := &aa.IoBundleList[i] - ioBundle.Error.removeByType(ErrIOBundleCollision{}) - } - - for i := range aa.IoBundleList { - ioBundle := &aa.IoBundleList[i] - if ioBundle.UsbAddr == "" && ioBundle.UsbProduct == "" && ioBundle.PciLong == "" { + if ioBundle.UsbAddr == "" && ioBundle.UsbProduct == "" { continue } id := [4]string{ioBundle.UsbAddr, ioBundle.UsbProduct, ioBundle.PciLong, ioBundle.AssignmentGroup} - if usbProductsAddressMap[id] == nil { - usbProductsAddressMap[id] = make([]*IoBundle, 0) - } usbProductsAddressMap[id] = append(usbProductsAddressMap[id], ioBundle) } + // Collision text per colliding bundle (a group-scoped error listing every + // colliding member; identical for all members of the collision). + collisionText := make(map[*IoBundle]string) for _, bundles := range usbProductsAddressMap { if len(bundles) <= 1 { continue } - collisionErr := newIoBundleCollisionErr() - for _, bundle := range bundles { collisionErr.Collisions = append(collisionErr.Collisions, IOBundleCollision{ Phylabel: bundle.Phylabel, @@ -740,8 +966,17 @@ func (aa *AssignableAdapters) CheckBadUSBBundles() { }) } for _, bundle := range bundles { - bundle.Error.Append(collisionErr) + collisionText[bundle] = collisionErr.Error() + } + } + + for i := range aa.IoBundleList { + ib := &aa.IoBundleList[i] + var desired []string + if s, ok := collisionText[ib]; ok { + desired = []string{s} } + ib.Error.SetSourceErrors(ErrIOBundleCollision{}, false, true, desired) } } @@ -752,6 +987,7 @@ func (aa *AssignableAdapters) CheckBadAssignmentGroups(log *base.LogObject, PCIS changed := false for i := range aa.IoBundleList { ib := &aa.IoBundleList[i] + var desired []string for _, ib2 := range aa.IoBundleList { if ib2.Phylabel == ib.Phylabel { continue @@ -767,13 +1003,15 @@ func (aa *AssignableAdapters) CheckBadAssignmentGroups(log *base.LogObject, PCIS continue } if PCISameController != nil && PCISameController(ib.PciLong, ib2.PciLong) { - err := fmt.Errorf("CheckBadAssignmentGroup: %s same PCI controller as %s; pci long %s vs %s", + s := fmt.Sprintf("CheckBadAssignmentGroup: %s same PCI controller as %s; pci long %s vs %s", ib2.Ifname, ib.Ifname, ib2.PciLong, ib.PciLong) - log.Error(err) - ib.Error.Append(err) - changed = true + log.Error(s) + desired = append(desired, s) } } + if ib.Error.SetSourceErrors(ErrIoBundleAssignmentGroupConflict{}, false, true, desired) { + changed = true + } } return changed || aa.CheckParentAssigngrp() @@ -807,8 +1045,12 @@ func (aa *AssignableAdapters) ExpandControllers(log *base.LogObject, list []*IoB continue } if PCISameController != nil && PCISameController(ib.PciLong, ib2.PciLong) { - log.Warnf("ExpandController found %s matching %s; long %s long %s", - ib2.Phylabel, ib.Phylabel, ib2.PciLong, ib.PciLong) + log.Warnf("ExpandController: adapter %s (logicallabel %s, ifname %q, "+ + "PCI %s) shares a PCI controller with %s (logicallabel %s, ifname %q, "+ + "PCI %s) and is pulled into the same assignment group %q, which the "+ + "controller's model did not include", + ib2.Phylabel, ib2.Logicallabel, ib2.Ifname, ib2.PciLong, + ib.Phylabel, ib.Logicallabel, ib.Ifname, ib.PciLong, ib.AssignmentGroup) elist = append(elist, ib2) } } diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/cachedresolvedip.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/cachedresolvedip.go deleted file mode 100644 index 7279c64e1f9..00000000000 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/cachedresolvedip.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2023 Zededa, Inc. -// SPDX-License-Identifier: Apache-2.0 - -package types - -import ( - "fmt" - "net" - "strings" - "time" - - "github.com/lf-edge/eve/pkg/pillar/base" -) - -// CachedIP : cached IP with time-limited validity. -type CachedIP struct { - IPAddress net.IP - ValidUntil time.Time -} - -// String representation of CachedIP. -func (c CachedIP) String() string { - return fmt.Sprintf("IP %s valid until %v", c.IPAddress, c.ValidUntil) -} - -// CachedResolvedIPs serves as a cache for storing the IP addresses obtained through -// DNS resolution for a given hostname. -type CachedResolvedIPs struct { - Hostname string - CachedIPs []CachedIP -} - -// String representation of CachedResolvedIPs. -func (c CachedResolvedIPs) String() string { - cachedIPs := make([]string, 0, len(c.CachedIPs)) - for _, ip := range c.CachedIPs { - cachedIPs = append(cachedIPs, ip.String()) - } - return fmt.Sprintf("Hostname %s with cached resolved IPs: [%s]", c.Hostname, - strings.Join(cachedIPs, ", ")) -} - -// Key is used for pubsub -func (c CachedResolvedIPs) Key() string { - return c.Hostname -} - -// LogCreate : -func (c CachedResolvedIPs) LogCreate(logBase *base.LogObject) { - logObject := base.NewLogObject(logBase, base.CachedResolvedIPsLogType, "", - nilUUID, c.LogKey()) - logObject.Metricf("CachedResolvedIPs create %s", c.String()) -} - -// LogModify : -func (c CachedResolvedIPs) LogModify(logBase *base.LogObject, old interface{}) { - logObject := base.EnsureLogObject(logBase, base.CachedResolvedIPsLogType, "", - nilUUID, c.LogKey()) - oldVal, ok := old.(CachedResolvedIPs) - if !ok { - logObject.Clone().Fatalf( - "LogModify: Old object interface passed is not of CachedResolvedIPs type") - } - logObject.Metricf("CachedResolvedIPs modified from %s to %s", - oldVal.String(), c.String()) -} - -// LogDelete : -func (c CachedResolvedIPs) LogDelete(logBase *base.LogObject) { - logObject := base.EnsureLogObject(logBase, base.CachedResolvedIPsLogType, "", - nilUUID, c.LogKey()) - logObject.Metricf("CachedResolvedIPs delete %s", c.String()) - base.DeleteLogObject(logBase, c.LogKey()) -} - -// LogKey : -func (c CachedResolvedIPs) LogKey() string { - return string(base.CachedResolvedIPsLogType) + "-" + c.Key() -} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/clustertypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/clustertypes.go index afdb7f3f201..deeadede1ba 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/clustertypes.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/clustertypes.go @@ -89,10 +89,19 @@ type EdgeNodeClusterConfig struct { // TieBreakerNodeID - uuid of a node which will be unscheduled for all workloads TieBreakerNodeID UUIDandVersion + // EnableNativeK8SOrchestration, when true on a ClusterTypeReplicatedStorage + // cluster, enables native Kubernetes orchestration of user workloads + // (registration manifest + kube-vip load balancer) in addition to the + // EVE-API-managed scheduling. Unlike ClusterTypeK3sBase it does NOT remove + // longhorn/kubevirt; the full replicated-storage stack keeps running. + // Sourced from EdgeNodeCluster.enable_native_k8s_orchestration. + EnableNativeK8SOrchestration bool + // LBInterfaces - load balancer interface configurations from the controller. - // Populated only for ClusterTypeK3sBase clusters. Mirrors the LoadBalancerService - // interfaces array from the protobuf; each entry holds one interface name and its - // first CIDR from address_cidrs. + // Populated when native k8s orchestration is enabled (see + // NativeK8sOrchestrationEnabled). Mirrors the LoadBalancerService interfaces + // array from the protobuf; each entry holds one interface name and its first + // CIDR from address_cidrs. LBInterfaces []LBInterfaceConfig // MasterNodeIDs - UUIDs of all designated control-plane nodes in the cluster @@ -101,6 +110,28 @@ type EdgeNodeClusterConfig struct { // (and thereby k3s embedded etcd members) for masters the controller has // removed via a "replace node" operation. Workers are not included. MasterNodeIDs []uuid.UUID + + // WitnessIP - virtual IP that the witness (a lightweight etcd-only 3rd + // voting member for a 2-physical-node cluster) binds its etcd to on + // ClusterInterface. Nil means no witness runs. Sourced from + // EdgeNodeCluster.witness.witness_ip. The witness always co-locates with + // whichever node currently owns JoinServerIP, so there is no separate + // placement field. + WitnessIP net.IP + + // WitnessConfigError describes why a witness configured by the controller + // was rejected, leaving WitnessIP nil. Empty when the witness config is + // valid or absent. Carried here so zedkube can report it to the controller + // without zedagent having to invalidate the whole cluster config over it. + WitnessConfigError string + + // QuorumRecoveryGeneration - controller-declared quorum-loss recovery + // trigger. Incrementing it tells the node named by JoinServerIP to + // promote itself to sole bootstrap via a forced etcd quorum reset. + // That node tracks the last generation it converged to and does + // nothing while this value is unchanged. Initial cluster formation is + // generation 0. + QuorumRecoveryGeneration uint32 } // AppKubeStatus represents this node's last view of an app's lifecycle in the @@ -162,6 +193,44 @@ func (config EdgeNodeClusterConfig) Key() string { return config.ClusterID.UUID.String() } +// NativeK8sOrchestrationEnabled reports whether native Kubernetes orchestration +// of user workloads is active for this cluster: always for the legacy +// ClusterTypeK3sBase, and for ClusterTypeReplicatedStorage when the controller +// opts in via EnableNativeK8SOrchestration. It gates the registration manifest +// and the kube-vip load balancer. The replicated-storage opt-in, unlike +// K3sBase, keeps longhorn/kubevirt installed. +func (config EdgeNodeClusterConfig) NativeK8sOrchestrationEnabled() bool { + if config.ClusterType == ClusterTypeK3sBase { + return true + } + return config.ClusterType == ClusterTypeReplicatedStorage && + config.EnableNativeK8SOrchestration +} + +// IsTieBreakerNode reports whether nodeUUID is the tie-breaker node the +// controller designated for this cluster. A tie-breaker node exists only to +// hold a quorum vote: it is kept cordoned, runs no workloads and carries no +// Longhorn replicas, so node-local storage configuration does not apply to it. +// +// This is the authoritative test. Do not infer tie-breaker-ness from a node +// being unschedulable: Longhorn drives its node Schedulable condition off the +// Kubernetes cordon, which every node passes through at boot and during +// drains, so that signal would misclassify ordinary storage nodes. +// +// Returns false when the controller designated no tie-breaker (zero UUID) or +// nodeUUID does not parse, so a node is only treated as the tie-breaker on +// positive evidence from the EVE API config. +func (config EdgeNodeClusterConfig) IsTieBreakerNode(nodeUUID string) bool { + if config.TieBreakerNodeID.UUID == uuid.Nil { + return false + } + parsed, err := uuid.FromString(nodeUUID) + if err != nil { + return false + } + return parsed == config.TieBreakerNodeID.UUID +} + // EdgeNodeClusterStatus - Status of the multi-node cluster published by zedkube type EdgeNodeClusterStatus struct { ClusterName string @@ -209,16 +278,133 @@ type EdgeNodeClusterStatus struct { // only report here since they do not control kube-vip deployment. LBConfigError ErrorDescription + // WitnessIP mirrors EdgeNodeClusterConfig.WitnessIP. Consumed by NIM, which + // bridges the cluster port and plugs a veth carrying this address into the + // witness container's network namespace, and by the witness itself. + WitnessIP net.IP + + // WitnessConfigError mirrors EdgeNodeClusterConfig.WitnessConfigError so a + // witness the controller configured but the device rejected is visible + // remotely rather than only in the device log. + WitnessConfigError ErrorDescription + + // QuorumRecoveryGeneration mirrors + // EdgeNodeClusterConfig.QuorumRecoveryGeneration. + QuorumRecoveryGeneration uint32 + Error ErrorDescription } -// KubeLeaderElectInfo - Information about the status reporter leader election +// Node annotations through which kube-init reports state that only the +// node itself knows, for the elected cluster-info reporter to read back +// and forward to the controller. The same route node-uuid already +// takes: a node has no other way to tell the reporter something the +// kube API does not already hold. +// +// Unprefixed, matching the keys EVE already sets on its nodes +// (node-uuid, tie-breaker-node). Keys carrying another project's state, +// such as Longhorn's, keep that project's prefix. +const ( + // NodeRecoveryAnnotation carries a KubeQuorumRecoveryStatus as JSON. + NodeRecoveryAnnotation = "quorum-recovery" + // NodeWitnessAnnotation carries a WitnessStatus as JSON, stamped + // only by the device hosting the witness. + NodeWitnessAnnotation = "witness-status" +) + +// KubeQuorumRecoveryStatus is a device's progress against +// EdgeNodeCluster.quorum_recovery_generation. Reported by the device +// promoted to sole bootstrap via a forced etcd quorum reset; every other +// current/former member converges to nothing, since its cluster config +// is withdrawn outright instead. +type KubeQuorumRecoveryStatus struct { + // AppliedGeneration is the last generation this device fully + // converged to. + AppliedGeneration uint32 + // Converging is true while it is still working towards a newer one. + Converging bool + // Error is set when the most recent attempt failed; + // AppliedGeneration stays at the last one that succeeded. + Error ErrorDescription + // LastTransitionAt is when the state above last changed. + LastTransitionAt time.Time +} + +// WitnessEtcdState is the witness's view of its own etcd membership. +type WitnessEtcdState uint8 + +const ( + // WitnessEtcdStateUnspecified - never reported. + WitnessEtcdStateUnspecified WitnessEtcdState = iota + // WitnessEtcdStateIdle - running no etcd at all: no witness is + // configured for this cluster, or the witness has not yet started + // joining. + WitnessEtcdStateIdle + // WitnessEtcdStateJoining - k3s is up but this member is not yet a + // started, voting member. Includes the learner phase, during which + // etcd replicates to it but it casts no vote. + WitnessEtcdStateJoining + // WitnessEtcdStateJoined - an active voter; the healthy steady state. + WitnessEtcdStateJoined + // WitnessEtcdStateError - the witness failed to reach or hold + // membership. + WitnessEtcdStateError +) + +// String returns a human-readable name for the WitnessEtcdState. +func (s WitnessEtcdState) String() string { + switch s { + case WitnessEtcdStateIdle: + return "Idle" + case WitnessEtcdStateJoining: + return "Joining" + case WitnessEtcdStateJoined: + return "Joined" + case WitnessEtcdStateError: + return "Error" + default: + return "Unspecified" + } +} + +// WitnessStatus - status of the 2-node-HA witness, published by the +// kube-init daemon running in the witness container and consumed by +// zedkube on the same device, which forwards it to the controller. +// +// Published only by the device hosting the witness. Every other device +// has no witness container contributing to this topic. +type WitnessStatus struct { + // WitnessIP is the address this witness binds its etcd to, echoing + // the controller's configuration. + WitnessIP string + // State is the witness's own view of its etcd membership. + State WitnessEtcdState + // Error describes why the witness is not where it should be, e.g. a + // wrong token, an unreachable seed or a stale cluster ID - detail + // WitnessEtcdStateError alone does not carry. + Error ErrorDescription +} + +// Key - returns the key for the WitnessStatus publication. +func (status WitnessStatus) Key() string { + return "global" +} + +// KubeLeaderElectInfo - Information about the leader elections this node runs. +// InLeaderElection, IsStatsLeader, ElectionRunning, and LeaderIdentity +// describe the status-reporter election only. type KubeLeaderElectInfo struct { InLeaderElection bool IsStatsLeader bool ElectionRunning bool LeaderIdentity string - LatestChange time.Time + // IsAppOpLeader reports whether this node holds the eve-app-op lease, + // which is what decides the one node allowed to act on an app whose + // designated node is down. AppOpLeaderIdentity is the holder this node + // last observed, whether or not that is this node. + IsAppOpLeader bool + AppOpLeaderIdentity string + LatestChange time.Time } // VmiVNCConfig is the JSON structure for vmiVNC.run file. diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/contenttreetypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/contenttreetypes.go index 06c368b75f7..34c1bb4cc1e 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/contenttreetypes.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/contenttreetypes.go @@ -31,6 +31,12 @@ type ContentTreeConfig struct { CustomMeta string // Do we download on this node ? IsLocal bool + // DesignatedNodeUUID is the device UUID of this content tree's actual + // designated node, straight off the wire (unlike VolumeConfig, a + // content tree carries this directly, not via an owning app). Needed + // to ask whether a peer may act as backup DNID for it while that node + // is down; IsLocal only ever encoded "not me", never "who". + DesignatedNodeUUID string } // Key is content info UUID which will be unique diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/deferredcontentdeletetypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/deferredcontentdeletetypes.go new file mode 100644 index 00000000000..16ade807fc4 --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/deferredcontentdeletetypes.go @@ -0,0 +1,72 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package types + +import ( + "time" + + "github.com/lf-edge/eve/pkg/pillar/base" + uuid "github.com/satori/go.uuid" +) + +// DeferredContentDeleteStatus records a content-tree delete that volumemgr has +// deferred (timer.defer.content.delete) so the content's CAS blobs and image are +// kept for possible reuse instead of being deleted and immediately +// re-downloaded. +// +// It is published Persistent so the deferral survives a reboot — in particular +// the EVE-kvm->EVE-k boot-disk conversion, which deletes the running app before +// repartitioning and reboots. On the next boot volumemgr re-reads these records; +// the boot-time GC keeps the listed blobs and image until DeleteTime, and the +// actual delete happens at expiry (or is cancelled when the content tree is +// re-created and reuses the still-present blobs). +type DeferredContentDeleteStatus struct { + ContentID uuid.UUID // also the publication key (matches ContentTreeStatus.Key()) + GenerationCounter int64 + ReferenceID string // CAS image reference to remove at expiry + Blobs []string // blob sha256 (lowercase, no "sha256:" prefix) to keep then reap + DeleteTime time.Time // when the deferred delete becomes due +} + +// Key is the ContentID, matching ContentTreeStatus.Key() so a re-created +// content tree maps 1:1 to its pending deferred delete. +func (status DeferredContentDeleteStatus) Key() string { + return status.ContentID.String() +} + +// LogCreate : +func (status DeferredContentDeleteStatus) LogCreate(logBase *base.LogObject) { + logObject := base.NewLogObject(logBase, base.DeferredContentDeleteStatusLogType, "", + status.ContentID, status.LogKey()) + if logObject == nil { + return + } + logObject.CloneAndAddField("reference-id", status.ReferenceID). + AddField("blob-count-int64", len(status.Blobs)). + AddField("delete-time", status.DeleteTime.String()). + Noticef("Deferred content delete create") +} + +// LogModify : +func (status DeferredContentDeleteStatus) LogModify(logBase *base.LogObject, old interface{}) { + logObject := base.EnsureLogObject(logBase, base.DeferredContentDeleteStatusLogType, "", + status.ContentID, status.LogKey()) + logObject.CloneAndAddField("reference-id", status.ReferenceID). + AddField("blob-count-int64", len(status.Blobs)). + AddField("delete-time", status.DeleteTime.String()). + Noticef("Deferred content delete modify") +} + +// LogDelete : +func (status DeferredContentDeleteStatus) LogDelete(logBase *base.LogObject) { + logObject := base.EnsureLogObject(logBase, base.DeferredContentDeleteStatusLogType, "", + status.ContentID, status.LogKey()) + logObject.Noticef("Deferred content delete delete") + base.DeleteLogObject(logBase, status.LogKey()) +} + +// LogKey : +func (status DeferredContentDeleteStatus) LogKey() string { + return string(base.DeferredContentDeleteStatusLogType) + "-" + status.Key() +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/diskmetrics.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/diskmetrics.go index 1c90626ff66..e265fef5ce5 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/diskmetrics.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/diskmetrics.go @@ -36,13 +36,14 @@ var ReportDirPaths = []string{ PersistDir + "/checkpoint", PersistDir + "/containerd-system-root", PersistDir + "/netdump", - PersistDir + "/pubsub-large", PersistDir + "/reserved", PersistDir + "/etcd-storage", + PersistDir + "/witness-storage", PersistDir + "/kcrashes", PersistDir + "/eve-info", PersistDir + "/kubelog", PersistDir + "/kube-save-var-lib", + PersistDir + "/lost+found", // e2fsck orphans; unowned, never reclaimed } // AppPersistPaths Application-related files live here @@ -70,6 +71,12 @@ type DiskMetric struct { UsedBytes uint64 // Value in Bytes. Total number of used Bytes by the disk. FreeBytes uint64 // Value in Bytes. Total number of free Bytes for the disk. IsDir bool // Will be true if DiskPath is a mountPath, will false if it's a disk. + + // GPT identity for block partitions. Empty when IsDir is true, + // for whole-disk entries, and for partitions on non-GPT disks. + PartitionLabel string // GPT PARTLABEL + PartitionType string // GPT partition type GUID + PartitionUUID string // GPT PARTUUID } // Key returns the pubsub Key. @@ -92,6 +99,9 @@ func (status DiskMetric) LogCreate(logBase *base.LogObject) { AddField("userbytes-int64", status.UsedBytes). AddField("freebytes-int64", status.FreeBytes). AddField("isdor", status.IsDir). + AddField("partition-label", status.PartitionLabel). + AddField("partition-type", status.PartitionType). + AddField("partition-uuid", status.PartitionUUID). Metricf("DiskMetric status create") } @@ -111,6 +121,9 @@ func (status DiskMetric) LogModify(logBase *base.LogObject, old interface{}) { AddField("old-userbytes-int64", status.UsedBytes). AddField("old-freebytes-int64", status.FreeBytes). AddField("isdor", status.IsDir). + AddField("partition-label", status.PartitionLabel). + AddField("partition-type", status.PartitionType). + AddField("partition-uuid", status.PartitionUUID). Metricf("DiskMetric status modify") } diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/dns.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/dns.go index b1c91dd4cca..5005665d2da 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/dns.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/dns.go @@ -33,6 +33,19 @@ type NetworkPortStatus struct { IfName string Phylabel string // Physical name set by controller/model Logicallabel string + // PciLong is the long-form PCI address (e.g. "0000:06:00.0") of the + // physical device backing this port, when it has one. It gives the port a + // stable identity independent of the kernel-assigned interface name, which + // can differ from the model (e.g. ethN vs enpNsN) or change across driver + // re-binds. Empty for ports not backed by a PCI device (e.g. USB NICs). + PciLong string + // UnderlyingIfInstanceID identifies the interface NIM enslaves under a + // bridge when bridging this port (a physical NIC, VLAN sub-interface, or + // bond) -- always defined, whether or not the port is currently bridged. + UnderlyingIfInstanceID IfInstanceID + // BridgeIfInstanceID identifies the bridge NIM creates over + // UnderlyingIfInstanceID. Zero when this port isn't bridged by NIM. + BridgeIfInstanceID IfInstanceID // Unlike the logicallabel, which is defined in the device model and unique // for each port, these user-configurable "shared" labels are potentially // assigned to multiple ports so that they can be used all together with @@ -78,6 +91,13 @@ type NetworkPortStatus struct { LpsConfigError string } +// IfInstanceID uniquely identifies one concrete network-interface object +// (NIC, bridge, VLAN sub-interface, or bond) managed by NIM, system-wide. +// Unlike ifindex (reused by the kernel) or ifname (renamed by NIM), it +// changes only when NIM actually destroys and recreates the object. Zero +// means undefined. +type IfInstanceID uint64 + type AddrInfo struct { Addr net.IP Mask net.IPMask @@ -244,7 +264,9 @@ func (status DeviceNetworkStatus) MostlyEqual(status2 DeviceNetworkStatus) bool p1.InvalidConfig != p2.InvalidConfig || p1.Cost != p2.Cost || p1.MTU != p2.MTU || - p1.ConfigSource.Origin != p2.ConfigSource.Origin { + p1.ConfigSource.Origin != p2.ConfigSource.Origin || + p1.UnderlyingIfInstanceID != p2.UnderlyingIfInstanceID || + p1.BridgeIfInstanceID != p2.BridgeIfInstanceID { return false } if p1.Dhcp != p2.Dhcp || @@ -675,13 +697,22 @@ func getLocalAddrListImpl(dns DeviceNetworkStatus, return addrs, nil } -// Check if an interface name is a port owned by nim -func IsPort(dns DeviceNetworkStatus, ifname string) bool { +// IsPort reports whether the named interface, or the physical device at the +// given PCI address, is currently used as a device port owned by nim. Matching +// on pciLong (when non-empty) in addition to the interface name makes the check +// robust to the kernel-assigned name differing from the model (e.g. ethN vs +// enpNsN) or changing across driver re-binds. Either argument may be empty and +// an empty argument never matches, so passing an empty ifname with a non-empty +// pciLong matches purely on the PCI address (useful for a device whose modeled +// type is not network but which is in fact backing a network port). +func IsPort(dns DeviceNetworkStatus, ifname, pciLong string) bool { for _, us := range dns.Ports { - if us.IfName != ifname { - continue + if ifname != "" && us.IfName == ifname { + return true + } + if pciLong != "" && us.PciLong == pciLong { + return true } - return true } return false } diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/domainmgrtypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/domainmgrtypes.go index a22ecb48631..3a57ca520f7 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/domainmgrtypes.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/domainmgrtypes.go @@ -5,6 +5,7 @@ package types import ( "fmt" + "io" "net" "os" "strconv" @@ -61,6 +62,14 @@ type DomainConfig struct { // if this node is the DNiD of the App IsDNidNode bool + // DesignatedNodeUUID is the device UUID of the app's actual designated + // node, whichever node that is -- copied from AppInstanceConfig's field + // of the same name. IsDNidNode above only answers whether *this* node + // is it; this is what lets the node creating the domain (e.g. a backup + // node standing in during a DNID outage) resolve and encode the true + // home's node affinity instead of always encoding its own. + DesignatedNodeUUID string + // Node Affinity for cluster IsDesignatedNodeID AffinityType Affinity @@ -137,11 +146,6 @@ func (config DomainConfig) GetTaskName() string { // DomainnameToUUID does the reverse of GetTaskName func DomainnameToUUID(name string) (uuid.UUID, string, int, error) { - // FIXME: we can likely drop this altogether - if name == "Domain-0" { - return uuid.UUID{}, "", 0, nil - } - res := strings.Split(name, ".") if len(res) != 3 { return uuid.UUID{}, "", 0, fmt.Errorf("Unknown domainname format %s", @@ -179,6 +183,9 @@ func (config DomainConfig) VirtualizationModeOrDefault() VmMode { func (status DiskStatus) GetPVCNameFromVolumeKey() (string, error) { volumeIDAndGeneration := status.VolumeKey generation := strings.Split(volumeIDAndGeneration, "#") + if len(generation) < 2 { + return "", fmt.Errorf("invalid volume key %q: missing generation", volumeIDAndGeneration) + } volUUID, err := uuid.FromString(generation[0]) if err != nil { return "", fmt.Errorf("failed to parse volUUID: %w", err) @@ -261,8 +268,8 @@ func (config DomainConfig) LogKey() string { type VmConfig struct { Kernel string // default "" Ramdisk string // default "" - Memory int // in kbytes; Rounded up to Mbytes for xen - MaxMem int // in kbytes; Default equal to 'Memory', so no ballooning for xen + Memory int // in kbytes + MaxMem int // in kbytes; Default equal to 'Memory', so no ballooning VCpus int // default 1 MaxCpus int // default VCpus RootDev string // default "/dev/xvda1" @@ -327,6 +334,51 @@ type Task interface { Delete(string) error Info(string) (int, SwState, error) Cleanup(string) error + // WatchCrash returns a channel on which the hypervisor reports that the + // domain's virtual machine has crashed into a capturable, still-alive + // state (KVM: QMP STOP with run-state internal-error — "mode A"). It lets + // domainmgr own crash policy while the QMP details stay in the hypervisor + // package. Returns nil for hypervisors without this capability (all but + // KVM); a nil channel blocks forever in a select, which is the intent. + WatchCrash(domainName string) <-chan DomainCrashEvent + // DumpGuestMemory writes the guest's physical RAM as an ELF core to the + // io.Writer (streamed, so pillar can compress and quota it on the fly). It + // is a policy-free primitive; the caller decides when to dump and what to + // do afterwards. includeUnusedRAM controls dump-guest-memory's paging + // flag. Not supported (returns an error) on non-KVM hypervisors. + DumpGuestMemory(domainName string, w io.Writer) error + // GetDomainRunState returns the raw hypervisor run-state string + // ("running", "internal-error", "paused", …) as a pollable backstop for a + // missed WatchCrash event. Empty string / error on hypervisors without it. + GetDomainRunState(domainName string) (string, error) +} + +// CrashHandlingState tracks where a domain is in domainmgr's capture-first +// crash state machine. Any value other than CrashNone freezes reconcile for +// the domain so neither the reconcile loop nor an incoming controller config +// tears down or restarts qemu while a dump is in flight or the domain is held +// for inspection. +type CrashHandlingState uint8 + +const ( + // CrashNone means the domain is not handling a crash (the normal state). + CrashNone CrashHandlingState = iota + // CrashCaptureInProgress means a guest-core dump is being taken; teardown + // must wait for it to finish or fail. + CrashCaptureInProgress + // CrashCaptured means the dump completed (or failed) and policy has + // been/will be applied. + CrashCaptured + // CrashHeld means pause-on-crash is holding qemu alive for live inspection. + CrashHeld +) + +// DomainCrashEvent is the hypervisor-agnostic notification that a domain's VM +// crashed into a capturable state (mode A). RunState is the raw run-state that +// identified the crash (e.g. "internal-error"). +type DomainCrashEvent struct { + RunState string + When time.Time } type DomainStatus struct { @@ -347,7 +399,20 @@ type DomainStatus struct { PendingAdd bool PendingModify bool PendingDelete bool - DomainName string // Name of Xen domain + DomainName string // Name of the domain + // DomainId identifies the running domain, with hypervisor-specific meaning: + // for kvm it is the underlying qemu process's pid; for kubevirt (HV=k) + // it is a value derived from the app's current VMIRS/ReplicaSet identity + // (see hypervisor/kubevirt.go's workloadID), since there is no pid. + // + // The one invariant every hypervisor backend must uphold, and every + // consumer relies on: DomainId is zero if and only if the domain is + // confirmed not present (no process for kvm; VMIRS/ReplicaSet + // confirmed absent for kubevirt). It must never be zero merely because + // the answer is unknown or unattributable - doInactivate's teardown + // gates and doCleanup's success test both key on zero meaning "already + // gone", so a zero returned for any other reason skips a teardown that + // never happened and reports it as done. DomainId int BootTime time.Time DiskStatusList []DiskStatus @@ -385,6 +450,23 @@ type DomainStatus struct { // emitted the "trusting cluster to recover" log line. Used to deduplicate // that log to state transitions only. Zero = not yet logged. KubeVirt only. KubeTrustLoggedState SwState `json:"-"` + + // Crash-dump handling (KVM "mode A" crash). + // CrashState != CrashNone is the authoritative freeze flag: while set, + // reconcile must not tear down or restart the domain. + CrashState CrashHandlingState + // CrashRunState is the hypervisor run-state that identified the crash + // (e.g. "internal-error"). + CrashRunState string + // GuestCoreDumpPath is the vault path of the most recent guest core. + GuestCoreDumpPath string + // LastDumpTaken is set once a guest core has been captured for the current + // crash, so releasing a held domain does not needlessly re-dump. + LastDumpTaken bool `json:"-"` + // HoldUntil is when a pause-on-crash hold auto-releases (mode A). + HoldUntil time.Time + // GdbSocket is the gdbstub UNIX socket exposed for a held domain, if any. + GdbSocket string } func (status DomainStatus) Key() string { @@ -500,7 +582,7 @@ type VifInfo struct { VifUsed string // Has -emu in name in Status if appropriate } -// DomainManager will pass these to the xen xl config file +// DomainManager will pass these to the domain config file // The vdev is automatically assigned as xvd[x], where X is a, b, c etc, // based on the order in the DiskList // Note that vdev in general can be hd[x], xvd[x], sd[x] but here we only @@ -666,7 +748,6 @@ type OemWindowsLicenseKeyInfo struct { Qemu struct { DomainArguments []string } - Xen struct{} } // DmiSystemInfo hold system information extracted from dmidecode diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/dpc.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/dpc.go index dce061ca9f3..48d7bd688ca 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/dpc.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/dpc.go @@ -10,6 +10,7 @@ import ( "net" "os" "reflect" + "sort" "time" "github.com/google/go-cmp/cmp" @@ -168,6 +169,10 @@ const ( // LpsDPCKey : key used for DPC containing local configuration changes submitted by LPS. LpsDPCKey = "lps" + + // ControllerDPCKey : key used for DPC submitted by zedagent, based on + // configuration received from the controller (or LOC). + ControllerDPCKey = "zedagent" ) // DevicePortConfig is a misnomer in that it includes the total test results @@ -488,6 +493,21 @@ func (config *DevicePortConfig) DoSanitize(log *base.LogObject, args DPCSanitize } } +// GetMgmtPortsSortedByCost returns all management ports sorted by cost in ascending +// order. Ports with equal cost retain their original relative order (stable sort). +func (config *DevicePortConfig) GetMgmtPortsSortedByCost() []NetworkPortConfig { + var ports []NetworkPortConfig + for _, port := range config.Ports { + if port.IsMgmt { + ports = append(ports, port) + } + } + sort.SliceStable(ports, func(i, j int) bool { + return ports[i].Cost < ports[j].Cost + }) + return ports +} + // CountMgmtPorts returns the number of management ports // Exclude any broken ones with Dhcp = DhcpTypeNone // Optionally exclude mgmt ports with invalid config @@ -595,6 +615,13 @@ func (config DevicePortConfig) IsDPCUsable() bool { return mgmtCount > 0 } +// IsFromController returns true if this DPC originates from the controller +// (submitted by zedagent, based on configuration received from the +// controller or LOC). +func (config DevicePortConfig) IsFromController() bool { + return config.Key == ControllerDPCKey +} + // WasDPCWorking - Check if the last results for the DPC was Success func (config DevicePortConfig) WasDPCWorking() bool { diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/errorbound.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/errorbound.go new file mode 100644 index 00000000000..39e72451153 --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/errorbound.go @@ -0,0 +1,103 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package types + +import ( + "fmt" + "strings" + "unicode/utf8" +) + +// MaxErrorLen is the longest error string an ErrorDescription carries; +// SetErrorDescription cuts longer ones down with TruncateError. The bound is +// what keeps a status publishable: a pubsub message carries 64 KiB, and an +// AppInstanceStatus embeds one error per volume reference on top of its own, +// so an error that grows with what went wrong (one entry per source address, +// per blob, per volume) has to be bounded somewhere every status passes. +const MaxErrorLen = 4096 + +// OversizedStatusErrorLen is what the error strings of a status are cut down +// to when the status still does not fit a pubsub message: short enough for +// a status with many volumes to fit, long enough to still say what failed. +const OversizedStatusErrorLen = 256 + +// truncatedNoteFmt replaces the bytes TruncateError drops from the middle. +const truncatedNoteFmt = " [... %d bytes dropped ...] " + +// TruncateError returns s when it is at most maxLen bytes long. Otherwise it +// keeps the head and the tail of s with a note in between saying how many +// bytes were dropped: the head because that is where the cause usually is, +// the tail because that is where a wrapped error or a command's output ends. +// Cuts land on rune boundaries. +func TruncateError(s string, maxLen int) string { + if len(s) <= maxLen { + return s + } + if maxLen <= 0 { + return "" + } + // The note is longest with the whole length in it, so the result stays + // within maxLen whatever the dropped count turns out to be. + keep := maxLen - len(fmt.Sprintf(truncatedNoteFmt, len(s))) + if keep < 2 { + return s[:runeStartBefore(s, maxLen)] + } + head := runeStartBefore(s, keep*2/3) + tailStart := runeStartAfter(s, len(s)-(keep-head)) + return s[:head] + fmt.Sprintf(truncatedNoteFmt, tailStart-head) + s[tailStart:] +} + +// JoinMaxErrorStrings joins errs with sep like strings.Join, as far as the result +// stays within maxLen bytes: the errors that do not fit are left out and +// replaced by a note of how many they were. The first error is always +// included, cut down with TruncateError when it alone does not fit. +func JoinMaxErrorStrings(errs []string, sep string, maxLen int) string { + if len(errs) == 0 { + return "" + } + if joined := strings.Join(errs, sep); len(joined) <= maxLen { + return joined + } + note := func(n int) string { return fmt.Sprintf("... and %d more", n) } + var b strings.Builder + for i, e := range errs { + after := len(errs) - i - 1 + if i == 0 { + budget := maxLen + if after > 0 { + budget -= len(sep) + len(note(after)) + } + b.WriteString(TruncateError(e, budget)) + continue + } + need := b.Len() + len(sep) + len(e) + if after > 0 { + need += len(sep) + len(note(after)) + } + if need > maxLen { + b.WriteString(sep) + b.WriteString(note(after + 1)) + break + } + b.WriteString(sep) + b.WriteString(e) + } + return b.String() +} + +// runeStartBefore moves i back to the start of the rune it falls into. +func runeStartBefore(s string, i int) int { + for i > 0 && i < len(s) && !utf8.RuneStart(s[i]) { + i-- + } + return i +} + +// runeStartAfter moves i forward to the start of the next rune. +func runeStartAfter(s string, i int) int { + for i < len(s) && !utf8.RuneStart(s[i]) { + i++ + } + return i +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/errortime.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/errortime.go index 48b22a6c0e9..d7b89bc8c13 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/errortime.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/errortime.go @@ -101,6 +101,7 @@ func (ed *ErrorDescription) SetErrorDescription(errDescription ErrorDescription) logrus.Fatal("Missing error string") } *ed = errDescription + ed.Error = TruncateError(ed.Error, MaxErrorLen) if ed.ErrorSeverity == ErrorSeverityUnspecified { ed.ErrorSeverity = ErrorSeverityError } diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/evaluation.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/evaluation.go deleted file mode 100644 index 6bb6e961e7d..00000000000 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/evaluation.go +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright (c) 2026 Zededa, Inc. -// SPDX-License-Identifier: Apache-2.0 - -package types - -import ( - "fmt" - "strings" - "time" - - "github.com/lf-edge/eve/pkg/pillar/base" -) - -// EvalPhase represents the current phase of evaluation -type EvalPhase string - -const ( - // EvalPhaseInit - Initial phase, evaluation manager starting up - EvalPhaseInit EvalPhase = "init" - // EvalPhaseTesting - Currently testing slots one by one - EvalPhaseTesting EvalPhase = "testing" - // EvalPhaseFinal - Evaluation complete, best slot selected and running - EvalPhaseFinal EvalPhase = "final" -) - -// SlotName represents a partition slot name -type SlotName string - -const ( - // SlotIMGA - Image A partition - SlotIMGA SlotName = "IMGA" - // SlotIMGB - Image B partition - SlotIMGB SlotName = "IMGB" - // SlotIMGC - Image C partition - SlotIMGC SlotName = "IMGC" - // SlotFinal - Special value indicating no more slots to test (evaluation complete) - SlotFinal SlotName = "FINAL" -) - -// AllSlots returns all valid slot names -func AllSlots() []SlotName { - return []SlotName{SlotIMGA, SlotIMGB, SlotIMGC} -} - -// SlotEvalState tracks the evaluation state of a single slot -type SlotEvalState struct { - // Tried indicates if this slot has been attempted to boot - Tried bool `json:"tried"` - // Success indicates if the slot booted successfully - Success bool `json:"success"` - // Note contains additional information about this slot's evaluation - Note string `json:"note,omitempty"` - // AttemptTime when this slot was last attempted - AttemptTime time.Time `json:"attempt_time,omitempty"` -} - -// EvalPersist represents the persistent state stored in /persist/eval/state.json -type EvalPersist struct { - // Slots maps slot names to their evaluation state - Slots map[SlotName]SlotEvalState `json:"slots"` - // BestSlot is the slot determined to be the best after evaluation - BestSlot SlotName `json:"best_slot,omitempty"` - // Phase tracks the current evaluation phase - Phase EvalPhase `json:"phase"` - // LastUpdated timestamp of last state update - LastUpdated time.Time `json:"last_updated"` -} - -// EvalStatus is published by evalmgr to communicate evaluation state -type EvalStatus struct { - // IsEvaluationPlatform indicates if this is an evaluation device - IsEvaluationPlatform bool - // CurrentSlot is the currently booted slot - CurrentSlot SlotName - // Phase is the current evaluation phase - Phase EvalPhase - // AllowOnboard gates whether onboarding should proceed - AllowOnboard bool - // Note contains human-readable status information - Note string - // LastUpdated timestamp when this status was last updated - LastUpdated time.Time - // TestStartTime when current test phase started - TestStartTime time.Time - // TestDuration total duration for current test phase - TestDuration time.Duration - // RebootCountdown seconds until reboot (0 if no reboot pending) - RebootCountdown int - // InventoryCollected indicates if hardware inventory was collected for current slot - InventoryCollected bool - // InventoryDir is the directory path where inventory was stored (empty if not collected) - InventoryDir string -} - -// Key returns the key for pubsub (single instance) -func (status EvalStatus) Key() string { - return "evalmgr" -} - -// LogCreate logs the creation of EvalStatus -func (status EvalStatus) LogCreate(logBase *base.LogObject) { - logObject := base.NewLogObject(logBase, base.EvalStatusLogType, "", - nilUUID, status.LogKey()) - if logObject == nil { - return - } - logObject.CloneAndAddField("is-evaluation", status.IsEvaluationPlatform). - AddField("current-slot", string(status.CurrentSlot)). - AddField("phase", string(status.Phase)). - AddField("allow-onboard", status.AllowOnboard). - AddField("note", status.Note). - AddField("test-duration", status.TestDuration). - AddField("reboot-countdown", status.RebootCountdown). - Noticef("EvalStatus create") -} - -// LogModify logs modifications to EvalStatus -func (status EvalStatus) LogModify(logBase *base.LogObject, old interface{}) { - logObject := base.EnsureLogObject(logBase, base.EvalStatusLogType, "", - nilUUID, status.LogKey()) - - oldStatus, ok := old.(EvalStatus) - if !ok { - logObject.Clone().Fatalf("LogModify: Old object interface passed is not of EvalStatus type") - } - - // Log changes to key fields - if oldStatus.Phase != status.Phase || - oldStatus.AllowOnboard != status.AllowOnboard || - oldStatus.CurrentSlot != status.CurrentSlot { - - logObject.CloneAndAddField("phase", string(status.Phase)). - AddField("old-phase", string(oldStatus.Phase)). - AddField("allow-onboard", status.AllowOnboard). - AddField("old-allow-onboard", oldStatus.AllowOnboard). - AddField("current-slot", string(status.CurrentSlot)). - AddField("old-current-slot", string(oldStatus.CurrentSlot)). - AddField("note", status.Note). - Noticef("EvalStatus modify") - } -} - -// LogDelete logs the deletion of EvalStatus -func (status EvalStatus) LogDelete(logBase *base.LogObject) { - logObject := base.EnsureLogObject(logBase, base.EvalStatusLogType, "", - nilUUID, status.LogKey()) - logObject.CloneAndAddField("phase", string(status.Phase)). - AddField("allow-onboard", status.AllowOnboard). - Noticef("EvalStatus delete") - - base.DeleteLogObject(logBase, status.LogKey()) -} - -// LogKey returns the log key for EvalStatus -func (status EvalStatus) LogKey() string { - return string(base.EvalStatusLogType) + "-evalmgr" -} - -// IsOnboardingAllowed returns whether onboarding should be allowed based on the current evaluation status. -// This method encapsulates the logic for determining onboarding permission based on multiple internal states. -func (status EvalStatus) IsOnboardingAllowed() bool { - // If not an evaluation platform, always allow onboarding - if !status.IsEvaluationPlatform { - return true - } - - // For evaluation platforms, check multiple conditions: - - // 1. Explicit AllowOnboard flag (primary control) - if !status.AllowOnboard { - return false - } - - // 2. Phase-based logic - don't allow onboarding during active testing - switch status.Phase { - case EvalPhaseInit: - // During init phase, allow if explicitly permitted - return status.AllowOnboard - case EvalPhaseTesting: - // During testing phase, be more restrictive - // Only allow if explicitly set (for manual overrides) - return status.AllowOnboard - case EvalPhaseFinal: - // Final phase - evaluation complete, allow onboarding - return true - default: - // Unknown phase - be conservative - return false - } -} - -// OnboardingBlockReason returns a human-readable reason why onboarding is blocked. -// Returns empty string if onboarding is allowed. -func (status EvalStatus) OnboardingBlockReason() string { - // If not an evaluation platform, always allow onboarding - if !status.IsEvaluationPlatform { - return "" - } - - // Check if onboarding is allowed first - if status.IsOnboardingAllowed() { - return "" - } - - // Provide specific reasons based on state - if !status.AllowOnboard { - switch status.Phase { - case EvalPhaseInit: - return "evaluation platform initializing" - case EvalPhaseTesting: - return "evaluation platform testing in progress" - case EvalPhaseFinal: - return "evaluation complete but onboarding explicitly disabled" - default: - return "evaluation platform not ready" - } - } - - // Phase-based restrictions - switch status.Phase { - case EvalPhaseTesting: - return "evaluation testing in progress" - default: - return "evaluation platform in unknown state" - } -} - -// RemainingTime returns the remaining time for current test phase -func (status EvalStatus) RemainingTime() time.Duration { - if status.TestStartTime.IsZero() || status.TestDuration == 0 { - return 0 - } - elapsed := time.Since(status.TestStartTime) - if elapsed >= status.TestDuration { - return 0 - } - return status.TestDuration - elapsed -} - -// ElapsedTime returns elapsed time since test started -func (status EvalStatus) ElapsedTime() time.Duration { - if status.TestStartTime.IsZero() { - return 0 - } - return time.Since(status.TestStartTime) -} - -// ProgressPercent returns test progress as percentage (0-100) -func (status EvalStatus) ProgressPercent() int { - if status.TestDuration == 0 { - return 0 - } - elapsed := status.ElapsedTime() - if elapsed >= status.TestDuration { - return 100 - } - return int((elapsed * 100) / status.TestDuration) -} - -// TimeStatusString returns human-readable time status -func (status EvalStatus) TimeStatusString() string { - if status.Phase != EvalPhaseTesting { - return "" - } - - remaining := status.RemainingTime() - elapsed := status.ElapsedTime() - progress := status.ProgressPercent() - - if remaining == 0 { - return fmt.Sprintf("Test complete (%v elapsed)", elapsed.Round(time.Second)) - } - - return fmt.Sprintf("Progress %d%% (%v/%v remaining: %v)", - progress, - elapsed.Round(time.Second), - status.TestDuration.Round(time.Second), - remaining.Round(time.Second)) -} - -// RebootStatusString returns reboot countdown status -func (status EvalStatus) RebootStatusString() string { - if status.RebootCountdown <= 0 { - return "" - } - return fmt.Sprintf("Requesting reboot in %d sec", status.RebootCountdown) -} - -// DetailedNote returns comprehensive status with timing info -func (status EvalStatus) DetailedNote() string { - parts := []string{status.Note} - - if timeStatus := status.TimeStatusString(); timeStatus != "" { - parts = append(parts, timeStatus) - } - - if rebootStatus := status.RebootStatusString(); rebootStatus != "" { - parts = append(parts, rebootStatus) - } - - if status.InventoryCollected && status.InventoryDir != "" { - parts = append(parts, fmt.Sprintf("inventory=%s", status.InventoryDir)) - } - - return strings.Join(parts, "; ") -} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/global.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/global.go index 4ec6b4849ff..3fa6d2c7c8d 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/global.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/global.go @@ -12,6 +12,7 @@ import ( "regexp" "strconv" "strings" + "time" "github.com/Masterminds/semver" "github.com/lf-edge/eve/pkg/pillar/base" @@ -150,6 +151,16 @@ func (gs *GlobalStatus) UpdateItemValuesFromGlobalConfig(gc ConfigItemValueMap) // A value of zero means we should use the default // All times are in seconds. +// DefaultVolumemgrWorkerPoolSize is the default for VolumemgrWorkerPoolSize. +// It matches the previously hardcoded pool size, so the setting is +// behaviour-neutral until an operator raises it. +const DefaultVolumemgrWorkerPoolSize = 20 + +// DefaultDownloaderTransportHandlers is the default for +// DownloaderTransportHandlers. It matches the default of the zedUpload +// transport itself, so that the knob changes nothing until it is set. +const DefaultDownloaderTransportHandlers = 11 + // GlobalSettingKey - Constants of all global setting keys type GlobalSettingKey string @@ -194,6 +205,10 @@ const ( NetworkTestDuration GlobalSettingKey = "timer.port.testduration" // NetworkTestInterval global setting key NetworkTestInterval GlobalSettingKey = "timer.port.testinterval" + // NetworkTestFailInterval global setting key: minimum time a DPC must + // wait after a verification failure before it is eligible to be + // retested again (DpcManager.DpcMinTimeSinceFailure). + NetworkTestFailInterval GlobalSettingKey = "timer.port.testfailinterval" // NetworkTestBetterInterval global setting key NetworkTestBetterInterval GlobalSettingKey = "timer.port.testbetterinterval" // NetworkTestTimeout global setting key @@ -223,6 +238,23 @@ const ( AppContainerStatsInterval GlobalSettingKey = "timer.appcontainer.stats.interval" // VaultReadyCutOffTime global setting key VaultReadyCutOffTime GlobalSettingKey = "timer.vault.ready.cutoff" + // VaultTrimMaxSecs is the maximum seconds per fstrim run on the vault + // zvol. 0 means no timeout (run to completion). Note: the boot-time trim + // runs before ConversionComplete is reported, which gates vaultmgr's + // waitUnsealed and therefore k3s startup on EVE-k. With 0 (unbounded) a + // slow first-boot trim can delay vault-ready reporting and block k3s + // startup for as long as the trim takes; keep this non-zero to bound it. + VaultTrimMaxSecs GlobalSettingKey = "timer.vault.trim.max.secs" + // VaultTrimCron is the cron schedule for periodic fstrim of the vault and + // zvol on EVE-k ZFS nodes. Empty string disables the timer. + // Standard 5-field cron syntax; cronValidator enforced. + VaultTrimCron GlobalSettingKey = "timer.vault.trim.cron" + // ZFSPoolTrimCron is the cron schedule for periodic zpool trim of the + // persist pool on EVE-k ZFS nodes. Empty string disables the timer. + ZFSPoolTrimCron GlobalSettingKey = "timer.zfs.pool.trim.cron" + // ZFSPoolTrimRate caps the average trim rate of each disk (leaf vdev) in + // the persist pool on EVE-k ZFS nodes, in bytes/s. + ZFSPoolTrimRate GlobalSettingKey = "storage.zfs.pool.trim.rate.bytespersec" // LogRemainToSendMBytes Max gzip log files remain on device to be sent in Mbytes LogRemainToSendMBytes GlobalSettingKey = "newlog.gzipfiles.ondisk.maxmegabytes" @@ -238,6 +270,24 @@ const ( // how many times EVE will retry to download a blob if its checksum is not verified BlobDownloadMaxRetries GlobalSettingKey = "blob.download.max.retries" + // VolumemgrWorkerPoolSize global setting key + // maximum number of concurrent volumemgr background jobs: loading images + // into the CAS, and preparing, creating and destroying volumes all draw + // on this single pool. Work that cannot be submitted is deferred and + // retried, so this bounds throughput rather than correctness. Raise it on + // nodes running many app instances; each concurrent CAS ingest streams a + // layer through pillar, so the practical ceiling is pillar's memory + // cgroup and the disk. + VolumemgrWorkerPoolSize GlobalSettingKey = "volumemgr.worker.pool.size" + + // DownloaderTransportHandlers global setting key + // number of workers of the downloader's zedUpload transport, which is + // also the depth of the request queue in front of them. A download whose + // request finds the queue full retries the submission with a backoff, for + // up to timer.download.stalled. The transport is sized once, when the + // downloader starts, so a change takes effect at the next reboot. + DownloaderTransportHandlers GlobalSettingKey = "downloader.transport.handlers" + // Bool Items // UsbAccess global setting key UsbAccess GlobalSettingKey = "debug.enable.usb" @@ -272,6 +322,11 @@ const ( AllowLogFastupload GlobalSettingKey = "newlog.allow.fastupload" // EnableARPSnoopOnNI global setting key EnableARPSnoop GlobalSettingKey = "network.switch.enable.arpsnoop" + // ARPSnoopIPExpiry : how long (in seconds) an IP address learned from ARP packets + // is still reported as assigned to an application interface after the last ARP + // packet carrying this address was seen. After that EVE only stops reporting + // the address, it is not removed from the application. + ARPSnoopIPExpiry GlobalSettingKey = "network.switch.arpsnoop.expiry" // WwanQueryVisibleProviders : periodically query visible cellular service providers WwanQueryVisibleProviders GlobalSettingKey = "wwan.query.visible.providers" // WwanModemRecoveryWatchdog : trigger watchdog when cellular modem crashes and fails to recover. @@ -290,6 +345,13 @@ const ( // descheduling. Currently only "boot" is supported. When empty (default), no // event-driven descheduling is performed. KubernetesVmiDescheduleEvents GlobalSettingKey = "kubernetes.vmi.deschedule.events" + // DnidOutageThresholdForUsage : how long an app's designated node has to + // have been unhealthy (seconds) before another cluster node may act on + // that app in its place. The effective delay is this plus the Kubernetes + // node-monitor grace period, and is floored at the eve-app-op lease + // duration: a threshold below the lease is bounded by how long the lease + // takes to change hands, not by this value. + DnidOutageThresholdForUsage GlobalSettingKey = "cluster.dnid.backupnode.threshold" // GoroutineLeakDetectionThreshold amount of goroutines, reaching which will trigger leak detection // regardless of growth rate. @@ -443,6 +505,51 @@ const ( // passthrough firmware-side issues with a TARGET=DEBUG OVMF rebuild. EnableEFIDebug GlobalSettingKey = "debug.enable.efi" + // QemuProcessCore: when true (default), the qemu process gets a large + // RLIMIT_CORE and the host kernel core_pattern points at the encrypted + // vault, so if qemu dies on a fatal signal (SIGBUS/SIGSEGV/SIGABRT — the + // "mode B" case) the kernel writes a process core that pillar then + // compresses and rotates. + QemuProcessCore GlobalSettingKey = "debug.qemu.process.core" + + // QemuGuestCore: when true (default), pillar dumps the guest's physical RAM + // (QMP dump-guest-memory, ELF) when qemu enters RUN_STATE_INTERNAL_ERROR + // after KVM_RUN -EFAULT (the "mode A" case). + QemuGuestCore GlobalSettingKey = "debug.qemu.guest.core" + + // QemuProcessCoreGuestRAM: when true, qemu sets `dump-guest-core = "on"` on + // the machine config so a qemu process core (QemuProcessCore) *includes* + // the guest's RAM. Off by default: it makes the core as large as the VM's + // RAM and it can hold guest secrets, and the guest RAM is already captured + // far more cheaply by the mode-A guest core (QemuGuestCore). + QemuProcessCoreGuestRAM GlobalSettingKey = "debug.qemu.process.core.guest.ram" + + // QemuPauseOnCrash: when true, on a mode-A crash domainmgr holds the domain + // (keeps qemu alive, freezes reconcile) for live inspection instead of + // tearing it down, until an operator releases it or a timeout expires. Off + // by default — an opt-in inspection aid layered on top of the always-on + // guest-core dump. + QemuPauseOnCrash GlobalSettingKey = "debug.qemu.pause.on.crash" + + // QemuTraceEvents: a comma-separated list of qemu trace-event names/globs + // and/or @ macros (e.g. "@vfio,@iommu,vfio_pci_write_config"). When + // non-empty, qemu runs with -trace writing a binary simpletrace log per VM + // to the encrypted vault. Empty (default) disables tracing. Presets are + // expanded by qemuTracePresets in kvm.go. + QemuTraceEvents GlobalSettingKey = "debug.qemu.trace.events" + + // QemuGdb: when true, qemu exposes a per-domain gdbstub UNIX socket for live + // vCPU inspection (and for a pause-on-crash hold). Off by default. + QemuGdb GlobalSettingKey = "debug.qemu.gdb" + + // QemuIgpuNoMmap: when true, add x-no-mmap=on to the Intel iGPU vfio-pci + // device so every BAR access traps into qemu instead of being mmap'd direct + // to hardware. Debug-only: it makes the guest's iGPU MMIO writes visible in + // the qemu trace (and lets us test whether the scanout corruption is an + // mmap/BAR-remap fast-path race). Large performance cost; off by default. + // Only affects the iGPU device. + QemuIgpuNoMmap GlobalSettingKey = "debug.qemu.igpu.no.mmap" + // MsrvPrometheusMetricsRequestPerSecond: limit the number of requests per second MsrvPrometheusMetricsRequestPerSecond GlobalSettingKey = "msrv.prometheus.metrics.rps" // MsrvPrometheusMetricsBurst: limit the burst of requests @@ -470,6 +577,17 @@ const ( // over any EVE-OS baseos version defined k3s version (pkg/kube/cluster-update.sh) K3sVersionOverride GlobalSettingKey = "k3s.version" + // LonghornSnapshotCron is the cron expression for the Longhorn recurring snapshot job + // used as delta-rebuild baselines after node power loss. Empty string disables recurring + // snapshots. Default "0 0 * * *" (daily at midnight UTC). Standard 5-field cron syntax. + LonghornSnapshotCron GlobalSettingKey = "storage.longhorn.snapshot.cron" + + // LonghornNodeDrainPolicy sets the Longhorn cluster-wide node-drain-policy setting. + // Valid values: "block-for-eviction", "block-for-eviction-if-contains-last-replica", + // "allow-if-replica-is-stopped", "always-allow". + // Default "block-for-eviction-if-contains-last-replica". EVE-k only. + LonghornNodeDrainPolicy GlobalSettingKey = "storage.longhorn.node-drain-policy" + // SCEPRetryInterval defines the time interval between retry attempts // for certificates that previously failed to enroll or returned PENDING // from the SCEP server. @@ -504,12 +622,25 @@ const ( LpsNetworkInterval GlobalSettingKey = "timer.lps.network.interval" // LpsAppBootInfoInterval defines interval between LPS app boot info POSTs. LpsAppBootInfoInterval GlobalSettingKey = "timer.lps.appbootinfo.interval" + + // DataStoreAllowInsecureAuth allows authentication header via http + DataStoreAllowInsecureAuth GlobalSettingKey = "datastore.http.security.allowinsecureauth" ) // LonghornDiskReservedGBDisabled is the sentinel value for LonghornDiskReservedGB that // disables EVE's override, leaving the current Longhorn storageReserved value untouched. const LonghornDiskReservedGBDisabled uint32 = 1024 * 1024 +// Valid values for LonghornNodeDrainPolicy. +// https://longhorn.io/docs/1.9.1/maintenance/maintenance/#node-drain-policy-recommendations +// Please update above if pkg/kube/longhorn-utils.sh LONGHORN_VERSION=v1.9.1 changes. +const ( + LonghornNodeDrainPolicyBlockForEviction = "block-for-eviction" + LonghornNodeDrainPolicyBlockIfContainsLastReplica = "block-for-eviction-if-contains-last-replica" + LonghornNodeDrainPolicyAllowIfReplicaIsStopped = "allow-if-replica-is-stopped" + LonghornNodeDrainPolicyAlwaysAllow = "always-allow" +) + // AgentSettingKey - keys for per-agent settings type AgentSettingKey string @@ -1092,7 +1223,8 @@ func NewConfigItemSpecMap() ConfigItemSpecMap { configItemSpecMap.AddIntItem(NetworkGeoRedoTime, HourInSec, 60, 0xFFFFFFFF) configItemSpecMap.AddIntItem(NetworkGeoRetryTime, 10*MinuteInSec, 5, 0xFFFFFFFF) configItemSpecMap.AddIntItem(NetworkTestDuration, 30, 10, HourInSec) - configItemSpecMap.AddIntItem(NetworkTestInterval, 5*MinuteInSec, 5*MinuteInSec, HourInSec) + configItemSpecMap.AddIntItem(NetworkTestInterval, 5*MinuteInSec, MinuteInSec, HourInSec) + configItemSpecMap.AddIntItem(NetworkTestFailInterval, 5*MinuteInSec, MinuteInSec, HourInSec) configItemSpecMap.AddIntItem(NetworkTestBetterInterval, 10*MinuteInSec, 0, 0xFFFFFFFF) configItemSpecMap.AddIntItem(NetworkTestTimeout, 15, 0, HourInSec) configItemSpecMap.AddIntItem(NetworkSendTimeout, 2*MinuteInSec, 0, HourInSec) @@ -1103,6 +1235,14 @@ func NewConfigItemSpecMap() ConfigItemSpecMap { configItemSpecMap.AddIntItem(Dom0MinDiskUsagePercent, 20, 20, 80) configItemSpecMap.AddIntItem(AppContainerStatsInterval, 5*MinuteInSec, 1, 0xFFFFFFFF) configItemSpecMap.AddIntItem(VaultReadyCutOffTime, 5*MinuteInSec, MinuteInSec, 0xFFFFFFFF) + // VaultTrimMaxSecs: default 30 min; 0 = unlimited (run to completion) + configItemSpecMap.AddIntItem(VaultTrimMaxSecs, 30*MinuteInSec, 0, 0xFFFFFFFF) + // VaultTrimCron / ZFSPoolTrimCron: weekends at 02:00 / 03:00 (staggered) + configItemSpecMap.AddStringItem(VaultTrimCron, "0 2 * * 6,0", cronValidator) + configItemSpecMap.AddStringItem(ZFSPoolTrimCron, "0 3 * * 6,0", cronValidator) + // ZFSPoolTrimRate: default 1.5 MiB/s per disk, one pass over 1 TB of free + // space on a disk in about a week + configItemSpecMap.AddIntItem(ZFSPoolTrimRate, 1536*1024, 64*1024, 0xFFFFFFFF) // Dom0DiskUsageMaxBytes - Default is 2GB, min is 100MB configItemSpecMap.AddIntItem(Dom0DiskUsageMaxBytes, 2*1024*1024*1024, 100*1024*1024, 0xFFFFFFFF) @@ -1134,6 +1274,8 @@ func NewConfigItemSpecMap() ConfigItemSpecMap { configItemSpecMap.AddIntItem(LogRemainToSendMBytes, 2048, 10, 0xFFFFFFFF) configItemSpecMap.AddIntItem(DownloadMaxPortCost, 0, 0, 255) configItemSpecMap.AddIntItem(BlobDownloadMaxRetries, 5, 1, 10) + configItemSpecMap.AddIntItem(VolumemgrWorkerPoolSize, DefaultVolumemgrWorkerPoolSize, 1, 200) + configItemSpecMap.AddIntItem(DownloaderTransportHandlers, DefaultDownloaderTransportHandlers, 1, 1024) // Goroutine Leak Detection section configItemSpecMap.AddIntItem(GoroutineLeakDetectionThreshold, 5000, 1, 0xFFFFFFFF) @@ -1162,6 +1304,7 @@ func NewConfigItemSpecMap() ConfigItemSpecMap { configItemSpecMap.AddBoolItem(ConsoleAccess, true) // Controller likely default to false configItemSpecMap.AddBoolItem(VncShimVMAccess, false) configItemSpecMap.AddBoolItem(EnableARPSnoop, true) + configItemSpecMap.AddIntItem(ARPSnoopIPExpiry, 10*MinuteInSec, 5, 24*HourInSec) configItemSpecMap.AddBoolItem(WwanQueryVisibleProviders, false) configItemSpecMap.AddBoolItem(WwanModemRecoveryWatchdog, false) configItemSpecMap.AddBoolItem(WwanModemRecoveryReloadDrivers, false) @@ -1170,6 +1313,14 @@ func NewConfigItemSpecMap() ConfigItemSpecMap { configItemSpecMap.AddBoolItem(MemoryMonitorEnabled, false) configItemSpecMap.AddBoolItem(DHCPEnableVendorClassID, true) configItemSpecMap.AddBoolItem(EnableEFIDebug, false) + configItemSpecMap.AddBoolItem(QemuProcessCore, true) + configItemSpecMap.AddBoolItem(QemuGuestCore, true) + configItemSpecMap.AddBoolItem(QemuProcessCoreGuestRAM, false) + configItemSpecMap.AddBoolItem(QemuPauseOnCrash, false) + configItemSpecMap.AddStringItem(QemuTraceEvents, "", blankValidator) + configItemSpecMap.AddBoolItem(QemuGdb, false) + configItemSpecMap.AddBoolItem(QemuIgpuNoMmap, false) + configItemSpecMap.AddBoolItem(DataStoreAllowInsecureAuth, false) // Add TriState Items configItemSpecMap.AddTriStateItem(NetworkFallbackAnyEth, TS_DISABLED) @@ -1227,6 +1378,17 @@ func NewConfigItemSpecMap() ConfigItemSpecMap { configItemSpecMap.AddStringItem(K3sConfigOverride, "", base64Validator) configItemSpecMap.AddStringItem(K3sVersionOverride, "", k3sVersionValidator) configItemSpecMap.AddStringItem(KubernetesVmiDescheduleEvents, "", blankValidator) + // DnidOutageThresholdForUsage - ten minutes by default. The minimum is a + // minute rather than zero: at zero a backup would take over as soon as + // the node-monitor grace period elapsed, which defeats the point of + // requiring a sustained outage, and anything under the eve-app-op lease + // duration is floored by lease handover anyway. + configItemSpecMap.AddIntItem(DnidOutageThresholdForUsage, 10*MinuteInSec, + MinuteInSec, 24*HourInSec) + // LonghornSnapshotCron - Default daily at midnight. Empty string = disable recurring snapshots. + configItemSpecMap.AddStringItem(LonghornSnapshotCron, "0 0 * * *", cronValidator) + configItemSpecMap.AddStringItem(LonghornNodeDrainPolicy, + LonghornNodeDrainPolicyBlockIfContainsLastReplica, validateLonghornNodeDrainPolicy) // SCEP settings configItemSpecMap.AddIntItem(SCEPRetryInterval, 5*MinuteInSec, MinuteInSec, HourInSec) @@ -1266,6 +1428,18 @@ func validateBootOrder(bootOrder string) error { } } +func validateLonghornNodeDrainPolicy(policy string) error { + switch policy { + case LonghornNodeDrainPolicyBlockForEviction, + LonghornNodeDrainPolicyBlockIfContainsLastReplica, + LonghornNodeDrainPolicyAllowIfReplicaIsStopped, + LonghornNodeDrainPolicyAlwaysAllow: + return nil + default: + return fmt.Errorf("validateLonghornNodeDrainPolicy: invalid value %q", policy) + } +} + // validateGOPRomFilename - require a plain basename with no path separators // or traversal components. Empty is allowed and means "use the bundled // VfioIgdPkg ROM". The file is loaded from /persist/vault/gop/ at runtime. @@ -1362,6 +1536,149 @@ func blankValidator(s string) error { return nil } +// CronMatch reports whether t matches a 5-field cron spec that has already +// passed cronValidator. Supports *, numeric values, comma lists, and ranges. +// Weekday field treats both 0 and 7 as Sunday. +func CronMatch(spec string, t time.Time) bool { + if spec == "" { + return false + } + fields := strings.Fields(spec) + if len(fields) != 5 { + return false + } + vals := [5]int{t.Minute(), t.Hour(), t.Day(), int(t.Month()), int(t.Weekday())} + // [lo, hi] inclusive range per field; used as the base/bound for "*" and + // "*/n" so a step starts at the field minimum (1 for day-of-month/month), + // matching standard cron. Must stay in sync with cronValidator. + fieldRanges := [5][2]int{{0, 59}, {0, 23}, {1, 31}, {1, 12}, {0, 7}} + for i, f := range fields { + if !cronFieldMatch(f, vals[i], fieldRanges[i][0], fieldRanges[i][1], i == 4) { + return false + } + } + return true +} + +// CronShouldFire reports whether a scheduled action should fire at time t. +// It combines CronMatch with single-minute deduplication: the action fires +// only when the spec matches AND the truncated minute differs from *lastFired. +// On a match, *lastFired is updated. Designed for use inside a +// time.NewTicker(time.Minute) loop; spec="" is always false. +func CronShouldFire(spec string, t time.Time, lastFired *time.Time) bool { + tMin := t.Truncate(time.Minute) + if CronMatch(spec, t) && tMin != *lastFired { + *lastFired = tMin + return true + } + return false +} + +// cronFieldMatch reports whether val matches a single cron field token. +// fieldLo/fieldHi are the field's inclusive valid range, used as the base and +// bound for "*"/"*/n". isWeekday causes both 0 and 7 to match Sunday (val +// always 0-6 from time). +func cronFieldMatch(field string, val, fieldLo, fieldHi int, isWeekday bool) bool { + for _, atom := range strings.Split(field, ",") { + if cronAtomMatch(atom, val, fieldLo, fieldHi, isWeekday) { + return true + } + } + return false +} + +func cronAtomMatch(atom string, val, fieldLo, fieldHi int, isWeekday bool) bool { + if atom == "*" { + return true + } + // Step: */n or lo-hi/n + step := 1 + if idx := strings.Index(atom, "/"); idx >= 0 { + s, err := strconv.Atoi(atom[idx+1:]) + if err != nil || s <= 0 { + return false + } + step = s + atom = atom[:idx] + } + // Range: lo-hi or single value + var lo, hi int + if idx := strings.Index(atom, "-"); idx >= 0 { + var err1, err2 error + lo, err1 = strconv.Atoi(atom[:idx]) + hi, err2 = strconv.Atoi(atom[idx+1:]) + if err1 != nil || err2 != nil { + return false + } + } else if atom == "*" { + // Bare "*" (with a step): iterate the full field range so "*/n" + // starts at the field minimum, matching standard cron. + lo, hi = fieldLo, fieldHi + } else { + n, err := strconv.Atoi(atom) + if err != nil { + return false + } + if isWeekday && n == 7 { + n = 0 + } + lo, hi = n, n + } + for v := lo; v <= hi; v += step { + check := v + if isWeekday && check == 7 { + check = 0 + } + if check == val { + return true + } + } + return false +} + +// cronValidator accepts empty (feature disabled) or standard 5-field cron expressions. +// It rejects non-5-field forms (@hourly, 6-field, etc.), fields with invalid characters, +// and field values that fall outside each position's valid numeric range. +func cronValidator(s string) error { + if s == "" { + return nil + } + fields := strings.Fields(s) + if len(fields) != 5 { + return fmt.Errorf("cronValidator: %q must be empty or a 5-field cron expression (got %d fields)", s, len(fields)) + } + // [lo, hi] inclusive range for minute, hour, day-of-month, month, day-of-week. + fieldRanges := [5][2]int{{0, 59}, {0, 23}, {1, 31}, {1, 12}, {0, 7}} + for i, f := range fields { + for _, c := range f { + if !strings.ContainsRune("0123456789*/-,", c) { + return fmt.Errorf("cronValidator: %q contains invalid character %q in field %q", s, c, f) + } + } + lo, hi := fieldRanges[i][0], fieldRanges[i][1] + for _, atom := range strings.Split(f, ",") { + // Strip step suffix: "*/5" → "*", "1-31/7" → "1-31". + valuePart := strings.SplitN(atom, "/", 2)[0] + if valuePart == "*" { + continue + } + for _, token := range strings.Split(valuePart, "-") { + if token == "" || token == "*" { + continue + } + n, err := strconv.Atoi(token) + if err != nil { + return fmt.Errorf("cronValidator: %q contains non-numeric token %q in field %q", s, token, f) + } + if n < lo || n > hi { + return fmt.Errorf("cronValidator: %q field %d value %d out of range [%d, %d]", s, i+1, n, lo, hi) + } + } + } + } + return nil +} + func base64Validator(s string) error { _, err := base64.StdEncoding.DecodeString(s) if err != nil { diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/ifnametopci.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/ifnametopci.go index aa82d781923..678cec23eb2 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/ifnametopci.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/ifnametopci.go @@ -7,7 +7,6 @@ package types import ( - "errors" "fmt" "os" "path" @@ -21,8 +20,11 @@ import ( "github.com/vishvananda/netlink" ) -const basePath = "/sys/class/net" -const pciPath = "/sys/bus/pci/devices" +// basePath and pciPath are the sysfs roots for interface and PCI lookups. +// They are variables (not constants) so tests can redirect them at a +// fabricated sysfs tree; production never changes them. +var basePath = "/sys/class/net" +var pciPath = "/sys/bus/pci/devices" // ExtractUSBBusnumPort extracts busnum and port number out of a sysfs device path func ExtractUSBBusnumPort(path string) (uint16, string, error) { @@ -45,8 +47,11 @@ func ExtractUSBBusnumPort(path string) (uint16, string, error) { return busnum, port, nil } -// Returns the long PCI IDs and the USB address (if available) -func ifNameToPciAndUsbAddr(log *base.LogObject, ifName string) (string, string, error) { +// IfNameToPciAndUsbAddr returns the long-form PCI address and USB address (if +// any) of the device backing ifName. An L3 port bridged by nim (renamed to +// "k"+ifName) is resolved transparently. Not reliable for cellular modems +// (returns the PCIe bridge, not the modem); use WwanNetworkStatus.PhysAddrs.PCI. +func IfNameToPciAndUsbAddr(log *base.LogObject, ifName string) (string, string, error) { // Match for PCI IDs re := regexp.MustCompile("([0-9a-f]){4}:([0-9a-f]){2}:([0-9a-f]){2}.[ls0-9a-f]") var usbAddr string @@ -121,10 +126,14 @@ func ifNameToPciAndUsbAddr(log *base.LogObject, ifName string) (string, string, } link = path.Clean(link) components := strings.Split(link, "/") - for _, c := range components { - if re.MatchString(c) { - log.Noticef("Fallback found %s", c) - return c, usbAddr, nil + // The path may contain several PCI addresses when the NIC sits behind + // PCI(e) bridges (e.g. behind a pcie-root-port in a VM): take the last + // match, which is the device itself -- the earlier matches are its + // upstream bridges, and assigning a bridge to vfio-pci fails (-EINVAL). + for i := len(components) - 1; i >= 0; i-- { + if re.MatchString(components[i]) { + log.Noticef("Fallback found %s", components[i]) + return components[i], usbAddr, nil } } return target, usbAddr, fmt.Errorf("Not PCI %s", target) @@ -149,7 +158,12 @@ func vfIfNameToPci(ifName string) (string, error) { // PCILongToShort returns the PCI ID without the domain id func PCILongToShort(long string) string { - return strings.SplitAfterN(long, ":", 2)[1] + parts := strings.SplitAfterN(long, ":", 2) + if len(parts) < 2 { + // No domain-id prefix to strip; return the input unchanged. + return long + } + return parts[1] } // PCISameController compares the PCI-ID without comparing the controller @@ -251,7 +265,7 @@ func IoBundleToPci(log *base.LogObject, ib *IoBundle) (string, error) { //nolint if ib.Type == IoNetEthVF { l, err = vfIfNameToPci(ib.Ifname) } else { - l, ib.UsbAddr, err = ifNameToPciAndUsbAddr(log, ib.Ifname) + l, ib.UsbAddr, err = IfNameToPciAndUsbAddr(log, ib.Ifname) } rename := false if err == nil { @@ -263,35 +277,44 @@ func IoBundleToPci(log *base.LogObject, ib *IoBundle) (string, error) { //nolint } else { rename = true } + var renameWarn []string if rename { found, ifname := PciLongToIfname(log, long) if found && ib.Ifname != ifname { log.Warnf("%s/%s moved to %s", ib.Ifname, long, ifname) + // Renaming to match the model is an auto-adjustment; warn so + // the controller sees it. + renameWarn = []string{fmt.Sprintf( + "adapter %s (logicallabel %s): model interface name %q does "+ + "not match kernel name %q for PCI %s; renamed to match the model", + ib.Phylabel, ib.Logicallabel, ib.Ifname, ifname, long)} IfRename(log, ifname, ib.Ifname) } } + // Reconcile the rename warning (self-clears when no longer renaming). + ib.Error.SetSourceErrors(ErrIoBundleRename{}, true, false, renameWarn) } } else if ib.Ifname != "" { var err error if ib.Type == IoNetEthVF { long, err = vfIfNameToPci(ib.Ifname) if err != nil { - return long, err + return long, ErrIoBundleMissingDevice{msg: err.Error()} } } else { - long, ib.UsbAddr, err = ifNameToPciAndUsbAddr(log, ib.Ifname) + long, ib.UsbAddr, err = IfNameToPciAndUsbAddr(log, ib.Ifname) if err != nil { - return long, err + return long, ErrIoBundleMissingDevice{msg: err.Error()} } } } else { return "", nil } if !pciLongExists(long) { - errStr := fmt.Sprintf("PCI device %s/%s long %s does not exist", - ib.Phylabel, ib.Logicallabel, long) - return long, errors.New(errStr) + return long, ErrIoBundleMissingDevice{msg: fmt.Sprintf( + "PCI device %s/%s long %s does not exist", + ib.Phylabel, ib.Logicallabel, long)} } return long, nil } diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/locationconsts.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/locationconsts.go index 5207178ca43..1a6e07b502d 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/locationconsts.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/locationconsts.go @@ -45,6 +45,10 @@ const ( PersistCachePatchEnvelopes = PersistDir + "/patchEnvelopesCache" // PersistCachePatchEnvelopesUsage - folder to store patch envelopes usage stat per app PersistCachePatchEnvelopesUsage = PersistDir + "/patchEnvelopesUsageCache" + // HWWatchdogBootStatusFile holds the hardware watchdog boot status flag + // names (one per line) recorded by pkg/watchdog at boot. A "CARDRESET" + // entry means the watchdog reset the device on the previous boot. + HWWatchdogBootStatusFile = PersistDir + "/hw_watchdog_bootstatus" // IdentityDirname - Config dir IdentityDirname = "/config" @@ -80,6 +84,9 @@ const ( ITokenFile = "/run/eve.integrity_token" //EveVersionFile contains the running version of EVE EveVersionFile = "/run/eve-release" + //EveOriginVersionPattern matches the origin.. file created in + //the config partition at install time. + EveOriginVersionPattern = IdentityDirname + "/origin.*" //DefaultVaultName is the name of the default vault DefaultVaultName = "Application Data Store" @@ -95,14 +102,6 @@ const ( NewlogUploadAppDir = NewlogDir + "/appUpload" // NewlogKeepSentQueueDir - a circular queue of gzip files already been sent NewlogKeepSentQueueDir = NewlogDir + "/keepSentQueue" - // PillarHardMemoryLimitFile - hard memory reserved for pillar - PillarHardMemoryLimitFile = "/hostfs/sys/fs/cgroup/memory/eve/services/pillar/memory.limit_in_bytes" - // EveMemoryLimitFile - stores memory reserved for eve - EveMemoryLimitFile = "/hostfs/sys/fs/cgroup/memory/eve/memory.limit_in_bytes" - // EveMemoryUsageFile - current usage - EveMemoryUsageFile = "/hostfs/sys/fs/cgroup/memory/eve/memory.usage_in_bytes" - // EveKmemUsageFile - current kernel usage - EveKmemUsageFile = "/hostfs/sys/fs/cgroup/memory/eve/memory.kmem.usage_in_bytes" // ZFSArcMaxSizeFile - file with zfs_arc_max size in bytes ZFSArcMaxSizeFile = "/hostfs/sys/module/zfs/parameters/zfs_arc_max" @@ -135,7 +134,7 @@ const ( // OVMFSettingsDir - directory for OVMF settings, they are stored in per-domain files OVMFSettingsDir = SealedDirName + "/ovmf" // OVMFSettingsTemplate - template file for OVMF settings - OVMFSettingsTemplate = "/usr/lib/xen/boot/OVMF_VARS.fd" + OVMFSettingsTemplate = "/usr/share/ovmf/OVMF_VARS.fd" // CustomOVMFSettingsDir - directory for custom OVMF settings (for different resolutions) CustomOVMFSettingsDir = "/hostfs/etc/ovmf" @@ -159,6 +158,11 @@ const ( // changing this file does not change the actual policy, hence // needs not be protected. PolicyPcrFile = PersistStatusDir + "/policy-pcr.json" + + // KvmToKubePendingFilename - marker under PersistStatusDir that EVE-kvm's + // baseosmgr writes before converting the device to EVE-k. The first EVE-k + // boot relocates the carried-over kvm volumes and removes it. + KvmToKubePendingFilename = "kvm-to-k-pending" ) var ( @@ -176,8 +180,25 @@ var ( VolumeClearZFSDataset = ClearDataset + "/volumes" //VolumeEncryptedZFSDataset - dataset to create volumes with encryption VolumeEncryptedZFSDataset = SealedDataset + "/volumes" + // KvmParkedSealedDataset - the EVE-kvm filesystem vault that the EVE-k + // vault migration renames aside. EVE-k keeps it until the app-volume zvols + // it holds have been carried into PVCs; an EVE-kvm fallback puts it back. + KvmParkedSealedDataset = SealedDataset + ".old" + // KvmParkedVolumeEncryptedZFSDataset - the EVE-kvm encrypted app-volume + // zvols inside KvmParkedSealedDataset + KvmParkedVolumeEncryptedZFSDataset = KvmParkedSealedDataset + "/volumes" // EtcdZvol - zvol encrypted for etcd storage EtcdZvol = PersistDataset + "/etcd-storage" + // WitnessZvol - zvol encrypted for the 2-node-HA witness's etcd. + // Only created when InstallOptionWitnessZvol was given at install. + WitnessZvol = PersistDataset + "/witness-storage" + // WitnessZvolMarker records that WitnessZvol was reserved at install + // time. The witness cannot tell a zvol that was never reserved from + // one whose device node has not appeared yet, and the two need + // opposite responses: fall back to vault-backed storage, or wait. + // Written by vault once the zvol is created; on /persist so it is + // readable before the vault is unsealed. + WitnessZvolMarker = PersistDir + "/witness-zvol-reserved" // TpmMeasurementLogFile is a kernel exposed variable that contains the // TPM measurements and events log. it is not a constant so tests can override it. TpmMeasurementLogFile = "/hostfs/sys/kernel/security/tpm0/binary_bios_measurements" diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/memory.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/memory.go index a52ff042cd6..90ad4db1bff 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/memory.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/memory.go @@ -5,34 +5,48 @@ package types import ( "fmt" + "math" "os" "runtime/debug" "strconv" "strings" + + "github.com/lf-edge/eve/pkg/pillar/utils/cgroup" +) + +// EveCgroup and PillarCgroup name EVE's cgroup and pillar's, relative to the +// cgroup v2 root (see pkg/dom0-ztools/rootfs/etc/init.d/010-eve-cgroup). +const ( + EveCgroup = "eve" + PillarCgroup = "eve/services/pillar" ) -// GetPillarHardMemoryLimitInBytes returns hard memory limit -// reserved for pillar in bytes +// GetPillarHardMemoryLimitInBytes returns pillar's cgroup memory.max; +// cgroup.Unlimited when it has none. func GetPillarHardMemoryLimitInBytes() (uint64, error) { - return readUint64File(PillarHardMemoryLimitFile) + return cgroup.ReadUint(PillarCgroup, "memory.max") } -// GetEveMemoryLimitInBytes returns memory limit -// reserved for eve in bytes +// GetEveMemoryLimitInBytes returns EVE's cgroup memory.max. func GetEveMemoryLimitInBytes() (uint64, error) { - return readUint64File(EveMemoryLimitFile) + return cgroup.ReadUint(EveCgroup, "memory.max") } -// GetEveMemoryUsageInBytes returns memory limit -// reserved for eve in bytes +// GetEveMemoryUsageInBytes returns the memory charged to EVE's cgroup, kernel +// memory included. func GetEveMemoryUsageInBytes() (uint64, error) { - return readUint64File(EveMemoryUsageFile) + return cgroup.ReadUint(EveCgroup, "memory.current") } -// GetEveKmemUsageInBytes returns memory limit -// reserved for eve in bytes +// GetEveKmemUsageInBytes returns the kernel memory charged to EVE's cgroup, +// already part of GetEveMemoryUsageInBytes; 0 on kernels before 5.18, whose +// memory.stat has no "kernel" line. func GetEveKmemUsageInBytes() (uint64, error) { - return readUint64File(EveKmemUsageFile) + stat, err := cgroup.MemoryStat(EveCgroup) + if err != nil { + return 0, err + } + return stat["kernel"], nil } // GetZFSArcMaxSizeInBytes returns memory limit @@ -71,7 +85,13 @@ func ConfigureGOGC(limit int64, percent int) (int64, int, error) { // significant to ensure that after the soft limit is reached, there // will be enough memory for the GOGC to do its job and, fortunately, // not to hit the hard limit. - limit = int64(ulimit) * 600 / 1000 + if ulimit <= math.MaxInt64/600 { + limit = int64(ulimit) * 600 / 1000 + } else { + // No cgroup limit (cgroup.Unlimited) or one too large to + // scale, so no Go memory limit either. + limit = math.MaxInt64 + } } if percent == 0 { // Disable GC diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/mgmtproxytypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/mgmtproxytypes.go new file mode 100644 index 00000000000..884b75d6da5 --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/mgmtproxytypes.go @@ -0,0 +1,48 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package types + +// These types describe the JSON payload served by the mgmtproxy agent's +// GET /healthz endpoint (127.0.0.1:5443/healthz). They are exported here, +// rather than kept private to the agent, so other components (e.g. edgeview) +// can unmarshal and process the snapshot, and so the wire contract of +// /healthz is documented in one place. The JSON tags are the contract — do +// not change them without updating consumers. + +// MgmtProxyPortSummary describes one management port as seen by mgmtproxy's +// cost-aware dialer, for /healthz output. +type MgmtProxyPortSummary struct { + IfName string `json:"ifname"` + Cost uint8 `json:"cost"` + IsMgmt bool `json:"isMgmt"` + HasError bool `json:"hasError,omitempty"` + LastError string `json:"lastError,omitempty"` + NumAddrs int `json:"numAddrs"` + UsableAddr string `json:"usableAddr,omitempty"` +} + +// MgmtProxyHealthz is the JSON snapshot returned by mgmtproxy's GET /healthz: +// listener state, the effective max port cost, the visible management ports, +// traffic counters, and the last success/error with timestamps. +type MgmtProxyHealthz struct { + Listening string `json:"listening"` + CNI0Listening bool `json:"cni0Listening"` + Ready bool `json:"ready"` + MaxPortCost uint8 `json:"maxPortCost"` + Ports []MgmtProxyPortSummary `json:"ports"` + Requests uint64 `json:"requests"` + DialFailures uint64 `json:"dialFailures"` + NotReady uint64 `json:"notReady"` + TunnelIdleClosed uint64 `json:"tunnelIdleClosed"` + BytesUp uint64 `json:"bytesUp"` + BytesDown uint64 `json:"bytesDown"` + SuccessByPort map[string]uint64 `json:"successByPort"` + FailureByPort map[string]uint64 `json:"failureByPort"` + LastSuccessTime string `json:"lastSuccessTime,omitempty"` + LastSuccessTarget string `json:"lastSuccessTarget,omitempty"` + LastSuccessPort string `json:"lastSuccessPort,omitempty"` + LastSuccessCost uint8 `json:"lastSuccessCost,omitempty"` + LastErrorTime string `json:"lastErrorTime,omitempty"` + LastError string `json:"lastError,omitempty"` +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/vaultmgrtypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/vaultmgrtypes.go index 830e937057e..ceaef29e172 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/vaultmgrtypes.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/vaultmgrtypes.go @@ -4,12 +4,107 @@ package types import ( + "fmt" + "time" + "github.com/lf-edge/eve-api/go/info" "github.com/google/go-cmp/cmp" "github.com/lf-edge/eve/pkg/pillar/base" ) +// VaultUnlockMethod records how a vault was unlocked this boot, so an operator +// can tell a clean local TPM unseal apart from a controller-key recovery (both +// of which end with Status enabled). +type VaultUnlockMethod uint8 + +const ( + // VaultUnlockNone means the vault is not (yet) unlocked. + VaultUnlockNone VaultUnlockMethod = iota + // VaultUnlockTPMLocalSealed means the locally TPM-sealed key unsealed + // against the current PCRs, with no controller involvement. + VaultUnlockTPMLocalSealed + // VaultUnlockControllerKey means the local unseal failed (e.g. a PCR policy + // mismatch) and the controller-provided escrowed key was used instead. + VaultUnlockControllerKey + // VaultUnlockNoTPM means the platform has no TPM; the key is not sealed. + VaultUnlockNoTPM + // VaultUnlockRecreated means the local unseal failed and the controller had + // no escrowed key to return, so the vault was wiped and recreated empty. No + // key unlocked the existing vault; its prior contents were lost. + VaultUnlockRecreated +) + +// String implements fmt.Stringer. +func (m VaultUnlockMethod) String() string { + switch m { + case VaultUnlockTPMLocalSealed: + return "tpm-local-sealed" + case VaultUnlockControllerKey: + return "controller-key" + case VaultUnlockNoTPM: + return "no-tpm" + case VaultUnlockRecreated: + return "recreated" + default: + return "none" + } +} + +// ToProto returns the protobuf representation. The info.VaultUnlockMethod +// values are numbered to match this type, so the conversion is a plain cast. +func (m VaultUnlockMethod) ToProto() info.VaultUnlockMethod { + return info.VaultUnlockMethod(m) +} + +// VaultKeyDerivation records how the vault key is derived: from the TPM key +// alone, or from that key merged with the fixed constant kept for vaults +// created before the TPM-only scheme, where half the key material is not +// TPM-held. +type VaultKeyDerivation uint8 + +const ( + // VaultKeyDerivationNone means no vault key is derived, either because the + // platform has no TPM or because the persist filesystem sets up no vault. + VaultKeyDerivationNone VaultKeyDerivation = iota + // VaultKeyDerivationTPMOnly means the key is the TPM key alone. + VaultKeyDerivationTPMOnly + // VaultKeyDerivationTPMAndConstant means the key is the TPM key merged with + // the fixed constant, the derivation used by vaults created before the + // TPM-only scheme. + VaultKeyDerivationTPMAndConstant +) + +// String implements fmt.Stringer. +func (d VaultKeyDerivation) String() string { + switch d { + case VaultKeyDerivationTPMOnly: + return "tpm-only" + case VaultKeyDerivationTPMAndConstant: + return "tpm-and-constant" + default: + return "none" + } +} + +// ToProto returns the protobuf representation. The info.VaultKeyDerivation +// values are numbered to match this type, so the conversion is a plain cast. +func (d VaultKeyDerivation) ToProto() info.VaultKeyDerivation { + return info.VaultKeyDerivation(d) +} + +// VaultTrimStatus records the outcome of the most recent vault fstrim +// operation. Nested inside VaultStatus. All fields are zero/empty if no trim +// has run since boot. EVE-k ZFS nodes only. +type VaultTrimStatus struct { + // LastStartTime is when the most recent fstrim began. + LastStartTime time.Time + // LastEndTime is when it completed. Zero while in progress or never run. + LastEndTime time.Time + // LastError is the error from the most recent fstrim, or empty on success. + LastError string +} + // VaultStatus represents running status of a Vault type VaultStatus struct { Name string @@ -18,6 +113,22 @@ type VaultStatus struct { ConversionComplete bool // only valid if TPM is enabled and Sealed key is used MismatchingPCRs []int + // UnlockMethod records how the vault was unlocked this boot (local TPM key, + // controller-provided key, no TPM, or a wipe-and-recreate). VaultUnlockNone + // until unlocked. VaultUnlockTPMLocalSealed means the locally TPM-sealed key + // unsealed on the first attempt; VaultUnlockControllerKey means the local + // unseal failed and the device is relying on the controller-key fallback; + // VaultUnlockRecreated means the local unseal failed with no escrowed key, so + // the vault was wiped and recreated (prior contents lost). + UnlockMethod VaultUnlockMethod + // KeyDerivation records whether the vault key comes from the TPM alone or + // is still merged with the fixed constant kept for vaults created before + // the TPM-only scheme. VaultKeyDerivationNone where no vault key is + // derived at all: no TPM, or a persist filesystem that sets up no vault. + KeyDerivation VaultKeyDerivation + // TrimStatus holds the result of the most recent vault fstrim. + // Populated on EVE-k ZFS nodes only; zero otherwise. + TrimStatus VaultTrimStatus // ErrorAndTime provides SetErrorNow() and ClearError() ErrorAndTime } @@ -198,3 +309,16 @@ func (key EncryptedVaultKeyFromController) LogKey() string { func (status VaultStatus) IsVaultInError() bool { return (status.Status == info.DataSecAtRestStatus_DATASEC_AT_REST_ERROR) && len(status.MismatchingPCRs) > 0 } + +// FormatMismatchingPCRs returns a human-readable clause naming the PCR indexes +// that probably prevented the sealed vault key from being unsealed, or an empty +// string when none are known. The wording is shared by vaultmgr (which folds it +// into VaultStatus.Error) and nodeagent (which adds it to the reboot reason), so +// the explanation reads the same wherever it surfaces - VaultStatus, diag, and +// the controller-visible BaseOsStatus error. +func FormatMismatchingPCRs(mismatchingPCRs []int) string { + if len(mismatchingPCRs) == 0 { + return "" + } + return fmt.Sprintf("possibly mismatching PCR indexes %v", mismatchingPCRs) +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/volumetypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/volumetypes.go index 38e3b78a959..5663e3bf58d 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/volumetypes.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/volumetypes.go @@ -33,6 +33,19 @@ type VolumeConfig struct { // This volume is container image for native container. // We will find out from NOHYPER flag in appinstanceconfig IsNativeContainer bool + // DesignatedNodeUUID is the device UUID of the owning app's actual + // designated node, cross-referenced from AppInstanceConfig via the + // owning app's VolumeRefList -- IsReplicated only says "not me", not + // who. Needed to ask whether a peer may act as backup DNID for this + // volume while that node is down. + DesignatedNodeUUID string + // AffinityType mirrors AppInstanceConfig.AffinityType for the same + // reason IsCurrentlyBackupDNID excludes Required-affinity apps from + // activation: a Required-affinity app can never run anywhere but its + // designated node, so backup-DNID eligibility must exclude it here + // too. If more than one app references this volume with different + // affinity, treat it as Required if any of them are. + AffinityType Affinity } // Key is volume UUID which will be unique @@ -41,6 +54,15 @@ func (config VolumeConfig) Key() string { config.GenerationCounter+config.LocalGenerationCounter) } +// GetPVCName : returns the kubernetes(longhorn) PVC name for this volume. +// Must produce the same name as VolumeStatus.GetPVCName() for the same volume +// and generation; callers rely on the generation being embedded in the name so +// that a lookup by name can only ever match this exact generation. +func (config VolumeConfig) GetPVCName() string { + return fmt.Sprintf("%s-pvc-%d", config.VolumeID.String(), + config.GenerationCounter+config.LocalGenerationCounter) +} + // LogCreate : func (config VolumeConfig) LogCreate(logBase *base.LogObject) { logObject := base.NewLogObject(logBase, base.VolumeConfigLogType, config.DisplayName, @@ -143,6 +165,18 @@ type VolumeStatus struct { // We find that info from NOHYPER flag set in appinstance. IsNativeContainer bool + // ClusterStorageTransientErr is set when the current volume-create Error came + // from the EVE-k cluster storage stack (Longhorn/CDI/k8s API) while it was + // still coming up, and is therefore worth retrying once it is ready. Set from + // the typed kubeapi verdict when the error is recorded; false on other HVs. + ClusterStorageTransientErr bool + + // ClusterStorageRetryCount counts how many times retryFailedClusterVolumeCreate + // has re-driven this volume after a transient cluster-storage failure. It bounds + // the retry so an un-typeable or misclassified failure cannot loop forever; + // reset to 0 when the volume-create succeeds. + ClusterStorageRetryCount int + ErrorAndTimeWithSource } @@ -344,6 +378,13 @@ func (config VolumeRefConfig) VolumeKey() string { config.GenerationCounter+config.LocalGenerationCounter) } +// GetPVCName : the kubernetes(longhorn) PVC name of the referenced volume. +// Must agree with VolumeStatus.GetPVCName, since both name the same object. +func (config VolumeRefConfig) GetPVCName() string { + return fmt.Sprintf("%s-pvc-%d", config.VolumeID.String(), + config.GenerationCounter+config.LocalGenerationCounter) +} + // LogCreate : func (config VolumeRefConfig) LogCreate(logBase *base.LogObject) { logObject := base.NewLogObject(logBase, base.VolumeRefConfigLogType, "", @@ -607,8 +648,14 @@ func (status VolumeCreatePending) LogDelete(logBase *base.LogObject) { // VolumeMgrStatus : type VolumeMgrStatus struct { - Name string - Initialized bool + Name string + Initialized bool + // UnmetCondition names the readiness gate still outstanding when + // Initialized is false, e.g. "longhorn not ready: longhorn missing + // daemonset:engine-image". Empty when Initialized is true. Informational: + // it exists so an operator can tell a converging cluster from a stuck one + // without correlating agent logs. + UnmetCondition string RemainingSpace uint64 // In bytes. Takes into account "reserved" for dom0 } diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedagenttypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedagenttypes.go index 3c166c62836..8c4976634fb 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedagenttypes.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedagenttypes.go @@ -88,6 +88,11 @@ type BaseOsStatus struct { // Minimum state across all steps/StorageStatus. // Error* set implies error. State SwState + // Converting is set while the boot disk is being repartitioned for an + // EVE-kvm -> EVE-k flavor change (before the A/B install). zedagent maps it + // to DEVICE_STATE_CONVERTING; ConvertSubState carries the progress phase. + Converting bool + ConvertSubState DeviceSubState // error strings across all steps/StorageStatus // ErrorAndTime provides SetErrorNow() and ClearError() ErrorAndTime @@ -259,12 +264,13 @@ const ( BootReasonOOM // OOM causing process to be killed BootReasonWatchdogHung // Software watchdog due stuck agent BootReasonWatchdogPid // Software watchdog due to e.g., golang panic - BootReasonKernel // Set by dump-capture kernel, see docs/KERNEL-DUMPS.md and pkg/kdump/kdump.sh for details + BootReasonKernel // Kernel panic recorded in pstore, see docs/KERNEL-DUMPS.md BootReasonPowerFail // Known power failure e.g., from disk controller S.M.A.R.T counter increase BootReasonUnknown // Could be power failure, kernel panic, or hardware watchdog BootReasonVaultFailure // Vault was not ready within the expected time BootReasonPoweroffCmd // Start after Local Profile Server poweroff BootReasonKubeTransition // Transition to/from kubernetes single/cluster modes + BootReasonHWWatchdog // Hardware watchdog reset the device; only on drivers reporting WDIOF_CARDRESET BootReasonParseFail = 255 // BootReasonFromString didn't find match ) @@ -303,6 +309,8 @@ func (br BootReason) String() string { return "BootReasonPoweroffCmd" case BootReasonKubeTransition: return "BootReasonKubeTransition" + case BootReasonHWWatchdog: + return "BootReasonHWWatchdog" default: return fmt.Sprintf("Unknown BootReason %d", br) } @@ -345,6 +353,8 @@ func (br BootReason) StartWithSavedConfig() bool { return true case BootReasonKubeTransition: return true + case BootReasonHWWatchdog: + return false default: return false } @@ -388,6 +398,8 @@ func BootReasonFromString(str string) BootReason { return BootReasonPoweroffCmd case "BootReasonKubeTransition": return BootReasonKubeTransition + case "BootReasonHWWatchdog": + return BootReasonHWWatchdog default: return BootReasonParseFail } @@ -592,6 +604,24 @@ const ( DEVICE_STATE_PREPARING_POWEROFF = 6 DEVICE_STATE_POWERING_OFF = 7 DEVICE_STATE_PREPARED_POWEROFF = 8 + DEVICE_STATE_CONVERTING = 9 +) + +//revive:enable:var-naming + +// DeviceSubState mirrors ZDeviceSubState in lf-edge/eve-api: the sub-state +// reported alongside DEVICE_STATE_CONVERTING for the EVE-kvm -> EVE-k +// boot-disk conversion. +type DeviceSubState uint8 + +// Integer values must match those in ZDeviceSubState in lf-edge/eve-api/proto/info/info.proto +// +//revive:disable:var-naming +const ( + DEVICE_SUBSTATE_UNSPECIFIED DeviceSubState = iota + DEVICE_SUBSTATE_CONVERT_REBOOTING_TO_RESIZE + DEVICE_SUBSTATE_CONVERT_INSTALLING + DEVICE_SUBSTATE_CONVERT_REBOOTING_TO_TARGET ) //revive:enable:var-naming @@ -616,6 +646,8 @@ func (ds DeviceState) String() string { return "powering_off" case DEVICE_STATE_PREPARED_POWEROFF: return "prepared_poweroff" + case DEVICE_STATE_CONVERTING: + return "converting" default: return fmt.Sprintf("Unknown state %d", ds) } diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedcloudmetrics.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedcloudmetrics.go index 2397d09d22a..8a12cb24e5b 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedcloudmetrics.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedcloudmetrics.go @@ -13,6 +13,21 @@ import ( // when logging type MetricsMap map[string]ControllerConnMetrics +// MaxURLCounters limits URLMetrics entries per MetricsMap (combined across +// interfaces): agents like downloader/mgmtproxy can otherwise grow +// URLCounters without bound and exceed the pubsub message size limit. +// The actual count may transiently exceed this; see AgentMetrics. +// +// The cap counts entries, but what it defends is a byte budget: pubsub +// base64-encodes the serialized value before measuring it against its 64KB +// socket message limit, which leaves about 48KB for the JSON. Eviction also +// runs in batches once the cap is passed, so the peak is +// MaxURLCounters+urlCountersWiggle (115 entries today), not MaxURLCounters. +// A long URL key can cost more than all the counters stored under it, so +// counters which stay zero for the agents that reach the cap are omitted from +// the encoding rather than written out as zeroes. +const MaxURLCounters = 100 + // ControllerConnMetrics holds communication statistics with the controller // for a single interface. // It tracks successes, failures, authentication failures, and per-URL metrics. @@ -23,6 +38,9 @@ type ControllerConnMetrics struct { LastSuccess time.Time URLCounters map[string]URLMetrics AuthFailCount uint64 + // URLCounterRedactedCount counts URLMetrics entries evicted to stay + // within MaxURLCounters. + URLCounterRedactedCount uint64 } // URLMetrics are metrics for a particular URL @@ -35,6 +53,18 @@ type URLMetrics struct { RecvByteCount int64 // Based on content-length which could be off TotalTimeSpent int64 SessionResume int64 + // DeliveredMsgCount counts the answers which accepted the payload. It is + // narrower than SentMsgCount, which counts every answer received. + DeliveredMsgCount int64 `json:",omitempty"` + // RetriableErrCount counts the answers which refused the payload with a + // status that may not repeat, so that offering it again is worthwhile. + RetriableErrCount int64 `json:",omitempty"` + // RejectedErrCount counts the answers which refused the payload itself, + // so that offering it again would be answered the same way. + RejectedErrCount int64 `json:",omitempty"` + // LastUpdated determines which entries to evict once MaxURLCounters + // is reached. + LastUpdated time.Time } // AddInto adds metrics from this instance of MetricsMap @@ -66,6 +96,7 @@ func (m MetricsMap) AddInto(toMap MetricsMap) { dst.FailureCount += src.FailureCount dst.SuccessCount += src.SuccessCount dst.AuthFailCount += src.AuthFailCount + dst.URLCounterRedactedCount += src.URLCounterRedactedCount if dst.URLCounters == nil { dst.URLCounters = make(map[string]URLMetrics) } @@ -85,6 +116,12 @@ func (m MetricsMap) AddInto(toMap MetricsMap) { dstURL.RecvByteCount += srcURL.RecvByteCount dstURL.TotalTimeSpent += srcURL.TotalTimeSpent dstURL.SessionResume += srcURL.SessionResume + dstURL.DeliveredMsgCount += srcURL.DeliveredMsgCount + dstURL.RetriableErrCount += srcURL.RetriableErrCount + dstURL.RejectedErrCount += srcURL.RejectedErrCount + if srcURL.LastUpdated.After(dstURL.LastUpdated) { + dstURL.LastUpdated = srcURL.LastUpdated + } dstURLs[url] = dstURL } toMap[ifname] = dst diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedkubetypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedkubetypes.go index a2b41018ab7..26ef217c8ff 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedkubetypes.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedkubetypes.go @@ -34,6 +34,7 @@ const ( // KubeNodeStatus - Enum for the status of a Kubernetes node type KubeNodeStatus int8 +// KubeNodeStatus values. const ( KubeNodeStatusUnknown KubeNodeStatus = iota // KubeNodeStatusUnknown - Node status is unknown KubeNodeStatusReady // KubeNodeStatusReady - Node is in ready status @@ -44,6 +45,7 @@ const ( // NodeAdmission - Enum for the admission status of a node in a cluster type NodeAdmission uint8 +// NodeAdmission values. const ( NodeAdmissionUnknown NodeAdmission = iota // NodeAdmissionUnknown - Node admission status is unknown NodeAdmissionNotClustered // NodeAdmissionNotClustered - Node is not part of the cluster @@ -82,6 +84,16 @@ type KubeNodeInfo struct { Schedulable bool Admission NodeAdmission NodeID string + // Recovery is this node's quorum-recovery convergence, read back + // from its own annotation. Nil when the node has reported none, + // which is the normal state in a cluster that has never recovered. + Recovery *KubeQuorumRecoveryStatus +} + +// Key returns the pubsub key for a KubeNodeInfo: the EVE device UUID it +// describes, so subscribers can look a node up by UUID directly. +func (kni KubeNodeInfo) Key() string { + return kni.NodeID } // ZKubeNodeInfo - Converts pubsub KubeNodeInfo to eve-api info.KubeNodeInfo @@ -101,12 +113,63 @@ func (kni KubeNodeInfo) ZKubeNodeInfo() *info.KubeNodeInfo { iKni.Schedulable = kni.Schedulable iKni.AdmissionStatus = kni.Admission.ZNodeAdmission() iKni.NodeId = kni.NodeID + iKni.Recovery = kni.Recovery.ZKubeQuorumRecoveryStatus() return iKni } +// ZKubeQuorumRecoveryStatus converts to the eve-api form. Nil in means +// nil out: a device that has never reported convergence is different +// from one reporting generation zero. +func (r *KubeQuorumRecoveryStatus) ZKubeQuorumRecoveryStatus() *info.KubeQuorumRecoveryStatus { + if r == nil { + return nil + } + out := &info.KubeQuorumRecoveryStatus{ + AppliedGeneration: r.AppliedGeneration, + Converging: r.Converging, + LastTransitionAt: timestamppb.New(r.LastTransitionAt), + } + if r.Error.Error != "" { + out.Error = r.Error.ToProto() + } + return out +} + +// ZWitnessEtcdState converts to the eve-api enum. +func (s WitnessEtcdState) ZWitnessEtcdState() info.WitnessEtcdState { + switch s { + case WitnessEtcdStateIdle: + return info.WitnessEtcdState_WITNESS_ETCD_STATE_IDLE + case WitnessEtcdStateJoining: + return info.WitnessEtcdState_WITNESS_ETCD_STATE_JOINING + case WitnessEtcdStateJoined: + return info.WitnessEtcdState_WITNESS_ETCD_STATE_JOINED + case WitnessEtcdStateError: + return info.WitnessEtcdState_WITNESS_ETCD_STATE_ERROR + default: + return info.WitnessEtcdState_WITNESS_ETCD_STATE_UNSPECIFIED + } +} + +// ZKubeWitnessInfo converts to the eve-api form. +func (w *WitnessStatus) ZKubeWitnessInfo() *info.KubeWitnessInfo { + if w == nil { + return nil + } + out := &info.KubeWitnessInfo{ + WitnessIp: w.WitnessIP, + State: w.State.ZWitnessEtcdState(), + } + if w.Error.Error != "" { + out.Error = w.Error.ToProto() + } + return out +} + // KubePodStatus - Enum for the status of a Kubernetes pod type KubePodStatus int8 +// KubePodStatus values. const ( KubePodStatusUnknown KubePodStatus = iota // KubePodStatusUnknown - Pod status is unknown KubePodStatusPending // KubePodStatusPending - Pod is in pending status @@ -176,6 +239,7 @@ type KubePodNameSpaceInfo struct { // KubeVMIStatus - Enum for the status of a VirtualMachineInstance type KubeVMIStatus int8 +// KubeVMIStatus values. const ( KubeVMIStatusUnset KubeVMIStatus = iota // KubeVMIStatusUnset - UnSet VMI status KubeVMIStatusPending // KubeVMIStatusPending - VMI in pending status @@ -240,11 +304,16 @@ type KubeClusterInfo struct { AppVMIs []KubeVMIInfo `json:"pubsub-large-AppVMIs"` // List of VirtualMachineInstance Storage KubeStorageInfo `json:"pubsub-large-Storage"` // Distributed storage info PodNsInfo []KubePodNameSpaceInfo // General namespace pod running/failed count + // Witness is the 2-node-HA witness's status, nil when no witness is + // configured. Collected from the annotation of whichever node hosts + // it, the witness having no Node object of its own. + Witness *WitnessStatus } // StorageHealthStatus - Enum for the redundancy level and replication status of a storage volume type StorageHealthStatus uint8 +// StorageHealthStatus values. const ( StorageHealthStatusUnknown StorageHealthStatus = iota // StorageHealthStatusUnknown - Storage health status is unknown StorageHealthStatusHealthy // StorageHealthStatusHealthy - All replicas healthy @@ -258,6 +327,7 @@ const ( // StorageVolumeState - Enum for the attachment state of a storage volume type StorageVolumeState uint8 +// StorageVolumeState values. const ( StorageVolumeStateUnknown StorageVolumeState = iota // StorageVolumeStateUnknown - Volume state is unknown StorageVolumeStateCreating // StorageVolumeStateCreating - Volume is being created @@ -293,6 +363,7 @@ func (svs StorageVolumeState) ZStorageVolumeState() info.StorageVolumeState { // StorageVolumeRobustness - Enum for the replica robustness of a storage volume type StorageVolumeRobustness uint8 +// StorageVolumeRobustness values. const ( StorageVolumeRobustnessUnknown StorageVolumeRobustness = iota // StorageVolumeRobustnessUnknown - Volume robustness is unknown StorageVolumeRobustnessHealthy // StorageVolumeRobustnessHealthy - All Volume replicas healthy @@ -303,6 +374,7 @@ const ( // StorageVolumePvcStatus - Enum for the status of a PVC associated with a volume instance type StorageVolumePvcStatus uint8 +// StorageVolumePvcStatus values. const ( StorageVolumePvcStatusUnknown StorageVolumePvcStatus = iota // StorageVolumePvcStatusUnknown - PVC status is unknown StorageVolumePvcStatusBound // StorageVolumePvcStatusBound - PVC is bound @@ -315,6 +387,7 @@ const ( // StorageVolumeReplicaStatus - Enum for the status of a replica of a storage volume type StorageVolumeReplicaStatus uint8 +// StorageVolumeReplicaStatus values. const ( StorageVolumeReplicaStatusUnknown StorageVolumeReplicaStatus = iota // StorageVolumeReplicaStatusUnknown - Replica status is unknown StorageVolumeReplicaStatusRebuilding // StorageVolumeReplicaStatusRebuilding - Replica is rebuilding @@ -400,6 +473,7 @@ func (kvi KubeVolumeInfo) ZKubeVolumeInfo() *info.KubeVolumeInfo { // ServiceStatus - Enum for the status of a service type ServiceStatus int8 +// ServiceStatus values. const ( ServiceStatusUnset ServiceStatus = iota // ServiceStatusUnset - Service status is unset ServiceStatusFailed // ServiceStatusFailed - Service status is failed diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedmanagertypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedmanagertypes.go index 56cba72ab0e..375a7c97066 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedmanagertypes.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedmanagertypes.go @@ -168,6 +168,13 @@ type AppInstanceConfig struct { // Am I Cluster Designated Node Id for this app IsDesignatedNodeID bool + // DesignatedNodeUUID is the device UUID of the app's designated node, + // whichever node that is. IsDesignatedNodeID above answers only whether + // it is this node; deciding whether a peer may act in that node's place + // needs to ask about that node's health, which needs its identity. + // Empty on a single-node device, where this node is always designated. + DesignatedNodeUUID string + // Node Affinity for cluster IsDesignatedNodeID AffinityType Affinity @@ -338,6 +345,9 @@ type AppInstanceStatus struct { // All error strings across all steps and all StorageStatus // ErrorAndTimeWithSource provides SetError, SetErrrorWithSource, etc ErrorAndTimeWithSource + // RuntimeErr is the error reported by the app's runtime (see AppRuntimeStatus), + // kept apart from the lifecycle error above. + RuntimeErr ErrorDescription // Effective time, when the application should start StartTime time.Time // Snapshot related information @@ -352,6 +362,18 @@ type AppInstanceStatus struct { IsDesignatedNodeID bool } +// TruncateErrors cuts the status's own error, its runtime error and the error +// of every volume reference down to maxLen bytes each, for a status that would +// otherwise not fit a pubsub message. +func (status *AppInstanceStatus) TruncateErrors(maxLen int) { + status.Error = TruncateError(status.Error, maxLen) + status.RuntimeErr.Error = TruncateError(status.RuntimeErr.Error, maxLen) + for i := range status.VolumeRefStatusList { + status.VolumeRefStatusList[i].Error = + TruncateError(status.VolumeRefStatusList[i].Error, maxLen) + } +} + // AppCount is uint8 and it should be sufficient for the number of apps we can support type AppCount uint8 diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedroutertypes.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedroutertypes.go index 7a66105a35b..b476654e845 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedroutertypes.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zedroutertypes.go @@ -32,6 +32,30 @@ type AppNetworkConfig struct { CipherBlockStatus CipherBlockStatus MetaDataType MetaDataType DeploymentType AppRuntimeType + // KubeApp is set only for app network configs synthesized by zedkube for directly-deployed + // Kubernetes workloads (helm/raw yaml) that have no controller-provided AppInstanceConfig. + // nil for the controller-managed (ENC) path. It lets zedrouter resolve an inbound CNI pod + // to this config by Kubernetes identity (namespace + ReplicaSet name) instead of the UUID + // prefix embedded in controller-managed pod names. + KubeApp *KubeAppInfo +} + +// KubeAppInfo carries the Kubernetes identity of a directly-deployed workload so zedrouter can +// resolve an inbound CNI pod to its synthesized AppNetworkConfig. The synthesized +// AppNetworkConfig.UUIDandVersion.UUID equals base.KubeAppUUID(Namespace, OwnerName). +type KubeAppInfo struct { + // Namespace of the Kubernetes workload. + Namespace string + // OwnerName is either the exact name of an ownerless bare Pod or the bare ReplicaSet name + // (or VMI name). ReplicaSet pods are "-<5char>"; zedrouter matches inbound pods + // against it with base.KubePodMatchesOwner. + OwnerName string + // ConfigError is set by zedkube when the workload's network attachments cannot be + // supported (e.g. a ReplicaSet with more than one replica). Such a config is published + // inactive and without adapters, only so that zedrouter can fail the workload's CNI + // requests with this message (returned verbatim, so it must be self-explanatory) + // instead of a generic "config not found". + ConfigError string } // Key : @@ -112,6 +136,10 @@ type AppNetworkStatus struct { PendingDelete bool ConfigInSync bool DisplayName string + // KubeApp is copied from AppNetworkConfig only for directly-deployed + // Kubernetes workloads. zedkube uses this identity together with the + // zedrouter-assigned adapter addresses to publish NI DNS records. + KubeApp *KubeAppInfo // AppPod is only valid in Kubernetes mode. AppPod cnirpc.AppPod // Copy from the AppNetworkConfig; used to delete when config is gone. @@ -314,6 +342,13 @@ type AppNetAdapterConfig struct { AccessVlanID uint32 IfIdx uint32 // If we have multiple interfaces on that network, we will increase the index AllowToDiscover bool + + // DefaultRouteVia, if set, overrides the default-route gateway for this adapter: the + // adapter's default route (if any) is installed via this address instead of the Network + // Instance's own gateway. The address must be reachable on the Network Instance (e.g. a + // peer application's IP). Currently only set by zedkube for directly-deployed Kubernetes + // workloads (the "default-route" networks-annotation field); nil otherwise. + DefaultRouteVia net.IP } // ACEDirection determines rule direction. @@ -778,6 +813,17 @@ type NetworkInstanceConfig struct { // by the forwarding plane. ForwardLLDP bool + // ClusterWide indicates whether this network instance is shared across an + // Edge Node Cluster (ENC) rather than being device-specific. + // If false (default), the network instance is only instantiated on this + // individual device. + // If true, the network instance is downloaded to and instantiated identically + // on every device that is a member of the Edge Node Cluster, allowing app + // instances on any cluster node to attach to the same logical network + // instance (e.g. for apps that may be relocated between nodes, or for native + // Kubernetes applications). + ClusterWide bool + // Any errors from the parser // ErrorAndTime provides SetErrorNow() and ClearError() ErrorAndTime @@ -1090,10 +1136,14 @@ type NetworkInstanceStatus struct { // Labels of device ports used for external connectivity. // The list is empty for air-gapped network instances. Ports []string - // List of NTP servers published to applications connected to this network instance. - // This includes the NTP server from the NI config (if any) and all NTP servers - // associated with ports used by the network instance for external connectivity. - NTPServers []netutils.HostnameOrIP + // CombinedNTPServers is the list of NTP servers published to applications + // connected to this network instance. It combines the NTP server from the + // NI config (if any) with all NTP servers associated with ports used by + // the network instance for external connectivity. Named distinctly from + // the embedded NetworkInstanceConfig.NtpServers (the NI-only raw config) + // since the two previously differed only by case, which let a caller + // silently read the wrong one through field promotion. + CombinedNTPServers []netutils.HostnameOrIP // The intended state of the routing table. // Includes user-configured static routes and potentially also automatically // generated default route. @@ -1533,3 +1583,15 @@ type NestedAppRuntimeDiskMetric struct { func (metric NestedAppRuntimeDiskMetric) Key() string { return metric.UUID } + +// AppRuntimeStatus carries errors reported by an app's runtime (e.g. cloud-init +// failures). Published by zedrouter, keyed by the app instance UUID. +type AppRuntimeStatus struct { + UUID string + ErrorAndTime +} + +// Key - returns the app instance UUID +func (status AppRuntimeStatus) Key() string { + return status.UUID +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zfs.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zfs.go index 4a2e5f65703..c65315a601e 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zfs.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/types/zfs.go @@ -177,6 +177,17 @@ const ( StorageStatusSuspended StorageStatus = 7 // A pool that is waiting for device connectivity to be restored. ) +// PoolTrimStatus records when the most recent zpool trim was started. +// Nested inside ZFSPoolStatus. zpool trim returns immediately and does the +// work in the background, so only the start time is tracked; use +// `zpool status -t persist` to check background progress. +type PoolTrimStatus struct { + // LastStartTime is when zpool trim last started a trim. Zero if none + // was started this boot, including when a cron tick found a trim + // already running. EVE-k ZFS nodes only. + LastStartTime time.Time +} + // ZFSPoolStatus stores collected information about zpool type ZFSPoolStatus struct { PoolName string @@ -191,6 +202,11 @@ type ZFSPoolStatus struct { Children []*StorageChildren PoolStatusMsg PoolStatus // pool status value from ZFS PoolStatusMsgStr string // pool status value from ZFS in string format + // TrimStatus holds the start time of the most recent zpool trim. + // EVE-k ZFS nodes only. zpool trim returns immediately and does the + // work in the background, so no end time or error is tracked here; + // use `zpool status -t persist` to check background progress. + TrimStatus PoolTrimStatus } // Key for pubsub diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/cgroup.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/cgroup.go new file mode 100644 index 00000000000..fc3f45f2d8f --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/cgroup.go @@ -0,0 +1,88 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +// Package cgroup reads and writes the host's cgroup v2 tree, which pillar sees +// read-write at /sys/fs/cgroup (bound in pkg/pillar/build*.yml). Groups are named +// relative to the root, e.g. "eve/services/pillar". +package cgroup + +import ( + "bufio" + "errors" + "fmt" + "math" + "os" + "path/filepath" + "strconv" + "strings" +) + +// Root is the cgroup v2 mount point; tests point it at a temporary tree. +var Root = "/sys/fs/cgroup" + +// Unlimited is what ReadUint returns for a file that reads "max". +const Unlimited = uint64(math.MaxUint64) + +// Path returns the path of file in group. +func Path(group, file string) string { + return filepath.Join(Root, group, file) +} + +// ReadUint reads a cgroup file holding one number, such as memory.max or +// memory.current; "max" reads as Unlimited. A file the kernel does not provide +// (memory.peak before 5.19) returns an error matching os.ErrNotExist. +func ReadUint(group, file string) (uint64, error) { + b, err := os.ReadFile(Path(group, file)) + if err != nil { + return 0, err + } + s := strings.TrimSpace(string(b)) + if s == "max" { + return Unlimited, nil + } + v, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return 0, fmt.Errorf("%s: %w", Path(group, file), err) + } + return v, nil +} + +// MemoryStat parses group's memory.stat. Keys the kernel does not report (the +// "kernel" line before 5.18) are absent from the map. +func MemoryStat(group string) (map[string]uint64, error) { + f, err := os.Open(Path(group, "memory.stat")) + if err != nil { + return nil, err + } + defer f.Close() + stat := make(map[string]uint64) + sc := bufio.NewScanner(f) + for sc.Scan() { + key, val, ok := strings.Cut(sc.Text(), " ") + if !ok { + continue + } + if v, err := strconv.ParseUint(val, 10, 64); err == nil { + stat[key] = v + } + } + return stat, sc.Err() +} + +// FormatCPUs formats a CPU list the way cpuset.cpus takes it: "1,3,5". +func FormatCPUs(cpus []uint32) string { + list := make([]string, len(cpus)) + for i, c := range cpus { + list[i] = strconv.FormatUint(uint64(c), 10) + } + return strings.Join(list, ",") +} + +// WriteCPUs sets group's cpuset.cpus. An empty list is refused: cgroup v2 +// reads an empty cpuset.cpus as "inherit the parent's CPUs". +func WriteCPUs(group string, cpus []uint32) error { + if len(cpus) == 0 { + return errors.New("refusing an empty CPU list: on cgroup v2 it means every CPU of the parent") + } + return os.WriteFile(Path(group, "cpuset.cpus"), []byte(FormatCPUs(cpus)), 0) +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/notify.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/notify.go new file mode 100644 index 00000000000..2fc5491fa49 --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cgroup/notify.go @@ -0,0 +1,110 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package cgroup + +import ( + "fmt" + "io" + "os" + "time" + + "golang.org/x/sys/unix" +) + +// Notifier wakes on kernel notifications from one cgroup file. +type Notifier struct { + f *os.File + // rearm re-reads the file after each wake: a kernfs change notification + // stays pending until the file is read again. + rearm bool +} + +// NewPressureTrigger arms a PSI trigger on group's .pressure (e.g. +// memory.pressure): Wait returns each time the group's tasks stall for stall +// within window, "some" counting any task, "full" all of them. It fails on a +// kernel without PSI. +func NewPressureTrigger(group, resource, kind string, stall, window time.Duration) (*Notifier, error) { + if kind != "some" && kind != "full" { + return nil, fmt.Errorf("PSI trigger kind %q, want some or full", kind) + } + f, err := os.OpenFile(Path(group, resource+".pressure"), os.O_RDWR, 0) + if err != nil { + return nil, err + } + trigger := fmt.Sprintf("%s %d %d", kind, stall.Microseconds(), window.Microseconds()) + if _, err := f.WriteString(trigger); err != nil { + f.Close() + return nil, fmt.Errorf("arming %q on %s: %w", trigger, f.Name(), err) + } + return &Notifier{f: f}, nil +} + +// NewChangeNotifier wakes each time the kernel changes group's file, such as +// memory.events, which generates a file modified event on every change. +func NewChangeNotifier(group, file string) (*Notifier, error) { + f, err := os.Open(Path(group, file)) + if err != nil { + return nil, err + } + // kernfs reports a file that was never read as changed, so without this + // read the first Wait would return at once. + if _, err := io.Copy(io.Discard, f); err != nil { + f.Close() + return nil, err + } + return &Notifier{f: f, rearm: true}, nil +} + +// pollOutcome decides what a poll's revents mean. A PSI trigger wakes on +// POLLPRI; POLLERR, POLLHUP or POLLNVAL means the trigger is gone, e.g. the +// cgroup was removed, and polling again would return at once. A change +// notifier gets POLLERR|POLLPRI for every change: kernfs sets POLLERR as the +// normal "changed" signal, and only POLLHUP or POLLNVAL means the file is gone. +func pollOutcome(revents int16, rearm bool) error { + if rearm { + if revents&(unix.POLLHUP|unix.POLLNVAL) == 0 && revents&unix.POLLPRI != 0 { + return nil + } + return fmt.Errorf("change notifier gone: poll returned %#x", revents) + } + if revents&(unix.POLLERR|unix.POLLHUP|unix.POLLNVAL) != 0 { + return fmt.Errorf("pressure trigger gone: poll returned %#x", revents) + } + if revents&unix.POLLPRI != 0 { + return nil + } + return fmt.Errorf("pressure trigger: poll returned %#x", revents) +} + +// Wait blocks until the next notification. +func (n *Notifier) Wait() error { + fds := []unix.PollFd{{Fd: int32(n.f.Fd()), Events: unix.POLLPRI}} + for { + if _, err := unix.Poll(fds, -1); err != nil { + if err == unix.EINTR { + continue + } + return err + } + if err := pollOutcome(fds[0].Revents, n.rearm); err != nil { + return fmt.Errorf("%s: %w", n.f.Name(), err) + } + if n.rearm { + // The re-read re-arms the notification and is also what reports a + // removed cgroup (it fails), so it must not be dropped. + if _, err := n.f.Seek(0, io.SeekStart); err != nil { + return err + } + if _, err := io.Copy(io.Discard, n.f); err != nil { + return err + } + } + return nil + } +} + +// Close releases the file, which disarms a PSI trigger. +func (n *Notifier) Close() error { + return n.f.Close() +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cloudconfig/cloudconfig.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cloudconfig/cloudconfig.go index b227c15468f..d1e904708f6 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cloudconfig/cloudconfig.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cloudconfig/cloudconfig.go @@ -4,16 +4,13 @@ import ( "compress/gzip" "encoding/base64" "errors" - "fmt" "io" "os" - "path/filepath" "strconv" "strings" "github.com/go-playground/validator/v10" "github.com/lf-edge/eve/pkg/pillar/base" - fileutils "github.com/lf-edge/eve/pkg/pillar/utils/file" "gopkg.in/yaml.v2" ) @@ -33,6 +30,14 @@ type WritableFile struct { Owner string `yaml:"owner"` } +// hostnameConfig holds only the cloud-config keys through which the user +// takes charge of the guest hostname. +type hostnameConfig struct { + Hostname string `yaml:"hostname"` + FQDN string `yaml:"fqdn"` + PreserveHostname bool `yaml:"preserve_hostname"` //nolint:tagliatelle // cloud-init standard uses snake_case +} + var validate = validator.New() // MaxDecompressedContentSize is the maximum size of a file that can be written to disk after decompression. @@ -73,12 +78,6 @@ func WriteFile(log *base.LogObject, file WritableFile, rootPath string) error { } mode := os.FileMode(perm) - writePath := filepath.Join(rootPath, file.Path) - // sanitize path - if !strings.HasPrefix(filepath.Clean(writePath), rootPath) { - return fmt.Errorf("detected possible attempt to write file outside of root path. invalid path %s", file.Path) - } - var contentBytes []byte switch file.Encoding { case "b64", "base64": @@ -101,23 +100,8 @@ func WriteFile(log *base.LogObject, file WritableFile, rootPath string) error { return err } - // check if the parent directory exists - parentDir := filepath.Dir(writePath) - if _, err := os.Stat(parentDir); os.IsNotExist(err) { - // create parent directory - err = os.MkdirAll(parentDir, 0755) - if err != nil { - return err - } - } - log.Tracef("Creating file %s with mode %s in %s\n", file.Path, mode, rootPath) - err = fileutils.WriteRename(writePath, contentBytes) - if err != nil { - return err - } - err = os.Chmod(writePath, mode) - if err != nil { + if err := writeFileInRoot(rootPath, file.Path, contentBytes, mode); err != nil { return err } if file.Owner != "" { @@ -127,6 +111,21 @@ func WriteFile(log *base.LogObject, file WritableFile, rootPath string) error { return nil } +// DeclaresHostname reports whether the given user-data is a cloud-config in +// which the user has taken charge of the guest hostname, via any of the +// `hostname`, `fqdn` or `preserve_hostname` directives. +func DeclaresHostname(ci string) bool { + if !IsCloudConfig(ci) { + return false + } + var hc hostnameConfig + if err := yaml.Unmarshal([]byte(ci), &hc); err != nil { + // Not parseable as cloud-config; no hostname directive to honour. + return false + } + return hc.Hostname != "" || hc.FQDN != "" || hc.PreserveHostname +} + func decodeGzipContent(content string) ([]byte, error) { gzipReader, err := gzip.NewReader(strings.NewReader(content)) if err != nil { diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cloudconfig/rootedwrite.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cloudconfig/rootedwrite.go new file mode 100644 index 00000000000..13f8a17beaa --- /dev/null +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/cloudconfig/rootedwrite.go @@ -0,0 +1,425 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package cloudconfig + +import ( + "errors" + "fmt" + "io" + "os" + "path" + "strings" + "sync/atomic" + + "golang.org/x/sys/unix" +) + +// Not os.Root: it refuses an absolute symlink outright ("Symbolic links must +// not be absolute"), so /var/run -> /run would fail rather than resolve to the +// application's own /run. It is the right tool only if refusing such a path +// ever becomes the wanted behaviour. + +// maxSymlinkDepth caps how many symlinks-to-missing-directories ensureDirPath +// will follow. Serves the same purpose as the kernel's ELOOP limit, on the one +// case the kernel cannot resolve for us: a directory that has to be created +// through a symlink whose target does not exist yet. +const maxSymlinkDepth = 8 + +// maxResolveRetries bounds the retries of a lookup the kernel declined to +// answer. It expects a retry to succeed promptly, so a tree being mutated hard +// enough to exhaust this fails rather than spinning. +const maxResolveRetries = 16 + +// tmpCounter distinguishes the temporary files of successive writes, so a +// leftover from an interrupted write cannot make the next one fail on O_EXCL. +var tmpCounter atomic.Uint64 + +// writeFileInRoot writes content at filePath with the given mode, resolving +// filePath as though rootPath were the filesystem root, and creates the parent +// directories that do not exist yet. +// +// filePath comes from a cloud-config write_files entry and is resolved against +// the rootfs of the application's own container image, so every symlink along +// the way is chosen by whoever built that image. openat2(2) with +// RESOLVE_IN_ROOT has the kernel resolve the path with rootPath as "/": +// absolute symlink targets are re-rooted at rootPath and ".." cannot climb +// above it. Those are chroot(2) semantics without chroot's process-wide +// effect, and unlike resolving the path in userspace there is no window +// between deciding a path is safe and writing to it. +// +// Re-rooting rather than rejecting is what the guest itself means by such a +// path: in a Debian-based image /var/lock is a symlink to /run/lock, and a +// write there belongs in the container's own /run/lock. +// +// Containment does not rest on this function being the only writer, nor on it +// never creating a symlink: every call re-resolves from its own root +// descriptor, so it tolerates whatever symlinks it finds. A container-format +// volume may in fact be shared writable with an already-running application +// (see checkReferences in volumemgr), so a concurrent writer must be assumed. +// +// It does rest on two properties of the caller's namespace: +// - No directory is moved out of rootPath mid-write, since a descriptor +// follows its directory. The mount boundary is what gives this: a guest +// sees such a volume only as a bind mount of that tree, and rename(2) +// cannot cross mounts. A rename within the root stays contained. +// - No outside inode is exposed beneath rootPath by a mount pillar can see. +// RESOLVE_IN_ROOT confines path resolution to the tree, not to one +// filesystem, so an interior mount would be followed (RESOLVE_NO_XDEV +// would forbid that, at the cost of any legitimate interior mount). +// +// Needs Linux 5.6 for openat2. +func writeFileInRoot(rootPath, filePath string, content []byte, mode os.FileMode) error { + dir, name, err := normalizeInRoot(filePath) + if err != nil { + return err + } + + rootFd, err := retryOnEINTR2(func() (int, error) { + return unix.Open(rootPath, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) + }) + if err != nil { + return fmt.Errorf("failed to open root path %s: %w", rootPath, err) + } + defer unix.Close(rootFd) + + if err := ensureDirPath(rootFd, dir, 0); err != nil { + return err + } + // Opened read-only rather than O_PATH so the directory can be fsynced + // after the rename. + dirFd, err := openInRoot(rootFd, dir, unix.O_RDONLY|unix.O_DIRECTORY) + if err != nil { + return fmt.Errorf("failed to open directory %s under %s: %w", dir, rootPath, err) + } + defer unix.Close(dirFd) + + return writeRenameAt(dirFd, name, content, mode) +} + +// normalizeInRoot splits a requested path into the directory to resolve and +// the name to write inside it, and rejects a path that climbs above the root. +// +// The split is not a containment measure -- RESOLVE_IN_ROOT already makes an +// escape impossible whatever this returns. It exists because rename(2) is what +// makes the write atomic, and renameat takes a directory descriptor plus a +// plain name, with no resolve-flag variant. path.Dir and path.Base alone would +// not do, as they disagree about a trailing separator: "/foo/" would name the +// file "foo" inside a directory "/foo". +// +// ".." is left in dir for the kernel to resolve. Collapsing it here would +// apply it before symlinks rather than after, naming a different directory: +// with "/alias" a symlink to "real/deep", "/alias/../f" is "/real/f", not +// "/f". +// +// The climb-out rejection is a lexical sanity check on the config, not a +// containment mechanism, and it is deliberately approximate in both +// directions: with "/a" a symlink to "/", "/a/../f" is accepted although the +// traversal does climb to the root, and with "/a" a symlink to "real/deep", +// "/a/../../f" is rejected although it resolves to a contained path. It earns +// its place only by turning a plainly malformed entry into an error instead of +// a file written somewhere its author did not name; the kernel is what keeps +// either outcome inside the root. +func normalizeInRoot(filePath string) (dir, name string, err error) { + invalid := fmt.Errorf( + "detected possible attempt to write file outside of root path. invalid path %s", + filePath) + + var components []string + for _, component := range strings.Split(filePath, "/") { + // Dropping "." changes no meaning; ".." is kept for the kernel. + if component != "" && component != "." { + components = append(components, component) + } + } + if len(components) == 0 { + // Names the root directory itself, not a file in it. + return "", "", invalid + } + if components[len(components)-1] == ".." { + return "", "", invalid + } + // Whether the path climbs out, counted lexically. A symlink can make the + // kernel disagree about which directory a ".." lands in, but not about + // whether the path stays inside the root. + depth := 0 + for _, component := range components { + if component == ".." { + if depth == 0 { + return "", "", invalid + } + depth-- + continue + } + depth++ + } + + last := len(components) - 1 + return "/" + strings.Join(components[:last], "/"), components[last], nil +} + +// openInRoot opens path with rootFd standing in for the filesystem root. +// +// A ".." under RESOLVE_IN_ROOT is only safe if the kernel can confirm it did +// not escape, which it cannot always do while the tree is changing underneath; +// it then reports EAGAIN and leaves retrying to the caller (openat2(2)). So +// EAGAIN here says nothing about the path -- treating it as a failure makes a +// perfectly good entry fail whenever something else touches the filesystem at +// the wrong moment. +func openInRoot(rootFd int, path string, flags int) (int, error) { + var fd int + var err error + for attempt := 0; attempt <= maxResolveRetries; attempt++ { + fd, err = retryOnEINTR2(func() (int, error) { + return unix.Openat2(rootFd, path, &unix.OpenHow{ + Flags: uint64(flags | unix.O_CLOEXEC), + Resolve: unix.RESOLVE_IN_ROOT, + }) + }) + if !errors.Is(err, unix.EAGAIN) { + return fd, err + } + } + return fd, err +} + +// ensureDirPath creates every component of dir that does not exist yet, each +// one below a parent the kernel has already resolved inside the root. +// +// Prefixes are built by concatenation rather than by path.Join, because a +// symlink target may contain "..": cleaning it would name an ancestor of the +// link's own lexical path instead of an ancestor of what the link points at. +// Left intact, every prefix is resolved by the kernel, which follows the real +// symlinks before applying the "..". +func ensureDirPath(rootFd int, dir string, depth int) error { + if depth > maxSymlinkDepth { + return fmt.Errorf("too many symbolic links while creating %s", dir) + } + parent, full := "/", "" + for _, name := range strings.Split(dir, "/") { + if name == "" || name == "." { + continue + } + if full != "" { + parent = full + } + full += "/" + name + // ".." always exists, and only the kernel can say what it refers to + // once symlinks are in play. + if name == ".." { + continue + } + if err := ensureDir(rootFd, parent, full, name, depth); err != nil { + return err + } + } + return nil +} + +// ensureDir makes sure name, whose full path within the root is full and whose +// parent is parent, exists as a directory. A name that is a symlink to a +// directory which does not exist yet is not created itself -- mkdir would fail +// on the symlink -- its target is created instead, which RESOLVE_IN_ROOT keeps +// inside the root. +func ensureDir(rootFd int, parent, full, name string, depth int) error { + fd, err := openInRoot(rootFd, full, unix.O_PATH|unix.O_DIRECTORY) + if err == nil { + unix.Close(fd) + return nil + } + // Anything but "not there" (ENOTDIR for a file in the way, ELOOP, EACCES) + // is the useful error and must not be masked by the EEXIST below. + if !errors.Is(err, unix.ENOENT) { + return fmt.Errorf("failed to open %s: %w", full, err) + } + + parentFd, err := openInRoot(rootFd, parent, unix.O_PATH|unix.O_DIRECTORY) + if err != nil { + return fmt.Errorf("failed to open %s: %w", parent, err) + } + defer unix.Close(parentFd) + + mkErr := retryOnEINTR(func() error { return unix.Mkdirat(parentFd, name, 0755) }) + if mkErr == nil { + return nil + } + if !errors.Is(mkErr, unix.EEXIST) { + return fmt.Errorf("failed to create %s: %w", full, mkErr) + } + + // The name exists yet did not resolve to a directory: either a symlink + // whose target is missing, whose target is created below, or a directory + // that appeared between the lookup and the mkdir. + target, err := readlinkAt(parentFd, name) + if err != nil { + if fd, openErr := openInRoot(rootFd, full, unix.O_PATH|unix.O_DIRECTORY); openErr == nil { + unix.Close(fd) + return nil + } + return fmt.Errorf("failed to create %s: exists but is not a usable directory: %w", + full, err) + } + if !path.IsAbs(target) { + // Concatenated rather than joined, for the reason in ensureDirPath. + target = parent + "/" + target + } + return ensureDirPath(rootFd, target, depth+1) +} + +func readlinkAt(dirFd int, name string) (string, error) { + for size := 256; size <= unix.PathMax; size *= 2 { + buf := make([]byte, size) + n, err := retryOnEINTR2(func() (int, error) { + return unix.Readlinkat(dirFd, name, buf) + }) + if err != nil { + return "", err + } + if n < size { + return string(buf[:n]), nil + } + } + return "", fmt.Errorf("symbolic link target of %s is too long", name) +} + +// writeRenameAt writes content to name inside dirFd via a temporary file and +// rename(2), so nothing observes a partially written file. Mirrors +// fileutils.WriteRename, except that every step is relative to dirFd: the +// directory was resolved once, under RESOLVE_IN_ROOT, and no step here walks a +// path a symlink could redirect. +func writeRenameAt(dirFd int, name string, content []byte, mode os.FileMode) error { + tmp, fd, err := createTempAt(dirFd) + if err != nil { + return err + } + defer func() { + if tmp != "" { + unix.Unlinkat(dirFd, tmp, 0) //nolint:errcheck // cleanup of a failed write + } + }() + + // Mode before the sync, so the file's permissions are part of the state + // that reaches the disk, and before the rename, so the file is never + // visible under its final name with the temporary's mode. + if err := writeAndSync(fd, content, mode); err != nil { + unix.Close(fd) //nolint:errcheck // the write already failed + return fmt.Errorf("failed to write %s: %w", name, err) + } + // Not retried on EINTR: on Linux the descriptor is released regardless, + // so a retry could close an unrelated file. + if err := unix.Close(fd); err != nil { + return fmt.Errorf("failed to close %s: %w", name, err) + } + + if err := retryOnEINTR(func() error { + return unix.Renameat(dirFd, tmp, dirFd, name) + }); err != nil { + return fmt.Errorf("failed to rename %s into place: %w", name, err) + } + tmp = "" + if err := retryOnEINTR(func() error { return unix.Fsync(dirFd) }); err != nil { + return fmt.Errorf("failed to sync directory of %s: %w", name, err) + } + return nil +} + +func writeAndSync(fd int, content []byte, mode os.FileMode) error { + if err := writeAll(fd, content); err != nil { + return err + } + if err := retryOnEINTR(func() error { return unix.Fchmod(fd, unixMode(mode)) }); err != nil { + return err + } + return retryOnEINTR(func() error { return unix.Fsync(fd) }) +} + +// createTempAt creates a uniquely named file inside dirFd. O_NOFOLLOW because +// the name may already exist as a symlink planted in the image; with O_EXCL +// that is refused rather than followed. +// +// O_EXCL authenticates the inode it returns, not the name for the rest of the +// operation. A concurrent writer sharing the volume can replace the name +// afterwards, in which case the rename below publishes what that writer put +// there and the deferred cleanup unlinks it rather than our own file. Both stay +// inside the root, and such a writer can already write this tree, so this +// costs integrity of the published file and no more. +func createTempAt(dirFd int) (string, int, error) { + flags := unix.O_CREAT | unix.O_EXCL | unix.O_WRONLY | unix.O_CLOEXEC | unix.O_NOFOLLOW + var lastErr error + for i := 0; i < 100; i++ { + name := fmt.Sprintf(".cloudinit-tmp-%d-%d", os.Getpid(), tmpCounter.Add(1)) + fd, err := retryOnEINTR2(func() (int, error) { + return unix.Openat(dirFd, name, flags, 0600) + }) + if err == nil { + return name, fd, nil + } + if !errors.Is(err, unix.EEXIST) { + return "", -1, fmt.Errorf("failed to create temporary file: %w", err) + } + lastErr = err + } + return "", -1, fmt.Errorf("failed to create temporary file: %w", lastErr) +} + +func writeAll(fd int, content []byte) error { + for len(content) > 0 { + n, err := unix.Write(fd, content) + if err != nil { + if errors.Is(err, unix.EINTR) { + continue + } + return err + } + if n <= 0 { + return io.ErrShortWrite + } + content = content[n:] + } + return nil +} + +// unixMode converts mode the way os.Chmod does, so a permissions string keeps +// meaning exactly what it meant before the write moved to a descriptor. +func unixMode(mode os.FileMode) uint32 { + m := uint32(mode.Perm()) + if mode&os.ModeSetuid != 0 { + m |= unix.S_ISUID + } + if mode&os.ModeSetgid != 0 { + m |= unix.S_ISGID + } + if mode&os.ModeSticky != 0 { + m |= unix.S_ISVTX + } + return m +} + +// retryOnEINTR repeats f while a signal interrupts it. +// +// Applied wherever the os-package call this write path replaced retried: open, +// mkdir, readlink, chmod, fsync, write and rename all loop inside os (see +// ignoringEINTR there). The runtime preempts goroutines with SIGURG, and while +// its own handlers carry SA_RESTART, anything else in the process may install +// one without it -- pillar is a single process running every agent -- so the +// guarantee is not ours to make. +// +// close(2) is deliberately excluded: on Linux the descriptor is released even +// when it reports EINTR, so retrying could close an unrelated file. +func retryOnEINTR(f func() error) error { + for { + if err := f(); !errors.Is(err, unix.EINTR) { + return err + } + } +} + +// retryOnEINTR2 is retryOnEINTR for a call that also returns a value. +func retryOnEINTR2[T any](f func() (T, error)) (T, error) { + for { + v, err := f() + if !errors.Is(err, unix.EINTR) { + return v, err + } + } +} diff --git a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/file/file.go b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/file/file.go index 3885f0c827d..c953bc784a5 100644 --- a/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/file/file.go +++ b/pkg/installer/src/vendor/github.com/lf-edge/eve/pkg/pillar/utils/file/file.go @@ -184,6 +184,39 @@ func writeRename(fileName string, b []byte, withBackup bool, tmpPath ...string) return DirSync(filepath.Dir(fileName)) } +// WriteRenameWithMtime atomically replaces fileName with b, setting its mtime +// to mtime unless mtime is zero, and fsyncs the file and its directory. +func WriteRenameWithMtime(fileName string, b []byte, mtime time.Time) error { + dirName := filepath.Dir(fileName) + tmpfile, err := os.CreateTemp(dirName, "tmp") + if err != nil { + return fmt.Errorf("WriteRenameWithMtime(%s): create temp: %w", fileName, err) + } + defer tmpfile.Close() + defer os.Remove(tmpfile.Name()) + if _, err := tmpfile.Write(b); err != nil { + return fmt.Errorf("WriteRenameWithMtime(%s): %w", fileName, err) + } + if err := tmpfile.Chmod(0o644); err != nil { + return fmt.Errorf("WriteRenameWithMtime(%s): %w", fileName, err) + } + if !mtime.IsZero() { + if err := os.Chtimes(tmpfile.Name(), mtime, mtime); err != nil { + return fmt.Errorf("WriteRenameWithMtime(%s): %w", fileName, err) + } + } + if err := tmpfile.Sync(); err != nil { + return fmt.Errorf("WriteRenameWithMtime(%s): sync: %w", fileName, err) + } + if err := tmpfile.Close(); err != nil { + return fmt.Errorf("WriteRenameWithMtime(%s): %w", fileName, err) + } + if err := os.Rename(tmpfile.Name(), fileName); err != nil { + return fmt.Errorf("WriteRenameWithMtime(%s): %w", fileName, err) + } + return DirSync(dirName) +} + // Writable checks if the directory is writable func Writable(dir string) bool { return unix.Access(dir, unix.W_OK) == nil @@ -223,8 +256,15 @@ func ReadWithMaxSize(log *base.LogObject, filename string, maxReadSize int) ([]b return nil, err } defer f.Close() + // Size the buffer to the file (capped at maxReadSize+1) instead of always + // allocating maxReadSize+1: callers reading many small files with a large + // maxReadSize would otherwise allocate maxReadSize for every one of them. + bufSize := maxReadSize + 1 + if fi, statErr := f.Stat(); statErr == nil && fi.Size() < int64(maxReadSize) { + bufSize = int(fi.Size()) + 1 + } r := bufio.NewReader(f) - content := make([]byte, maxReadSize+1) + content := make([]byte, bufSize) n, err := r.Read(content) if err != nil { err = fmt.Errorf("ReadWithMaxSize %s failed: %v", filename, err) diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/.golangci.yml b/pkg/installer/src/vendor/github.com/sirupsen/logrus/.golangci.yml index 65dc2850377..792db361813 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/.golangci.yml +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/.golangci.yml @@ -1,40 +1,67 @@ +version: "2" run: - # do not run on test files yet tests: false - -# all available settings of specific linters -linters-settings: - errcheck: - # report about not checking of errors in type assetions: `a := b.(MyStruct)`; - # default is false: such cases aren't reported by default. - check-type-assertions: false - - # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; - # default is false: such cases aren't reported by default. - check-blank: false - - lll: - line-length: 100 - tab-width: 4 - - prealloc: - simple: false - range-loops: false - for-loops: false - - whitespace: - multi-if: false # Enforces newlines (or comments) after every multi-line if statement - multi-func: false # Enforces newlines (or comments) after every multi-line function signature - linters: enable: - - megacheck - - govet + - asasalint + - asciicheck + - bidichk + - bodyclose + - contextcheck + - durationcheck + - errchkjson + - errorlint + - exhaustive + - gocheckcompilerdirectives + - gochecksumtype + - gosec + - gosmopolitan + - loggercheck + - makezero + - musttag + - nilerr + - nilnesserr + - noctx + - protogetter + - reassign + - recvcheck + - rowserrcheck + - spancheck + - sqlclosecheck + - testifylint + - unparam + - zerologlint disable: - - maligned - prealloc - disable-all: false - presets: - - bugs - - unused - fast: false + settings: + errcheck: + check-type-assertions: false + check-blank: false + lll: + line-length: 100 + tab-width: 4 + prealloc: + simple: false + range-loops: false + for-loops: false + whitespace: + multi-if: false + multi-func: false + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/CHANGELOG.md b/pkg/installer/src/vendor/github.com/sirupsen/logrus/CHANGELOG.md index 7567f612898..098608ff4b4 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/CHANGELOG.md +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/CHANGELOG.md @@ -37,7 +37,7 @@ Features: # 1.6.0 Fixes: * end of line cleanup - * revert the entry concurrency bug fix whic leads to deadlock under some circumstances + * revert the entry concurrency bug fix which leads to deadlock under some circumstances * update dependency on go-windows-terminal-sequences to fix a crash with go 1.14 Features: @@ -129,7 +129,7 @@ This new release introduces: which is mostly useful for logger wrapper * a fix reverting the immutability of the entry given as parameter to the hooks a new configuration field of the json formatter in order to put all the fields - in a nested dictionnary + in a nested dictionary * a new SetOutput method in the Logger * a new configuration of the textformatter to configure the name of the default keys * a new configuration of the text formatter to disable the level truncation diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/README.md b/pkg/installer/src/vendor/github.com/sirupsen/logrus/README.md index d1d4a85fd75..cc5dab7eb78 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/README.md +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/README.md @@ -1,4 +1,4 @@ -# Logrus :walrus: [![Build Status](https://github.com/sirupsen/logrus/workflows/CI/badge.svg)](https://github.com/sirupsen/logrus/actions?query=workflow%3ACI) [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![Go Reference](https://pkg.go.dev/badge/github.com/sirupsen/logrus.svg)](https://pkg.go.dev/github.com/sirupsen/logrus) +# Logrus :walrus: [![Build Status](https://github.com/sirupsen/logrus/workflows/CI/badge.svg)](https://github.com/sirupsen/logrus/actions?query=workflow%3ACI) [![Go Reference](https://pkg.go.dev/badge/github.com/sirupsen/logrus.svg)](https://pkg.go.dev/github.com/sirupsen/logrus) Logrus is a structured logger for Go (golang), completely API compatible with the standard library logger. @@ -40,7 +40,7 @@ plain text): ![Colored](http://i.imgur.com/PY7qMwd.png) -With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash +With `logrus.SetFormatter(&logrus.JSONFormatter{})`, for easy parsing by logstash or Splunk: ```text @@ -60,9 +60,9 @@ ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} "time":"2014-03-10 19:57:38.562543128 -0400 EDT"} ``` -With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not +With the default `logrus.SetFormatter(&logrus.TextFormatter{})` when a TTY is not attached, the output is compatible with the -[logfmt](http://godoc.org/github.com/kr/logfmt) format: +[logfmt](https://pkg.go.dev/github.com/kr/logfmt) format: ```text time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 @@ -75,17 +75,18 @@ time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x20822 To ensure this behaviour even if a TTY is attached, set your formatter as follows: ```go - log.SetFormatter(&log.TextFormatter{ - DisableColors: true, - FullTimestamp: true, - }) +logrus.SetFormatter(&logrus.TextFormatter{ + DisableColors: true, + FullTimestamp: true, +}) ``` #### Logging Method Name If you wish to add the calling method as a field, instruct the logger via: + ```go -log.SetReportCaller(true) +logrus.SetReportCaller(true) ``` This adds the caller as 'method' like so: @@ -100,11 +101,11 @@ time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcr Note that this does add measurable overhead - the cost will depend on the version of Go, but is between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your environment via benchmarks: -``` + +```bash go test -bench=.*CallerTracing ``` - #### Case-sensitivity The organization's name was changed to lower-case--and this will not be changed @@ -118,12 +119,10 @@ The simplest way to use Logrus is simply the package-level exported logger: ```go package main -import ( - log "github.com/sirupsen/logrus" -) +import "github.com/sirupsen/logrus" func main() { - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "animal": "walrus", }).Info("A walrus appears") } @@ -139,6 +138,7 @@ package main import ( "os" + log "github.com/sirupsen/logrus" ) @@ -190,26 +190,27 @@ package main import ( "os" + "github.com/sirupsen/logrus" ) // Create a new instance of the logger. You can have any number of instances. -var log = logrus.New() +var logger = logrus.New() func main() { // The API for setting attributes is a little different than the package level - // exported logger. See Godoc. - log.Out = os.Stdout + // exported logger. See Godoc. + logger.Out = os.Stdout // You could set this to any `io.Writer` such as a file // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) // if err == nil { - // log.Out = file + // logger.Out = file // } else { - // log.Info("Failed to log to file, using default stderr") + // logger.Info("Failed to log to file, using default stderr") // } - log.WithFields(logrus.Fields{ + logger.WithFields(logrus.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean") @@ -219,12 +220,12 @@ func main() { #### Fields Logrus encourages careful, structured logging through logging fields instead of -long, unparseable error messages. For example, instead of: `log.Fatalf("Failed +long, unparseable error messages. For example, instead of: `logrus.Fatalf("Failed to send event %s to topic %s with key %d")`, you should log the much more discoverable: ```go -log.WithFields(log.Fields{ +logrus.WithFields(logrus.Fields{ "event": event, "topic": topic, "key": key, @@ -245,12 +246,12 @@ seen as a hint you should add a field, however, you can still use the Often it's helpful to have fields _always_ attached to log statements in an application or parts of one. For example, you may want to always log the `request_id` and `user_ip` in the context of a request. Instead of writing -`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on +`logger.WithFields(logrus.Fields{"request_id": request_id, "user_ip": user_ip})` on every line, you can create a `logrus.Entry` to pass around instead: ```go -requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) -requestLogger.Info("something happened on that request") # will log request_id and user_ip +requestLogger := logger.WithFields(logrus.Fields{"request_id": request_id, "user_ip": user_ip}) +requestLogger.Info("something happened on that request") // will log request_id and user_ip requestLogger.Warn("something not great happened") ``` @@ -264,28 +265,31 @@ Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in `init`: ```go +package main + import ( - log "github.com/sirupsen/logrus" - "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake" - logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" "log/syslog" + + "github.com/sirupsen/logrus" + airbrake "gopkg.in/gemnasium/logrus-airbrake-hook.v2" + logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" ) func init() { // Use the Airbrake hook to report errors that have Error severity or above to // an exception tracker. You can create custom hooks, see the Hooks section. - log.AddHook(airbrake.NewHook(123, "xyz", "production")) + logrus.AddHook(airbrake.NewHook(123, "xyz", "production")) hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") if err != nil { - log.Error("Unable to connect to local syslog daemon") + logrus.Error("Unable to connect to local syslog daemon") } else { - log.AddHook(hook) + logrus.AddHook(hook) } } ``` -Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). +Note: Syslog hooks also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) @@ -295,15 +299,15 @@ A list of currently known service hooks can be found in this wiki [page](https:/ Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic. ```go -log.Trace("Something very low level.") -log.Debug("Useful debugging information.") -log.Info("Something noteworthy happened!") -log.Warn("You should probably take a look at this.") -log.Error("Something failed but I'm not quitting.") +logrus.Trace("Something very low level.") +logrus.Debug("Useful debugging information.") +logrus.Info("Something noteworthy happened!") +logrus.Warn("You should probably take a look at this.") +logrus.Error("Something failed but I'm not quitting.") // Calls os.Exit(1) after logging -log.Fatal("Bye.") +logrus.Fatal("Bye.") // Calls panic() after logging -log.Panic("I'm bailing.") +logrus.Panic("I'm bailing.") ``` You can set the logging level on a `Logger`, then it will only log entries with @@ -311,13 +315,13 @@ that severity or anything above it: ```go // Will log anything that is info or above (warn, error, fatal, panic). Default. -log.SetLevel(log.InfoLevel) +logrus.SetLevel(logrus.InfoLevel) ``` -It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose +It may be useful to set `logrus.Level = logrus.DebugLevel` in a debug or verbose environment if your application has that. -Note: If you want different log levels for global (`log.SetLevel(...)`) and syslog logging, please check the [syslog hook README](hooks/syslog/README.md#different-log-levels-for-local-and-remote-logging). +Note: If you want different log levels for global (`logrus.SetLevel(...)`) and syslog logging, please check the [syslog hook README](hooks/syslog/README.md#different-log-levels-for-local-and-remote-logging). #### Entries @@ -340,17 +344,17 @@ could do: ```go import ( - log "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus" ) func init() { // do something here to set environment depending on an environment variable // or command-line flag if Environment == "production" { - log.SetFormatter(&log.JSONFormatter{}) + logrus.SetFormatter(&logrus.JSONFormatter{}) } else { // The TextFormatter is default, you don't actually have to do this. - log.SetFormatter(&log.TextFormatter{}) + logrus.SetFormatter(&logrus.TextFormatter{}) } } ``` @@ -372,11 +376,11 @@ The built-in logging formatters are: * When colors are enabled, levels are truncated to 4 characters by default. To disable truncation set the `DisableLevelTruncation` field to `true`. * When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text. - * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). + * All options are listed in the [generated docs](https://pkg.go.dev/github.com/sirupsen/logrus#TextFormatter). * `logrus.JSONFormatter`. Logs fields as JSON. - * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). + * All options are listed in the [generated docs](https://pkg.go.dev/github.com/sirupsen/logrus#JSONFormatter). -Third party logging formatters: +Third-party logging formatters: * [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine. * [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html). @@ -384,7 +388,7 @@ Third party logging formatters: * [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. * [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the Power of Zalgo. * [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure. -* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Sava log to files. +* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Save log to files. * [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added. You can define your formatter by implementing the `Formatter` interface, @@ -393,10 +397,9 @@ requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a default ones (see Entries section above): ```go -type MyJSONFormatter struct { -} +type MyJSONFormatter struct{} -log.SetFormatter(new(MyJSONFormatter)) +logrus.SetFormatter(new(MyJSONFormatter)) func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { // Note this doesn't include Time, Level and Message which are available on @@ -455,17 +458,18 @@ entries. It should not be a feature of the application-level logger. #### Testing -Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: +Logrus has a built-in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: * decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook * a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): ```go import( + "testing" + "github.com/sirupsen/logrus" "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" - "testing" ) func TestSomething(t*testing.T){ @@ -486,15 +490,15 @@ func TestSomething(t*testing.T){ Logrus can register one or more functions that will be called when any `fatal` level message is logged. The registered handlers will be executed before logrus performs an `os.Exit(1)`. This behavior may be helpful if callers need -to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. +to gracefully shut down. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. -``` -... +```go +// ... handler := func() { - // gracefully shutdown something... + // gracefully shut down something... } logrus.RegisterExitHandler(handler) -... +// ... ``` #### Thread safety @@ -502,7 +506,7 @@ logrus.RegisterExitHandler(handler) By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs. If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. -Situation when locking is not needed includes: +Situations when locking is not needed include: * You have no hooks registered, or hooks calling is already thread-safe. diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/appveyor.yml b/pkg/installer/src/vendor/github.com/sirupsen/logrus/appveyor.yml index df9d65c3a5b..e90f09ea68c 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/appveyor.yml +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/appveyor.yml @@ -1,14 +1,12 @@ -version: "{build}" +# Minimal stub to satisfy AppVeyor CI +version: 1.0.{build} platform: x64 -clone_folder: c:\gopath\src\github.com\sirupsen\logrus -environment: - GOPATH: c:\gopath +shallow_clone: true + branches: only: - master -install: - - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% - - go version + - main + build_script: - - go get -t - - go test + - echo "No-op build to satisfy AppVeyor CI" diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/entry.go b/pkg/installer/src/vendor/github.com/sirupsen/logrus/entry.go index 71cdbbc35d2..71d796d0b13 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/entry.go +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/entry.go @@ -34,13 +34,15 @@ func init() { minimumCallerDepth = 1 } -// Defines the key when adding errors using WithError. +// ErrorKey defines the key when adding errors using [WithError], [Logger.WithError]. var ErrorKey = "error" -// An entry is the final or intermediate Logrus logging entry. It contains all +// Entry is the final or intermediate Logrus logging entry. It contains all // the fields passed with WithField{,s}. It's finally logged when Trace, Debug, // Info, Warn, Error, Fatal or Panic is called on it. These objects can be // reused and passed around as much as you wish to avoid field duplication. +// +//nolint:recvcheck // the methods of "Entry" use pointer receiver and non-pointer receiver. type Entry struct { Logger *Logger @@ -86,12 +88,12 @@ func (entry *Entry) Dup() *Entry { return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, Context: entry.Context, err: entry.err} } -// Returns the bytes representation of this entry from the formatter. +// Bytes returns the bytes representation of this entry from the formatter. func (entry *Entry) Bytes() ([]byte, error) { return entry.Logger.Formatter.Format(entry) } -// Returns the string representation from the reader and ultimately the +// String returns the string representation from the reader and ultimately the // formatter. func (entry *Entry) String() (string, error) { serialized, err := entry.Bytes() @@ -102,12 +104,13 @@ func (entry *Entry) String() (string, error) { return str, nil } -// Add an error as single field (using the key defined in ErrorKey) to the Entry. +// WithError adds an error as single field (using the key defined in [ErrorKey]) +// to the Entry. func (entry *Entry) WithError(err error) *Entry { return entry.WithField(ErrorKey, err) } -// Add a context to the Entry. +// WithContext adds a context to the Entry. func (entry *Entry) WithContext(ctx context.Context) *Entry { dataCopy := make(Fields, len(entry.Data)) for k, v := range entry.Data { @@ -116,12 +119,12 @@ func (entry *Entry) WithContext(ctx context.Context) *Entry { return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx} } -// Add a single field to the Entry. +// WithField adds a single field to the Entry. func (entry *Entry) WithField(key string, value interface{}) *Entry { return entry.WithFields(Fields{key: value}) } -// Add a map of fields to the Entry. +// WithFields adds a map of fields to the Entry. func (entry *Entry) WithFields(fields Fields) *Entry { data := make(Fields, len(entry.Data)+len(fields)) for k, v := range entry.Data { @@ -150,7 +153,7 @@ func (entry *Entry) WithFields(fields Fields) *Entry { return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context} } -// Overrides the time of the Entry. +// WithTime overrides the time of the Entry. func (entry *Entry) WithTime(t time.Time) *Entry { dataCopy := make(Fields, len(entry.Data)) for k, v := range entry.Data { @@ -204,7 +207,7 @@ func getCaller() *runtime.Frame { // If the caller isn't part of this package, we're done if pkg != logrusPackage { - return &f //nolint:scopelint + return &f } } @@ -432,7 +435,7 @@ func (entry *Entry) Panicln(args ...interface{}) { entry.Logln(PanicLevel, args...) } -// Sprintlnn => Sprint no newline. This is to get the behavior of how +// sprintlnn => Sprint no newline. This is to get the behavior of how // fmt.Sprintln where spaces are always added between operands, regardless of // their type. Instead of vendoring the Sprintln implementation to spare a // string allocation, we do the simplest thing. diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/hooks.go b/pkg/installer/src/vendor/github.com/sirupsen/logrus/hooks.go index 3f151cdc392..9ab978a4578 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/hooks.go +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/hooks.go @@ -1,16 +1,16 @@ package logrus -// A hook to be fired when logging on the logging levels returned from -// `Levels()` on your implementation of the interface. Note that this is not +// Hook describes hooks to be fired when logging on the logging levels returned from +// [Hook.Levels] on your implementation of the interface. Note that this is not // fired in a goroutine or a channel with workers, you should handle such -// functionality yourself if your call is non-blocking and you don't wish for +// functionality yourself if your call is non-blocking, and you don't wish for // the logging calls for levels returned from `Levels()` to block. type Hook interface { Levels() []Level Fire(*Entry) error } -// Internal type for storing the hooks on a logger instance. +// LevelHooks is an internal type for storing the hooks on a logger instance. type LevelHooks map[Level][]Hook // Add a hook to an instance of logger. This is called with diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/logger.go b/pkg/installer/src/vendor/github.com/sirupsen/logrus/logger.go index 5ff0aef6d3f..f5b8c439ee8 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/logger.go +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/logger.go @@ -72,16 +72,16 @@ func (mw *MutexWrap) Disable() { mw.disabled = true } -// Creates a new logger. Configuration should be set by changing `Formatter`, -// `Out` and `Hooks` directly on the default logger instance. You can also just +// New Creates a new logger. Configuration should be set by changing [Formatter], +// Out and Hooks directly on the default Logger instance. You can also just // instantiate your own: // -// var log = &logrus.Logger{ -// Out: os.Stderr, -// Formatter: new(logrus.TextFormatter), -// Hooks: make(logrus.LevelHooks), -// Level: logrus.DebugLevel, -// } +// var log = &logrus.Logger{ +// Out: os.Stderr, +// Formatter: new(logrus.TextFormatter), +// Hooks: make(logrus.LevelHooks), +// Level: logrus.DebugLevel, +// } // // It's recommended to make this a global instance called `log`. func New() *Logger { @@ -118,30 +118,30 @@ func (logger *Logger) WithField(key string, value interface{}) *Entry { return entry.WithField(key, value) } -// Adds a struct of fields to the log entry. All it does is call `WithField` for -// each `Field`. +// WithFields adds a struct of fields to the log entry. It calls [Entry.WithField] +// for each Field. func (logger *Logger) WithFields(fields Fields) *Entry { entry := logger.newEntry() defer logger.releaseEntry(entry) return entry.WithFields(fields) } -// Add an error as single field to the log entry. All it does is call -// `WithError` for the given `error`. +// WithError adds an error as single field to the log entry. It calls +// [Entry.WithError] for the given error. func (logger *Logger) WithError(err error) *Entry { entry := logger.newEntry() defer logger.releaseEntry(entry) return entry.WithError(err) } -// Add a context to the log entry. +// WithContext add a context to the log entry. func (logger *Logger) WithContext(ctx context.Context) *Entry { entry := logger.newEntry() defer logger.releaseEntry(entry) return entry.WithContext(ctx) } -// Overrides the time of the log entry. +// WithTime overrides the time of the log entry. func (logger *Logger) WithTime(t time.Time) *Entry { entry := logger.newEntry() defer logger.releaseEntry(entry) @@ -347,9 +347,9 @@ func (logger *Logger) Exit(code int) { logger.ExitFunc(code) } -//When file is opened with appending mode, it's safe to -//write concurrently to a file (within 4k message on Linux). -//In these cases user can choose to disable the lock. +// SetNoLock disables the lock for situations where a file is opened with +// appending mode, and safe for concurrent writes to the file (within 4k +// message on Linux). In these cases user can choose to disable the lock. func (logger *Logger) SetNoLock() { logger.mu.Disable() } diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/logrus.go b/pkg/installer/src/vendor/github.com/sirupsen/logrus/logrus.go index 2f16224cb9f..37fc4fef85a 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/logrus.go +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/logrus.go @@ -6,13 +6,15 @@ import ( "strings" ) -// Fields type, used to pass to `WithFields`. +// Fields type, used to pass to [WithFields]. type Fields map[string]interface{} // Level type +// +//nolint:recvcheck // the methods of "Entry" use pointer receiver and non-pointer receiver. type Level uint32 -// Convert the Level to a string. E.g. PanicLevel becomes "panic". +// Convert the Level to a string. E.g. [PanicLevel] becomes "panic". func (level Level) String() string { if b, err := level.MarshalText(); err == nil { return string(b) @@ -77,7 +79,7 @@ func (level Level) MarshalText() ([]byte, error) { return nil, fmt.Errorf("not a valid logrus level %d", level) } -// A constant exposing all logging levels +// AllLevels exposing all logging levels. var AllLevels = []Level{ PanicLevel, FatalLevel, @@ -119,8 +121,8 @@ var ( ) // StdLogger is what your logrus-enabled library should take, that way -// it'll accept a stdlib logger and a logrus logger. There's no standard -// interface, this is the closest we get, unfortunately. +// it'll accept a stdlib logger ([log.Logger]) and a logrus logger. +// There's no standard interface, so this is the closest we get, unfortunately. type StdLogger interface { Print(...interface{}) Printf(string, ...interface{}) @@ -135,7 +137,8 @@ type StdLogger interface { Panicln(...interface{}) } -// The FieldLogger interface generalizes the Entry and Logger types +// FieldLogger extends the [StdLogger] interface, generalizing +// the [Entry] and [Logger] types. type FieldLogger interface { WithField(key string, value interface{}) *Entry WithFields(fields Fields) *Entry @@ -176,8 +179,9 @@ type FieldLogger interface { // IsPanicEnabled() bool } -// Ext1FieldLogger (the first extension to FieldLogger) is superfluous, it is -// here for consistancy. Do not use. Use Logger or Entry instead. +// Ext1FieldLogger (the first extension to [FieldLogger]) is superfluous, it is +// here for consistency. Do not use. Use [FieldLogger], [Logger] or [Entry] +// instead. type Ext1FieldLogger interface { FieldLogger Tracef(format string, args ...interface{}) diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go b/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go index 499789984d2..69956b425a1 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go @@ -1,4 +1,4 @@ -// +build darwin dragonfly freebsd netbsd openbsd +// +build darwin dragonfly freebsd netbsd openbsd hurd // +build !js package logrus diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_unix.go b/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_unix.go index 04748b8515f..c9aed267a4c 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_unix.go +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_unix.go @@ -1,5 +1,7 @@ +//go:build (linux || aix || zos) && !js && !wasi // +build linux aix zos // +build !js +// +build !wasi package logrus diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_wasi.go b/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_wasi.go new file mode 100644 index 00000000000..2822b212fbf --- /dev/null +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_wasi.go @@ -0,0 +1,8 @@ +//go:build wasi +// +build wasi + +package logrus + +func isTerminal(fd int) bool { + return false +} diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_wasip1.go b/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_wasip1.go new file mode 100644 index 00000000000..108a6be12b1 --- /dev/null +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/terminal_check_wasip1.go @@ -0,0 +1,8 @@ +//go:build wasip1 +// +build wasip1 + +package logrus + +func isTerminal(fd int) bool { + return false +} diff --git a/pkg/installer/src/vendor/github.com/sirupsen/logrus/text_formatter.go b/pkg/installer/src/vendor/github.com/sirupsen/logrus/text_formatter.go index be2c6efe5ed..6dfeb18b10e 100644 --- a/pkg/installer/src/vendor/github.com/sirupsen/logrus/text_formatter.go +++ b/pkg/installer/src/vendor/github.com/sirupsen/logrus/text_formatter.go @@ -306,6 +306,7 @@ func (f *TextFormatter) needsQuoting(text string) bool { return false } for _, ch := range text { + //nolint:staticcheck // QF1001: could apply De Morgan's law if !((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || @@ -334,6 +335,6 @@ func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { if !f.needsQuoting(stringVal) { b.WriteString(stringVal) } else { - b.WriteString(fmt.Sprintf("%q", stringVal)) + fmt.Fprintf(b, "%q", stringVal) } } diff --git a/pkg/installer/src/vendor/golang.org/x/net/html/entity.go b/pkg/installer/src/vendor/golang.org/x/net/html/entity.go index b628880a014..4e8d5d55f26 100644 --- a/pkg/installer/src/vendor/golang.org/x/net/html/entity.go +++ b/pkg/installer/src/vendor/golang.org/x/net/html/entity.go @@ -2156,9 +2156,8 @@ var entity = map[string]rune{ // HTML entities that are two unicode codepoints. var entity2 = map[string][2]rune{ - // TODO(nigeltao): Handle replacements that are wider than their names. - // "nLt;": {'\u226A', '\u20D2'}, - // "nGt;": {'\u226B', '\u20D2'}, + "nLt;": {'\u226A', '\u20D2'}, + "nGt;": {'\u226B', '\u20D2'}, "NotEqualTilde;": {'\u2242', '\u0338'}, "NotGreaterFullEqual;": {'\u2267', '\u0338'}, "NotGreaterGreater;": {'\u226B', '\u0338'}, diff --git a/pkg/installer/src/vendor/golang.org/x/net/html/escape.go b/pkg/installer/src/vendor/golang.org/x/net/html/escape.go index 12f22737062..df3edc5b125 100644 --- a/pkg/installer/src/vendor/golang.org/x/net/html/escape.go +++ b/pkg/installer/src/vendor/golang.org/x/net/html/escape.go @@ -6,6 +6,7 @@ package html import ( "bytes" + "slices" "strings" "unicode/utf8" ) @@ -50,25 +51,24 @@ var replacementTable = [...]rune{ // 0x0D->'\u000D' is a no-op. } -// unescapeEntity reads an entity like "<" from b[src:] and writes the -// corresponding "<" to b[dst:], returning the incremented dst and src cursors. -// Precondition: b[src] == '&' && dst <= src. -// attribute should be true if parsing an attribute value. -func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { +// unescapeEntity attempts to consume a character reference from s[src:], +// returning the rune, potential second rune, and number of bytes consumed +// (which indicates the length of the character reference). It is assumed that +// the first byte of s is '&'. attribute should be true if parsing an attribute +// value. +func unescapeEntity(s []byte, attribute bool) (rune, rune, int) { // https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference // i starts at 1 because we already know that s[0] == '&'. - i, s := 1, b[src:] + i := 1 if len(s) <= 1 { - b[dst] = b[src] - return dst + 1, src + 1 + return '&', 0, 1 } if s[i] == '#' { - if len(s) <= 3 { // We need to have at least "&#.". - b[dst] = b[src] - return dst + 1, src + 1 + if len(s) <= 2 { // We need to have at least "&#". + return '&', 0, 1 } i++ c := s[i] @@ -78,34 +78,43 @@ func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { i++ } + i0 := i x := '\x00' for i < len(s) { c = s[i] - i++ + var d rune + var mult rune if hex { + mult = 16 if '0' <= c && c <= '9' { - x = 16*x + rune(c) - '0' - continue + d = rune(c) - '0' } else if 'a' <= c && c <= 'f' { - x = 16*x + rune(c) - 'a' + 10 - continue + d = rune(c) - 'a' + 10 } else if 'A' <= c && c <= 'F' { - x = 16*x + rune(c) - 'A' + 10 - continue + d = rune(c) - 'A' + 10 + } else { + break + } + } else { + mult = 10 + if '0' <= c && c <= '9' { + d = rune(c) - '0' + } else { + break } - } else if '0' <= c && c <= '9' { - x = 10*x + rune(c) - '0' - continue } - if c != ';' { - i-- + if x <= 0x10FFFF { + x = mult*x + d } - break + i++ + } + + if i == i0 { // No characters matched. + return '&', 0, 1 } - if i <= 3 { // No characters matched. - b[dst] = b[src] - return dst + 1, src + 1 + if i < len(s) && s[i] == ';' { + i++ } if 0x80 <= x && x <= 0x9F { @@ -116,7 +125,7 @@ func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { x = '\uFFFD' } - return dst + utf8.EncodeRune(b[dst:], x), src + i + return x, 0, i } // Consume the maximum number of characters possible, with the @@ -141,10 +150,9 @@ func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { } else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' { // No-op. } else if x := entity[entityName]; x != 0 { - return dst + utf8.EncodeRune(b[dst:], x), src + i + return x, 0, i } else if x := entity2[entityName]; x[0] != 0 { - dst1 := dst + utf8.EncodeRune(b[dst:], x[0]) - return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i + return x[0], x[1], i } else if !attribute { maxLen := len(entityName) - 1 if maxLen > longestEntityWithoutSemicolon { @@ -152,35 +160,67 @@ func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { } for j := maxLen; j > 1; j-- { if x := entity[entityName[:j]]; x != 0 { - return dst + utf8.EncodeRune(b[dst:], x), src + j + 1 + return x, 0, j + 1 } } } - dst1, src1 = dst+i, src+i - copy(b[dst:dst1], b[src:src1]) - return dst1, src1 + return '&', 0, 1 } -// unescape unescapes b's entities in-place, so that "a<b" becomes "a entityNameLen { + if reusingB { + out = slices.Clone(out) + reusingB = false } - return b[0:dst] + out = slices.Grow(out, replLen) + } + out = utf8.AppendRune(out, r1) + if r2 != 0 { + out = utf8.AppendRune(out, r2) } + + src += entityNameLen } - return b + + return out } // lower lower-cases the A-Z bytes in b in-place, so that "aBc" becomes "abc". diff --git a/pkg/installer/src/vendor/golang.org/x/net/html/foreign.go b/pkg/installer/src/vendor/golang.org/x/net/html/foreign.go index e8515d8e887..65d01d1ed9e 100644 --- a/pkg/installer/src/vendor/golang.org/x/net/html/foreign.go +++ b/pkg/installer/src/vendor/golang.org/x/net/html/foreign.go @@ -23,7 +23,7 @@ func adjustForeignAttributes(aa []Attribute) { } switch a.Key { case "xlink:actuate", "xlink:arcrole", "xlink:href", "xlink:role", "xlink:show", - "xlink:title", "xlink:type", "xml:base", "xml:lang", "xml:space", "xmlns:xlink": + "xlink:title", "xlink:type", "xml:lang", "xml:space", "xmlns:xlink": j := strings.Index(a.Key, ":") aa[i].Namespace = a.Key[:j] aa[i].Key = a.Key[j+1:] diff --git a/pkg/installer/src/vendor/golang.org/x/net/html/parse.go b/pkg/installer/src/vendor/golang.org/x/net/html/parse.go index b3d2a255817..165b6108d40 100644 --- a/pkg/installer/src/vendor/golang.org/x/net/html/parse.go +++ b/pkg/installer/src/vendor/golang.org/x/net/html/parse.go @@ -63,7 +63,7 @@ func (p *parser) top() *Node { // Stop tags for use in popUntil. These come from section 12.2.4.2. var ( defaultScopeStopTags = map[string][]a.Atom{ - "": {a.Applet, a.Caption, a.Html, a.Table, a.Td, a.Th, a.Marquee, a.Object, a.Template}, + "": {a.Applet, a.Caption, a.Html, a.Table, a.Td, a.Th, a.Marquee, a.Object, a.Template, a.Select}, "math": {a.AnnotationXml, a.Mi, a.Mn, a.Mo, a.Ms, a.Mtext}, "svg": {a.Desc, a.ForeignObject, a.Title}, } @@ -78,7 +78,6 @@ const ( tableScope tableRowScope tableBodyScope - selectScope ) // popUntil pops the stack of open elements at the highest element whose tag @@ -133,10 +132,6 @@ func (p *parser) indexOfElementInScope(s scope, matchTags ...a.Atom) int { if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template { return -1 } - case selectScope: - if tagAtom != a.Optgroup && tagAtom != a.Option { - return -1 - } default: panic(fmt.Sprintf("html: internal error: indexOfElementInScope unknown scope: %d", s)) } @@ -460,21 +455,6 @@ func (p *parser) resetInsertionMode() { } switch n.DataAtom { - case a.Select: - if !last { - for ancestor, first := n, p.oe[0]; ancestor != first; { - ancestor = p.oe[p.oe.index(ancestor)-1] - switch ancestor.DataAtom { - case a.Template: - p.im = inSelectIM - return - case a.Table: - p.im = inSelectInTableIM - return - } - } - } - p.im = inSelectIM case a.Td, a.Th: // TODO: remove this divergence from the HTML5 spec. // @@ -1002,7 +982,10 @@ func inBodyIM(p *parser) bool { p.popUntil(buttonScope, a.P) p.addElement() case a.Button: - p.popUntil(defaultScope, a.Button) + if p.elementInScope(defaultScope, a.Button) { + p.generateImpliedEndTags() + p.popUntil(defaultScope, a.Button) + } p.reconstructActiveFormattingElements() p.addElement() p.framesetOK = false @@ -1040,7 +1023,18 @@ func inBodyIM(p *parser) bool { p.framesetOK = false p.im = inTableIM return true - case a.Area, a.Br, a.Embed, a.Img, a.Input, a.Keygen, a.Wbr: + case a.Area, a.Br, a.Embed, a.Img, a.Keygen, a.Wbr: + p.reconstructActiveFormattingElements() + p.addElement() + p.oe.pop() + p.acknowledgeSelfClosingTag() + p.framesetOK = false + case a.Input: + if p.fragment && p.context.DataAtom == a.Select { + // Ignore the token. + return true + } + p.popUntil(defaultScope, a.Select) p.reconstructActiveFormattingElements() p.addElement() p.oe.pop() @@ -1061,7 +1055,13 @@ func inBodyIM(p *parser) bool { p.oe.pop() p.acknowledgeSelfClosingTag() case a.Hr: - p.popUntil(buttonScope, a.P) + if p.elementInScope(buttonScope, a.P) { + p.generateImpliedEndTags("p") + p.popUntil(defaultScope, a.P) + } + if p.elementInScope(defaultScope, a.Select) { + p.generateImpliedEndTags() + } p.addElement() p.oe.pop() p.acknowledgeSelfClosingTag() @@ -1095,13 +1095,30 @@ func inBodyIM(p *parser) bool { // Don't let the tokenizer go into raw text mode when scripting is disabled. p.tokenizer.NextIsNotRawText() case a.Select: + if p.fragment && p.context.DataAtom == a.Select { + // Ignore the token. + return true + } else if p.popUntil(defaultScope, a.Select) { + return true + } p.reconstructActiveFormattingElements() p.addElement() p.framesetOK = false - p.im = inSelectIM return true - case a.Optgroup, a.Option: - if p.top().DataAtom == a.Option { + case a.Option: + if p.elementInScope(defaultScope, a.Select) { + p.generateImpliedEndTags("optgroup") + // If oe has option element in scope, parse error? + } else if p.top().DataAtom == a.Option { + p.oe.pop() + } + p.reconstructActiveFormattingElements() + p.addElement() + case a.Optgroup: + if p.elementInScope(defaultScope, a.Select) { + p.generateImpliedEndTags() + // If oe has option or optgroup element in scope, parse error? + } else if p.top().DataAtom == a.Option { p.oe.pop() } p.reconstructActiveFormattingElements() @@ -1149,7 +1166,12 @@ func inBodyIM(p *parser) bool { return false } return true - case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dialog, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Main, a.Menu, a.Nav, a.Ol, a.Pre, a.Search, a.Section, a.Summary, a.Ul: + case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dialog, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Main, a.Menu, a.Nav, a.Ol, a.Pre, a.Search, a.Section, a.Select, a.Summary, a.Ul: + if !p.elementInScope(defaultScope, p.tok.DataAtom) { + // Ignore the token. + return true + } + p.generateImpliedEndTags() p.popUntil(defaultScope, p.tok.DataAtom) case a.Form: if p.oe.contains(a.Template) { @@ -1488,17 +1510,6 @@ func inTableIM(p *parser) bool { } p.addElement() p.form = p.oe.pop() - case a.Select: - p.reconstructActiveFormattingElements() - switch p.top().DataAtom { - case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: - p.fosterParenting = true - } - p.addElement() - p.fosterParenting = false - p.framesetOK = false - p.im = inSelectInTableIM - return true } case EndTagToken: switch p.tok.DataAtom { @@ -1547,12 +1558,6 @@ func inCaptionIM(p *parser) bool { p.clearActiveFormattingElements() p.im = inTableIM return false - case a.Select: - p.reconstructActiveFormattingElements() - p.addElement() - p.framesetOK = false - p.im = inSelectInTableIM - return true } case EndTagToken: switch p.tok.DataAtom { @@ -1762,12 +1767,6 @@ func inCellIM(p *parser) bool { } // Ignore the token. return true - case a.Select: - p.reconstructActiveFormattingElements() - p.addElement() - p.framesetOK = false - p.im = inSelectInTableIM - return true } case EndTagToken: switch p.tok.DataAtom { @@ -1798,118 +1797,6 @@ func inCellIM(p *parser) bool { return inBodyIM(p) } -// Section 12.2.6.4.16. -func inSelectIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - p.addText(strings.Replace(p.tok.Data, "\x00", "", -1)) - case StartTagToken: - switch p.tok.DataAtom { - case a.Html: - return inBodyIM(p) - case a.Option: - if p.top().DataAtom == a.Option { - p.oe.pop() - } - p.addElement() - case a.Optgroup: - if p.top().DataAtom == a.Option { - p.oe.pop() - } - if p.top().DataAtom == a.Optgroup { - p.oe.pop() - } - p.addElement() - case a.Select: - if !p.popUntil(selectScope, a.Select) { - // Ignore the token. - return true - } - p.resetInsertionMode() - case a.Input, a.Keygen, a.Textarea: - if p.elementInScope(selectScope, a.Select) { - p.parseImpliedToken(EndTagToken, a.Select, a.Select.String()) - return false - } - // In order to properly ignore