From e41a61276a7f3e6b4c00a49cc5e11cf92b010b1d Mon Sep 17 00:00:00 2001 From: Joel Takvorian Date: Tue, 31 Mar 2026 17:57:53 +0200 Subject: [PATCH 1/4] NETOBSERV-2471: Allow space in filtered values --- go.mod | 12 +- go.sum | 30 +- pkg/loki/flow_query.go | 2 +- pkg/loki/query_test.go | 22 +- .../flowlogs-pipeline/pkg/api/ingest_ipfix.go | 23 +- .../flowlogs-pipeline/pkg/utils/kubernetes.go | 41 - vendor/github.com/netsampler/goflow2/LICENSE | 29 - .../goflow2/decoders/netflow/ipfix.go | 989 ------------- .../goflow2/decoders/netflow/netflow.go | 537 ------- .../goflow2/decoders/netflow/nfv9.go | 317 ---- .../goflow2/decoders/netflow/packet.go | 158 -- .../decoders/netflow/templates/templates.go | 139 -- .../goflow2/decoders/netflowlegacy/netflow.go | 90 -- .../goflow2/decoders/netflowlegacy/packet.go | 96 -- .../goflow2/decoders/sflow/datastructure.go | 103 -- .../goflow2/decoders/sflow/packet.go | 73 - .../goflow2/decoders/sflow/sflow.go | 482 ------ .../goflow2/decoders/utils/utils.go | 128 -- .../netsampler/goflow2/pb/flow.pb.go | 924 ------------ .../netsampler/goflow2/pb/flow.proto | 131 -- .../goflow2/producer/producer_nf.go | 683 --------- .../goflow2/producer/producer_nflegacy.go | 81 -- .../goflow2/producer/producer_sf.go | 349 ----- .../netsampler/goflow2/producer/reflect.go | 233 --- vendor/github.com/spf13/pflag/.editorconfig | 12 - vendor/github.com/spf13/pflag/.gitignore | 2 - vendor/github.com/spf13/pflag/.golangci.yaml | 4 - vendor/github.com/spf13/pflag/.travis.yml | 22 - vendor/github.com/spf13/pflag/LICENSE | 28 - vendor/github.com/spf13/pflag/README.md | 323 ----- vendor/github.com/spf13/pflag/bool.go | 94 -- vendor/github.com/spf13/pflag/bool_func.go | 40 - vendor/github.com/spf13/pflag/bool_slice.go | 185 --- vendor/github.com/spf13/pflag/bytes.go | 209 --- vendor/github.com/spf13/pflag/count.go | 96 -- vendor/github.com/spf13/pflag/duration.go | 86 -- .../github.com/spf13/pflag/duration_slice.go | 166 --- vendor/github.com/spf13/pflag/errors.go | 149 -- vendor/github.com/spf13/pflag/flag.go | 1289 ----------------- vendor/github.com/spf13/pflag/float32.go | 88 -- .../github.com/spf13/pflag/float32_slice.go | 174 --- vendor/github.com/spf13/pflag/float64.go | 84 -- .../github.com/spf13/pflag/float64_slice.go | 166 --- vendor/github.com/spf13/pflag/func.go | 37 - vendor/github.com/spf13/pflag/golangflag.go | 161 -- vendor/github.com/spf13/pflag/int.go | 84 -- vendor/github.com/spf13/pflag/int16.go | 88 -- vendor/github.com/spf13/pflag/int32.go | 88 -- vendor/github.com/spf13/pflag/int32_slice.go | 174 --- vendor/github.com/spf13/pflag/int64.go | 84 -- vendor/github.com/spf13/pflag/int64_slice.go | 166 --- vendor/github.com/spf13/pflag/int8.go | 88 -- vendor/github.com/spf13/pflag/int_slice.go | 158 -- vendor/github.com/spf13/pflag/ip.go | 97 -- vendor/github.com/spf13/pflag/ip_slice.go | 186 --- vendor/github.com/spf13/pflag/ipmask.go | 122 -- vendor/github.com/spf13/pflag/ipnet.go | 98 -- vendor/github.com/spf13/pflag/ipnet_slice.go | 147 -- vendor/github.com/spf13/pflag/string.go | 80 - vendor/github.com/spf13/pflag/string_array.go | 125 -- vendor/github.com/spf13/pflag/string_slice.go | 163 --- .../github.com/spf13/pflag/string_to_int.go | 149 -- .../github.com/spf13/pflag/string_to_int64.go | 149 -- .../spf13/pflag/string_to_string.go | 168 --- vendor/github.com/spf13/pflag/text.go | 81 -- vendor/github.com/spf13/pflag/time.go | 124 -- vendor/github.com/spf13/pflag/uint.go | 88 -- vendor/github.com/spf13/pflag/uint16.go | 88 -- vendor/github.com/spf13/pflag/uint32.go | 88 -- vendor/github.com/spf13/pflag/uint64.go | 88 -- vendor/github.com/spf13/pflag/uint8.go | 88 -- vendor/github.com/spf13/pflag/uint_slice.go | 168 --- .../net/http2/writesched_priority_rfc9218.go | 15 + .../golang.org/x/sys/plan9/syscall_plan9.go | 8 +- vendor/golang.org/x/sys/unix/ztypes_linux.go | 229 +-- vendor/golang.org/x/sys/windows/aliases.go | 1 + .../x/sys/windows/syscall_windows.go | 14 - vendor/golang.org/x/term/terminal.go | 28 +- vendor/k8s.io/client-go/tools/auth/OWNERS | 8 - .../k8s.io/client-go/tools/auth/clientauth.go | 125 -- .../tools/clientcmd/api/latest/latest.go | 61 - .../tools/clientcmd/api/v1/conversion.go | 174 --- .../tools/clientcmd/api/v1/defaults.go | 37 - .../client-go/tools/clientcmd/api/v1/doc.go | 21 - .../tools/clientcmd/api/v1/register.go | 56 - .../client-go/tools/clientcmd/api/v1/types.go | 274 ---- .../api/v1/zz_generated.conversion.go | 459 ------ .../clientcmd/api/v1/zz_generated.deepcopy.go | 349 ----- .../clientcmd/api/v1/zz_generated.defaults.go | 43 - .../client-go/tools/clientcmd/auth_loaders.go | 110 -- .../tools/clientcmd/client_config.go | 702 --------- .../client-go/tools/clientcmd/config.go | 499 ------- .../k8s.io/client-go/tools/clientcmd/doc.go | 37 - .../k8s.io/client-go/tools/clientcmd/flag.go | 49 - .../client-go/tools/clientcmd/helpers.go | 50 - .../client-go/tools/clientcmd/loader.go | 679 --------- .../k8s.io/client-go/tools/clientcmd/merge.go | 121 -- .../tools/clientcmd/merged_client_builder.go | 172 --- .../client-go/tools/clientcmd/overrides.go | 263 ---- .../client-go/tools/clientcmd/validation.go | 376 ----- .../k8s.io/client-go/util/homedir/homedir.go | 92 -- vendor/modules.txt | 29 +- 102 files changed, 230 insertions(+), 17165 deletions(-) delete mode 100644 vendor/github.com/netobserv/flowlogs-pipeline/pkg/utils/kubernetes.go delete mode 100644 vendor/github.com/netsampler/goflow2/LICENSE delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/netflow/ipfix.go delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/netflow/netflow.go delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/netflow/nfv9.go delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/netflow/packet.go delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/netflow/templates/templates.go delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/netflowlegacy/netflow.go delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/netflowlegacy/packet.go delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/sflow/datastructure.go delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/sflow/packet.go delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/sflow/sflow.go delete mode 100644 vendor/github.com/netsampler/goflow2/decoders/utils/utils.go delete mode 100644 vendor/github.com/netsampler/goflow2/pb/flow.pb.go delete mode 100644 vendor/github.com/netsampler/goflow2/pb/flow.proto delete mode 100644 vendor/github.com/netsampler/goflow2/producer/producer_nf.go delete mode 100644 vendor/github.com/netsampler/goflow2/producer/producer_nflegacy.go delete mode 100644 vendor/github.com/netsampler/goflow2/producer/producer_sf.go delete mode 100644 vendor/github.com/netsampler/goflow2/producer/reflect.go delete mode 100644 vendor/github.com/spf13/pflag/.editorconfig delete mode 100644 vendor/github.com/spf13/pflag/.gitignore delete mode 100644 vendor/github.com/spf13/pflag/.golangci.yaml delete mode 100644 vendor/github.com/spf13/pflag/.travis.yml delete mode 100644 vendor/github.com/spf13/pflag/LICENSE delete mode 100644 vendor/github.com/spf13/pflag/README.md delete mode 100644 vendor/github.com/spf13/pflag/bool.go delete mode 100644 vendor/github.com/spf13/pflag/bool_func.go delete mode 100644 vendor/github.com/spf13/pflag/bool_slice.go delete mode 100644 vendor/github.com/spf13/pflag/bytes.go delete mode 100644 vendor/github.com/spf13/pflag/count.go delete mode 100644 vendor/github.com/spf13/pflag/duration.go delete mode 100644 vendor/github.com/spf13/pflag/duration_slice.go delete mode 100644 vendor/github.com/spf13/pflag/errors.go delete mode 100644 vendor/github.com/spf13/pflag/flag.go delete mode 100644 vendor/github.com/spf13/pflag/float32.go delete mode 100644 vendor/github.com/spf13/pflag/float32_slice.go delete mode 100644 vendor/github.com/spf13/pflag/float64.go delete mode 100644 vendor/github.com/spf13/pflag/float64_slice.go delete mode 100644 vendor/github.com/spf13/pflag/func.go delete mode 100644 vendor/github.com/spf13/pflag/golangflag.go delete mode 100644 vendor/github.com/spf13/pflag/int.go delete mode 100644 vendor/github.com/spf13/pflag/int16.go delete mode 100644 vendor/github.com/spf13/pflag/int32.go delete mode 100644 vendor/github.com/spf13/pflag/int32_slice.go delete mode 100644 vendor/github.com/spf13/pflag/int64.go delete mode 100644 vendor/github.com/spf13/pflag/int64_slice.go delete mode 100644 vendor/github.com/spf13/pflag/int8.go delete mode 100644 vendor/github.com/spf13/pflag/int_slice.go delete mode 100644 vendor/github.com/spf13/pflag/ip.go delete mode 100644 vendor/github.com/spf13/pflag/ip_slice.go delete mode 100644 vendor/github.com/spf13/pflag/ipmask.go delete mode 100644 vendor/github.com/spf13/pflag/ipnet.go delete mode 100644 vendor/github.com/spf13/pflag/ipnet_slice.go delete mode 100644 vendor/github.com/spf13/pflag/string.go delete mode 100644 vendor/github.com/spf13/pflag/string_array.go delete mode 100644 vendor/github.com/spf13/pflag/string_slice.go delete mode 100644 vendor/github.com/spf13/pflag/string_to_int.go delete mode 100644 vendor/github.com/spf13/pflag/string_to_int64.go delete mode 100644 vendor/github.com/spf13/pflag/string_to_string.go delete mode 100644 vendor/github.com/spf13/pflag/text.go delete mode 100644 vendor/github.com/spf13/pflag/time.go delete mode 100644 vendor/github.com/spf13/pflag/uint.go delete mode 100644 vendor/github.com/spf13/pflag/uint16.go delete mode 100644 vendor/github.com/spf13/pflag/uint32.go delete mode 100644 vendor/github.com/spf13/pflag/uint64.go delete mode 100644 vendor/github.com/spf13/pflag/uint8.go delete mode 100644 vendor/github.com/spf13/pflag/uint_slice.go delete mode 100644 vendor/k8s.io/client-go/tools/auth/OWNERS delete mode 100644 vendor/k8s.io/client-go/tools/auth/clientauth.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/latest/latest.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/v1/defaults.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/v1/doc.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/v1/register.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/v1/types.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.conversion.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.deepcopy.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.defaults.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/auth_loaders.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/client_config.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/config.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/doc.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/flag.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/helpers.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/loader.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/merge.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/overrides.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/validation.go delete mode 100644 vendor/k8s.io/client-go/util/homedir/homedir.go diff --git a/go.mod b/go.mod index 2d06e2189..14f9d835c 100644 --- a/go.mod +++ b/go.mod @@ -37,22 +37,20 @@ require ( github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect - github.com/netobserv/flowlogs-pipeline v1.11.0-community // indirect - github.com/netsampler/goflow2 v1.3.7 // indirect + github.com/netobserv/flowlogs-pipeline v1.11.2-community // indirect github.com/ovn-org/ovn-kubernetes/go-controller v0.0.0-20250227173154-57a2590a1d16 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/procfs v0.16.1 // indirect - github.com/spf13/pflag v1.0.10 // indirect github.com/stretchr/objx v0.5.2 // indirect github.com/x448/float16 v0.8.4 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/net v0.48.0 // indirect + golang.org/x/net v0.49.0 // indirect golang.org/x/oauth2 v0.34.0 // indirect - golang.org/x/sys v0.41.0 // indirect - golang.org/x/term v0.38.0 // indirect - golang.org/x/text v0.32.0 // indirect + golang.org/x/sys v0.42.0 // indirect + golang.org/x/term v0.39.0 // indirect + golang.org/x/text v0.33.0 // indirect golang.org/x/time v0.11.0 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect diff --git a/go.sum b/go.sum index fe24f029d..340226a83 100644 --- a/go.sum +++ b/go.sum @@ -83,12 +83,10 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/netobserv/flowlogs-pipeline v1.11.0-community h1:SMdhbEM/OowhHO8lefnzztu83RkXOky+h0Q+kQV8PYg= -github.com/netobserv/flowlogs-pipeline v1.11.0-community/go.mod h1:GUltBJPGXTglxawEZhtGNp4kdOP5PqMU2oB5JQp6xv0= +github.com/netobserv/flowlogs-pipeline v1.11.2-community h1:OdcKKyvfTWtoFIQk2tQEWlnfEuLdJTmskffM/RKmlMk= +github.com/netobserv/flowlogs-pipeline v1.11.2-community/go.mod h1:j6eOnbQBcUkWqmP20BNSUuQE/UQMEL146yYVHHtmECQ= github.com/netobserv/netobserv-ebpf-agent v1.11.2-community h1:WRZEhfdpSIdLI6FLQVf2cR7tOAsUZj4jpyUIX4uclao= github.com/netobserv/netobserv-ebpf-agent v1.11.2-community/go.mod h1:J/GPFE2k/MKnL6yGqPoQpzfxXMM10MtfIS2uko3hA/Y= -github.com/netsampler/goflow2 v1.3.7 h1:XZaTy8kkMnGXpJ9hS3KbO1McyrFTpVNhVFEx9rNhMmc= -github.com/netsampler/goflow2 v1.3.7/go.mod h1:4UZsVGVAs//iMCptUHn3WNScztJeUhZH7kDW2+/vDdQ= github.com/onsi/ginkgo/v2 v2.27.2 h1:LzwLj0b89qtIy6SSASkzlNvX6WktqurSHwkk2ipF/Ns= github.com/onsi/ginkgo/v2 v2.27.2/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A= @@ -154,24 +152,24 @@ go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= 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/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk= -golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= -golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= -golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= +golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI= +golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg= +golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= +golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= -golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= -golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q= -golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg= -golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= -golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY= +golang.org/x/term v0.39.0/go.mod h1:yxzUCTP/U+FzoxfdKmLaA0RV1WgE0VY7hXBwKtY/4ww= +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0= golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= -golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= -golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= +golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= +golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= 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= diff --git a/pkg/loki/flow_query.go b/pkg/loki/flow_query.go index 1606f7f31..d32ccb79c 100644 --- a/pkg/loki/flow_query.go +++ b/pkg/loki/flow_query.go @@ -23,7 +23,7 @@ const ( ) // can contains only alphanumeric / '-' / '_' / '.' / ',' / '"' / '*' / ':' / '/' characteres -var filterRegexpValidation = regexp.MustCompile(`^[\w-_.,\"*:/]*$`) +var filterRegexpValidation = regexp.MustCompile(`^[\w -_.,\"*:/]*$`) // FlowQueryBuilder stores a state to build a LogQL query type FlowQueryBuilder struct { diff --git a/pkg/loki/query_test.go b/pkg/loki/query_test.go index 7bf32db96..ce66ae142 100644 --- a/pkg/loki/query_test.go +++ b/pkg/loki/query_test.go @@ -20,10 +20,28 @@ func TestFlowQuery_AddLabelFilters(t *testing.T) { assert.Equal(t, `/loki/api/v1/query_range?query={app="netobserv-flowcollector",foo="bar",flis="flas"}`, urlQuery) } -func TestQuery_BackQuote_Error(t *testing.T) { +func TestQuery_AuthorizedChars(t *testing.T) { cfg := config.Loki{URL: "/", Labels: []string{"lab1", "lab2"}} query := NewFlowQueryBuilderWithDefaults(&cfg) - assert.Error(t, query.addFilter(filters.NewRegexMatch("key", "backquoted`val"))) + err := query.addFilter(filters.NewRegexMatch("key", "with/slash")) + assert.NoError(t, err) + + query = NewFlowQueryBuilderWithDefaults(&cfg) + err = query.addFilter(filters.NewRegexMatch("key", "with.dot")) + assert.NoError(t, err) + + query = NewFlowQueryBuilderWithDefaults(&cfg) + err = query.addFilter(filters.NewRegexMatch("key", "with-dash")) + assert.NoError(t, err) + + query = NewFlowQueryBuilderWithDefaults(&cfg) + err = query.addFilter(filters.NewRegexMatch("key", "with space")) + assert.NoError(t, err) + + query = NewFlowQueryBuilderWithDefaults(&cfg) + err = query.addFilter(filters.NewRegexMatch("key", "backquoted`val")) + assert.Error(t, err) + assert.Equal(t, "unauthorized sign in flows request: backquoted`val", err.Error()) } func TestFlowQuery_AddNotLabelFilters(t *testing.T) { diff --git a/vendor/github.com/netobserv/flowlogs-pipeline/pkg/api/ingest_ipfix.go b/vendor/github.com/netobserv/flowlogs-pipeline/pkg/api/ingest_ipfix.go index 6453c36db..a6ca2d085 100644 --- a/vendor/github.com/netobserv/flowlogs-pipeline/pkg/api/ingest_ipfix.go +++ b/vendor/github.com/netobserv/flowlogs-pipeline/pkg/api/ingest_ipfix.go @@ -19,17 +19,24 @@ package api import ( "fmt" - - "github.com/netsampler/goflow2/producer" ) type IngestIpfix struct { - HostName string `yaml:"hostName,omitempty" json:"hostName,omitempty" doc:"the hostname to listen on; defaults to 0.0.0.0"` - Port uint `yaml:"port,omitempty" json:"port,omitempty" doc:"the port number to listen on, for IPFIX/NetFlow v9. Omit or set to 0 to disable IPFIX/NetFlow v9 ingestion. If both port and portLegacy are omitted, defaults to 2055"` - PortLegacy uint `yaml:"portLegacy,omitempty" json:"portLegacy,omitempty" doc:"the port number to listen on, for legacy NetFlow v5. Omit or set to 0 to disable NetFlow v5 ingestion"` - Workers uint `yaml:"workers,omitempty" json:"workers,omitempty" doc:"the number of netflow/ipfix decoding workers"` - Sockets uint `yaml:"sockets,omitempty" json:"sockets,omitempty" doc:"the number of listening sockets"` - Mapping []producer.NetFlowMapField `yaml:"mapping,omitempty" json:"mapping,omitempty" doc:"custom field mapping"` + HostName string `yaml:"hostName,omitempty" json:"hostName,omitempty" doc:"the hostname to listen on; defaults to 0.0.0.0"` + Port uint `yaml:"port,omitempty" json:"port,omitempty" doc:"the port number to listen on, for IPFIX/NetFlow v9. Omit or set to 0 to disable IPFIX/NetFlow v9 ingestion. If both port and portLegacy are omitted, defaults to 2055"` + PortLegacy uint `yaml:"portLegacy,omitempty" json:"portLegacy,omitempty" doc:"the port number to listen on, for legacy NetFlow v5. Omit or set to 0 to disable NetFlow v5 ingestion"` + Workers uint `yaml:"workers,omitempty" json:"workers,omitempty" doc:"the number of netflow/ipfix decoding workers"` + Sockets uint `yaml:"sockets,omitempty" json:"sockets,omitempty" doc:"the number of listening sockets"` + Mapping []NetFlowMapField `yaml:"mapping,omitempty" json:"mapping,omitempty" doc:"custom field mapping"` +} + +// NetFlowMapField copied from github.com/netsampler/goflow2/producer (we don't want this hard dependency in api) +type NetFlowMapField struct { + PenProvided bool `json:"penprovided" yaml:"penprovided"` + Type uint16 `json:"field" yaml:"field"` + Pen uint32 `json:"pen" yaml:"pen"` + Destination string `json:"destination" yaml:"destination"` + Endian string `json:"endianness" yaml:"endianness"` } func (i *IngestIpfix) SetDefaults() { diff --git a/vendor/github.com/netobserv/flowlogs-pipeline/pkg/utils/kubernetes.go b/vendor/github.com/netobserv/flowlogs-pipeline/pkg/utils/kubernetes.go deleted file mode 100644 index 3503492ed..000000000 --- a/vendor/github.com/netobserv/flowlogs-pipeline/pkg/utils/kubernetes.go +++ /dev/null @@ -1,41 +0,0 @@ -package utils - -import ( - "fmt" - "os" - "path" - - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" -) - -const ( - kubeConfigEnvVariable = "KUBECONFIG" -) - -func LoadK8sConfig(kubeConfigPath string) (*rest.Config, error) { - // if no config path is provided, load it from the env variable - if kubeConfigPath == "" { - kubeConfigPath = os.Getenv(kubeConfigEnvVariable) - } - // otherwise, load it from the $HOME/.kube/config file - if kubeConfigPath == "" { - homeDir, err := os.UserHomeDir() - if err != nil { - return nil, fmt.Errorf("can't get user home dir: %w", err) - } - kubeConfigPath = path.Join(homeDir, ".kube", "config") - } - config, err := clientcmd.BuildConfigFromFlags("", kubeConfigPath) - if err == nil { - return config, nil - } - // fallback: use in-cluster config - config, err = rest.InClusterConfig() - if err != nil { - return nil, fmt.Errorf("can't access kubenetes. Tried using config from: "+ - "config parameter, %s env, homedir and InClusterConfig. Got: %w", - kubeConfigEnvVariable, err) - } - return config, nil -} diff --git a/vendor/github.com/netsampler/goflow2/LICENSE b/vendor/github.com/netsampler/goflow2/LICENSE deleted file mode 100644 index a2fee077c..000000000 --- a/vendor/github.com/netsampler/goflow2/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -BSD 3-Clause License - -Copyright (c) 2021, NetSampler -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/netsampler/goflow2/decoders/netflow/ipfix.go b/vendor/github.com/netsampler/goflow2/decoders/netflow/ipfix.go deleted file mode 100644 index 954b7d38c..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/netflow/ipfix.go +++ /dev/null @@ -1,989 +0,0 @@ -package netflow - -import ( - "fmt" - "time" -) - -const ( - IPFIX_FIELD_Reserved = 0 - IPFIX_FIELD_octetDeltaCount = 1 - IPFIX_FIELD_packetDeltaCount = 2 - IPFIX_FIELD_deltaFlowCount = 3 - IPFIX_FIELD_protocolIdentifier = 4 - IPFIX_FIELD_ipClassOfService = 5 - IPFIX_FIELD_tcpControlBits = 6 - IPFIX_FIELD_sourceTransportPort = 7 - IPFIX_FIELD_sourceIPv4Address = 8 - IPFIX_FIELD_sourceIPv4PrefixLength = 9 - IPFIX_FIELD_ingressInterface = 10 - IPFIX_FIELD_destinationTransportPort = 11 - IPFIX_FIELD_destinationIPv4Address = 12 - IPFIX_FIELD_destinationIPv4PrefixLength = 13 - IPFIX_FIELD_egressInterface = 14 - IPFIX_FIELD_ipNextHopIPv4Address = 15 - IPFIX_FIELD_bgpSourceAsNumber = 16 - IPFIX_FIELD_bgpDestinationAsNumber = 17 - IPFIX_FIELD_bgpNextHopIPv4Address = 18 - IPFIX_FIELD_postMCastPacketDeltaCount = 19 - IPFIX_FIELD_postMCastOctetDeltaCount = 20 - IPFIX_FIELD_flowEndSysUpTime = 21 - IPFIX_FIELD_flowStartSysUpTime = 22 - IPFIX_FIELD_postOctetDeltaCount = 23 - IPFIX_FIELD_postPacketDeltaCount = 24 - IPFIX_FIELD_minimumIpTotalLength = 25 - IPFIX_FIELD_maximumIpTotalLength = 26 - IPFIX_FIELD_sourceIPv6Address = 27 - IPFIX_FIELD_destinationIPv6Address = 28 - IPFIX_FIELD_sourceIPv6PrefixLength = 29 - IPFIX_FIELD_destinationIPv6PrefixLength = 30 - IPFIX_FIELD_flowLabelIPv6 = 31 - IPFIX_FIELD_icmpTypeCodeIPv4 = 32 - IPFIX_FIELD_igmpType = 33 - IPFIX_FIELD_samplingInterval = 34 - IPFIX_FIELD_samplingAlgorithm = 35 - IPFIX_FIELD_flowActiveTimeout = 36 - IPFIX_FIELD_flowIdleTimeout = 37 - IPFIX_FIELD_engineType = 38 - IPFIX_FIELD_engineId = 39 - IPFIX_FIELD_exportedOctetTotalCount = 40 - IPFIX_FIELD_exportedMessageTotalCount = 41 - IPFIX_FIELD_exportedFlowRecordTotalCount = 42 - IPFIX_FIELD_ipv4RouterSc = 43 - IPFIX_FIELD_sourceIPv4Prefix = 44 - IPFIX_FIELD_destinationIPv4Prefix = 45 - IPFIX_FIELD_mplsTopLabelType = 46 - IPFIX_FIELD_mplsTopLabelIPv4Address = 47 - IPFIX_FIELD_samplerId = 48 - IPFIX_FIELD_samplerMode = 49 - IPFIX_FIELD_samplerRandomInterval = 50 - IPFIX_FIELD_classId = 51 - IPFIX_FIELD_minimumTTL = 52 - IPFIX_FIELD_maximumTTL = 53 - IPFIX_FIELD_fragmentIdentification = 54 - IPFIX_FIELD_postIpClassOfService = 55 - IPFIX_FIELD_sourceMacAddress = 56 - IPFIX_FIELD_postDestinationMacAddress = 57 - IPFIX_FIELD_vlanId = 58 - IPFIX_FIELD_postVlanId = 59 - IPFIX_FIELD_ipVersion = 60 - IPFIX_FIELD_flowDirection = 61 - IPFIX_FIELD_ipNextHopIPv6Address = 62 - IPFIX_FIELD_bgpNextHopIPv6Address = 63 - IPFIX_FIELD_ipv6ExtensionHeaders = 64 - IPFIX_FIELD_mplsTopLabelStackSection = 70 - IPFIX_FIELD_mplsLabelStackSection2 = 71 - IPFIX_FIELD_mplsLabelStackSection3 = 72 - IPFIX_FIELD_mplsLabelStackSection4 = 73 - IPFIX_FIELD_mplsLabelStackSection5 = 74 - IPFIX_FIELD_mplsLabelStackSection6 = 75 - IPFIX_FIELD_mplsLabelStackSection7 = 76 - IPFIX_FIELD_mplsLabelStackSection8 = 77 - IPFIX_FIELD_mplsLabelStackSection9 = 78 - IPFIX_FIELD_mplsLabelStackSection10 = 79 - IPFIX_FIELD_destinationMacAddress = 80 - IPFIX_FIELD_postSourceMacAddress = 81 - IPFIX_FIELD_interfaceName = 82 - IPFIX_FIELD_interfaceDescription = 83 - IPFIX_FIELD_samplerName = 84 - IPFIX_FIELD_octetTotalCount = 85 - IPFIX_FIELD_packetTotalCount = 86 - IPFIX_FIELD_flagsAndSamplerId = 87 - IPFIX_FIELD_fragmentOffset = 88 - IPFIX_FIELD_forwardingStatus = 89 - IPFIX_FIELD_mplsVpnRouteDistinguisher = 90 - IPFIX_FIELD_mplsTopLabelPrefixLength = 91 - IPFIX_FIELD_srcTrafficIndex = 92 - IPFIX_FIELD_dstTrafficIndex = 93 - IPFIX_FIELD_applicationDescription = 94 - IPFIX_FIELD_applicationId = 95 - IPFIX_FIELD_applicationName = 96 - IPFIX_FIELD_postIpDiffServCodePoint = 98 - IPFIX_FIELD_multicastReplicationFactor = 99 - IPFIX_FIELD_className = 100 - IPFIX_FIELD_classificationEngineId = 101 - IPFIX_FIELD_layer2packetSectionOffset = 102 - IPFIX_FIELD_layer2packetSectionSize = 103 - IPFIX_FIELD_layer2packetSectionData = 104 - IPFIX_FIELD_bgpNextAdjacentAsNumber = 128 - IPFIX_FIELD_bgpPrevAdjacentAsNumber = 129 - IPFIX_FIELD_exporterIPv4Address = 130 - IPFIX_FIELD_exporterIPv6Address = 131 - IPFIX_FIELD_droppedOctetDeltaCount = 132 - IPFIX_FIELD_droppedPacketDeltaCount = 133 - IPFIX_FIELD_droppedOctetTotalCount = 134 - IPFIX_FIELD_droppedPacketTotalCount = 135 - IPFIX_FIELD_flowEndReason = 136 - IPFIX_FIELD_commonPropertiesId = 137 - IPFIX_FIELD_observationPointId = 138 - IPFIX_FIELD_icmpTypeCodeIPv6 = 139 - IPFIX_FIELD_mplsTopLabelIPv6Address = 140 - IPFIX_FIELD_lineCardId = 141 - IPFIX_FIELD_portId = 142 - IPFIX_FIELD_meteringProcessId = 143 - IPFIX_FIELD_exportingProcessId = 144 - IPFIX_FIELD_templateId = 145 - IPFIX_FIELD_wlanChannelId = 146 - IPFIX_FIELD_wlanSSID = 147 - IPFIX_FIELD_flowId = 148 - IPFIX_FIELD_observationDomainId = 149 - IPFIX_FIELD_flowStartSeconds = 150 - IPFIX_FIELD_flowEndSeconds = 151 - IPFIX_FIELD_flowStartMilliseconds = 152 - IPFIX_FIELD_flowEndMilliseconds = 153 - IPFIX_FIELD_flowStartMicroseconds = 154 - IPFIX_FIELD_flowEndMicroseconds = 155 - IPFIX_FIELD_flowStartNanoseconds = 156 - IPFIX_FIELD_flowEndNanoseconds = 157 - IPFIX_FIELD_flowStartDeltaMicroseconds = 158 - IPFIX_FIELD_flowEndDeltaMicroseconds = 159 - IPFIX_FIELD_systemInitTimeMilliseconds = 160 - IPFIX_FIELD_flowDurationMilliseconds = 161 - IPFIX_FIELD_flowDurationMicroseconds = 162 - IPFIX_FIELD_observedFlowTotalCount = 163 - IPFIX_FIELD_ignoredPacketTotalCount = 164 - IPFIX_FIELD_ignoredOctetTotalCount = 165 - IPFIX_FIELD_notSentFlowTotalCount = 166 - IPFIX_FIELD_notSentPacketTotalCount = 167 - IPFIX_FIELD_notSentOctetTotalCount = 168 - IPFIX_FIELD_destinationIPv6Prefix = 169 - IPFIX_FIELD_sourceIPv6Prefix = 170 - IPFIX_FIELD_postOctetTotalCount = 171 - IPFIX_FIELD_postPacketTotalCount = 172 - IPFIX_FIELD_flowKeyIndicator = 173 - IPFIX_FIELD_postMCastPacketTotalCount = 174 - IPFIX_FIELD_postMCastOctetTotalCount = 175 - IPFIX_FIELD_icmpTypeIPv4 = 176 - IPFIX_FIELD_icmpCodeIPv4 = 177 - IPFIX_FIELD_icmpTypeIPv6 = 178 - IPFIX_FIELD_icmpCodeIPv6 = 179 - IPFIX_FIELD_udpSourcePort = 180 - IPFIX_FIELD_udpDestinationPort = 181 - IPFIX_FIELD_tcpSourcePort = 182 - IPFIX_FIELD_tcpDestinationPort = 183 - IPFIX_FIELD_tcpSequenceNumber = 184 - IPFIX_FIELD_tcpAcknowledgementNumber = 185 - IPFIX_FIELD_tcpWindowSize = 186 - IPFIX_FIELD_tcpUrgentPointer = 187 - IPFIX_FIELD_tcpHeaderLength = 188 - IPFIX_FIELD_ipHeaderLength = 189 - IPFIX_FIELD_totalLengthIPv4 = 190 - IPFIX_FIELD_payloadLengthIPv6 = 191 - IPFIX_FIELD_ipTTL = 192 - IPFIX_FIELD_nextHeaderIPv6 = 193 - IPFIX_FIELD_mplsPayloadLength = 194 - IPFIX_FIELD_ipDiffServCodePoint = 195 - IPFIX_FIELD_ipPrecedence = 196 - IPFIX_FIELD_fragmentFlags = 197 - IPFIX_FIELD_octetDeltaSumOfSquares = 198 - IPFIX_FIELD_octetTotalSumOfSquares = 199 - IPFIX_FIELD_mplsTopLabelTTL = 200 - IPFIX_FIELD_mplsLabelStackLength = 201 - IPFIX_FIELD_mplsLabelStackDepth = 202 - IPFIX_FIELD_mplsTopLabelExp = 203 - IPFIX_FIELD_ipPayloadLength = 204 - IPFIX_FIELD_udpMessageLength = 205 - IPFIX_FIELD_isMulticast = 206 - IPFIX_FIELD_ipv4IHL = 207 - IPFIX_FIELD_ipv4Options = 208 - IPFIX_FIELD_tcpOptions = 209 - IPFIX_FIELD_paddingOctets = 210 - IPFIX_FIELD_collectorIPv4Address = 211 - IPFIX_FIELD_collectorIPv6Address = 212 - IPFIX_FIELD_exportInterface = 213 - IPFIX_FIELD_exportProtocolVersion = 214 - IPFIX_FIELD_exportTransportProtocol = 215 - IPFIX_FIELD_collectorTransportPort = 216 - IPFIX_FIELD_exporterTransportPort = 217 - IPFIX_FIELD_tcpSynTotalCount = 218 - IPFIX_FIELD_tcpFinTotalCount = 219 - IPFIX_FIELD_tcpRstTotalCount = 220 - IPFIX_FIELD_tcpPshTotalCount = 221 - IPFIX_FIELD_tcpAckTotalCount = 222 - IPFIX_FIELD_tcpUrgTotalCount = 223 - IPFIX_FIELD_ipTotalLength = 224 - IPFIX_FIELD_postNATSourceIPv4Address = 225 - IPFIX_FIELD_postNATDestinationIPv4Address = 226 - IPFIX_FIELD_postNAPTSourceTransportPort = 227 - IPFIX_FIELD_postNAPTDestinationTransportPort = 228 - IPFIX_FIELD_natOriginatingAddressRealm = 229 - IPFIX_FIELD_natEvent = 230 - IPFIX_FIELD_initiatorOctets = 231 - IPFIX_FIELD_responderOctets = 232 - IPFIX_FIELD_firewallEvent = 233 - IPFIX_FIELD_ingressVRFID = 234 - IPFIX_FIELD_egressVRFID = 235 - IPFIX_FIELD_VRFname = 236 - IPFIX_FIELD_postMplsTopLabelExp = 237 - IPFIX_FIELD_tcpWindowScale = 238 - IPFIX_FIELD_biflowDirection = 239 - IPFIX_FIELD_ethernetHeaderLength = 240 - IPFIX_FIELD_ethernetPayloadLength = 241 - IPFIX_FIELD_ethernetTotalLength = 242 - IPFIX_FIELD_dot1qVlanId = 243 - IPFIX_FIELD_dot1qPriority = 244 - IPFIX_FIELD_dot1qCustomerVlanId = 245 - IPFIX_FIELD_dot1qCustomerPriority = 246 - IPFIX_FIELD_metroEvcId = 247 - IPFIX_FIELD_metroEvcType = 248 - IPFIX_FIELD_pseudoWireId = 249 - IPFIX_FIELD_pseudoWireType = 250 - IPFIX_FIELD_pseudoWireControlWord = 251 - IPFIX_FIELD_ingressPhysicalInterface = 252 - IPFIX_FIELD_egressPhysicalInterface = 253 - IPFIX_FIELD_postDot1qVlanId = 254 - IPFIX_FIELD_postDot1qCustomerVlanId = 255 - IPFIX_FIELD_ethernetType = 256 - IPFIX_FIELD_postIpPrecedence = 257 - IPFIX_FIELD_collectionTimeMilliseconds = 258 - IPFIX_FIELD_exportSctpStreamId = 259 - IPFIX_FIELD_maxExportSeconds = 260 - IPFIX_FIELD_maxFlowEndSeconds = 261 - IPFIX_FIELD_messageMD5Checksum = 262 - IPFIX_FIELD_messageScope = 263 - IPFIX_FIELD_minExportSeconds = 264 - IPFIX_FIELD_minFlowStartSeconds = 265 - IPFIX_FIELD_opaqueOctets = 266 - IPFIX_FIELD_sessionScope = 267 - IPFIX_FIELD_maxFlowEndMicroseconds = 268 - IPFIX_FIELD_maxFlowEndMilliseconds = 269 - IPFIX_FIELD_maxFlowEndNanoseconds = 270 - IPFIX_FIELD_minFlowStartMicroseconds = 271 - IPFIX_FIELD_minFlowStartMilliseconds = 272 - IPFIX_FIELD_minFlowStartNanoseconds = 273 - IPFIX_FIELD_collectorCertificate = 274 - IPFIX_FIELD_exporterCertificate = 275 - IPFIX_FIELD_dataRecordsReliability = 276 - IPFIX_FIELD_observationPointType = 277 - IPFIX_FIELD_newConnectionDeltaCount = 278 - IPFIX_FIELD_connectionSumDurationSeconds = 279 - IPFIX_FIELD_connectionTransactionId = 280 - IPFIX_FIELD_postNATSourceIPv6Address = 281 - IPFIX_FIELD_postNATDestinationIPv6Address = 282 - IPFIX_FIELD_natPoolId = 283 - IPFIX_FIELD_natPoolName = 284 - IPFIX_FIELD_anonymizationFlags = 285 - IPFIX_FIELD_anonymizationTechnique = 286 - IPFIX_FIELD_informationElementIndex = 287 - IPFIX_FIELD_p2pTechnology = 288 - IPFIX_FIELD_tunnelTechnology = 289 - IPFIX_FIELD_encryptedTechnology = 290 - IPFIX_FIELD_basicList = 291 - IPFIX_FIELD_subTemplateList = 292 - IPFIX_FIELD_subTemplateMultiList = 293 - IPFIX_FIELD_bgpValidityState = 294 - IPFIX_FIELD_IPSecSPI = 295 - IPFIX_FIELD_greKey = 296 - IPFIX_FIELD_natType = 297 - IPFIX_FIELD_initiatorPackets = 298 - IPFIX_FIELD_responderPackets = 299 - IPFIX_FIELD_observationDomainName = 300 - IPFIX_FIELD_selectionSequenceId = 301 - IPFIX_FIELD_selectorId = 302 - IPFIX_FIELD_informationElementId = 303 - IPFIX_FIELD_selectorAlgorithm = 304 - IPFIX_FIELD_samplingPacketInterval = 305 - IPFIX_FIELD_samplingPacketSpace = 306 - IPFIX_FIELD_samplingTimeInterval = 307 - IPFIX_FIELD_samplingTimeSpace = 308 - IPFIX_FIELD_samplingSize = 309 - IPFIX_FIELD_samplingPopulation = 310 - IPFIX_FIELD_samplingProbability = 311 - IPFIX_FIELD_dataLinkFrameSize = 312 - IPFIX_FIELD_ipHeaderPacketSection = 313 - IPFIX_FIELD_ipPayloadPacketSection = 314 - IPFIX_FIELD_dataLinkFrameSection = 315 - IPFIX_FIELD_mplsLabelStackSection = 316 - IPFIX_FIELD_mplsPayloadPacketSection = 317 - IPFIX_FIELD_selectorIdTotalPktsObserved = 318 - IPFIX_FIELD_selectorIdTotalPktsSelected = 319 - IPFIX_FIELD_absoluteError = 320 - IPFIX_FIELD_relativeError = 321 - IPFIX_FIELD_observationTimeSeconds = 322 - IPFIX_FIELD_observationTimeMilliseconds = 323 - IPFIX_FIELD_observationTimeMicroseconds = 324 - IPFIX_FIELD_observationTimeNanoseconds = 325 - IPFIX_FIELD_digestHashValue = 326 - IPFIX_FIELD_hashIPPayloadOffset = 327 - IPFIX_FIELD_hashIPPayloadSize = 328 - IPFIX_FIELD_hashOutputRangeMin = 329 - IPFIX_FIELD_hashOutputRangeMax = 330 - IPFIX_FIELD_hashSelectedRangeMin = 331 - IPFIX_FIELD_hashSelectedRangeMax = 332 - IPFIX_FIELD_hashDigestOutput = 333 - IPFIX_FIELD_hashInitialiserValue = 334 - IPFIX_FIELD_selectorName = 335 - IPFIX_FIELD_upperCILimit = 336 - IPFIX_FIELD_lowerCILimit = 337 - IPFIX_FIELD_confidenceLevel = 338 - IPFIX_FIELD_informationElementDataType = 339 - IPFIX_FIELD_informationElementDescription = 340 - IPFIX_FIELD_informationElementName = 341 - IPFIX_FIELD_informationElementRangeBegin = 342 - IPFIX_FIELD_informationElementRangeEnd = 343 - IPFIX_FIELD_informationElementSemantics = 344 - IPFIX_FIELD_informationElementUnits = 345 - IPFIX_FIELD_privateEnterpriseNumber = 346 - IPFIX_FIELD_virtualStationInterfaceId = 347 - IPFIX_FIELD_virtualStationInterfaceName = 348 - IPFIX_FIELD_virtualStationUUID = 349 - IPFIX_FIELD_virtualStationName = 350 - IPFIX_FIELD_layer2SegmentId = 351 - IPFIX_FIELD_layer2OctetDeltaCount = 352 - IPFIX_FIELD_layer2OctetTotalCount = 353 - IPFIX_FIELD_ingressUnicastPacketTotalCount = 354 - IPFIX_FIELD_ingressMulticastPacketTotalCount = 355 - IPFIX_FIELD_ingressBroadcastPacketTotalCount = 356 - IPFIX_FIELD_egressUnicastPacketTotalCount = 357 - IPFIX_FIELD_egressBroadcastPacketTotalCount = 358 - IPFIX_FIELD_monitoringIntervalStartMilliSeconds = 359 - IPFIX_FIELD_monitoringIntervalEndMilliSeconds = 360 - IPFIX_FIELD_portRangeStart = 361 - IPFIX_FIELD_portRangeEnd = 362 - IPFIX_FIELD_portRangeStepSize = 363 - IPFIX_FIELD_portRangeNumPorts = 364 - IPFIX_FIELD_staMacAddress = 365 - IPFIX_FIELD_staIPv4Address = 366 - IPFIX_FIELD_wtpMacAddress = 367 - IPFIX_FIELD_ingressInterfaceType = 368 - IPFIX_FIELD_egressInterfaceType = 369 - IPFIX_FIELD_rtpSequenceNumber = 370 - IPFIX_FIELD_userName = 371 - IPFIX_FIELD_applicationCategoryName = 372 - IPFIX_FIELD_applicationSubCategoryName = 373 - IPFIX_FIELD_applicationGroupName = 374 - IPFIX_FIELD_originalFlowsPresent = 375 - IPFIX_FIELD_originalFlowsInitiated = 376 - IPFIX_FIELD_originalFlowsCompleted = 377 - IPFIX_FIELD_distinctCountOfSourceIPAddress = 378 - IPFIX_FIELD_distinctCountOfDestinationIPAddress = 379 - IPFIX_FIELD_distinctCountOfSourceIPv4Address = 380 - IPFIX_FIELD_distinctCountOfDestinationIPv4Address = 381 - IPFIX_FIELD_distinctCountOfSourceIPv6Address = 382 - IPFIX_FIELD_distinctCountOfDestinationIPv6Address = 383 - IPFIX_FIELD_valueDistributionMethod = 384 - IPFIX_FIELD_rfc3550JitterMilliseconds = 385 - IPFIX_FIELD_rfc3550JitterMicroseconds = 386 - IPFIX_FIELD_rfc3550JitterNanoseconds = 387 - IPFIX_FIELD_dot1qDEI = 388 - IPFIX_FIELD_dot1qCustomerDEI = 389 - IPFIX_FIELD_flowSelectorAlgorithm = 390 - IPFIX_FIELD_flowSelectedOctetDeltaCount = 391 - IPFIX_FIELD_flowSelectedPacketDeltaCount = 392 - IPFIX_FIELD_flowSelectedFlowDeltaCount = 393 - IPFIX_FIELD_selectorIDTotalFlowsObserved = 394 - IPFIX_FIELD_selectorIDTotalFlowsSelected = 395 - IPFIX_FIELD_samplingFlowInterval = 396 - IPFIX_FIELD_samplingFlowSpacing = 397 - IPFIX_FIELD_flowSamplingTimeInterval = 398 - IPFIX_FIELD_flowSamplingTimeSpacing = 399 - IPFIX_FIELD_hashFlowDomain = 400 - IPFIX_FIELD_transportOctetDeltaCount = 401 - IPFIX_FIELD_transportPacketDeltaCount = 402 - IPFIX_FIELD_originalExporterIPv4Address = 403 - IPFIX_FIELD_originalExporterIPv6Address = 404 - IPFIX_FIELD_originalObservationDomainId = 405 - IPFIX_FIELD_intermediateProcessId = 406 - IPFIX_FIELD_ignoredDataRecordTotalCount = 407 - IPFIX_FIELD_dataLinkFrameType = 408 - IPFIX_FIELD_sectionOffset = 409 - IPFIX_FIELD_sectionExportedOctets = 410 - IPFIX_FIELD_dot1qServiceInstanceTag = 411 - IPFIX_FIELD_dot1qServiceInstanceId = 412 - IPFIX_FIELD_dot1qServiceInstancePriority = 413 - IPFIX_FIELD_dot1qCustomerSourceMacAddress = 414 - IPFIX_FIELD_dot1qCustomerDestinationMacAddress = 415 - IPFIX_FIELD_postLayer2OctetDeltaCount = 417 - IPFIX_FIELD_postMCastLayer2OctetDeltaCount = 418 - IPFIX_FIELD_postLayer2OctetTotalCount = 420 - IPFIX_FIELD_postMCastLayer2OctetTotalCount = 421 - IPFIX_FIELD_minimumLayer2TotalLength = 422 - IPFIX_FIELD_maximumLayer2TotalLength = 423 - IPFIX_FIELD_droppedLayer2OctetDeltaCount = 424 - IPFIX_FIELD_droppedLayer2OctetTotalCount = 425 - IPFIX_FIELD_ignoredLayer2OctetTotalCount = 426 - IPFIX_FIELD_notSentLayer2OctetTotalCount = 427 - IPFIX_FIELD_layer2OctetDeltaSumOfSquares = 428 - IPFIX_FIELD_layer2OctetTotalSumOfSquares = 429 - IPFIX_FIELD_layer2FrameDeltaCount = 430 - IPFIX_FIELD_layer2FrameTotalCount = 431 - IPFIX_FIELD_pseudoWireDestinationIPv4Address = 432 - IPFIX_FIELD_ignoredLayer2FrameTotalCount = 433 - IPFIX_FIELD_mibObjectValueInteger = 434 - IPFIX_FIELD_mibObjectValueOctetString = 435 - IPFIX_FIELD_mibObjectValueOID = 436 - IPFIX_FIELD_mibObjectValueBits = 437 - IPFIX_FIELD_mibObjectValueIPAddress = 438 - IPFIX_FIELD_mibObjectValueCounter = 439 - IPFIX_FIELD_mibObjectValueGauge = 440 - IPFIX_FIELD_mibObjectValueTimeTicks = 441 - IPFIX_FIELD_mibObjectValueUnsigned = 442 - IPFIX_FIELD_mibObjectValueTable = 443 - IPFIX_FIELD_mibObjectValueRow = 444 - IPFIX_FIELD_mibObjectIdentifier = 445 - IPFIX_FIELD_mibSubIdentifier = 446 - IPFIX_FIELD_mibIndexIndicator = 447 - IPFIX_FIELD_mibCaptureTimeSemantics = 448 - IPFIX_FIELD_mibContextEngineID = 449 - IPFIX_FIELD_mibContextName = 450 - IPFIX_FIELD_mibObjectName = 451 - IPFIX_FIELD_mibObjectDescription = 452 - IPFIX_FIELD_mibObjectSyntax = 453 - IPFIX_FIELD_mibModuleName = 454 - IPFIX_FIELD_mobileIMSI = 455 - IPFIX_FIELD_mobileMSISDN = 456 - IPFIX_FIELD_httpStatusCode = 457 - IPFIX_FIELD_sourceTransportPortsLimit = 458 - IPFIX_FIELD_httpRequestMethod = 459 - IPFIX_FIELD_httpRequestHost = 460 - IPFIX_FIELD_httpRequestTarget = 461 - IPFIX_FIELD_httpMessageVersion = 462 - IPFIX_FIELD_natInstanceID = 463 - IPFIX_FIELD_internalAddressRealm = 464 - IPFIX_FIELD_externalAddressRealm = 465 - IPFIX_FIELD_natQuotaExceededEvent = 466 - IPFIX_FIELD_natThresholdEvent = 467 -) - -type IPFIXPacket struct { - Version uint16 - Length uint16 - ExportTime uint32 - SequenceNumber uint32 - ObservationDomainId uint32 - FlowSets []interface{} -} - -type IPFIXOptionsTemplateFlowSet struct { - FlowSetHeader - Records []IPFIXOptionsTemplateRecord -} - -type IPFIXOptionsTemplateRecord struct { - TemplateId uint16 - FieldCount uint16 - ScopeFieldCount uint16 - Options []Field - Scopes []Field -} - -func IPFIXTypeToString(typeId uint16) string { - - nameList := map[uint16]string{ - 0: "Reserved", - 1: "octetDeltaCount", - 2: "packetDeltaCount", - 3: "deltaFlowCount", - 4: "protocolIdentifier", - 5: "ipClassOfService", - 6: "tcpControlBits", - 7: "sourceTransportPort", - 8: "sourceIPv4Address", - 9: "sourceIPv4PrefixLength", - 10: "ingressInterface", - 11: "destinationTransportPort", - 12: "destinationIPv4Address", - 13: "destinationIPv4PrefixLength", - 14: "egressInterface", - 15: "ipNextHopIPv4Address", - 16: "bgpSourceAsNumber", - 17: "bgpDestinationAsNumber", - 18: "bgpNextHopIPv4Address", - 19: "postMCastPacketDeltaCount", - 20: "postMCastOctetDeltaCount", - 21: "flowEndSysUpTime", - 22: "flowStartSysUpTime", - 23: "postOctetDeltaCount", - 24: "postPacketDeltaCount", - 25: "minimumIpTotalLength", - 26: "maximumIpTotalLength", - 27: "sourceIPv6Address", - 28: "destinationIPv6Address", - 29: "sourceIPv6PrefixLength", - 30: "destinationIPv6PrefixLength", - 31: "flowLabelIPv6", - 32: "icmpTypeCodeIPv4", - 33: "igmpType", - 34: "samplingInterval", - 35: "samplingAlgorithm", - 36: "flowActiveTimeout", - 37: "flowIdleTimeout", - 38: "engineType", - 39: "engineId", - 40: "exportedOctetTotalCount", - 41: "exportedMessageTotalCount", - 42: "exportedFlowRecordTotalCount", - 43: "ipv4RouterSc", - 44: "sourceIPv4Prefix", - 45: "destinationIPv4Prefix", - 46: "mplsTopLabelType", - 47: "mplsTopLabelIPv4Address", - 48: "samplerId", - 49: "samplerMode", - 50: "samplerRandomInterval", - 51: "classId", - 52: "minimumTTL", - 53: "maximumTTL", - 54: "fragmentIdentification", - 55: "postIpClassOfService", - 56: "sourceMacAddress", - 57: "postDestinationMacAddress", - 58: "vlanId", - 59: "postVlanId", - 60: "ipVersion", - 61: "flowDirection", - 62: "ipNextHopIPv6Address", - 63: "bgpNextHopIPv6Address", - 64: "ipv6ExtensionHeaders", - 65: "Assigned for NetFlow v9 compatibility", - 66: "Assigned for NetFlow v9 compatibility", - 67: "Assigned for NetFlow v9 compatibility", - 68: "Assigned for NetFlow v9 compatibility", - 69: "Assigned for NetFlow v9 compatibility", - 70: "mplsTopLabelStackSection", - 71: "mplsLabelStackSection2", - 72: "mplsLabelStackSection3", - 73: "mplsLabelStackSection4", - 74: "mplsLabelStackSection5", - 75: "mplsLabelStackSection6", - 76: "mplsLabelStackSection7", - 77: "mplsLabelStackSection8", - 78: "mplsLabelStackSection9", - 79: "mplsLabelStackSection10", - 80: "destinationMacAddress", - 81: "postSourceMacAddress", - 82: "interfaceName", - 83: "interfaceDescription", - 84: "samplerName", - 85: "octetTotalCount", - 86: "packetTotalCount", - 87: "flagsAndSamplerId", - 88: "fragmentOffset", - 89: "forwardingStatus", - 90: "mplsVpnRouteDistinguisher", - 91: "mplsTopLabelPrefixLength", - 92: "srcTrafficIndex", - 93: "dstTrafficIndex", - 94: "applicationDescription", - 95: "applicationId", - 96: "applicationName", - 97: "Assigned for NetFlow v9 compatibility", - 98: "postIpDiffServCodePoint", - 99: "multicastReplicationFactor", - 100: "className", - 101: "classificationEngineId", - 102: "layer2packetSectionOffset", - 103: "layer2packetSectionSize", - 104: "layer2packetSectionData", - 128: "bgpNextAdjacentAsNumber", - 129: "bgpPrevAdjacentAsNumber", - 130: "exporterIPv4Address", - 131: "exporterIPv6Address", - 132: "droppedOctetDeltaCount", - 133: "droppedPacketDeltaCount", - 134: "droppedOctetTotalCount", - 135: "droppedPacketTotalCount", - 136: "flowEndReason", - 137: "commonPropertiesId", - 138: "observationPointId", - 139: "icmpTypeCodeIPv6", - 140: "mplsTopLabelIPv6Address", - 141: "lineCardId", - 142: "portId", - 143: "meteringProcessId", - 144: "exportingProcessId", - 145: "templateId", - 146: "wlanChannelId", - 147: "wlanSSID", - 148: "flowId", - 149: "observationDomainId", - 150: "flowStartSeconds", - 151: "flowEndSeconds", - 152: "flowStartMilliseconds", - 153: "flowEndMilliseconds", - 154: "flowStartMicroseconds", - 155: "flowEndMicroseconds", - 156: "flowStartNanoseconds", - 157: "flowEndNanoseconds", - 158: "flowStartDeltaMicroseconds", - 159: "flowEndDeltaMicroseconds", - 160: "systemInitTimeMilliseconds", - 161: "flowDurationMilliseconds", - 162: "flowDurationMicroseconds", - 163: "observedFlowTotalCount", - 164: "ignoredPacketTotalCount", - 165: "ignoredOctetTotalCount", - 166: "notSentFlowTotalCount", - 167: "notSentPacketTotalCount", - 168: "notSentOctetTotalCount", - 169: "destinationIPv6Prefix", - 170: "sourceIPv6Prefix", - 171: "postOctetTotalCount", - 172: "postPacketTotalCount", - 173: "flowKeyIndicator", - 174: "postMCastPacketTotalCount", - 175: "postMCastOctetTotalCount", - 176: "icmpTypeIPv4", - 177: "icmpCodeIPv4", - 178: "icmpTypeIPv6", - 179: "icmpCodeIPv6", - 180: "udpSourcePort", - 181: "udpDestinationPort", - 182: "tcpSourcePort", - 183: "tcpDestinationPort", - 184: "tcpSequenceNumber", - 185: "tcpAcknowledgementNumber", - 186: "tcpWindowSize", - 187: "tcpUrgentPointer", - 188: "tcpHeaderLength", - 189: "ipHeaderLength", - 190: "totalLengthIPv4", - 191: "payloadLengthIPv6", - 192: "ipTTL", - 193: "nextHeaderIPv6", - 194: "mplsPayloadLength", - 195: "ipDiffServCodePoint", - 196: "ipPrecedence", - 197: "fragmentFlags", - 198: "octetDeltaSumOfSquares", - 199: "octetTotalSumOfSquares", - 200: "mplsTopLabelTTL", - 201: "mplsLabelStackLength", - 202: "mplsLabelStackDepth", - 203: "mplsTopLabelExp", - 204: "ipPayloadLength", - 205: "udpMessageLength", - 206: "isMulticast", - 207: "ipv4IHL", - 208: "ipv4Options", - 209: "tcpOptions", - 210: "paddingOctets", - 211: "collectorIPv4Address", - 212: "collectorIPv6Address", - 213: "exportInterface", - 214: "exportProtocolVersion", - 215: "exportTransportProtocol", - 216: "collectorTransportPort", - 217: "exporterTransportPort", - 218: "tcpSynTotalCount", - 219: "tcpFinTotalCount", - 220: "tcpRstTotalCount", - 221: "tcpPshTotalCount", - 222: "tcpAckTotalCount", - 223: "tcpUrgTotalCount", - 224: "ipTotalLength", - 225: "postNATSourceIPv4Address", - 226: "postNATDestinationIPv4Address", - 227: "postNAPTSourceTransportPort", - 228: "postNAPTDestinationTransportPort", - 229: "natOriginatingAddressRealm", - 230: "natEvent", - 231: "initiatorOctets", - 232: "responderOctets", - 233: "firewallEvent", - 234: "ingressVRFID", - 235: "egressVRFID", - 236: "VRFname", - 237: "postMplsTopLabelExp", - 238: "tcpWindowScale", - 239: "biflowDirection", - 240: "ethernetHeaderLength", - 241: "ethernetPayloadLength", - 242: "ethernetTotalLength", - 243: "dot1qVlanId", - 244: "dot1qPriority", - 245: "dot1qCustomerVlanId", - 246: "dot1qCustomerPriority", - 247: "metroEvcId", - 248: "metroEvcType", - 249: "pseudoWireId", - 250: "pseudoWireType", - 251: "pseudoWireControlWord", - 252: "ingressPhysicalInterface", - 253: "egressPhysicalInterface", - 254: "postDot1qVlanId", - 255: "postDot1qCustomerVlanId", - 256: "ethernetType", - 257: "postIpPrecedence", - 258: "collectionTimeMilliseconds", - 259: "exportSctpStreamId", - 260: "maxExportSeconds", - 261: "maxFlowEndSeconds", - 262: "messageMD5Checksum", - 263: "messageScope", - 264: "minExportSeconds", - 265: "minFlowStartSeconds", - 266: "opaqueOctets", - 267: "sessionScope", - 268: "maxFlowEndMicroseconds", - 269: "maxFlowEndMilliseconds", - 270: "maxFlowEndNanoseconds", - 271: "minFlowStartMicroseconds", - 272: "minFlowStartMilliseconds", - 273: "minFlowStartNanoseconds", - 274: "collectorCertificate", - 275: "exporterCertificate", - 276: "dataRecordsReliability", - 277: "observationPointType", - 278: "newConnectionDeltaCount", - 279: "connectionSumDurationSeconds", - 280: "connectionTransactionId", - 281: "postNATSourceIPv6Address", - 282: "postNATDestinationIPv6Address", - 283: "natPoolId", - 284: "natPoolName", - 285: "anonymizationFlags", - 286: "anonymizationTechnique", - 287: "informationElementIndex", - 288: "p2pTechnology", - 289: "tunnelTechnology", - 290: "encryptedTechnology", - 291: "basicList", - 292: "subTemplateList", - 293: "subTemplateMultiList", - 294: "bgpValidityState", - 295: "IPSecSPI", - 296: "greKey", - 297: "natType", - 298: "initiatorPackets", - 299: "responderPackets", - 300: "observationDomainName", - 301: "selectionSequenceId", - 302: "selectorId", - 303: "informationElementId", - 304: "selectorAlgorithm", - 305: "samplingPacketInterval", - 306: "samplingPacketSpace", - 307: "samplingTimeInterval", - 308: "samplingTimeSpace", - 309: "samplingSize", - 310: "samplingPopulation", - 311: "samplingProbability", - 312: "dataLinkFrameSize", - 313: "ipHeaderPacketSection", - 314: "ipPayloadPacketSection", - 315: "dataLinkFrameSection", - 316: "mplsLabelStackSection", - 317: "mplsPayloadPacketSection", - 318: "selectorIdTotalPktsObserved", - 319: "selectorIdTotalPktsSelected", - 320: "absoluteError", - 321: "relativeError", - 322: "observationTimeSeconds", - 323: "observationTimeMilliseconds", - 324: "observationTimeMicroseconds", - 325: "observationTimeNanoseconds", - 326: "digestHashValue", - 327: "hashIPPayloadOffset", - 328: "hashIPPayloadSize", - 329: "hashOutputRangeMin", - 330: "hashOutputRangeMax", - 331: "hashSelectedRangeMin", - 332: "hashSelectedRangeMax", - 333: "hashDigestOutput", - 334: "hashInitialiserValue", - 335: "selectorName", - 336: "upperCILimit", - 337: "lowerCILimit", - 338: "confidenceLevel", - 339: "informationElementDataType", - 340: "informationElementDescription", - 341: "informationElementName", - 342: "informationElementRangeBegin", - 343: "informationElementRangeEnd", - 344: "informationElementSemantics", - 345: "informationElementUnits", - 346: "privateEnterpriseNumber", - 347: "virtualStationInterfaceId", - 348: "virtualStationInterfaceName", - 349: "virtualStationUUID", - 350: "virtualStationName", - 351: "layer2SegmentId", - 352: "layer2OctetDeltaCount", - 353: "layer2OctetTotalCount", - 354: "ingressUnicastPacketTotalCount", - 355: "ingressMulticastPacketTotalCount", - 356: "ingressBroadcastPacketTotalCount", - 357: "egressUnicastPacketTotalCount", - 358: "egressBroadcastPacketTotalCount", - 359: "monitoringIntervalStartMilliSeconds", - 360: "monitoringIntervalEndMilliSeconds", - 361: "portRangeStart", - 362: "portRangeEnd", - 363: "portRangeStepSize", - 364: "portRangeNumPorts", - 365: "staMacAddress", - 366: "staIPv4Address", - 367: "wtpMacAddress", - 368: "ingressInterfaceType", - 369: "egressInterfaceType", - 370: "rtpSequenceNumber", - 371: "userName", - 372: "applicationCategoryName", - 373: "applicationSubCategoryName", - 374: "applicationGroupName", - 375: "originalFlowsPresent", - 376: "originalFlowsInitiated", - 377: "originalFlowsCompleted", - 378: "distinctCountOfSourceIPAddress", - 379: "distinctCountOfDestinationIPAddress", - 380: "distinctCountOfSourceIPv4Address", - 381: "distinctCountOfDestinationIPv4Address", - 382: "distinctCountOfSourceIPv6Address", - 383: "distinctCountOfDestinationIPv6Address", - 384: "valueDistributionMethod", - 385: "rfc3550JitterMilliseconds", - 386: "rfc3550JitterMicroseconds", - 387: "rfc3550JitterNanoseconds", - 388: "dot1qDEI", - 389: "dot1qCustomerDEI", - 390: "flowSelectorAlgorithm", - 391: "flowSelectedOctetDeltaCount", - 392: "flowSelectedPacketDeltaCount", - 393: "flowSelectedFlowDeltaCount", - 394: "selectorIDTotalFlowsObserved", - 395: "selectorIDTotalFlowsSelected", - 396: "samplingFlowInterval", - 397: "samplingFlowSpacing", - 398: "flowSamplingTimeInterval", - 399: "flowSamplingTimeSpacing", - 400: "hashFlowDomain", - 401: "transportOctetDeltaCount", - 402: "transportPacketDeltaCount", - 403: "originalExporterIPv4Address", - 404: "originalExporterIPv6Address", - 405: "originalObservationDomainId", - 406: "intermediateProcessId", - 407: "ignoredDataRecordTotalCount", - 408: "dataLinkFrameType", - 409: "sectionOffset", - 410: "sectionExportedOctets", - 411: "dot1qServiceInstanceTag", - 412: "dot1qServiceInstanceId", - 413: "dot1qServiceInstancePriority", - 414: "dot1qCustomerSourceMacAddress", - 415: "dot1qCustomerDestinationMacAddress", - 416: "", - 417: "postLayer2OctetDeltaCount", - 418: "postMCastLayer2OctetDeltaCount", - 419: "", - 420: "postLayer2OctetTotalCount", - 421: "postMCastLayer2OctetTotalCount", - 422: "minimumLayer2TotalLength", - 423: "maximumLayer2TotalLength", - 424: "droppedLayer2OctetDeltaCount", - 425: "droppedLayer2OctetTotalCount", - 426: "ignoredLayer2OctetTotalCount", - 427: "notSentLayer2OctetTotalCount", - 428: "layer2OctetDeltaSumOfSquares", - 429: "layer2OctetTotalSumOfSquares", - 430: "layer2FrameDeltaCount", - 431: "layer2FrameTotalCount", - 432: "pseudoWireDestinationIPv4Address", - 433: "ignoredLayer2FrameTotalCount", - 434: "mibObjectValueInteger", - 435: "mibObjectValueOctetString", - 436: "mibObjectValueOID", - 437: "mibObjectValueBits", - 438: "mibObjectValueIPAddress", - 439: "mibObjectValueCounter", - 440: "mibObjectValueGauge", - 441: "mibObjectValueTimeTicks", - 442: "mibObjectValueUnsigned", - 443: "mibObjectValueTable", - 444: "mibObjectValueRow", - 445: "mibObjectIdentifier", - 446: "mibSubIdentifier", - 447: "mibIndexIndicator", - 448: "mibCaptureTimeSemantics", - 449: "mibContextEngineID", - 450: "mibContextName", - 451: "mibObjectName", - 452: "mibObjectDescription", - 453: "mibObjectSyntax", - 454: "mibModuleName", - 455: "mobileIMSI", - 456: "mobileMSISDN", - 457: "httpStatusCode", - 458: "sourceTransportPortsLimit", - 459: "httpRequestMethod", - 460: "httpRequestHost", - 461: "httpRequestTarget", - 462: "httpMessageVersion", - 463: "natInstanceID", - 464: "internalAddressRealm", - 465: "externalAddressRealm", - 466: "natQuotaExceededEvent", - 467: "natThresholdEvent", - } - - if typeId >= 105 && typeId <= 127 { - return "Assigned for NetFlow v9 compatibility" - } else if typeId >= 468 && typeId <= 32767 { - return "Unassigned" - } else { - return nameList[typeId] - } -} - -func (flowSet IPFIXOptionsTemplateFlowSet) String(TypeToString func(uint16) string) string { - str := fmt.Sprintf(" Id %v\n", flowSet.Id) - str += fmt.Sprintf(" Length: %v\n", flowSet.Length) - str += fmt.Sprintf(" Records (%v records):\n", len(flowSet.Records)) - - for j, record := range flowSet.Records { - str += fmt.Sprintf(" - Record %v:\n", j) - str += fmt.Sprintf(" TemplateId: %v\n", record.TemplateId) - str += fmt.Sprintf(" FieldCount: %v\n", record.FieldCount) - str += fmt.Sprintf(" ScopeFieldCount: %v\n", record.ScopeFieldCount) - - str += fmt.Sprintf(" Scopes (%v):\n", len(record.Scopes)) - - for k, field := range record.Scopes { - str += fmt.Sprintf(" - %v. %v (%v): %v\n", k, TypeToString(field.Type), field.Type, field.Length) - } - - str += fmt.Sprintf(" Options (%v):\n", len(record.Options)) - - for k, field := range record.Options { - str += fmt.Sprintf(" - %v. %v (%v): %v\n", k, TypeToString(field.Type), field.Type, field.Length) - } - - } - - return str -} - -func (p IPFIXPacket) String() string { - str := "Flow Packet\n" - str += "------------\n" - str += fmt.Sprintf(" Version: %v\n", p.Version) - str += fmt.Sprintf(" Length: %v\n", p.Length) - - exportTime := time.Unix(int64(p.ExportTime), 0) - str += fmt.Sprintf(" ExportTime: %v\n", exportTime.String()) - str += fmt.Sprintf(" SequenceNumber: %v\n", p.SequenceNumber) - str += fmt.Sprintf(" ObservationDomainId: %v\n", p.ObservationDomainId) - str += fmt.Sprintf(" FlowSets (%v):\n", len(p.FlowSets)) - - for i, flowSet := range p.FlowSets { - switch flowSet := flowSet.(type) { - case TemplateFlowSet: - str += fmt.Sprintf(" - TemplateFlowSet %v:\n", i) - str += flowSet.String(IPFIXTypeToString) - case IPFIXOptionsTemplateFlowSet: - str += fmt.Sprintf(" - OptionsTemplateFlowSet %v:\n", i) - str += flowSet.String(IPFIXTypeToString) - case DataFlowSet: - str += fmt.Sprintf(" - DataFlowSet %v:\n", i) - str += flowSet.String(IPFIXTypeToString) - case OptionsDataFlowSet: - str += fmt.Sprintf(" - OptionsDataFlowSet %v:\n", i) - str += flowSet.String(IPFIXTypeToString, IPFIXTypeToString) - default: - str += fmt.Sprintf(" - (unknown type) %v: %v\n", i, flowSet) - } - } - - return str -} diff --git a/vendor/github.com/netsampler/goflow2/decoders/netflow/netflow.go b/vendor/github.com/netsampler/goflow2/decoders/netflow/netflow.go deleted file mode 100644 index 8191b632f..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/netflow/netflow.go +++ /dev/null @@ -1,537 +0,0 @@ -package netflow - -import ( - "bytes" - "context" - "encoding/binary" - "fmt" - "sync" - - "github.com/netsampler/goflow2/decoders/netflow/templates" - "github.com/netsampler/goflow2/decoders/utils" -) - -type FlowBaseTemplateSet map[uint16]map[uint32]map[uint16]interface{} - -type NetFlowTemplateSystem interface { - GetTemplate(version uint16, obsDomainId uint32, templateId uint16) (interface{}, error) - AddTemplate(version uint16, obsDomainId uint32, template interface{}) -} - -// Transition structure to ease the conversion with the new template systems -type TemplateWrapper struct { - Ctx context.Context - Key string - Inner templates.TemplateInterface -} - -func (w *TemplateWrapper) getTemplateId(template interface{}) (templateId uint16) { - switch templateIdConv := template.(type) { - case IPFIXOptionsTemplateRecord: - templateId = templateIdConv.TemplateId - case NFv9OptionsTemplateRecord: - templateId = templateIdConv.TemplateId - case TemplateRecord: - templateId = templateIdConv.TemplateId - } - return templateId -} - -func (w TemplateWrapper) GetTemplate(version uint16, obsDomainId uint32, templateId uint16) (interface{}, error) { - return w.Inner.GetTemplate(w.Ctx, &templates.TemplateKey{w.Key, version, obsDomainId, templateId}) -} - -func (w TemplateWrapper) AddTemplate(version uint16, obsDomainId uint32, template interface{}) { - w.Inner.AddTemplate(w.Ctx, &templates.TemplateKey{w.Key, version, obsDomainId, w.getTemplateId(template)}, template) -} - -func DecodeNFv9OptionsTemplateSet(payload *bytes.Buffer) ([]NFv9OptionsTemplateRecord, error) { - var records []NFv9OptionsTemplateRecord - var err error - for payload.Len() >= 4 { - optsTemplateRecord := NFv9OptionsTemplateRecord{} - err = utils.BinaryDecoder(payload, &optsTemplateRecord.TemplateId, &optsTemplateRecord.ScopeLength, &optsTemplateRecord.OptionLength) - if err != nil { - return records, err - } - - sizeScope := int(optsTemplateRecord.ScopeLength) / 4 - sizeOptions := int(optsTemplateRecord.OptionLength) / 4 - if sizeScope < 0 || sizeOptions < 0 { - return records, fmt.Errorf("Error decoding OptionsTemplateSet: negative length.") - } - - fields := make([]Field, sizeScope) - for i := 0; i < sizeScope; i++ { - field := Field{} - if err := DecodeField(payload, &field, false); err != nil { - return records, err - } - fields[i] = field - } - optsTemplateRecord.Scopes = fields - - fields = make([]Field, sizeOptions) - for i := 0; i < sizeOptions; i++ { - field := Field{} - if err := DecodeField(payload, &field, false); err != nil { - return records, err - } - fields[i] = field - } - optsTemplateRecord.Options = fields - - records = append(records, optsTemplateRecord) - } - - return records, err -} - -func DecodeField(payload *bytes.Buffer, field *Field, pen bool) error { - err := utils.BinaryDecoder(payload, &field.Type, &field.Length) - if pen && err == nil && field.Type&0x8000 != 0 { - field.PenProvided = true - err = utils.BinaryDecoder(payload, &field.Pen) - } - return err -} - -func DecodeIPFIXOptionsTemplateSet(payload *bytes.Buffer) ([]IPFIXOptionsTemplateRecord, error) { - var records []IPFIXOptionsTemplateRecord - var err error - for payload.Len() >= 4 { - optsTemplateRecord := IPFIXOptionsTemplateRecord{} - err = utils.BinaryDecoder(payload, &optsTemplateRecord.TemplateId, &optsTemplateRecord.FieldCount, &optsTemplateRecord.ScopeFieldCount) - if err != nil { - return records, err - } - - fields := make([]Field, int(optsTemplateRecord.ScopeFieldCount)) - for i := 0; i < int(optsTemplateRecord.ScopeFieldCount); i++ { - field := Field{} - if err := DecodeField(payload, &field, true); err != nil { - return records, err - } - fields[i] = field - } - optsTemplateRecord.Scopes = fields - - optionsSize := int(optsTemplateRecord.FieldCount) - int(optsTemplateRecord.ScopeFieldCount) - if optionsSize < 0 { - return records, fmt.Errorf("Error decoding OptionsTemplateSet: negative length.") - } - fields = make([]Field, optionsSize) - for i := 0; i < optionsSize; i++ { - field := Field{} - if err := DecodeField(payload, &field, true); err != nil { - return records, err - } - fields[i] = field - } - optsTemplateRecord.Options = fields - - records = append(records, optsTemplateRecord) - } - - return records, nil -} - -func DecodeTemplateSet(version uint16, payload *bytes.Buffer) ([]TemplateRecord, error) { - var records []TemplateRecord - var err error - for payload.Len() >= 4 { - templateRecord := TemplateRecord{} - err = utils.BinaryDecoder(payload, &templateRecord.TemplateId, &templateRecord.FieldCount) - if err != nil { - return records, err - } - - if int(templateRecord.FieldCount) < 0 { - return records, fmt.Errorf("Error decoding TemplateSet: zero count.") - } - - fields := make([]Field, int(templateRecord.FieldCount)) - for i := 0; i < int(templateRecord.FieldCount); i++ { - field := Field{} - err := utils.BinaryDecoder(payload, &field.Type, &field.Length) - if err == nil && version == 10 && field.Type&0x8000 != 0 { - field.PenProvided = true - field.Type = field.Type ^ 0x8000 - err = utils.BinaryDecoder(payload, &field.Pen) - } - if err != nil { - return records, err - } - fields[i] = field - } - templateRecord.Fields = fields - records = append(records, templateRecord) - } - - return records, nil -} - -func GetTemplateSize(version uint16, template []Field) int { - sum := 0 - for _, templateField := range template { - if templateField.Length == 0xffff { - continue - } - - sum += int(templateField.Length) - } - return sum -} - -func DecodeDataSetUsingFields(version uint16, payload *bytes.Buffer, listFields []Field) []DataField { - for payload.Len() >= GetTemplateSize(version, listFields) { - - dataFields := make([]DataField, len(listFields)) - for i, templateField := range listFields { - - finalLength := int(templateField.Length) - if templateField.Length == 0xffff { - var variableLen8 byte - var variableLen16 uint16 - err := utils.BinaryDecoder(payload, &variableLen8) - if err != nil { - return []DataField{} - } - if variableLen8 == 0xff { - err := utils.BinaryDecoder(payload, &variableLen16) - if err != nil { - return []DataField{} - } - finalLength = int(variableLen16) - } else { - finalLength = int(variableLen8) - } - } - - value := payload.Next(finalLength) - nfvalue := DataField{ - Type: templateField.Type, - PenProvided: templateField.PenProvided, - Pen: templateField.Pen, - Value: value, - } - dataFields[i] = nfvalue - } - return dataFields - } - return []DataField{} -} - -type ErrorTemplateNotFound struct { - version uint16 - obsDomainId uint32 - templateId uint16 - typeTemplate string -} - -func NewErrorTemplateNotFound(version uint16, obsDomainId uint32, templateId uint16, typeTemplate string) *ErrorTemplateNotFound { - return &ErrorTemplateNotFound{ - version: version, - obsDomainId: obsDomainId, - templateId: templateId, - typeTemplate: typeTemplate, - } -} - -func (e *ErrorTemplateNotFound) Error() string { - return fmt.Sprintf("No %v template %v found for and domain id %v", e.typeTemplate, e.templateId, e.obsDomainId) -} - -func DecodeOptionsDataSet(version uint16, payload *bytes.Buffer, listFieldsScopes, listFieldsOption []Field) ([]OptionsDataRecord, error) { - var records []OptionsDataRecord - - listFieldsScopesSize := GetTemplateSize(version, listFieldsScopes) - listFieldsOptionSize := GetTemplateSize(version, listFieldsOption) - - for payload.Len() >= listFieldsScopesSize+listFieldsOptionSize { - scopeValues := DecodeDataSetUsingFields(version, payload, listFieldsScopes) - optionValues := DecodeDataSetUsingFields(version, payload, listFieldsOption) - - record := OptionsDataRecord{ - ScopesValues: scopeValues, - OptionsValues: optionValues, - } - - records = append(records, record) - } - return records, nil -} - -func DecodeDataSet(version uint16, payload *bytes.Buffer, listFields []Field) ([]DataRecord, error) { - var records []DataRecord - - listFieldsSize := GetTemplateSize(version, listFields) - for payload.Len() >= listFieldsSize { - values := DecodeDataSetUsingFields(version, payload, listFields) - - record := DataRecord{ - Values: values, - } - - records = append(records, record) - } - return records, nil -} - -func (ts *BasicTemplateSystem) GetTemplates() map[uint16]map[uint32]map[uint16]interface{} { - ts.templateslock.RLock() - tmp := ts.templates - ts.templateslock.RUnlock() - return tmp -} - -func (ts *BasicTemplateSystem) AddTemplate(version uint16, obsDomainId uint32, template interface{}) { - ts.templateslock.Lock() - defer ts.templateslock.Unlock() - _, exists := ts.templates[version] - if exists != true { - ts.templates[version] = make(map[uint32]map[uint16]interface{}) - } - _, exists = ts.templates[version][obsDomainId] - if exists != true { - ts.templates[version][obsDomainId] = make(map[uint16]interface{}) - } - var templateId uint16 - switch templateIdConv := template.(type) { - case IPFIXOptionsTemplateRecord: - templateId = templateIdConv.TemplateId - case NFv9OptionsTemplateRecord: - templateId = templateIdConv.TemplateId - case TemplateRecord: - templateId = templateIdConv.TemplateId - } - ts.templates[version][obsDomainId][templateId] = template -} - -func (ts *BasicTemplateSystem) GetTemplate(version uint16, obsDomainId uint32, templateId uint16) (interface{}, error) { - ts.templateslock.RLock() - defer ts.templateslock.RUnlock() - templatesVersion, okver := ts.templates[version] - if okver { - templatesObsDom, okobs := templatesVersion[obsDomainId] - if okobs { - template, okid := templatesObsDom[templateId] - if okid { - return template, nil - } - } - } - return nil, NewErrorTemplateNotFound(version, obsDomainId, templateId, "info") -} - -type BasicTemplateSystem struct { - templates FlowBaseTemplateSet - templateslock *sync.RWMutex -} - -func CreateTemplateSystem() *BasicTemplateSystem { - ts := &BasicTemplateSystem{ - templates: make(FlowBaseTemplateSet), - templateslock: &sync.RWMutex{}, - } - return ts -} - -func DecodeMessage(payload *bytes.Buffer, templates NetFlowTemplateSystem) (interface{}, error) { - return DecodeMessageContext(context.Background(), payload, "", templates) -} - -func DecodeMessageContext(ctx context.Context, payload *bytes.Buffer, templateKey string, tpli NetFlowTemplateSystem) (interface{}, error) { - var size uint16 - packetNFv9 := NFv9Packet{} - packetIPFIX := IPFIXPacket{} - var returnItem interface{} - - var version uint16 - var obsDomainId uint32 - if err := utils.BinaryRead(payload, binary.BigEndian, &version); err != nil { - return nil, fmt.Errorf("Error decoding version: %v", err) - } - - if version == 9 { - err := utils.BinaryDecoder(payload, &packetNFv9.Count, &packetNFv9.SystemUptime, &packetNFv9.UnixSeconds, &packetNFv9.SequenceNumber, &packetNFv9.SourceId) - if err != nil { - return nil, fmt.Errorf("Error decoding NetFlow v9 header: %v", err) - } - size = packetNFv9.Count - packetNFv9.Version = version - returnItem = *(&packetNFv9) - obsDomainId = packetNFv9.SourceId - } else if version == 10 { - err := utils.BinaryDecoder(payload, &packetIPFIX.Length, &packetIPFIX.ExportTime, &packetIPFIX.SequenceNumber, &packetIPFIX.ObservationDomainId) - if err != nil { - return nil, fmt.Errorf("Error decoding IPFIX header: %v", err) - } - size = packetIPFIX.Length - packetIPFIX.Version = version - returnItem = *(&packetIPFIX) - obsDomainId = packetIPFIX.ObservationDomainId - } else { - return nil, fmt.Errorf("NetFlow/IPFIX version error: %d", version) - } - read := 16 - startSize := payload.Len() - - for i := 0; ((i < int(size) && version == 9) || (uint16(read) < size && version == 10)) && payload.Len() > 0; i++ { - fsheader := FlowSetHeader{} - if err := utils.BinaryDecoder(payload, &fsheader.Id, &fsheader.Length); err != nil { - return returnItem, fmt.Errorf("Error decoding FlowSet header: %v", err) - } - - nextrelpos := int(fsheader.Length) - binary.Size(fsheader) - if nextrelpos < 0 { - return returnItem, fmt.Errorf("Error decoding packet: non-terminated stream") - } - - var flowSet interface{} - - if fsheader.Id == 0 && version == 9 { - templateReader := bytes.NewBuffer(payload.Next(nextrelpos)) - records, err := DecodeTemplateSet(version, templateReader) - if err != nil { - return returnItem, fmt.Errorf("Error decoding FlowSet header: %v", err) - } - templatefs := TemplateFlowSet{ - FlowSetHeader: fsheader, - Records: records, - } - - flowSet = templatefs - - if tpli != nil { - for _, record := range records { - tpli.AddTemplate(version, obsDomainId, record) - //tpli.AddTemplate(ctx, templates.NewTemplateKey(templateKey, version, obsDomainId, record.TemplateId), record) - } - } - - } else if fsheader.Id == 1 && version == 9 { - templateReader := bytes.NewBuffer(payload.Next(nextrelpos)) - records, err := DecodeNFv9OptionsTemplateSet(templateReader) - if err != nil { - return returnItem, fmt.Errorf("Error decoding NetFlow OptionsTemplateSet: %v", err) - } - optsTemplatefs := NFv9OptionsTemplateFlowSet{ - FlowSetHeader: fsheader, - Records: records, - } - flowSet = optsTemplatefs - - if tpli != nil { - for _, record := range records { - tpli.AddTemplate(version, obsDomainId, record) - //tpli.AddTemplate(ctx, templates.NewTemplateKey(templateKey, version, obsDomainId, record.TemplateId), record) - } - } - - } else if fsheader.Id == 2 && version == 10 { - templateReader := bytes.NewBuffer(payload.Next(nextrelpos)) - records, err := DecodeTemplateSet(version, templateReader) - if err != nil { - return returnItem, fmt.Errorf("Error decoding IPFIX TemplateSet: %v", err) - } - templatefs := TemplateFlowSet{ - FlowSetHeader: fsheader, - Records: records, - } - flowSet = templatefs - - if tpli != nil { - for _, record := range records { - tpli.AddTemplate(version, obsDomainId, record) - //tpli.AddTemplate(ctx, templates.NewTemplateKey(templateKey, version, obsDomainId, record.TemplateId), record) - } - } - - } else if fsheader.Id == 3 && version == 10 { - templateReader := bytes.NewBuffer(payload.Next(nextrelpos)) - records, err := DecodeIPFIXOptionsTemplateSet(templateReader) - if err != nil { - return returnItem, fmt.Errorf("Error decoding IPFIX OptionsTemplateSet: %v", err) - } - optsTemplatefs := IPFIXOptionsTemplateFlowSet{ - FlowSetHeader: fsheader, - Records: records, - } - flowSet = optsTemplatefs - - if tpli != nil { - for _, record := range records { - tpli.AddTemplate(version, obsDomainId, record) - //tpli.AddTemplate(ctx, templates.NewTemplateKey(templateKey, version, obsDomainId, record.TemplateId), record) - } - } - - } else if fsheader.Id >= 256 { - dataReader := bytes.NewBuffer(payload.Next(nextrelpos)) - - if tpli == nil { - continue - } - - template, err := tpli.GetTemplate(version, obsDomainId, fsheader.Id) - //template, err := tpli.GetTemplate(ctx, templates.NewTemplateKey(templateKey, version, obsDomainId, fsheader.Id)) - - if err == nil { - switch templatec := template.(type) { - case TemplateRecord: - records, err := DecodeDataSet(version, dataReader, templatec.Fields) - if err != nil { - return returnItem, fmt.Errorf("Error decoding DataSet: %v", err) - } - datafs := DataFlowSet{ - FlowSetHeader: fsheader, - Records: records, - } - flowSet = datafs - case IPFIXOptionsTemplateRecord: - records, err := DecodeOptionsDataSet(version, dataReader, templatec.Scopes, templatec.Options) - if err != nil { - return returnItem, fmt.Errorf("Error decoding DataSet: %v", err) - } - - datafs := OptionsDataFlowSet{ - FlowSetHeader: fsheader, - Records: records, - } - flowSet = datafs - case NFv9OptionsTemplateRecord: - records, err := DecodeOptionsDataSet(version, dataReader, templatec.Scopes, templatec.Options) - if err != nil { - return returnItem, fmt.Errorf("Error decoding OptionDataSet: %v", err) - } - - datafs := OptionsDataFlowSet{ - FlowSetHeader: fsheader, - Records: records, - } - flowSet = datafs - } - } else { - return returnItem, err - } - } else { - return returnItem, fmt.Errorf("Error with ID %d", fsheader.Id) - } - - if version == 9 && flowSet != nil { - packetNFv9.FlowSets = append(packetNFv9.FlowSets, flowSet) - } else if version == 10 && flowSet != nil { - packetIPFIX.FlowSets = append(packetIPFIX.FlowSets, flowSet) - } - read = startSize - payload.Len() + 16 - } - - if version == 9 { - return packetNFv9, nil - } else if version == 10 { - return packetIPFIX, nil - } else { - return returnItem, fmt.Errorf("Unknown version: %d", version) - } -} diff --git a/vendor/github.com/netsampler/goflow2/decoders/netflow/nfv9.go b/vendor/github.com/netsampler/goflow2/decoders/netflow/nfv9.go deleted file mode 100644 index 64fe227d8..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/netflow/nfv9.go +++ /dev/null @@ -1,317 +0,0 @@ -package netflow - -import ( - "fmt" - "time" -) - -const ( - NFV9_FIELD_IN_BYTES = 1 - NFV9_FIELD_IN_PKTS = 2 - NFV9_FIELD_FLOWS = 3 - NFV9_FIELD_PROTOCOL = 4 - NFV9_FIELD_SRC_TOS = 5 - NFV9_FIELD_TCP_FLAGS = 6 - NFV9_FIELD_L4_SRC_PORT = 7 - NFV9_FIELD_IPV4_SRC_ADDR = 8 - NFV9_FIELD_SRC_MASK = 9 - NFV9_FIELD_INPUT_SNMP = 10 - NFV9_FIELD_L4_DST_PORT = 11 - NFV9_FIELD_IPV4_DST_ADDR = 12 - NFV9_FIELD_DST_MASK = 13 - NFV9_FIELD_OUTPUT_SNMP = 14 - NFV9_FIELD_IPV4_NEXT_HOP = 15 - NFV9_FIELD_SRC_AS = 16 - NFV9_FIELD_DST_AS = 17 - NFV9_FIELD_BGP_IPV4_NEXT_HOP = 18 - NFV9_FIELD_MUL_DST_PKTS = 19 - NFV9_FIELD_MUL_DST_BYTES = 20 - NFV9_FIELD_LAST_SWITCHED = 21 - NFV9_FIELD_FIRST_SWITCHED = 22 - NFV9_FIELD_OUT_BYTES = 23 - NFV9_FIELD_OUT_PKTS = 24 - NFV9_FIELD_MIN_PKT_LNGTH = 25 - NFV9_FIELD_MAX_PKT_LNGTH = 26 - NFV9_FIELD_IPV6_SRC_ADDR = 27 - NFV9_FIELD_IPV6_DST_ADDR = 28 - NFV9_FIELD_IPV6_SRC_MASK = 29 - NFV9_FIELD_IPV6_DST_MASK = 30 - NFV9_FIELD_IPV6_FLOW_LABEL = 31 - NFV9_FIELD_ICMP_TYPE = 32 - NFV9_FIELD_MUL_IGMP_TYPE = 33 - NFV9_FIELD_SAMPLING_INTERVAL = 34 - NFV9_FIELD_SAMPLING_ALGORITHM = 35 - NFV9_FIELD_FLOW_ACTIVE_TIMEOUT = 36 - NFV9_FIELD_FLOW_INACTIVE_TIMEOUT = 37 - NFV9_FIELD_ENGINE_TYPE = 38 - NFV9_FIELD_ENGINE_ID = 39 - NFV9_FIELD_TOTAL_BYTES_EXP = 40 - NFV9_FIELD_TOTAL_PKTS_EXP = 41 - NFV9_FIELD_TOTAL_FLOWS_EXP = 42 - NFV9_FIELD_IPV4_SRC_PREFIX = 44 - NFV9_FIELD_IPV4_DST_PREFIX = 45 - NFV9_FIELD_MPLS_TOP_LABEL_TYPE = 46 - NFV9_FIELD_MPLS_TOP_LABEL_IP_ADDR = 47 - NFV9_FIELD_FLOW_SAMPLER_ID = 48 - NFV9_FIELD_FLOW_SAMPLER_MODE = 49 - NFV9_FIELD_FLOW_SAMPLER_RANDOM_INTERVAL = 50 - NFV9_FIELD_MIN_TTL = 52 - NFV9_FIELD_MAX_TTL = 53 - NFV9_FIELD_IPV4_IDENT = 54 - NFV9_FIELD_DST_TOS = 55 - NFV9_FIELD_IN_SRC_MAC = 56 - NFV9_FIELD_OUT_DST_MAC = 57 - NFV9_FIELD_SRC_VLAN = 58 - NFV9_FIELD_DST_VLAN = 59 - NFV9_FIELD_IP_PROTOCOL_VERSION = 60 - NFV9_FIELD_DIRECTION = 61 - NFV9_FIELD_IPV6_NEXT_HOP = 62 - NFV9_FIELD_BGP_IPV6_NEXT_HOP = 63 - NFV9_FIELD_IPV6_OPTION_HEADERS = 64 - NFV9_FIELD_MPLS_LABEL_1 = 70 - NFV9_FIELD_MPLS_LABEL_2 = 71 - NFV9_FIELD_MPLS_LABEL_3 = 72 - NFV9_FIELD_MPLS_LABEL_4 = 73 - NFV9_FIELD_MPLS_LABEL_5 = 74 - NFV9_FIELD_MPLS_LABEL_6 = 75 - NFV9_FIELD_MPLS_LABEL_7 = 76 - NFV9_FIELD_MPLS_LABEL_8 = 77 - NFV9_FIELD_MPLS_LABEL_9 = 78 - NFV9_FIELD_MPLS_LABEL_10 = 79 - NFV9_FIELD_IN_DST_MAC = 80 - NFV9_FIELD_OUT_SRC_MAC = 81 - NFV9_FIELD_IF_NAME = 82 - NFV9_FIELD_IF_DESC = 83 - NFV9_FIELD_SAMPLER_NAME = 84 - NFV9_FIELD_IN_PERMANENT_BYTES = 85 - NFV9_FIELD_IN_PERMANENT_PKTS = 86 - NFV9_FIELD_FRAGMENT_OFFSET = 88 - NFV9_FIELD_FORWARDING_STATUS = 89 - NFV9_FIELD_MPLS_PAL_RD = 90 - NFV9_FIELD_MPLS_PREFIX_LEN = 91 - NFV9_FIELD_SRC_TRAFFIC_INDEX = 92 - NFV9_FIELD_DST_TRAFFIC_INDEX = 93 - NFV9_FIELD_APPLICATION_DESCRIPTION = 94 - NFV9_FIELD_APPLICATION_TAG = 95 - NFV9_FIELD_APPLICATION_NAME = 96 - NFV9_FIELD_postipDiffServCodePoint = 98 - NFV9_FIELD_replication_factor = 99 - NFV9_FIELD_layer2packetSectionOffset = 102 - NFV9_FIELD_layer2packetSectionSize = 103 - NFV9_FIELD_layer2packetSectionData = 104 -) - -type NFv9Packet struct { - Version uint16 - Count uint16 - SystemUptime uint32 - UnixSeconds uint32 - SequenceNumber uint32 - SourceId uint32 - FlowSets []interface{} -} - -type NFv9OptionsTemplateFlowSet struct { - FlowSetHeader - Records []NFv9OptionsTemplateRecord -} - -type NFv9OptionsTemplateRecord struct { - TemplateId uint16 - ScopeLength uint16 - OptionLength uint16 - Scopes []Field - Options []Field -} - -func NFv9TypeToString(typeId uint16) string { - - nameList := map[uint16]string{ - 1: "IN_BYTES", - 2: "IN_PKTS", - 3: "FLOWS", - 4: "PROTOCOL", - 5: "SRC_TOS", - 6: "TCP_FLAGS", - 7: "L4_SRC_PORT", - 8: "IPV4_SRC_ADDR", - 9: "SRC_MASK", - 10: "INPUT_SNMP", - 11: "L4_DST_PORT", - 12: "IPV4_DST_ADDR", - 13: "DST_MASK", - 14: "OUTPUT_SNMP", - 15: "IPV4_NEXT_HOP", - 16: "SRC_AS", - 17: "DST_AS", - 18: "BGP_IPV4_NEXT_HOP", - 19: "MUL_DST_PKTS", - 20: "MUL_DST_BYTES", - 21: "LAST_SWITCHED", - 22: "FIRST_SWITCHED", - 23: "OUT_BYTES", - 24: "OUT_PKTS", - 25: "MIN_PKT_LNGTH", - 26: "MAX_PKT_LNGTH", - 27: "IPV6_SRC_ADDR", - 28: "IPV6_DST_ADDR", - 29: "IPV6_SRC_MASK", - 30: "IPV6_DST_MASK", - 31: "IPV6_FLOW_LABEL", - 32: "ICMP_TYPE", - 33: "MUL_IGMP_TYPE", - 34: "SAMPLING_INTERVAL", - 35: "SAMPLING_ALGORITHM", - 36: "FLOW_ACTIVE_TIMEOUT", - 37: "FLOW_INACTIVE_TIMEOUT", - 38: "ENGINE_TYPE", - 39: "ENGINE_ID", - 40: "TOTAL_BYTES_EXP", - 41: "TOTAL_PKTS_EXP", - 42: "TOTAL_FLOWS_EXP", - 43: "*Vendor Proprietary*", - 44: "IPV4_SRC_PREFIX", - 45: "IPV4_DST_PREFIX", - 46: "MPLS_TOP_LABEL_TYPE", - 47: "MPLS_TOP_LABEL_IP_ADDR", - 48: "FLOW_SAMPLER_ID", - 49: "FLOW_SAMPLER_MODE", - 50: "FLOW_SAMPLER_RANDOM_INTERVAL", - 51: "*Vendor Proprietary*", - 52: "MIN_TTL", - 53: "MAX_TTL", - 54: "IPV4_IDENT", - 55: "DST_TOS", - 56: "IN_SRC_MAC", - 57: "OUT_DST_MAC", - 58: "SRC_VLAN", - 59: "DST_VLAN", - 60: "IP_PROTOCOL_VERSION", - 61: "DIRECTION", - 62: "IPV6_NEXT_HOP", - 63: "BPG_IPV6_NEXT_HOP", - 64: "IPV6_OPTION_HEADERS", - 65: "*Vendor Proprietary*", - 66: "*Vendor Proprietary*", - 67: "*Vendor Proprietary*", - 68: "*Vendor Proprietary*", - 69: "*Vendor Proprietary*", - 70: "MPLS_LABEL_1", - 71: "MPLS_LABEL_2", - 72: "MPLS_LABEL_3", - 73: "MPLS_LABEL_4", - 74: "MPLS_LABEL_5", - 75: "MPLS_LABEL_6", - 76: "MPLS_LABEL_7", - 77: "MPLS_LABEL_8", - 78: "MPLS_LABEL_9", - 79: "MPLS_LABEL_10", - 80: "IN_DST_MAC", - 81: "OUT_SRC_MAC", - 82: "IF_NAME", - 83: "IF_DESC", - 84: "SAMPLER_NAME", - 85: "IN_ PERMANENT _BYTES", - 86: "IN_ PERMANENT _PKTS", - 87: "*Vendor Proprietary*", - 88: "FRAGMENT_OFFSET", - 89: "FORWARDING STATUS", - 90: "MPLS PAL RD", - 91: "MPLS PREFIX LEN", - 92: "SRC TRAFFIC INDEX", - 93: "DST TRAFFIC INDEX", - 94: "APPLICATION DESCRIPTION", - 95: "APPLICATION TAG", - 96: "APPLICATION NAME", - 98: "postipDiffServCodePoint", - 99: "replication factor", - 100: "DEPRECATED", - 102: "layer2packetSectionOffset", - 103: "layer2packetSectionSize", - 104: "layer2packetSectionData", - 234: "ingressVRFID", - 235: "egressVRFID", - } - - if typeId > 104 || typeId == 0 { - return "Unassigned" - } else { - return nameList[typeId] - } -} - -func NFv9ScopeToString(scopeId uint16) string { - nameList := map[uint16]string{ - 1: "System", - 2: "Interface", - 3: "Line Card", - 4: "NetFlow Cache", - 5: "Template", - } - - if scopeId >= 1 && scopeId <= 5 { - return nameList[scopeId] - } else { - return "Unassigned" - } -} - -func (flowSet NFv9OptionsTemplateFlowSet) String(TypeToString func(uint16) string) string { - str := fmt.Sprintf(" Id %v\n", flowSet.Id) - str += fmt.Sprintf(" Length: %v\n", flowSet.Length) - str += fmt.Sprintf(" Records (%v records):\n", len(flowSet.Records)) - - for j, record := range flowSet.Records { - str += fmt.Sprintf(" - Record %v:\n", j) - str += fmt.Sprintf(" TemplateId: %v\n", record.TemplateId) - str += fmt.Sprintf(" ScopeLength: %v\n", record.ScopeLength) - str += fmt.Sprintf(" OptionLength: %v\n", record.OptionLength) - str += fmt.Sprintf(" Scopes (%v):\n", len(record.Scopes)) - - for k, field := range record.Scopes { - str += fmt.Sprintf(" - %v. %v (%v): %v\n", k, NFv9ScopeToString(field.Type), field.Type, field.Length) - } - - str += fmt.Sprintf(" Options (%v):\n", len(record.Options)) - - for k, field := range record.Options { - str += fmt.Sprintf(" - %v. %v (%v): %v\n", k, TypeToString(field.Type), field.Type, field.Length) - } - } - - return str -} - -func (p NFv9Packet) String() string { - str := "Flow Packet\n" - str += "------------\n" - str += fmt.Sprintf(" Version: %v\n", p.Version) - str += fmt.Sprintf(" Count: %v\n", p.Count) - - unixSeconds := time.Unix(int64(p.UnixSeconds), 0) - str += fmt.Sprintf(" SystemUptime: %v\n", p.SystemUptime) - str += fmt.Sprintf(" UnixSeconds: %v\n", unixSeconds.UTC().String()) - str += fmt.Sprintf(" SequenceNumber: %v\n", p.SequenceNumber) - str += fmt.Sprintf(" SourceId: %v\n", p.SourceId) - str += fmt.Sprintf(" FlowSets (%v):\n", len(p.FlowSets)) - - for i, flowSet := range p.FlowSets { - switch flowSet := flowSet.(type) { - case TemplateFlowSet: - str += fmt.Sprintf(" - TemplateFlowSet %v:\n", i) - str += flowSet.String(NFv9TypeToString) - case NFv9OptionsTemplateFlowSet: - str += fmt.Sprintf(" - OptionsTemplateFlowSet %v:\n", i) - str += flowSet.String(NFv9TypeToString) - case DataFlowSet: - str += fmt.Sprintf(" - DataFlowSet %v:\n", i) - str += flowSet.String(NFv9TypeToString) - case OptionsDataFlowSet: - str += fmt.Sprintf(" - OptionsDataFlowSet %v:\n", i) - str += flowSet.String(NFv9TypeToString, NFv9ScopeToString) - default: - str += fmt.Sprintf(" - (unknown type) %v: %v\n", i, flowSet) - } - } - return str -} diff --git a/vendor/github.com/netsampler/goflow2/decoders/netflow/packet.go b/vendor/github.com/netsampler/goflow2/decoders/netflow/packet.go deleted file mode 100644 index 3e3707d64..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/netflow/packet.go +++ /dev/null @@ -1,158 +0,0 @@ -package netflow - -import ( - "fmt" -) - -// FlowSetHeader contains fields shared by all Flow Sets (DataFlowSet, -// TemplateFlowSet, OptionsTemplateFlowSet). -type FlowSetHeader struct { - // FlowSet ID: - // 0 for TemplateFlowSet - // 1 for OptionsTemplateFlowSet - // 256-65535 for DataFlowSet (used as TemplateId) - Id uint16 - - // The total length of this FlowSet in bytes (including padding). - Length uint16 -} - -// TemplateFlowSet is a collection of templates that describe structure of Data -// Records (actual NetFlow data). -type TemplateFlowSet struct { - FlowSetHeader - - // List of Template Records - Records []TemplateRecord -} - -// DataFlowSet is a collection of Data Records (actual NetFlow data) and Options -// Data Records (meta data). -type DataFlowSet struct { - FlowSetHeader - - Records []DataRecord -} - -type OptionsDataFlowSet struct { - FlowSetHeader - - Records []OptionsDataRecord -} - -// TemplateRecord is a single template that describes structure of a Flow Record -// (actual Netflow data). -type TemplateRecord struct { - // Each of the newly generated Template Records is given a unique - // Template ID. This uniqueness is local to the Observation Domain that - // generated the Template ID. Template IDs of Data FlowSets are numbered - // from 256 to 65535. - TemplateId uint16 - - // Number of fields in this Template Record. Because a Template FlowSet - // usually contains multiple Template Records, this field allows the - // Collector to determine the end of the current Template Record and - // the start of the next. - FieldCount uint16 - - // List of fields in this Template Record. - Fields []Field -} - -type DataRecord struct { - Values []DataField -} - -// OptionsDataRecord is meta data sent alongide actual NetFlow data. Combined -// with OptionsTemplateRecord it can be decoded to a single data row. -type OptionsDataRecord struct { - // List of Scope values stored in raw format as []byte - ScopesValues []DataField - - // List of Optons values stored in raw format as []byte - OptionsValues []DataField -} - -// Field describes type and length of a single value in a Flow Data Record. -// Field does not contain the record value itself it is just a description of -// what record value will look like. -type Field struct { - // A numeric value that represents the type of field. - PenProvided bool - Type uint16 - - // The length (in bytes) of the field. - Length uint16 - - Pen uint32 -} - -type DataField struct { - // A numeric value that represents the type of field. - PenProvided bool - Type uint16 - Pen uint32 - - // The value (in bytes) of the field. - Value interface{} - //Value []byte -} - -func (flowSet OptionsDataFlowSet) String(TypeToString func(uint16) string, ScopeToString func(uint16) string) string { - str := fmt.Sprintf(" Id %v\n", flowSet.Id) - str += fmt.Sprintf(" Length: %v\n", flowSet.Length) - str += fmt.Sprintf(" Records (%v records):\n", len(flowSet.Records)) - - for j, record := range flowSet.Records { - str += fmt.Sprintf(" - Record %v:\n", j) - str += fmt.Sprintf(" Scopes (%v):\n", len(record.ScopesValues)) - - for k, value := range record.ScopesValues { - str += fmt.Sprintf(" - %v. %v (%v): %v\n", k, ScopeToString(value.Type), value.Type, value.Value) - } - - str += fmt.Sprintf(" Options (%v):\n", len(record.OptionsValues)) - - for k, value := range record.OptionsValues { - str += fmt.Sprintf(" - %v. %v (%v): %v\n", k, TypeToString(value.Type), value.Type, value.Value) - } - } - - return str -} - -func (flowSet DataFlowSet) String(TypeToString func(uint16) string) string { - str := fmt.Sprintf(" Id %v\n", flowSet.Id) - str += fmt.Sprintf(" Length: %v\n", flowSet.Length) - str += fmt.Sprintf(" Records (%v records):\n", len(flowSet.Records)) - - for j, record := range flowSet.Records { - str += fmt.Sprintf(" - Record %v:\n", j) - str += fmt.Sprintf(" Values (%v):\n", len(record.Values)) - - for k, value := range record.Values { - str += fmt.Sprintf(" - %v. %v (%v): %v\n", k, TypeToString(value.Type), value.Type, value.Value) - } - } - - return str -} - -func (flowSet TemplateFlowSet) String(TypeToString func(uint16) string) string { - str := fmt.Sprintf(" Id %v\n", flowSet.Id) - str += fmt.Sprintf(" Length: %v\n", flowSet.Length) - str += fmt.Sprintf(" Records (%v records):\n", len(flowSet.Records)) - - for j, record := range flowSet.Records { - str += fmt.Sprintf(" - %v. Record:\n", j) - str += fmt.Sprintf(" TemplateId: %v\n", record.TemplateId) - str += fmt.Sprintf(" FieldCount: %v\n", record.FieldCount) - str += fmt.Sprintf(" Fields (%v):\n", len(record.Fields)) - - for k, field := range record.Fields { - str += fmt.Sprintf(" - %v. %v (%v/%v): %v\n", k, TypeToString(field.Type), field.Type, field.PenProvided, field.Length) - } - } - - return str -} diff --git a/vendor/github.com/netsampler/goflow2/decoders/netflow/templates/templates.go b/vendor/github.com/netsampler/goflow2/decoders/netflow/templates/templates.go deleted file mode 100644 index 525e6b10e..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/netflow/templates/templates.go +++ /dev/null @@ -1,139 +0,0 @@ -package templates - -import ( - "context" - "fmt" - "strconv" - "strings" - "sync" -) - -var ( - templateDrivers = make(map[string]TemplateDriver) // might be better to change into "factory" - lock = &sync.RWMutex{} -) - -type TemplateDriver interface { - TemplateInterface - - Prepare() error // Prepare driver (eg: flag registration) - Init(context.Context) error // Initialize driver (eg: parse keying) - Close(context.Context) error // Close drive (eg: close file) -} - -type TemplateKey struct { - TemplateKey string - Version uint16 - ObsDomainId uint32 - TemplateId uint16 -} - -func NewTemplateKey(templateKey string, version uint16, obsDomainId uint32, templateId uint16) *TemplateKey { - return &TemplateKey{ - TemplateKey: templateKey, - Version: version, - ObsDomainId: obsDomainId, - TemplateId: templateId, - } -} - -func (k *TemplateKey) String() string { - return fmt.Sprintf("%s-%d-%d-%d", k.TemplateKey, k.Version, k.ObsDomainId, k.TemplateId) -} - -func ParseTemplateKey(key string, k *TemplateKey) error { - if k != nil { - return nil - } - var version uint16 - var obsDomainId uint32 - var templateId uint16 - - keySplit := strings.Split(key, "-") - if len(keySplit) != 4 { - return fmt.Errorf("template key format is invalid") - } - templateKey := keySplit[0] - if val, err := strconv.ParseUint(keySplit[1], 10, 64); err != nil { - return fmt.Errorf("template key version is invalid") - } else { - version = uint16(val) - } - if val, err := strconv.ParseUint(keySplit[2], 10, 64); err != nil { - fmt.Errorf("template key observation domain I Dis invalid") - } else { - obsDomainId = uint32(val) - } - if val, err := strconv.ParseUint(keySplit[3], 10, 64); err != nil { - fmt.Errorf("template key template ID is invalid") - } else { - templateId = uint16(val) - } - - k.TemplateKey = templateKey - k.Version = version - k.ObsDomainId = obsDomainId - k.TemplateId = templateId - - return nil -} - -type TemplateInterface interface { - ListTemplates(ctx context.Context, ch chan *TemplateKey) error - GetTemplate(ctx context.Context, key *TemplateKey) (interface{}, error) - AddTemplate(ctx context.Context, key *TemplateKey, template interface{}) error // add expiration -} - -type TemplateSystem struct { - driver TemplateDriver -} - -func (t *TemplateSystem) ListTemplates(ctx context.Context, ch chan *TemplateKey) error { - return t.driver.ListTemplates(ctx, ch) -} - -func (t *TemplateSystem) AddTemplate(ctx context.Context, key *TemplateKey, template interface{}) error { - return t.driver.AddTemplate(ctx, key, template) -} - -func (t *TemplateSystem) GetTemplate(ctx context.Context, key *TemplateKey) (interface{}, error) { - return t.driver.GetTemplate(ctx, key) -} - -func (t *TemplateSystem) Close(ctx context.Context) error { - return t.driver.Close(ctx) -} - -func RegisterTemplateDriver(name string, t TemplateDriver) { - lock.Lock() - templateDrivers[name] = t - lock.Unlock() - - if err := t.Prepare(); err != nil { - panic(err) - } -} - -func FindTemplateSystem(ctx context.Context, name string) (*TemplateSystem, error) { - lock.RLock() - t, ok := templateDrivers[name] - lock.RUnlock() - if !ok { - return nil, fmt.Errorf("Template %s not found", name) - } - - err := t.Init(ctx) - return &TemplateSystem{t}, err -} - -func GetTemplates() []string { - lock.RLock() - defer lock.RUnlock() - t := make([]string, len(templateDrivers)) - var i int - for k, _ := range templateDrivers { - t[i] = k - i++ - } - return t -} diff --git a/vendor/github.com/netsampler/goflow2/decoders/netflowlegacy/netflow.go b/vendor/github.com/netsampler/goflow2/decoders/netflowlegacy/netflow.go deleted file mode 100644 index 955f82cef..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/netflowlegacy/netflow.go +++ /dev/null @@ -1,90 +0,0 @@ -package netflowlegacy - -import ( - "bytes" - "fmt" - - "github.com/netsampler/goflow2/decoders/utils" -) - -const ( - MAX_COUNT = 1536 -) - -type ErrorVersion struct { - version uint16 -} - -func NewErrorVersion(version uint16) *ErrorVersion { - return &ErrorVersion{ - version: version, - } -} - -func (e *ErrorVersion) Error() string { - return fmt.Sprintf("Unknown NetFlow version %v (only decodes v5)", e.version) -} - -func DecodeMessage(payload *bytes.Buffer) (interface{}, error) { - var version uint16 - err := utils.BinaryDecoder(payload, &version) - if err != nil { - return nil, err - } - packet := PacketNetFlowV5{} - if version == 5 { - packet.Version = version - - utils.BinaryDecoder(payload, - &(packet.Count), - &(packet.SysUptime), - &(packet.UnixSecs), - &(packet.UnixNSecs), - &(packet.FlowSequence), - &(packet.EngineType), - &(packet.EngineId), - &(packet.SamplingInterval), - ) - - packet.SamplingInterval = packet.SamplingInterval & 0x3FFF - - if packet.Count > MAX_COUNT { - return nil, fmt.Errorf("Too many samples (%d > %d) in packet", packet.Count, MAX_COUNT) - } - - packet.Records = make([]RecordsNetFlowV5, int(packet.Count)) - for i := 0; i < int(packet.Count) && payload.Len() >= 48; i++ { - record := RecordsNetFlowV5{} - err := utils.BinaryDecoder(payload, - &record.SrcAddr, - &record.DstAddr, - &record.NextHop, - &record.Input, - &record.Output, - &record.DPkts, - &record.DOctets, - &record.First, - &record.Last, - &record.SrcPort, - &record.DstPort, - &record.Pad1, - &record.TCPFlags, - &record.Proto, - &record.Tos, - &record.SrcAS, - &record.DstAS, - &record.SrcMask, - &record.DstMask, - &record.Pad2, - ) - if err != nil { - return packet, err - } - packet.Records[i] = record - } - - return packet, nil - } else { - return nil, NewErrorVersion(version) - } -} diff --git a/vendor/github.com/netsampler/goflow2/decoders/netflowlegacy/packet.go b/vendor/github.com/netsampler/goflow2/decoders/netflowlegacy/packet.go deleted file mode 100644 index 078bba4df..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/netflowlegacy/packet.go +++ /dev/null @@ -1,96 +0,0 @@ -package netflowlegacy - -import ( - "encoding/binary" - "fmt" - "net" - "time" -) - -type PacketNetFlowV5 struct { - Version uint16 - Count uint16 - SysUptime uint32 - UnixSecs uint32 - UnixNSecs uint32 - FlowSequence uint32 - EngineType uint8 - EngineId uint8 - SamplingInterval uint16 - Records []RecordsNetFlowV5 -} - -type RecordsNetFlowV5 struct { - SrcAddr uint32 - DstAddr uint32 - NextHop uint32 - Input uint16 - Output uint16 - DPkts uint32 - DOctets uint32 - First uint32 - Last uint32 - SrcPort uint16 - DstPort uint16 - Pad1 byte - TCPFlags uint8 - Proto uint8 - Tos uint8 - SrcAS uint16 - DstAS uint16 - SrcMask uint8 - DstMask uint8 - Pad2 uint16 -} - -func (p PacketNetFlowV5) String() string { - str := "NetFlow v5 Packet\n" - str += "-----------------\n" - str += fmt.Sprintf(" Version: %v\n", p.Version) - str += fmt.Sprintf(" Count: %v\n", p.Count) - - unixSeconds := time.Unix(int64(p.UnixSecs), int64(p.UnixNSecs)) - str += fmt.Sprintf(" SystemUptime: %v\n", time.Duration(p.SysUptime)*time.Millisecond) - str += fmt.Sprintf(" UnixSeconds: %v\n", unixSeconds.String()) - str += fmt.Sprintf(" FlowSequence: %v\n", p.FlowSequence) - str += fmt.Sprintf(" EngineType: %v\n", p.EngineType) - str += fmt.Sprintf(" EngineId: %v\n", p.EngineId) - str += fmt.Sprintf(" SamplingInterval: %v\n", p.SamplingInterval) - str += fmt.Sprintf(" Records (%v):\n", len(p.Records)) - - for i, record := range p.Records { - str += fmt.Sprintf(" Record %v:\n", i) - str += record.String() - } - return str -} - -func (r RecordsNetFlowV5) String() string { - srcaddr := make(net.IP, 4) - binary.BigEndian.PutUint32(srcaddr, r.SrcAddr) - dstaddr := make(net.IP, 4) - binary.BigEndian.PutUint32(dstaddr, r.DstAddr) - nexthop := make(net.IP, 4) - binary.BigEndian.PutUint32(nexthop, r.NextHop) - - str := fmt.Sprintf(" SrcAddr: %v\n", srcaddr.String()) - str += fmt.Sprintf(" DstAddr: %v\n", dstaddr.String()) - str += fmt.Sprintf(" NextHop: %v\n", nexthop.String()) - str += fmt.Sprintf(" Input: %v\n", r.Input) - str += fmt.Sprintf(" Output: %v\n", r.Output) - str += fmt.Sprintf(" DPkts: %v\n", r.DPkts) - str += fmt.Sprintf(" DOctets: %v\n", r.DOctets) - str += fmt.Sprintf(" First: %v\n", time.Duration(r.First)*time.Millisecond) - str += fmt.Sprintf(" Last: %v\n", time.Duration(r.Last)*time.Millisecond) - str += fmt.Sprintf(" SrcPort: %v\n", r.SrcPort) - str += fmt.Sprintf(" DstPort: %v\n", r.DstPort) - str += fmt.Sprintf(" TCPFlags: %v\n", r.TCPFlags) - str += fmt.Sprintf(" Proto: %v\n", r.Proto) - str += fmt.Sprintf(" Tos: %v\n", r.Tos) - str += fmt.Sprintf(" SrcAS: %v\n", r.SrcAS) - str += fmt.Sprintf(" DstAS: %v\n", r.DstAS) - str += fmt.Sprintf(" SrcMask: %v\n", r.SrcMask) - str += fmt.Sprintf(" DstMask: %v\n", r.DstMask) - - return str -} diff --git a/vendor/github.com/netsampler/goflow2/decoders/sflow/datastructure.go b/vendor/github.com/netsampler/goflow2/decoders/sflow/datastructure.go deleted file mode 100644 index 670652a2c..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/sflow/datastructure.go +++ /dev/null @@ -1,103 +0,0 @@ -package sflow - -type SampledHeader struct { - Protocol uint32 - FrameLength uint32 - Stripped uint32 - OriginalLength uint32 - HeaderData []byte -} - -type SampledEthernet struct { - Length uint32 - SrcMac []byte - DstMac []byte - EthType uint32 -} - -type SampledIP_Base struct { - Length uint32 - Protocol uint32 - SrcIP []byte - DstIP []byte - SrcPort uint32 - DstPort uint32 - TcpFlags uint32 -} - -type SampledIPv4 struct { - Base SampledIP_Base - Tos uint32 -} - -type SampledIPv6 struct { - Base SampledIP_Base - Priority uint32 -} - -type ExtendedSwitch struct { - SrcVlan uint32 - SrcPriority uint32 - DstVlan uint32 - DstPriority uint32 -} - -type ExtendedRouter struct { - NextHopIPVersion uint32 - NextHop []byte - SrcMaskLen uint32 - DstMaskLen uint32 -} - -type ExtendedGateway struct { - NextHopIPVersion uint32 - NextHop []byte - AS uint32 - SrcAS uint32 - SrcPeerAS uint32 - ASDestinations uint32 - ASPathType uint32 - ASPathLength uint32 - ASPath []uint32 - CommunitiesLength uint32 - Communities []uint32 - LocalPref uint32 -} - -type IfCounters struct { - IfIndex uint32 - IfType uint32 - IfSpeed uint64 - IfDirection uint32 - IfStatus uint32 - IfInOctets uint64 - IfInUcastPkts uint32 - IfInMulticastPkts uint32 - IfInBroadcastPkts uint32 - IfInDiscards uint32 - IfInErrors uint32 - IfInUnknownProtos uint32 - IfOutOctets uint64 - IfOutUcastPkts uint32 - IfOutMulticastPkts uint32 - IfOutBroadcastPkts uint32 - IfOutDiscards uint32 - IfOutErrors uint32 - IfPromiscuousMode uint32 -} - -type EthernetCounters struct { - Dot3StatsAlignmentErrors uint32 - Dot3StatsFCSErrors uint32 - Dot3StatsSingleCollisionFrames uint32 - Dot3StatsMultipleCollisionFrames uint32 - Dot3StatsSQETestErrors uint32 - Dot3StatsDeferredTransmissions uint32 - Dot3StatsLateCollisions uint32 - Dot3StatsExcessiveCollisions uint32 - Dot3StatsInternalMacTransmitErrors uint32 - Dot3StatsCarrierSenseErrors uint32 - Dot3StatsFrameTooLongs uint32 - Dot3StatsInternalMacReceiveErrors uint32 - Dot3StatsSymbolErrors uint32 -} diff --git a/vendor/github.com/netsampler/goflow2/decoders/sflow/packet.go b/vendor/github.com/netsampler/goflow2/decoders/sflow/packet.go deleted file mode 100644 index 647f83db3..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/sflow/packet.go +++ /dev/null @@ -1,73 +0,0 @@ -package sflow - -type Packet struct { - Version uint32 - IPVersion uint32 - AgentIP []byte - SubAgentId uint32 - SequenceNumber uint32 - Uptime uint32 - SamplesCount uint32 - Samples []interface{} -} - -type SampleHeader struct { - Format uint32 - Length uint32 - - SampleSequenceNumber uint32 - SourceIdType uint32 - SourceIdValue uint32 -} - -type FlowSample struct { - Header SampleHeader - - SamplingRate uint32 - SamplePool uint32 - Drops uint32 - Input uint32 - Output uint32 - FlowRecordsCount uint32 - Records []FlowRecord -} - -type CounterSample struct { - Header SampleHeader - - CounterRecordsCount uint32 - Records []CounterRecord -} - -type ExpandedFlowSample struct { - Header SampleHeader - - SamplingRate uint32 - SamplePool uint32 - Drops uint32 - InputIfFormat uint32 - InputIfValue uint32 - OutputIfFormat uint32 - OutputIfValue uint32 - FlowRecordsCount uint32 - Records []FlowRecord -} - -type RecordHeader struct { - DataFormat uint32 - Length uint32 -} - -type FlowRecord struct { - Header RecordHeader - Data interface{} -} - -type FlowRecordRaw struct { - Data []byte -} - -type CounterRecord struct { - Header RecordHeader - Data interface{} -} diff --git a/vendor/github.com/netsampler/goflow2/decoders/sflow/sflow.go b/vendor/github.com/netsampler/goflow2/decoders/sflow/sflow.go deleted file mode 100644 index 309e965aa..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/sflow/sflow.go +++ /dev/null @@ -1,482 +0,0 @@ -package sflow - -import ( - "bytes" - "errors" - "fmt" - - "github.com/netsampler/goflow2/decoders/utils" -) - -const ( - FORMAT_EXT_SWITCH = 1001 - FORMAT_EXT_ROUTER = 1002 - FORMAT_EXT_GATEWAY = 1003 - FORMAT_RAW_PKT = 1 - FORMAT_ETH = 2 - FORMAT_IPV4 = 3 - FORMAT_IPV6 = 4 - - MAX_SAMPLES = 512 - MAX_RECORDS = 8192 - MAX_ATTRS = 16383 -) - -type ErrorDecodingSFlow struct { - msg string -} - -func NewErrorDecodingSFlow(msg string) *ErrorDecodingSFlow { - return &ErrorDecodingSFlow{ - msg: msg, - } -} - -func (e *ErrorDecodingSFlow) Error() string { - return fmt.Sprintf("Error decoding sFlow: %v", e.msg) -} - -type ErrorDataFormat struct { - dataformat uint32 -} - -func NewErrorDataFormat(dataformat uint32) *ErrorDataFormat { - return &ErrorDataFormat{ - dataformat: dataformat, - } -} - -func (e *ErrorDataFormat) Error() string { - return fmt.Sprintf("Unknown data format %v", e.dataformat) -} - -type ErrorIPVersion struct { - version uint32 -} - -func NewErrorIPVersion(version uint32) *ErrorIPVersion { - return &ErrorIPVersion{ - version: version, - } -} - -func (e *ErrorIPVersion) Error() string { - return fmt.Sprintf("Unknown IP version: %v", e.version) -} - -type ErrorVersion struct { - version uint32 -} - -func NewErrorVersion(version uint32) *ErrorVersion { - return &ErrorVersion{ - version: version, - } -} - -func (e *ErrorVersion) Error() string { - return fmt.Sprintf("Unknown sFlow version %v (supported v5)", e.version) -} - -func DecodeCounterRecord(header *RecordHeader, payload *bytes.Buffer) (CounterRecord, error) { - counterRecord := CounterRecord{ - Header: *header, - } - switch (*header).DataFormat { - case 1: - ifCounters := IfCounters{} - err := utils.BinaryDecoder(payload, - &ifCounters.IfIndex, - &ifCounters.IfType, - &ifCounters.IfSpeed, - &ifCounters.IfDirection, - &ifCounters.IfStatus, - &ifCounters.IfInOctets, - &ifCounters.IfInUcastPkts, - &ifCounters.IfInMulticastPkts, - &ifCounters.IfInBroadcastPkts, - &ifCounters.IfInDiscards, - &ifCounters.IfInErrors, - &ifCounters.IfInUnknownProtos, - &ifCounters.IfOutOctets, - &ifCounters.IfOutUcastPkts, - &ifCounters.IfOutMulticastPkts, - &ifCounters.IfOutBroadcastPkts, - &ifCounters.IfOutDiscards, - &ifCounters.IfOutErrors, - &ifCounters.IfPromiscuousMode, - ) - if err != nil { - return counterRecord, err - } - counterRecord.Data = ifCounters - case 2: - ethernetCounters := EthernetCounters{} - err := utils.BinaryDecoder(payload, - ðernetCounters.Dot3StatsAlignmentErrors, - ðernetCounters.Dot3StatsFCSErrors, - ðernetCounters.Dot3StatsSingleCollisionFrames, - ðernetCounters.Dot3StatsMultipleCollisionFrames, - ðernetCounters.Dot3StatsSQETestErrors, - ðernetCounters.Dot3StatsDeferredTransmissions, - ðernetCounters.Dot3StatsLateCollisions, - ðernetCounters.Dot3StatsExcessiveCollisions, - ðernetCounters.Dot3StatsInternalMacTransmitErrors, - ðernetCounters.Dot3StatsCarrierSenseErrors, - ðernetCounters.Dot3StatsFrameTooLongs, - ðernetCounters.Dot3StatsInternalMacReceiveErrors, - ðernetCounters.Dot3StatsSymbolErrors, - ) - if err != nil { - return counterRecord, err - } - counterRecord.Data = ethernetCounters - default: - counterRecord.Data = &FlowRecordRaw{ - Data: payload.Next(int(header.Length)), - } - } - - return counterRecord, nil -} - -func DecodeIP(payload *bytes.Buffer) (uint32, []byte, error) { - var ipVersion uint32 - err := utils.BinaryDecoder(payload, &ipVersion) - if err != nil { - return 0, nil, err - } - var ip []byte - if ipVersion == 1 { - ip = make([]byte, 4) - } else if ipVersion == 2 { - ip = make([]byte, 16) - } else { - return ipVersion, ip, NewErrorIPVersion(ipVersion) - } - if payload.Len() >= len(ip) { - err := utils.BinaryDecoder(payload, ip) - if err != nil { - return 0, nil, err - } - } else { - return ipVersion, ip, NewErrorDecodingSFlow(fmt.Sprintf("Not enough data: %v, needs %v.", payload.Len(), len(ip))) - } - return ipVersion, ip, nil -} - -func DecodeFlowRecord(header *RecordHeader, payload *bytes.Buffer) (FlowRecord, error) { - flowRecord := FlowRecord{ - Header: *header, - } - switch (*header).DataFormat { - case FORMAT_EXT_SWITCH: - extendedSwitch := ExtendedSwitch{} - err := utils.BinaryDecoder(payload, &extendedSwitch.SrcVlan, &extendedSwitch.SrcPriority, &extendedSwitch.DstVlan, &extendedSwitch.DstPriority) - if err != nil { - return flowRecord, err - } - flowRecord.Data = extendedSwitch - case FORMAT_RAW_PKT: - sampledHeader := SampledHeader{} - err := utils.BinaryDecoder(payload, &sampledHeader.Protocol, &sampledHeader.FrameLength, &sampledHeader.Stripped, &sampledHeader.OriginalLength) - if err != nil { - return flowRecord, err - } - sampledHeader.HeaderData = payload.Bytes() - flowRecord.Data = sampledHeader - case FORMAT_IPV4: - sampledIPBase := SampledIP_Base{ - SrcIP: make([]byte, 4), - DstIP: make([]byte, 4), - } - err := utils.BinaryDecoder(payload, &sampledIPBase.Length, &sampledIPBase.Protocol, sampledIPBase.SrcIP, sampledIPBase.DstIP, &sampledIPBase.SrcPort, &sampledIPBase.DstPort, &sampledIPBase.TcpFlags) - if err != nil { - return flowRecord, err - } - sampledIPv4 := SampledIPv4{ - Base: sampledIPBase, - } - err = utils.BinaryDecoder(payload, &(sampledIPv4.Tos)) - if err != nil { - return flowRecord, err - } - flowRecord.Data = sampledIPv4 - case FORMAT_IPV6: - sampledIPBase := SampledIP_Base{ - SrcIP: make([]byte, 16), - DstIP: make([]byte, 16), - } - err := utils.BinaryDecoder(payload, &sampledIPBase.Length, &sampledIPBase.Protocol, sampledIPBase.SrcIP, sampledIPBase.DstIP, &sampledIPBase.SrcPort, &sampledIPBase.DstPort, &sampledIPBase.TcpFlags) - if err != nil { - return flowRecord, err - } - sampledIPv6 := SampledIPv6{ - Base: sampledIPBase, - } - err = utils.BinaryDecoder(payload, &sampledIPv6.Priority) - if err != nil { - return flowRecord, err - } - flowRecord.Data = sampledIPv6 - case FORMAT_EXT_ROUTER: - extendedRouter := ExtendedRouter{} - - ipVersion, ip, err := DecodeIP(payload) - if err != nil { - return flowRecord, err - } - extendedRouter.NextHopIPVersion = ipVersion - extendedRouter.NextHop = ip - err = utils.BinaryDecoder(payload, &extendedRouter.SrcMaskLen, &extendedRouter.DstMaskLen) - if err != nil { - return flowRecord, err - } - flowRecord.Data = extendedRouter - case FORMAT_EXT_GATEWAY: - extendedGateway := ExtendedGateway{} - ipVersion, ip, err := DecodeIP(payload) - if err != nil { - return flowRecord, err - } - extendedGateway.NextHopIPVersion = ipVersion - extendedGateway.NextHop = ip - err = utils.BinaryDecoder(payload, &extendedGateway.AS, &extendedGateway.SrcAS, &extendedGateway.SrcPeerAS, - &extendedGateway.ASDestinations) - if err != nil { - return flowRecord, err - } - var asPath []uint32 - if extendedGateway.ASDestinations != 0 { - err := utils.BinaryDecoder(payload, &extendedGateway.ASPathType, &extendedGateway.ASPathLength) - if err != nil { - return flowRecord, err - } - if int(extendedGateway.ASPathLength) > payload.Len()-4 { - return flowRecord, errors.New(fmt.Sprintf("Invalid AS path length: %v.", extendedGateway.ASPathLength)) - } - - if extendedGateway.ASPathLength > MAX_ATTRS { - return flowRecord, fmt.Errorf("AS path too large (%d > %d) in record", extendedGateway.ASPathLength, MAX_ATTRS) - } - - asPath = make([]uint32, extendedGateway.ASPathLength) - if len(asPath) > 0 { - err = utils.BinaryDecoder(payload, asPath) - if err != nil { - return flowRecord, err - } - } - } - extendedGateway.ASPath = asPath - - err = utils.BinaryDecoder(payload, &extendedGateway.CommunitiesLength) - if err != nil { - return flowRecord, err - } - if extendedGateway.CommunitiesLength > MAX_ATTRS { - return flowRecord, fmt.Errorf("Communities list too large (%d > %d) in record", extendedGateway.CommunitiesLength, MAX_ATTRS) - } - - if int(extendedGateway.CommunitiesLength) > payload.Len()-4 { - return flowRecord, errors.New(fmt.Sprintf("Invalid Communities length: %v.", extendedGateway.ASPathLength)) - } - communities := make([]uint32, extendedGateway.CommunitiesLength) - if len(communities) > 0 { - err = utils.BinaryDecoder(payload, communities) - if err != nil { - return flowRecord, err - } - } - err = utils.BinaryDecoder(payload, &extendedGateway.LocalPref) - if err != nil { - return flowRecord, err - } - extendedGateway.Communities = communities - - flowRecord.Data = extendedGateway - default: - //return flowRecord, errors.New(fmt.Sprintf("Unknown data format %v.", (*header).DataFormat)) - flowRecord.Data = &FlowRecordRaw{ - Data: payload.Next(int(header.Length)), - } - } - return flowRecord, nil -} - -func DecodeSample(header *SampleHeader, payload *bytes.Buffer) (interface{}, error) { - format := header.Format - var sample interface{} - - err := utils.BinaryDecoder(payload, &header.SampleSequenceNumber) - if err != nil { - return sample, err - } - if format == FORMAT_RAW_PKT || format == FORMAT_ETH { - var sourceId uint32 - err = utils.BinaryDecoder(payload, &sourceId) - if err != nil { - return sample, err - } - - (*header).SourceIdType = sourceId >> 24 - (*header).SourceIdValue = sourceId & 0x00ffffff - } else if format == FORMAT_IPV4 || format == FORMAT_IPV6 { - err = utils.BinaryDecoder(payload, &header.SourceIdType, &header.SourceIdValue) - if err != nil { - return sample, err - } - } else { - return nil, NewErrorDataFormat(format) - } - - var recordsCount uint32 - var flowSample FlowSample - var counterSample CounterSample - var expandedFlowSample ExpandedFlowSample - if format == FORMAT_RAW_PKT { - flowSample = FlowSample{ - Header: *header, - } - err = utils.BinaryDecoder(payload, &flowSample.SamplingRate, &flowSample.SamplePool, - &flowSample.Drops, &flowSample.Input, &flowSample.Output, &flowSample.FlowRecordsCount) - if err != nil { - return sample, err - } - recordsCount = flowSample.FlowRecordsCount - - if recordsCount > MAX_RECORDS { - return flowSample, fmt.Errorf("Too many records (%d > %d) in packet", recordsCount, MAX_RECORDS) - } - - flowSample.Records = make([]FlowRecord, recordsCount) - sample = flowSample - } else if format == FORMAT_ETH || format == FORMAT_IPV6 { - err = utils.BinaryDecoder(payload, &recordsCount) - if err != nil { - return sample, err - } - counterSample = CounterSample{ - Header: *header, - CounterRecordsCount: recordsCount, - } - - if recordsCount > MAX_RECORDS { - return flowSample, fmt.Errorf("Too many records (%d > %d) in packet", recordsCount, MAX_RECORDS) - } - counterSample.Records = make([]CounterRecord, recordsCount) - sample = counterSample - } else if format == FORMAT_IPV4 { - expandedFlowSample = ExpandedFlowSample{ - Header: *header, - } - err = utils.BinaryDecoder(payload, &expandedFlowSample.SamplingRate, &expandedFlowSample.SamplePool, - &expandedFlowSample.Drops, &expandedFlowSample.InputIfFormat, &expandedFlowSample.InputIfValue, - &expandedFlowSample.OutputIfFormat, &expandedFlowSample.OutputIfValue, &expandedFlowSample.FlowRecordsCount) - if err != nil { - return sample, err - } - recordsCount = expandedFlowSample.FlowRecordsCount - - if recordsCount > MAX_RECORDS { - return flowSample, fmt.Errorf("Too many records (%d > %d) in packet", recordsCount, MAX_RECORDS) - } - expandedFlowSample.Records = make([]FlowRecord, recordsCount) - sample = expandedFlowSample - } - for i := 0; i < int(recordsCount) && payload.Len() >= 8; i++ { - recordHeader := RecordHeader{} - err = utils.BinaryDecoder(payload, &recordHeader.DataFormat, &recordHeader.Length) - if err != nil { - return sample, err - } - if int(recordHeader.Length) > payload.Len() { - break - } - recordReader := bytes.NewBuffer(payload.Next(int(recordHeader.Length))) - if format == FORMAT_RAW_PKT || format == FORMAT_IPV4 { - record, err := DecodeFlowRecord(&recordHeader, recordReader) - if err != nil { - continue - } - if format == FORMAT_RAW_PKT { - flowSample.Records[i] = record - } else if format == FORMAT_IPV4 { - expandedFlowSample.Records[i] = record - } - } else if format == FORMAT_ETH || format == FORMAT_IPV6 { - record, err := DecodeCounterRecord(&recordHeader, recordReader) - if err != nil { - continue - } - counterSample.Records[i] = record - } - } - return sample, nil -} - -func DecodeMessage(payload *bytes.Buffer) (interface{}, error) { - var version uint32 - err := utils.BinaryDecoder(payload, &version) - if err != nil { - return nil, err - } - packetV5 := Packet{} - if version == 5 { - packetV5.Version = version - err = utils.BinaryDecoder(payload, &(packetV5.IPVersion)) - if err != nil { - return packetV5, err - } - var ip []byte - if packetV5.IPVersion == 1 { - ip = make([]byte, 4) - err = utils.BinaryDecoder(payload, ip) - if err != nil { - return packetV5, err - } - } else if packetV5.IPVersion == 2 { - ip = make([]byte, 16) - err = utils.BinaryDecoder(payload, ip) - if err != nil { - return packetV5, err - } - } else { - return nil, NewErrorIPVersion(packetV5.IPVersion) - } - - packetV5.AgentIP = ip - err = utils.BinaryDecoder(payload, &packetV5.SubAgentId, &packetV5.SequenceNumber, &packetV5.Uptime, &packetV5.SamplesCount) - if err != nil { - return packetV5, err - } - - if packetV5.SamplesCount > MAX_SAMPLES { - return nil, fmt.Errorf("Too many samples (%d > %d) in packet", packetV5.SamplesCount, MAX_SAMPLES) - } - - packetV5.Samples = make([]interface{}, int(packetV5.SamplesCount)) - for i := 0; i < int(packetV5.SamplesCount) && payload.Len() >= 8; i++ { - header := SampleHeader{} - err = utils.BinaryDecoder(payload, &(header.Format), &(header.Length)) - if err != nil { - return packetV5, err - } - if int(header.Length) > payload.Len() { - break - } - sampleReader := bytes.NewBuffer(payload.Next(int(header.Length))) - - sample, err := DecodeSample(&header, sampleReader) - if err != nil { - continue - } else { - packetV5.Samples[i] = sample - } - } - - return packetV5, nil - } else { - return nil, NewErrorVersion(version) - } -} diff --git a/vendor/github.com/netsampler/goflow2/decoders/utils/utils.go b/vendor/github.com/netsampler/goflow2/decoders/utils/utils.go deleted file mode 100644 index 9c8e597f5..000000000 --- a/vendor/github.com/netsampler/goflow2/decoders/utils/utils.go +++ /dev/null @@ -1,128 +0,0 @@ -package utils - -import ( - "bytes" - "encoding/binary" - "errors" - "io" - "reflect" -) - -type BytesBuffer interface { - io.Reader - Next(int) []byte -} - -func BinaryDecoder(payload *bytes.Buffer, dests ...interface{}) error { - for _, dest := range dests { - err := BinaryRead(payload, binary.BigEndian, dest) - if err != nil { - return err - } - } - return nil -} -func BinaryRead(payload BytesBuffer, order binary.ByteOrder, data any) error { - // Fast path for basic types and slices. - if n := intDataSize(data); n != 0 { - bs := payload.Next(n) - if len(bs) < n { - return io.ErrUnexpectedEOF - } - switch data := data.(type) { - case *bool: - *data = bs[0] != 0 - case *int8: - *data = int8(bs[0]) - case *uint8: - *data = bs[0] - case *int16: - *data = int16(order.Uint16(bs)) - case *uint16: - *data = order.Uint16(bs) - case *int32: - *data = int32(order.Uint32(bs)) - case *uint32: - *data = order.Uint32(bs) - case *int64: - *data = int64(order.Uint64(bs)) - case *uint64: - *data = order.Uint64(bs) - case []bool: - for i, x := range bs { // Easier to loop over the input for 8-bit values. - data[i] = x != 0 - } - case []int8: - for i, x := range bs { - data[i] = int8(x) - } - case []uint8: - copy(data, bs) - case []int16: - for i := range data { - data[i] = int16(order.Uint16(bs[2*i:])) - } - case []uint16: - for i := range data { - data[i] = order.Uint16(bs[2*i:]) - } - case []int32: - for i := range data { - data[i] = int32(order.Uint32(bs[4*i:])) - } - case []uint32: - for i := range data { - data[i] = order.Uint32(bs[4*i:]) - } - case []int64: - for i := range data { - data[i] = int64(order.Uint64(bs[8*i:])) - } - case []uint64: - for i := range data { - data[i] = order.Uint64(bs[8*i:]) - } - default: - n = 0 // fast path doesn't apply - } - if n != 0 { - return nil - } - } - - return errors.New("binary.Read: invalid type " + reflect.TypeOf(data).String()) -} - -// intDataSize returns the size of the data required to represent the data when encoded. -// It returns zero if the type cannot be implemented by the fast path in Read or Write. -func intDataSize(data any) int { - switch data := data.(type) { - case bool, int8, uint8, *bool, *int8, *uint8: - return 1 - case []bool: - return len(data) - case []int8: - return len(data) - case []uint8: - return len(data) - case int16, uint16, *int16, *uint16: - return 2 - case []int16: - return 2 * len(data) - case []uint16: - return 2 * len(data) - case int32, uint32, *int32, *uint32: - return 4 - case []int32: - return 4 * len(data) - case []uint32: - return 4 * len(data) - case int64, uint64, *int64, *uint64: - return 8 - case []int64: - return 8 * len(data) - case []uint64: - return 8 * len(data) - } - return 0 -} diff --git a/vendor/github.com/netsampler/goflow2/pb/flow.pb.go b/vendor/github.com/netsampler/goflow2/pb/flow.pb.go deleted file mode 100644 index 4b3402ceb..000000000 --- a/vendor/github.com/netsampler/goflow2/pb/flow.pb.go +++ /dev/null @@ -1,924 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.4 -// source: pb/flow.proto - -package flowpb - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -type FlowMessage_FlowType int32 - -const ( - FlowMessage_FLOWUNKNOWN FlowMessage_FlowType = 0 - FlowMessage_SFLOW_5 FlowMessage_FlowType = 1 - FlowMessage_NETFLOW_V5 FlowMessage_FlowType = 2 - FlowMessage_NETFLOW_V9 FlowMessage_FlowType = 3 - FlowMessage_IPFIX FlowMessage_FlowType = 4 -) - -// Enum value maps for FlowMessage_FlowType. -var ( - FlowMessage_FlowType_name = map[int32]string{ - 0: "FLOWUNKNOWN", - 1: "SFLOW_5", - 2: "NETFLOW_V5", - 3: "NETFLOW_V9", - 4: "IPFIX", - } - FlowMessage_FlowType_value = map[string]int32{ - "FLOWUNKNOWN": 0, - "SFLOW_5": 1, - "NETFLOW_V5": 2, - "NETFLOW_V9": 3, - "IPFIX": 4, - } -) - -func (x FlowMessage_FlowType) Enum() *FlowMessage_FlowType { - p := new(FlowMessage_FlowType) - *p = x - return p -} - -func (x FlowMessage_FlowType) String() string { - return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) -} - -func (FlowMessage_FlowType) Descriptor() protoreflect.EnumDescriptor { - return file_pb_flow_proto_enumTypes[0].Descriptor() -} - -func (FlowMessage_FlowType) Type() protoreflect.EnumType { - return &file_pb_flow_proto_enumTypes[0] -} - -func (x FlowMessage_FlowType) Number() protoreflect.EnumNumber { - return protoreflect.EnumNumber(x) -} - -// Deprecated: Use FlowMessage_FlowType.Descriptor instead. -func (FlowMessage_FlowType) EnumDescriptor() ([]byte, []int) { - return file_pb_flow_proto_rawDescGZIP(), []int{0, 0} -} - -type FlowMessage struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Type FlowMessage_FlowType `protobuf:"varint,1,opt,name=type,proto3,enum=flowpb.FlowMessage_FlowType" json:"type,omitempty"` - TimeReceived uint64 `protobuf:"varint,2,opt,name=time_received,json=timeReceived,proto3" json:"time_received,omitempty"` - SequenceNum uint32 `protobuf:"varint,4,opt,name=sequence_num,json=sequenceNum,proto3" json:"sequence_num,omitempty"` - SamplingRate uint64 `protobuf:"varint,3,opt,name=sampling_rate,json=samplingRate,proto3" json:"sampling_rate,omitempty"` - FlowDirection uint32 `protobuf:"varint,42,opt,name=flow_direction,json=flowDirection,proto3" json:"flow_direction,omitempty"` - // Sampler information - SamplerAddress []byte `protobuf:"bytes,11,opt,name=sampler_address,json=samplerAddress,proto3" json:"sampler_address,omitempty"` - // Found inside packet - TimeFlowStart uint64 `protobuf:"varint,38,opt,name=time_flow_start,json=timeFlowStart,proto3" json:"time_flow_start,omitempty"` - TimeFlowEnd uint64 `protobuf:"varint,5,opt,name=time_flow_end,json=timeFlowEnd,proto3" json:"time_flow_end,omitempty"` - TimeFlowStartMs uint64 `protobuf:"varint,63,opt,name=time_flow_start_ms,json=timeFlowStartMs,proto3" json:"time_flow_start_ms,omitempty"` - TimeFlowEndMs uint64 `protobuf:"varint,64,opt,name=time_flow_end_ms,json=timeFlowEndMs,proto3" json:"time_flow_end_ms,omitempty"` - // Size of the sampled packet - Bytes uint64 `protobuf:"varint,9,opt,name=bytes,proto3" json:"bytes,omitempty"` - Packets uint64 `protobuf:"varint,10,opt,name=packets,proto3" json:"packets,omitempty"` - // Source/destination addresses - SrcAddr []byte `protobuf:"bytes,6,opt,name=src_addr,json=srcAddr,proto3" json:"src_addr,omitempty"` - DstAddr []byte `protobuf:"bytes,7,opt,name=dst_addr,json=dstAddr,proto3" json:"dst_addr,omitempty"` - // Layer 3 protocol (IPv4/IPv6/ARP/MPLS...) - Etype uint32 `protobuf:"varint,30,opt,name=etype,proto3" json:"etype,omitempty"` - // Layer 4 protocol - Proto uint32 `protobuf:"varint,20,opt,name=proto,proto3" json:"proto,omitempty"` - // Ports for UDP and TCP - SrcPort uint32 `protobuf:"varint,21,opt,name=src_port,json=srcPort,proto3" json:"src_port,omitempty"` - DstPort uint32 `protobuf:"varint,22,opt,name=dst_port,json=dstPort,proto3" json:"dst_port,omitempty"` - // Interfaces - InIf uint32 `protobuf:"varint,18,opt,name=in_if,json=inIf,proto3" json:"in_if,omitempty"` - OutIf uint32 `protobuf:"varint,19,opt,name=out_if,json=outIf,proto3" json:"out_if,omitempty"` - // Ethernet information - SrcMac uint64 `protobuf:"varint,27,opt,name=src_mac,json=srcMac,proto3" json:"src_mac,omitempty"` - DstMac uint64 `protobuf:"varint,28,opt,name=dst_mac,json=dstMac,proto3" json:"dst_mac,omitempty"` - // Vlan - SrcVlan uint32 `protobuf:"varint,33,opt,name=src_vlan,json=srcVlan,proto3" json:"src_vlan,omitempty"` - DstVlan uint32 `protobuf:"varint,34,opt,name=dst_vlan,json=dstVlan,proto3" json:"dst_vlan,omitempty"` - // 802.1q VLAN in sampled packet - VlanId uint32 `protobuf:"varint,29,opt,name=vlan_id,json=vlanId,proto3" json:"vlan_id,omitempty"` - // VRF - IngressVrfId uint32 `protobuf:"varint,39,opt,name=ingress_vrf_id,json=ingressVrfId,proto3" json:"ingress_vrf_id,omitempty"` - EgressVrfId uint32 `protobuf:"varint,40,opt,name=egress_vrf_id,json=egressVrfId,proto3" json:"egress_vrf_id,omitempty"` - // IP and TCP special flags - IpTos uint32 `protobuf:"varint,23,opt,name=ip_tos,json=ipTos,proto3" json:"ip_tos,omitempty"` - ForwardingStatus uint32 `protobuf:"varint,24,opt,name=forwarding_status,json=forwardingStatus,proto3" json:"forwarding_status,omitempty"` - IpTtl uint32 `protobuf:"varint,25,opt,name=ip_ttl,json=ipTtl,proto3" json:"ip_ttl,omitempty"` - TcpFlags uint32 `protobuf:"varint,26,opt,name=tcp_flags,json=tcpFlags,proto3" json:"tcp_flags,omitempty"` - IcmpType uint32 `protobuf:"varint,31,opt,name=icmp_type,json=icmpType,proto3" json:"icmp_type,omitempty"` - IcmpCode uint32 `protobuf:"varint,32,opt,name=icmp_code,json=icmpCode,proto3" json:"icmp_code,omitempty"` - Ipv6FlowLabel uint32 `protobuf:"varint,37,opt,name=ipv6_flow_label,json=ipv6FlowLabel,proto3" json:"ipv6_flow_label,omitempty"` - // Fragments (IPv4/IPv6) - FragmentId uint32 `protobuf:"varint,35,opt,name=fragment_id,json=fragmentId,proto3" json:"fragment_id,omitempty"` - FragmentOffset uint32 `protobuf:"varint,36,opt,name=fragment_offset,json=fragmentOffset,proto3" json:"fragment_offset,omitempty"` - BiFlowDirection uint32 `protobuf:"varint,41,opt,name=bi_flow_direction,json=biFlowDirection,proto3" json:"bi_flow_direction,omitempty"` - // Autonomous system information - SrcAs uint32 `protobuf:"varint,14,opt,name=src_as,json=srcAs,proto3" json:"src_as,omitempty"` - DstAs uint32 `protobuf:"varint,15,opt,name=dst_as,json=dstAs,proto3" json:"dst_as,omitempty"` - NextHop []byte `protobuf:"bytes,12,opt,name=next_hop,json=nextHop,proto3" json:"next_hop,omitempty"` - NextHopAs uint32 `protobuf:"varint,13,opt,name=next_hop_as,json=nextHopAs,proto3" json:"next_hop_as,omitempty"` - // Prefix size - SrcNet uint32 `protobuf:"varint,16,opt,name=src_net,json=srcNet,proto3" json:"src_net,omitempty"` - DstNet uint32 `protobuf:"varint,17,opt,name=dst_net,json=dstNet,proto3" json:"dst_net,omitempty"` - // BGP information - BgpNextHop []byte `protobuf:"bytes,100,opt,name=bgp_next_hop,json=bgpNextHop,proto3" json:"bgp_next_hop,omitempty"` - BgpCommunities []uint32 `protobuf:"varint,101,rep,packed,name=bgp_communities,json=bgpCommunities,proto3" json:"bgp_communities,omitempty"` - AsPath []uint32 `protobuf:"varint,102,rep,packed,name=as_path,json=asPath,proto3" json:"as_path,omitempty"` - // MPLS information - HasMpls bool `protobuf:"varint,53,opt,name=has_mpls,json=hasMpls,proto3" json:"has_mpls,omitempty"` - MplsCount uint32 `protobuf:"varint,54,opt,name=mpls_count,json=mplsCount,proto3" json:"mpls_count,omitempty"` - Mpls_1Ttl uint32 `protobuf:"varint,55,opt,name=mpls_1_ttl,json=mpls1Ttl,proto3" json:"mpls_1_ttl,omitempty"` // First TTL - Mpls_1Label uint32 `protobuf:"varint,56,opt,name=mpls_1_label,json=mpls1Label,proto3" json:"mpls_1_label,omitempty"` // First Label - Mpls_2Ttl uint32 `protobuf:"varint,57,opt,name=mpls_2_ttl,json=mpls2Ttl,proto3" json:"mpls_2_ttl,omitempty"` // Second TTL - Mpls_2Label uint32 `protobuf:"varint,58,opt,name=mpls_2_label,json=mpls2Label,proto3" json:"mpls_2_label,omitempty"` // Second Label - Mpls_3Ttl uint32 `protobuf:"varint,59,opt,name=mpls_3_ttl,json=mpls3Ttl,proto3" json:"mpls_3_ttl,omitempty"` // Third TTL - Mpls_3Label uint32 `protobuf:"varint,60,opt,name=mpls_3_label,json=mpls3Label,proto3" json:"mpls_3_label,omitempty"` // Third Label - MplsLastTtl uint32 `protobuf:"varint,61,opt,name=mpls_last_ttl,json=mplsLastTtl,proto3" json:"mpls_last_ttl,omitempty"` // Last TTL - MplsLastLabel uint32 `protobuf:"varint,62,opt,name=mpls_last_label,json=mplsLastLabel,proto3" json:"mpls_last_label,omitempty"` // Last Label - MplsLabelIp []byte `protobuf:"bytes,65,opt,name=mpls_label_ip,json=mplsLabelIp,proto3" json:"mpls_label_ip,omitempty"` // MPLS TOP Label IP - ObservationDomainId uint32 `protobuf:"varint,70,opt,name=observation_domain_id,json=observationDomainId,proto3" json:"observation_domain_id,omitempty"` - ObservationPointId uint32 `protobuf:"varint,71,opt,name=observation_point_id,json=observationPointId,proto3" json:"observation_point_id,omitempty"` - // Custom allocations - CustomInteger_1 uint64 `protobuf:"varint,1001,opt,name=custom_integer_1,json=customInteger1,proto3" json:"custom_integer_1,omitempty"` - CustomInteger_2 uint64 `protobuf:"varint,1002,opt,name=custom_integer_2,json=customInteger2,proto3" json:"custom_integer_2,omitempty"` - CustomInteger_3 uint64 `protobuf:"varint,1003,opt,name=custom_integer_3,json=customInteger3,proto3" json:"custom_integer_3,omitempty"` - CustomInteger_4 uint64 `protobuf:"varint,1004,opt,name=custom_integer_4,json=customInteger4,proto3" json:"custom_integer_4,omitempty"` - CustomInteger_5 uint64 `protobuf:"varint,1005,opt,name=custom_integer_5,json=customInteger5,proto3" json:"custom_integer_5,omitempty"` - CustomBytes_1 []byte `protobuf:"bytes,1011,opt,name=custom_bytes_1,json=customBytes1,proto3" json:"custom_bytes_1,omitempty"` - CustomBytes_2 []byte `protobuf:"bytes,1012,opt,name=custom_bytes_2,json=customBytes2,proto3" json:"custom_bytes_2,omitempty"` - CustomBytes_3 []byte `protobuf:"bytes,1013,opt,name=custom_bytes_3,json=customBytes3,proto3" json:"custom_bytes_3,omitempty"` - CustomBytes_4 []byte `protobuf:"bytes,1014,opt,name=custom_bytes_4,json=customBytes4,proto3" json:"custom_bytes_4,omitempty"` - CustomBytes_5 []byte `protobuf:"bytes,1015,opt,name=custom_bytes_5,json=customBytes5,proto3" json:"custom_bytes_5,omitempty"` - CustomList_1 []uint32 `protobuf:"varint,1021,rep,packed,name=custom_list_1,json=customList1,proto3" json:"custom_list_1,omitempty"` -} - -func (x *FlowMessage) Reset() { - *x = FlowMessage{} - if protoimpl.UnsafeEnabled { - mi := &file_pb_flow_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *FlowMessage) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*FlowMessage) ProtoMessage() {} - -func (x *FlowMessage) ProtoReflect() protoreflect.Message { - mi := &file_pb_flow_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use FlowMessage.ProtoReflect.Descriptor instead. -func (*FlowMessage) Descriptor() ([]byte, []int) { - return file_pb_flow_proto_rawDescGZIP(), []int{0} -} - -func (x *FlowMessage) GetType() FlowMessage_FlowType { - if x != nil { - return x.Type - } - return FlowMessage_FLOWUNKNOWN -} - -func (x *FlowMessage) GetTimeReceived() uint64 { - if x != nil { - return x.TimeReceived - } - return 0 -} - -func (x *FlowMessage) GetSequenceNum() uint32 { - if x != nil { - return x.SequenceNum - } - return 0 -} - -func (x *FlowMessage) GetSamplingRate() uint64 { - if x != nil { - return x.SamplingRate - } - return 0 -} - -func (x *FlowMessage) GetFlowDirection() uint32 { - if x != nil { - return x.FlowDirection - } - return 0 -} - -func (x *FlowMessage) GetSamplerAddress() []byte { - if x != nil { - return x.SamplerAddress - } - return nil -} - -func (x *FlowMessage) GetTimeFlowStart() uint64 { - if x != nil { - return x.TimeFlowStart - } - return 0 -} - -func (x *FlowMessage) GetTimeFlowEnd() uint64 { - if x != nil { - return x.TimeFlowEnd - } - return 0 -} - -func (x *FlowMessage) GetTimeFlowStartMs() uint64 { - if x != nil { - return x.TimeFlowStartMs - } - return 0 -} - -func (x *FlowMessage) GetTimeFlowEndMs() uint64 { - if x != nil { - return x.TimeFlowEndMs - } - return 0 -} - -func (x *FlowMessage) GetBytes() uint64 { - if x != nil { - return x.Bytes - } - return 0 -} - -func (x *FlowMessage) GetPackets() uint64 { - if x != nil { - return x.Packets - } - return 0 -} - -func (x *FlowMessage) GetSrcAddr() []byte { - if x != nil { - return x.SrcAddr - } - return nil -} - -func (x *FlowMessage) GetDstAddr() []byte { - if x != nil { - return x.DstAddr - } - return nil -} - -func (x *FlowMessage) GetEtype() uint32 { - if x != nil { - return x.Etype - } - return 0 -} - -func (x *FlowMessage) GetProto() uint32 { - if x != nil { - return x.Proto - } - return 0 -} - -func (x *FlowMessage) GetSrcPort() uint32 { - if x != nil { - return x.SrcPort - } - return 0 -} - -func (x *FlowMessage) GetDstPort() uint32 { - if x != nil { - return x.DstPort - } - return 0 -} - -func (x *FlowMessage) GetInIf() uint32 { - if x != nil { - return x.InIf - } - return 0 -} - -func (x *FlowMessage) GetOutIf() uint32 { - if x != nil { - return x.OutIf - } - return 0 -} - -func (x *FlowMessage) GetSrcMac() uint64 { - if x != nil { - return x.SrcMac - } - return 0 -} - -func (x *FlowMessage) GetDstMac() uint64 { - if x != nil { - return x.DstMac - } - return 0 -} - -func (x *FlowMessage) GetSrcVlan() uint32 { - if x != nil { - return x.SrcVlan - } - return 0 -} - -func (x *FlowMessage) GetDstVlan() uint32 { - if x != nil { - return x.DstVlan - } - return 0 -} - -func (x *FlowMessage) GetVlanId() uint32 { - if x != nil { - return x.VlanId - } - return 0 -} - -func (x *FlowMessage) GetIngressVrfId() uint32 { - if x != nil { - return x.IngressVrfId - } - return 0 -} - -func (x *FlowMessage) GetEgressVrfId() uint32 { - if x != nil { - return x.EgressVrfId - } - return 0 -} - -func (x *FlowMessage) GetIpTos() uint32 { - if x != nil { - return x.IpTos - } - return 0 -} - -func (x *FlowMessage) GetForwardingStatus() uint32 { - if x != nil { - return x.ForwardingStatus - } - return 0 -} - -func (x *FlowMessage) GetIpTtl() uint32 { - if x != nil { - return x.IpTtl - } - return 0 -} - -func (x *FlowMessage) GetTcpFlags() uint32 { - if x != nil { - return x.TcpFlags - } - return 0 -} - -func (x *FlowMessage) GetIcmpType() uint32 { - if x != nil { - return x.IcmpType - } - return 0 -} - -func (x *FlowMessage) GetIcmpCode() uint32 { - if x != nil { - return x.IcmpCode - } - return 0 -} - -func (x *FlowMessage) GetIpv6FlowLabel() uint32 { - if x != nil { - return x.Ipv6FlowLabel - } - return 0 -} - -func (x *FlowMessage) GetFragmentId() uint32 { - if x != nil { - return x.FragmentId - } - return 0 -} - -func (x *FlowMessage) GetFragmentOffset() uint32 { - if x != nil { - return x.FragmentOffset - } - return 0 -} - -func (x *FlowMessage) GetBiFlowDirection() uint32 { - if x != nil { - return x.BiFlowDirection - } - return 0 -} - -func (x *FlowMessage) GetSrcAs() uint32 { - if x != nil { - return x.SrcAs - } - return 0 -} - -func (x *FlowMessage) GetDstAs() uint32 { - if x != nil { - return x.DstAs - } - return 0 -} - -func (x *FlowMessage) GetNextHop() []byte { - if x != nil { - return x.NextHop - } - return nil -} - -func (x *FlowMessage) GetNextHopAs() uint32 { - if x != nil { - return x.NextHopAs - } - return 0 -} - -func (x *FlowMessage) GetSrcNet() uint32 { - if x != nil { - return x.SrcNet - } - return 0 -} - -func (x *FlowMessage) GetDstNet() uint32 { - if x != nil { - return x.DstNet - } - return 0 -} - -func (x *FlowMessage) GetBgpNextHop() []byte { - if x != nil { - return x.BgpNextHop - } - return nil -} - -func (x *FlowMessage) GetBgpCommunities() []uint32 { - if x != nil { - return x.BgpCommunities - } - return nil -} - -func (x *FlowMessage) GetAsPath() []uint32 { - if x != nil { - return x.AsPath - } - return nil -} - -func (x *FlowMessage) GetHasMpls() bool { - if x != nil { - return x.HasMpls - } - return false -} - -func (x *FlowMessage) GetMplsCount() uint32 { - if x != nil { - return x.MplsCount - } - return 0 -} - -func (x *FlowMessage) GetMpls_1Ttl() uint32 { - if x != nil { - return x.Mpls_1Ttl - } - return 0 -} - -func (x *FlowMessage) GetMpls_1Label() uint32 { - if x != nil { - return x.Mpls_1Label - } - return 0 -} - -func (x *FlowMessage) GetMpls_2Ttl() uint32 { - if x != nil { - return x.Mpls_2Ttl - } - return 0 -} - -func (x *FlowMessage) GetMpls_2Label() uint32 { - if x != nil { - return x.Mpls_2Label - } - return 0 -} - -func (x *FlowMessage) GetMpls_3Ttl() uint32 { - if x != nil { - return x.Mpls_3Ttl - } - return 0 -} - -func (x *FlowMessage) GetMpls_3Label() uint32 { - if x != nil { - return x.Mpls_3Label - } - return 0 -} - -func (x *FlowMessage) GetMplsLastTtl() uint32 { - if x != nil { - return x.MplsLastTtl - } - return 0 -} - -func (x *FlowMessage) GetMplsLastLabel() uint32 { - if x != nil { - return x.MplsLastLabel - } - return 0 -} - -func (x *FlowMessage) GetMplsLabelIp() []byte { - if x != nil { - return x.MplsLabelIp - } - return nil -} - -func (x *FlowMessage) GetObservationDomainId() uint32 { - if x != nil { - return x.ObservationDomainId - } - return 0 -} - -func (x *FlowMessage) GetObservationPointId() uint32 { - if x != nil { - return x.ObservationPointId - } - return 0 -} - -func (x *FlowMessage) GetCustomInteger_1() uint64 { - if x != nil { - return x.CustomInteger_1 - } - return 0 -} - -func (x *FlowMessage) GetCustomInteger_2() uint64 { - if x != nil { - return x.CustomInteger_2 - } - return 0 -} - -func (x *FlowMessage) GetCustomInteger_3() uint64 { - if x != nil { - return x.CustomInteger_3 - } - return 0 -} - -func (x *FlowMessage) GetCustomInteger_4() uint64 { - if x != nil { - return x.CustomInteger_4 - } - return 0 -} - -func (x *FlowMessage) GetCustomInteger_5() uint64 { - if x != nil { - return x.CustomInteger_5 - } - return 0 -} - -func (x *FlowMessage) GetCustomBytes_1() []byte { - if x != nil { - return x.CustomBytes_1 - } - return nil -} - -func (x *FlowMessage) GetCustomBytes_2() []byte { - if x != nil { - return x.CustomBytes_2 - } - return nil -} - -func (x *FlowMessage) GetCustomBytes_3() []byte { - if x != nil { - return x.CustomBytes_3 - } - return nil -} - -func (x *FlowMessage) GetCustomBytes_4() []byte { - if x != nil { - return x.CustomBytes_4 - } - return nil -} - -func (x *FlowMessage) GetCustomBytes_5() []byte { - if x != nil { - return x.CustomBytes_5 - } - return nil -} - -func (x *FlowMessage) GetCustomList_1() []uint32 { - if x != nil { - return x.CustomList_1 - } - return nil -} - -var File_pb_flow_proto protoreflect.FileDescriptor - -var file_pb_flow_proto_rawDesc = []byte{ - 0x0a, 0x0d, 0x70, 0x62, 0x2f, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, - 0x06, 0x66, 0x6c, 0x6f, 0x77, 0x70, 0x62, 0x22, 0x90, 0x13, 0x0a, 0x0b, 0x46, 0x6c, 0x6f, 0x77, - 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x30, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1c, 0x2e, 0x66, 0x6c, 0x6f, 0x77, 0x70, 0x62, 0x2e, 0x46, - 0x6c, 0x6f, 0x77, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x2e, 0x46, 0x6c, 0x6f, 0x77, 0x54, - 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x74, 0x69, 0x6d, - 0x65, 0x5f, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, - 0x52, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x12, 0x21, - 0x0a, 0x0c, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, 0x65, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x04, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0b, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63, 0x65, 0x4e, 0x75, - 0x6d, 0x12, 0x23, 0x0a, 0x0d, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x69, 0x6e, 0x67, 0x5f, 0x72, 0x61, - 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0c, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x69, - 0x6e, 0x67, 0x52, 0x61, 0x74, 0x65, 0x12, 0x25, 0x0a, 0x0e, 0x66, 0x6c, 0x6f, 0x77, 0x5f, 0x64, - 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x2a, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0d, - 0x66, 0x6c, 0x6f, 0x77, 0x44, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x27, 0x0a, - 0x0f, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, - 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x41, - 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x26, 0x0a, 0x0f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x66, - 0x6c, 0x6f, 0x77, 0x5f, 0x73, 0x74, 0x61, 0x72, 0x74, 0x18, 0x26, 0x20, 0x01, 0x28, 0x04, 0x52, - 0x0d, 0x74, 0x69, 0x6d, 0x65, 0x46, 0x6c, 0x6f, 0x77, 0x53, 0x74, 0x61, 0x72, 0x74, 0x12, 0x22, - 0x0a, 0x0d, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x66, 0x6c, 0x6f, 0x77, 0x5f, 0x65, 0x6e, 0x64, 0x18, - 0x05, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0b, 0x74, 0x69, 0x6d, 0x65, 0x46, 0x6c, 0x6f, 0x77, 0x45, - 0x6e, 0x64, 0x12, 0x2b, 0x0a, 0x12, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x66, 0x6c, 0x6f, 0x77, 0x5f, - 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x6d, 0x73, 0x18, 0x3f, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, - 0x74, 0x69, 0x6d, 0x65, 0x46, 0x6c, 0x6f, 0x77, 0x53, 0x74, 0x61, 0x72, 0x74, 0x4d, 0x73, 0x12, - 0x27, 0x0a, 0x10, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x66, 0x6c, 0x6f, 0x77, 0x5f, 0x65, 0x6e, 0x64, - 0x5f, 0x6d, 0x73, 0x18, 0x40, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0d, 0x74, 0x69, 0x6d, 0x65, 0x46, - 0x6c, 0x6f, 0x77, 0x45, 0x6e, 0x64, 0x4d, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, - 0x73, 0x18, 0x09, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x18, - 0x0a, 0x07, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x04, 0x52, - 0x07, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x73, 0x72, 0x63, 0x5f, - 0x61, 0x64, 0x64, 0x72, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x73, 0x72, 0x63, 0x41, - 0x64, 0x64, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x64, 0x73, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, - 0x07, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x64, 0x73, 0x74, 0x41, 0x64, 0x64, 0x72, 0x12, 0x14, - 0x0a, 0x05, 0x65, 0x74, 0x79, 0x70, 0x65, 0x18, 0x1e, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x65, - 0x74, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x18, 0x14, 0x20, - 0x01, 0x28, 0x0d, 0x52, 0x05, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x19, 0x0a, 0x08, 0x73, 0x72, - 0x63, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x15, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x73, 0x72, - 0x63, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x64, 0x73, 0x74, 0x5f, 0x70, 0x6f, 0x72, - 0x74, 0x18, 0x16, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x64, 0x73, 0x74, 0x50, 0x6f, 0x72, 0x74, - 0x12, 0x13, 0x0a, 0x05, 0x69, 0x6e, 0x5f, 0x69, 0x66, 0x18, 0x12, 0x20, 0x01, 0x28, 0x0d, 0x52, - 0x04, 0x69, 0x6e, 0x49, 0x66, 0x12, 0x15, 0x0a, 0x06, 0x6f, 0x75, 0x74, 0x5f, 0x69, 0x66, 0x18, - 0x13, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6f, 0x75, 0x74, 0x49, 0x66, 0x12, 0x17, 0x0a, 0x07, - 0x73, 0x72, 0x63, 0x5f, 0x6d, 0x61, 0x63, 0x18, 0x1b, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x73, - 0x72, 0x63, 0x4d, 0x61, 0x63, 0x12, 0x17, 0x0a, 0x07, 0x64, 0x73, 0x74, 0x5f, 0x6d, 0x61, 0x63, - 0x18, 0x1c, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x64, 0x73, 0x74, 0x4d, 0x61, 0x63, 0x12, 0x19, - 0x0a, 0x08, 0x73, 0x72, 0x63, 0x5f, 0x76, 0x6c, 0x61, 0x6e, 0x18, 0x21, 0x20, 0x01, 0x28, 0x0d, - 0x52, 0x07, 0x73, 0x72, 0x63, 0x56, 0x6c, 0x61, 0x6e, 0x12, 0x19, 0x0a, 0x08, 0x64, 0x73, 0x74, - 0x5f, 0x76, 0x6c, 0x61, 0x6e, 0x18, 0x22, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x64, 0x73, 0x74, - 0x56, 0x6c, 0x61, 0x6e, 0x12, 0x17, 0x0a, 0x07, 0x76, 0x6c, 0x61, 0x6e, 0x5f, 0x69, 0x64, 0x18, - 0x1d, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x76, 0x6c, 0x61, 0x6e, 0x49, 0x64, 0x12, 0x24, 0x0a, - 0x0e, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x76, 0x72, 0x66, 0x5f, 0x69, 0x64, 0x18, - 0x27, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0c, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x73, 0x73, 0x56, 0x72, - 0x66, 0x49, 0x64, 0x12, 0x22, 0x0a, 0x0d, 0x65, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x76, 0x72, - 0x66, 0x5f, 0x69, 0x64, 0x18, 0x28, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0b, 0x65, 0x67, 0x72, 0x65, - 0x73, 0x73, 0x56, 0x72, 0x66, 0x49, 0x64, 0x12, 0x15, 0x0a, 0x06, 0x69, 0x70, 0x5f, 0x74, 0x6f, - 0x73, 0x18, 0x17, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x69, 0x70, 0x54, 0x6f, 0x73, 0x12, 0x2b, - 0x0a, 0x11, 0x66, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x69, 0x6e, 0x67, 0x5f, 0x73, 0x74, 0x61, - 0x74, 0x75, 0x73, 0x18, 0x18, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x10, 0x66, 0x6f, 0x72, 0x77, 0x61, - 0x72, 0x64, 0x69, 0x6e, 0x67, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x15, 0x0a, 0x06, 0x69, - 0x70, 0x5f, 0x74, 0x74, 0x6c, 0x18, 0x19, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x69, 0x70, 0x54, - 0x74, 0x6c, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x63, 0x70, 0x5f, 0x66, 0x6c, 0x61, 0x67, 0x73, 0x18, - 0x1a, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x08, 0x74, 0x63, 0x70, 0x46, 0x6c, 0x61, 0x67, 0x73, 0x12, - 0x1b, 0x0a, 0x09, 0x69, 0x63, 0x6d, 0x70, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x1f, 0x20, 0x01, - 0x28, 0x0d, 0x52, 0x08, 0x69, 0x63, 0x6d, 0x70, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1b, 0x0a, 0x09, - 0x69, 0x63, 0x6d, 0x70, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x20, 0x20, 0x01, 0x28, 0x0d, 0x52, - 0x08, 0x69, 0x63, 0x6d, 0x70, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x26, 0x0a, 0x0f, 0x69, 0x70, 0x76, - 0x36, 0x5f, 0x66, 0x6c, 0x6f, 0x77, 0x5f, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x25, 0x20, 0x01, - 0x28, 0x0d, 0x52, 0x0d, 0x69, 0x70, 0x76, 0x36, 0x46, 0x6c, 0x6f, 0x77, 0x4c, 0x61, 0x62, 0x65, - 0x6c, 0x12, 0x1f, 0x0a, 0x0b, 0x66, 0x72, 0x61, 0x67, 0x6d, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, - 0x18, 0x23, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x66, 0x72, 0x61, 0x67, 0x6d, 0x65, 0x6e, 0x74, - 0x49, 0x64, 0x12, 0x27, 0x0a, 0x0f, 0x66, 0x72, 0x61, 0x67, 0x6d, 0x65, 0x6e, 0x74, 0x5f, 0x6f, - 0x66, 0x66, 0x73, 0x65, 0x74, 0x18, 0x24, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0e, 0x66, 0x72, 0x61, - 0x67, 0x6d, 0x65, 0x6e, 0x74, 0x4f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x12, 0x2a, 0x0a, 0x11, 0x62, - 0x69, 0x5f, 0x66, 0x6c, 0x6f, 0x77, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, - 0x18, 0x29, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0f, 0x62, 0x69, 0x46, 0x6c, 0x6f, 0x77, 0x44, 0x69, - 0x72, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x15, 0x0a, 0x06, 0x73, 0x72, 0x63, 0x5f, 0x61, - 0x73, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x73, 0x72, 0x63, 0x41, 0x73, 0x12, 0x15, - 0x0a, 0x06, 0x64, 0x73, 0x74, 0x5f, 0x61, 0x73, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, - 0x64, 0x73, 0x74, 0x41, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x68, 0x6f, - 0x70, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x6e, 0x65, 0x78, 0x74, 0x48, 0x6f, 0x70, - 0x12, 0x1e, 0x0a, 0x0b, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x68, 0x6f, 0x70, 0x5f, 0x61, 0x73, 0x18, - 0x0d, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x6e, 0x65, 0x78, 0x74, 0x48, 0x6f, 0x70, 0x41, 0x73, - 0x12, 0x17, 0x0a, 0x07, 0x73, 0x72, 0x63, 0x5f, 0x6e, 0x65, 0x74, 0x18, 0x10, 0x20, 0x01, 0x28, - 0x0d, 0x52, 0x06, 0x73, 0x72, 0x63, 0x4e, 0x65, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x64, 0x73, 0x74, - 0x5f, 0x6e, 0x65, 0x74, 0x18, 0x11, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x64, 0x73, 0x74, 0x4e, - 0x65, 0x74, 0x12, 0x20, 0x0a, 0x0c, 0x62, 0x67, 0x70, 0x5f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x68, - 0x6f, 0x70, 0x18, 0x64, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x62, 0x67, 0x70, 0x4e, 0x65, 0x78, - 0x74, 0x48, 0x6f, 0x70, 0x12, 0x27, 0x0a, 0x0f, 0x62, 0x67, 0x70, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, - 0x75, 0x6e, 0x69, 0x74, 0x69, 0x65, 0x73, 0x18, 0x65, 0x20, 0x03, 0x28, 0x0d, 0x52, 0x0e, 0x62, - 0x67, 0x70, 0x43, 0x6f, 0x6d, 0x6d, 0x75, 0x6e, 0x69, 0x74, 0x69, 0x65, 0x73, 0x12, 0x17, 0x0a, - 0x07, 0x61, 0x73, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, 0x66, 0x20, 0x03, 0x28, 0x0d, 0x52, 0x06, - 0x61, 0x73, 0x50, 0x61, 0x74, 0x68, 0x12, 0x19, 0x0a, 0x08, 0x68, 0x61, 0x73, 0x5f, 0x6d, 0x70, - 0x6c, 0x73, 0x18, 0x35, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x68, 0x61, 0x73, 0x4d, 0x70, 0x6c, - 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x6d, 0x70, 0x6c, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, - 0x36, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x6d, 0x70, 0x6c, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, - 0x12, 0x1c, 0x0a, 0x0a, 0x6d, 0x70, 0x6c, 0x73, 0x5f, 0x31, 0x5f, 0x74, 0x74, 0x6c, 0x18, 0x37, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x08, 0x6d, 0x70, 0x6c, 0x73, 0x31, 0x54, 0x74, 0x6c, 0x12, 0x20, - 0x0a, 0x0c, 0x6d, 0x70, 0x6c, 0x73, 0x5f, 0x31, 0x5f, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x38, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x6d, 0x70, 0x6c, 0x73, 0x31, 0x4c, 0x61, 0x62, 0x65, 0x6c, - 0x12, 0x1c, 0x0a, 0x0a, 0x6d, 0x70, 0x6c, 0x73, 0x5f, 0x32, 0x5f, 0x74, 0x74, 0x6c, 0x18, 0x39, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x08, 0x6d, 0x70, 0x6c, 0x73, 0x32, 0x54, 0x74, 0x6c, 0x12, 0x20, - 0x0a, 0x0c, 0x6d, 0x70, 0x6c, 0x73, 0x5f, 0x32, 0x5f, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x3a, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x6d, 0x70, 0x6c, 0x73, 0x32, 0x4c, 0x61, 0x62, 0x65, 0x6c, - 0x12, 0x1c, 0x0a, 0x0a, 0x6d, 0x70, 0x6c, 0x73, 0x5f, 0x33, 0x5f, 0x74, 0x74, 0x6c, 0x18, 0x3b, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x08, 0x6d, 0x70, 0x6c, 0x73, 0x33, 0x54, 0x74, 0x6c, 0x12, 0x20, - 0x0a, 0x0c, 0x6d, 0x70, 0x6c, 0x73, 0x5f, 0x33, 0x5f, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x3c, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0a, 0x6d, 0x70, 0x6c, 0x73, 0x33, 0x4c, 0x61, 0x62, 0x65, 0x6c, - 0x12, 0x22, 0x0a, 0x0d, 0x6d, 0x70, 0x6c, 0x73, 0x5f, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x74, 0x74, - 0x6c, 0x18, 0x3d, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0b, 0x6d, 0x70, 0x6c, 0x73, 0x4c, 0x61, 0x73, - 0x74, 0x54, 0x74, 0x6c, 0x12, 0x26, 0x0a, 0x0f, 0x6d, 0x70, 0x6c, 0x73, 0x5f, 0x6c, 0x61, 0x73, - 0x74, 0x5f, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x3e, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x0d, 0x6d, - 0x70, 0x6c, 0x73, 0x4c, 0x61, 0x73, 0x74, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x12, 0x22, 0x0a, 0x0d, - 0x6d, 0x70, 0x6c, 0x73, 0x5f, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x5f, 0x69, 0x70, 0x18, 0x41, 0x20, - 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x6d, 0x70, 0x6c, 0x73, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x49, 0x70, - 0x12, 0x32, 0x0a, 0x15, 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, - 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x46, 0x20, 0x01, 0x28, 0x0d, 0x52, - 0x13, 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x6f, 0x6d, 0x61, - 0x69, 0x6e, 0x49, 0x64, 0x12, 0x30, 0x0a, 0x14, 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x5f, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x47, 0x20, 0x01, - 0x28, 0x0d, 0x52, 0x12, 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, - 0x6f, 0x69, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, - 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x5f, 0x31, 0x18, 0xe9, 0x07, 0x20, 0x01, 0x28, - 0x04, 0x52, 0x0e, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x49, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, - 0x31, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x69, 0x6e, 0x74, 0x65, - 0x67, 0x65, 0x72, 0x5f, 0x32, 0x18, 0xea, 0x07, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0e, 0x63, 0x75, - 0x73, 0x74, 0x6f, 0x6d, 0x49, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x32, 0x12, 0x29, 0x0a, 0x10, - 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x5f, 0x33, - 0x18, 0xeb, 0x07, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0e, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x49, - 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x33, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x75, 0x73, 0x74, 0x6f, - 0x6d, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x5f, 0x34, 0x18, 0xec, 0x07, 0x20, 0x01, - 0x28, 0x04, 0x52, 0x0e, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x49, 0x6e, 0x74, 0x65, 0x67, 0x65, - 0x72, 0x34, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x69, 0x6e, 0x74, - 0x65, 0x67, 0x65, 0x72, 0x5f, 0x35, 0x18, 0xed, 0x07, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0e, 0x63, - 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x49, 0x6e, 0x74, 0x65, 0x67, 0x65, 0x72, 0x35, 0x12, 0x25, 0x0a, - 0x0e, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x5f, 0x31, 0x18, - 0xf3, 0x07, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x42, 0x79, - 0x74, 0x65, 0x73, 0x31, 0x12, 0x25, 0x0a, 0x0e, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x62, - 0x79, 0x74, 0x65, 0x73, 0x5f, 0x32, 0x18, 0xf4, 0x07, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x63, - 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x42, 0x79, 0x74, 0x65, 0x73, 0x32, 0x12, 0x25, 0x0a, 0x0e, 0x63, - 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x5f, 0x33, 0x18, 0xf5, 0x07, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x42, 0x79, 0x74, 0x65, - 0x73, 0x33, 0x12, 0x25, 0x0a, 0x0e, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x62, 0x79, 0x74, - 0x65, 0x73, 0x5f, 0x34, 0x18, 0xf6, 0x07, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x63, 0x75, 0x73, - 0x74, 0x6f, 0x6d, 0x42, 0x79, 0x74, 0x65, 0x73, 0x34, 0x12, 0x25, 0x0a, 0x0e, 0x63, 0x75, 0x73, - 0x74, 0x6f, 0x6d, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x5f, 0x35, 0x18, 0xf7, 0x07, 0x20, 0x01, - 0x28, 0x0c, 0x52, 0x0c, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x42, 0x79, 0x74, 0x65, 0x73, 0x35, - 0x12, 0x23, 0x0a, 0x0d, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, - 0x31, 0x18, 0xfd, 0x07, 0x20, 0x03, 0x28, 0x0d, 0x52, 0x0b, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, - 0x4c, 0x69, 0x73, 0x74, 0x31, 0x22, 0x53, 0x0a, 0x08, 0x46, 0x6c, 0x6f, 0x77, 0x54, 0x79, 0x70, - 0x65, 0x12, 0x0f, 0x0a, 0x0b, 0x46, 0x4c, 0x4f, 0x57, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, - 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x46, 0x4c, 0x4f, 0x57, 0x5f, 0x35, 0x10, 0x01, 0x12, - 0x0e, 0x0a, 0x0a, 0x4e, 0x45, 0x54, 0x46, 0x4c, 0x4f, 0x57, 0x5f, 0x56, 0x35, 0x10, 0x02, 0x12, - 0x0e, 0x0a, 0x0a, 0x4e, 0x45, 0x54, 0x46, 0x4c, 0x4f, 0x57, 0x5f, 0x56, 0x39, 0x10, 0x03, 0x12, - 0x09, 0x0a, 0x05, 0x49, 0x50, 0x46, 0x49, 0x58, 0x10, 0x04, 0x42, 0x29, 0x5a, 0x27, 0x67, 0x69, - 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6e, 0x65, 0x74, 0x73, 0x61, 0x6d, 0x70, - 0x6c, 0x65, 0x72, 0x2f, 0x67, 0x6f, 0x66, 0x6c, 0x6f, 0x77, 0x32, 0x2f, 0x70, 0x62, 0x3b, 0x66, - 0x6c, 0x6f, 0x77, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_pb_flow_proto_rawDescOnce sync.Once - file_pb_flow_proto_rawDescData = file_pb_flow_proto_rawDesc -) - -func file_pb_flow_proto_rawDescGZIP() []byte { - file_pb_flow_proto_rawDescOnce.Do(func() { - file_pb_flow_proto_rawDescData = protoimpl.X.CompressGZIP(file_pb_flow_proto_rawDescData) - }) - return file_pb_flow_proto_rawDescData -} - -var file_pb_flow_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_pb_flow_proto_msgTypes = make([]protoimpl.MessageInfo, 1) -var file_pb_flow_proto_goTypes = []interface{}{ - (FlowMessage_FlowType)(0), // 0: flowpb.FlowMessage.FlowType - (*FlowMessage)(nil), // 1: flowpb.FlowMessage -} -var file_pb_flow_proto_depIdxs = []int32{ - 0, // 0: flowpb.FlowMessage.type:type_name -> flowpb.FlowMessage.FlowType - 1, // [1:1] is the sub-list for method output_type - 1, // [1:1] is the sub-list for method input_type - 1, // [1:1] is the sub-list for extension type_name - 1, // [1:1] is the sub-list for extension extendee - 0, // [0:1] is the sub-list for field type_name -} - -func init() { file_pb_flow_proto_init() } -func file_pb_flow_proto_init() { - if File_pb_flow_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_pb_flow_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*FlowMessage); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_pb_flow_proto_rawDesc, - NumEnums: 1, - NumMessages: 1, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_pb_flow_proto_goTypes, - DependencyIndexes: file_pb_flow_proto_depIdxs, - EnumInfos: file_pb_flow_proto_enumTypes, - MessageInfos: file_pb_flow_proto_msgTypes, - }.Build() - File_pb_flow_proto = out.File - file_pb_flow_proto_rawDesc = nil - file_pb_flow_proto_goTypes = nil - file_pb_flow_proto_depIdxs = nil -} diff --git a/vendor/github.com/netsampler/goflow2/pb/flow.proto b/vendor/github.com/netsampler/goflow2/pb/flow.proto deleted file mode 100644 index 1cbaae8d5..000000000 --- a/vendor/github.com/netsampler/goflow2/pb/flow.proto +++ /dev/null @@ -1,131 +0,0 @@ -syntax = "proto3"; -package flowpb; -option go_package = "github.com/netsampler/goflow2/pb;flowpb"; - -message FlowMessage { - - enum FlowType { - FLOWUNKNOWN = 0; - SFLOW_5 = 1; - NETFLOW_V5 = 2; - NETFLOW_V9 = 3; - IPFIX = 4; - } - FlowType type = 1; - - uint64 time_received = 2; - uint32 sequence_num = 4; - uint64 sampling_rate = 3; - - uint32 flow_direction = 42; - - // Sampler information - bytes sampler_address = 11; - - // Found inside packet - uint64 time_flow_start = 38; - uint64 time_flow_end = 5; - uint64 time_flow_start_ms = 63; - uint64 time_flow_end_ms = 64; - - // Size of the sampled packet - uint64 bytes = 9; - uint64 packets = 10; - - // Source/destination addresses - bytes src_addr = 6; - bytes dst_addr = 7; - - // Layer 3 protocol (IPv4/IPv6/ARP/MPLS...) - uint32 etype = 30; - - // Layer 4 protocol - uint32 proto = 20; - - // Ports for UDP and TCP - uint32 src_port = 21; - uint32 dst_port = 22; - - // Interfaces - uint32 in_if = 18; - uint32 out_if = 19; - - // Ethernet information - uint64 src_mac = 27; - uint64 dst_mac = 28; - - // Vlan - uint32 src_vlan = 33; - uint32 dst_vlan = 34; - // 802.1q VLAN in sampled packet - uint32 vlan_id = 29; - - // VRF - uint32 ingress_vrf_id = 39; - uint32 egress_vrf_id = 40; - - // IP and TCP special flags - uint32 ip_tos = 23; - uint32 forwarding_status = 24; - uint32 ip_ttl = 25; - uint32 tcp_flags = 26; - uint32 icmp_type = 31; - uint32 icmp_code = 32; - uint32 ipv6_flow_label = 37; - // Fragments (IPv4/IPv6) - uint32 fragment_id = 35; - uint32 fragment_offset = 36; - uint32 bi_flow_direction = 41; - - // Autonomous system information - uint32 src_as = 14; - uint32 dst_as = 15; - - bytes next_hop = 12; - uint32 next_hop_as = 13; - - // Prefix size - uint32 src_net = 16; - uint32 dst_net = 17; - - // BGP information - bytes bgp_next_hop = 100; - repeated uint32 bgp_communities = 101; - repeated uint32 as_path = 102; - - // MPLS information - bool has_mpls = 53; - uint32 mpls_count = 54; - uint32 mpls_1_ttl = 55; // First TTL - uint32 mpls_1_label = 56; // First Label - uint32 mpls_2_ttl = 57; // Second TTL - uint32 mpls_2_label = 58; // Second Label - uint32 mpls_3_ttl = 59; // Third TTL - uint32 mpls_3_label = 60; // Third Label - uint32 mpls_last_ttl = 61; // Last TTL - uint32 mpls_last_label = 62; // Last Label - bytes mpls_label_ip = 65; // MPLS TOP Label IP - - uint32 observation_domain_id = 70; - uint32 observation_point_id = 71; - - // Custom fields: start after ID 1000: - // uint32 my_custom_field = 1000; - - - // Custom allocations - uint64 custom_integer_1 = 1001; - uint64 custom_integer_2 = 1002; - uint64 custom_integer_3 = 1003; - uint64 custom_integer_4 = 1004; - uint64 custom_integer_5 = 1005; - - bytes custom_bytes_1 = 1011; - bytes custom_bytes_2 = 1012; - bytes custom_bytes_3 = 1013; - bytes custom_bytes_4 = 1014; - bytes custom_bytes_5 = 1015; - - repeated uint32 custom_list_1 = 1021; - -} diff --git a/vendor/github.com/netsampler/goflow2/producer/producer_nf.go b/vendor/github.com/netsampler/goflow2/producer/producer_nf.go deleted file mode 100644 index d14936553..000000000 --- a/vendor/github.com/netsampler/goflow2/producer/producer_nf.go +++ /dev/null @@ -1,683 +0,0 @@ -package producer - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "net" - "sync" - "time" - - "github.com/netsampler/goflow2/decoders/netflow" - "github.com/netsampler/goflow2/decoders/utils" - flowmessage "github.com/netsampler/goflow2/pb" -) - -type SamplingRateSystem interface { - GetSamplingRate(version uint16, obsDomainId uint32) (uint32, error) - AddSamplingRate(version uint16, obsDomainId uint32, samplingRate uint32) -} - -type basicSamplingRateSystem struct { - sampling map[uint16]map[uint32]uint32 - samplinglock *sync.RWMutex -} - -func CreateSamplingSystem() SamplingRateSystem { - ts := &basicSamplingRateSystem{ - sampling: make(map[uint16]map[uint32]uint32), - samplinglock: &sync.RWMutex{}, - } - return ts -} - -func (s *basicSamplingRateSystem) AddSamplingRate(version uint16, obsDomainId uint32, samplingRate uint32) { - s.samplinglock.Lock() - defer s.samplinglock.Unlock() - _, exists := s.sampling[version] - if exists != true { - s.sampling[version] = make(map[uint32]uint32) - } - s.sampling[version][obsDomainId] = samplingRate -} - -func (s *basicSamplingRateSystem) GetSamplingRate(version uint16, obsDomainId uint32) (uint32, error) { - s.samplinglock.RLock() - defer s.samplinglock.RUnlock() - samplingVersion, okver := s.sampling[version] - if okver { - samplingRate, okid := samplingVersion[obsDomainId] - if okid { - return samplingRate, nil - } - return 0, errors.New("") // TBC - } - return 0, errors.New("") // TBC -} - -type SingleSamplingRateSystem struct { - Sampling uint32 -} - -func (s *SingleSamplingRateSystem) AddSamplingRate(version uint16, obsDomainId uint32, samplingRate uint32) { -} - -func (s *SingleSamplingRateSystem) GetSamplingRate(version uint16, obsDomainId uint32) (uint32, error) { - return s.Sampling, nil -} - -func NetFlowLookFor(dataFields []netflow.DataField, typeId uint16) (bool, interface{}) { - for _, dataField := range dataFields { - if dataField.Type == typeId { - return true, dataField.Value - } - } - return false, nil -} - -func NetFlowPopulate(dataFields []netflow.DataField, typeId uint16, addr interface{}) bool { - exists, value := NetFlowLookFor(dataFields, typeId) - if exists && value != nil { - valueBytes, ok := value.([]byte) - valueReader := bytes.NewBuffer(valueBytes) - if ok { - switch addrt := addr.(type) { - case *(net.IP): - *addrt = valueBytes - case *(time.Time): - t := uint64(0) - utils.BinaryRead(valueReader, binary.BigEndian, &t) - t64 := int64(t / 1000) - *addrt = time.Unix(t64, 0) - default: - utils.BinaryRead(valueReader, binary.BigEndian, addr) - } - } - } - return exists -} - -func WriteUDecoded(o uint64, out interface{}) error { - switch t := out.(type) { - case *byte: - *t = byte(o) - case *uint16: - *t = uint16(o) - case *uint32: - *t = uint32(o) - case *uint64: - *t = o - default: - return errors.New("The parameter is not a pointer to a byte/uint16/uint32/uint64 structure") - } - return nil -} - -func WriteDecoded(o int64, out interface{}) error { - switch t := out.(type) { - case *int8: - *t = int8(o) - case *int16: - *t = int16(o) - case *int32: - *t = int32(o) - case *int64: - *t = o - default: - return errors.New("The parameter is not a pointer to a int8/int16/int32/int64 structure") - } - return nil -} - -func DecodeUNumber(b []byte, out interface{}) error { - var o uint64 - l := len(b) - switch l { - case 1: - o = uint64(b[0]) - case 2: - o = uint64(binary.BigEndian.Uint16(b)) - case 4: - o = uint64(binary.BigEndian.Uint32(b)) - case 8: - o = binary.BigEndian.Uint64(b) - default: - if l < 8 { - var iter uint - for i := range b { - o |= uint64(b[i]) << uint(8*(uint(l)-iter-1)) - iter++ - } - } else { - return errors.New(fmt.Sprintf("Non-regular number of bytes for a number: %v", l)) - } - } - return WriteUDecoded(o, out) -} - -func DecodeUNumberLE(b []byte, out interface{}) error { - var o uint64 - l := len(b) - switch l { - case 1: - o = uint64(b[0]) - case 2: - o = uint64(binary.LittleEndian.Uint16(b)) - case 4: - o = uint64(binary.LittleEndian.Uint32(b)) - case 8: - o = binary.LittleEndian.Uint64(b) - default: - if l < 8 { - var iter uint - for i := range b { - o |= uint64(b[i]) << uint(8*(iter)) - iter++ - } - } else { - return errors.New(fmt.Sprintf("Non-regular number of bytes for a number: %v", l)) - } - } - return WriteUDecoded(o, out) -} - -func DecodeNumber(b []byte, out interface{}) error { - var o int64 - l := len(b) - switch l { - case 1: - o = int64(int8(b[0])) - case 2: - o = int64(int16(binary.BigEndian.Uint16(b))) - case 4: - o = int64(int32(binary.BigEndian.Uint32(b))) - case 8: - o = int64(binary.BigEndian.Uint64(b)) - default: - if l < 8 { - var iter int - for i := range b { - o |= int64(b[i]) << int(8*(int(l)-iter-1)) - iter++ - } - } else { - return errors.New(fmt.Sprintf("Non-regular number of bytes for a number: %v", l)) - } - } - return WriteDecoded(o, out) -} - -func DecodeNumberLE(b []byte, out interface{}) error { - var o int64 - l := len(b) - switch l { - case 1: - o = int64(int8(b[0])) - case 2: - o = int64(int16(binary.LittleEndian.Uint16(b))) - case 4: - o = int64(int32(binary.LittleEndian.Uint32(b))) - case 8: - o = int64(binary.LittleEndian.Uint64(b)) - default: - if l < 8 { - var iter int - for i := range b { - o |= int64(b[i]) << int(8*(iter)) - iter++ - } - } else { - return errors.New(fmt.Sprintf("Non-regular number of bytes for a number: %v", l)) - } - } - return WriteDecoded(o, out) -} - -func allZeroes(v []byte) bool { - for _, b := range v { - if b != 0 { - return false - } - } - return true -} - -func addrReplaceCheck(dstAddr *[]byte, v []byte, eType *uint32, ipv6 bool) { - if (len(*dstAddr) == 0 && len(v) > 0) || - (len(*dstAddr) != 0 && len(v) > 0 && !allZeroes(v)) { - *dstAddr = v - - if ipv6 { - *eType = 0x86dd - } else { - *eType = 0x800 - } - - } -} - -func ConvertNetFlowDataSet(version uint16, baseTime uint32, uptime uint32, record []netflow.DataField, mapperNetFlow *NetFlowMapper, mapperSFlow *SFlowMapper) *flowmessage.FlowMessage { - flowMessage := &flowmessage.FlowMessage{} - var time uint64 - - if version == 9 { - flowMessage.Type = flowmessage.FlowMessage_NETFLOW_V9 - } else if version == 10 { - flowMessage.Type = flowmessage.FlowMessage_IPFIX - } - - for i := range record { - df := record[i] - - v, ok := df.Value.([]byte) - if !ok { - continue - } - - MapCustomNetFlow(flowMessage, df, mapperNetFlow) - - if df.PenProvided { - continue - } - - switch df.Type { - - case netflow.IPFIX_FIELD_observationPointId: - DecodeUNumber(v, &(flowMessage.ObservationPointId)) - - // Statistics - case netflow.NFV9_FIELD_IN_BYTES: - DecodeUNumber(v, &(flowMessage.Bytes)) - case netflow.NFV9_FIELD_IN_PKTS: - DecodeUNumber(v, &(flowMessage.Packets)) - case netflow.NFV9_FIELD_OUT_BYTES: - DecodeUNumber(v, &(flowMessage.Bytes)) - case netflow.NFV9_FIELD_OUT_PKTS: - DecodeUNumber(v, &(flowMessage.Packets)) - - // L4 - case netflow.NFV9_FIELD_L4_SRC_PORT: - DecodeUNumber(v, &(flowMessage.SrcPort)) - case netflow.NFV9_FIELD_L4_DST_PORT: - DecodeUNumber(v, &(flowMessage.DstPort)) - case netflow.NFV9_FIELD_PROTOCOL: - DecodeUNumber(v, &(flowMessage.Proto)) - - // Network - case netflow.NFV9_FIELD_SRC_AS: - DecodeUNumber(v, &(flowMessage.SrcAs)) - case netflow.NFV9_FIELD_DST_AS: - DecodeUNumber(v, &(flowMessage.DstAs)) - - // Interfaces - case netflow.NFV9_FIELD_INPUT_SNMP: - DecodeUNumber(v, &(flowMessage.InIf)) - case netflow.NFV9_FIELD_OUTPUT_SNMP: - DecodeUNumber(v, &(flowMessage.OutIf)) - - case netflow.NFV9_FIELD_FORWARDING_STATUS: - DecodeUNumber(v, &(flowMessage.ForwardingStatus)) - case netflow.NFV9_FIELD_SRC_TOS: - DecodeUNumber(v, &(flowMessage.IpTos)) - case netflow.NFV9_FIELD_TCP_FLAGS: - DecodeUNumber(v, &(flowMessage.TcpFlags)) - case netflow.NFV9_FIELD_MIN_TTL: - DecodeUNumber(v, &(flowMessage.IpTtl)) - - // IP - case netflow.NFV9_FIELD_IP_PROTOCOL_VERSION: - if len(v) > 0 { - if v[0] == 4 { - flowMessage.Etype = 0x800 - } else if v[0] == 6 { - flowMessage.Etype = 0x86dd - } - } - - case netflow.NFV9_FIELD_IPV4_SRC_ADDR: - addrReplaceCheck(&(flowMessage.SrcAddr), v, &(flowMessage.Etype), false) - - case netflow.NFV9_FIELD_IPV4_DST_ADDR: - addrReplaceCheck(&(flowMessage.DstAddr), v, &(flowMessage.Etype), false) - - case netflow.NFV9_FIELD_SRC_MASK: - DecodeUNumber(v, &(flowMessage.SrcNet)) - case netflow.NFV9_FIELD_DST_MASK: - DecodeUNumber(v, &(flowMessage.DstNet)) - - case netflow.NFV9_FIELD_IPV6_SRC_ADDR: - addrReplaceCheck(&(flowMessage.SrcAddr), v, &(flowMessage.Etype), true) - - case netflow.NFV9_FIELD_IPV6_DST_ADDR: - addrReplaceCheck(&(flowMessage.DstAddr), v, &(flowMessage.Etype), true) - - case netflow.NFV9_FIELD_IPV6_SRC_MASK: - DecodeUNumber(v, &(flowMessage.SrcNet)) - case netflow.NFV9_FIELD_IPV6_DST_MASK: - DecodeUNumber(v, &(flowMessage.DstNet)) - - case netflow.NFV9_FIELD_IPV4_NEXT_HOP: - flowMessage.NextHop = v - case netflow.NFV9_FIELD_BGP_IPV4_NEXT_HOP: - flowMessage.BgpNextHop = v - - case netflow.NFV9_FIELD_IPV6_NEXT_HOP: - flowMessage.NextHop = v - case netflow.NFV9_FIELD_BGP_IPV6_NEXT_HOP: - flowMessage.BgpNextHop = v - - // ICMP - case netflow.NFV9_FIELD_ICMP_TYPE: - var icmpTypeCode uint16 - DecodeUNumber(v, &icmpTypeCode) - flowMessage.IcmpType = uint32(icmpTypeCode >> 8) - flowMessage.IcmpCode = uint32(icmpTypeCode & 0xff) - case netflow.IPFIX_FIELD_icmpTypeCodeIPv6: - var icmpTypeCode uint16 - DecodeUNumber(v, &icmpTypeCode) - flowMessage.IcmpType = uint32(icmpTypeCode >> 8) - flowMessage.IcmpCode = uint32(icmpTypeCode & 0xff) - case netflow.IPFIX_FIELD_icmpTypeIPv4: - DecodeUNumber(v, &(flowMessage.IcmpType)) - case netflow.IPFIX_FIELD_icmpTypeIPv6: - DecodeUNumber(v, &(flowMessage.IcmpType)) - case netflow.IPFIX_FIELD_icmpCodeIPv4: - DecodeUNumber(v, &(flowMessage.IcmpCode)) - case netflow.IPFIX_FIELD_icmpCodeIPv6: - DecodeUNumber(v, &(flowMessage.IcmpCode)) - - // Mac - case netflow.NFV9_FIELD_IN_SRC_MAC: - DecodeUNumber(v, &(flowMessage.SrcMac)) - case netflow.NFV9_FIELD_IN_DST_MAC: - DecodeUNumber(v, &(flowMessage.DstMac)) - case netflow.NFV9_FIELD_OUT_SRC_MAC: - DecodeUNumber(v, &(flowMessage.SrcMac)) - case netflow.NFV9_FIELD_OUT_DST_MAC: - DecodeUNumber(v, &(flowMessage.DstMac)) - - case netflow.NFV9_FIELD_SRC_VLAN: - DecodeUNumber(v, &(flowMessage.VlanId)) - DecodeUNumber(v, &(flowMessage.SrcVlan)) - case netflow.NFV9_FIELD_DST_VLAN: - DecodeUNumber(v, &(flowMessage.DstVlan)) - - case netflow.IPFIX_FIELD_ingressVRFID: - DecodeUNumber(v, &(flowMessage.IngressVrfId)) - case netflow.IPFIX_FIELD_egressVRFID: - DecodeUNumber(v, &(flowMessage.EgressVrfId)) - - case netflow.NFV9_FIELD_IPV4_IDENT: - DecodeUNumber(v, &(flowMessage.FragmentId)) - case netflow.NFV9_FIELD_FRAGMENT_OFFSET: - var fragOffset uint32 - DecodeUNumber(v, &fragOffset) - flowMessage.FragmentOffset |= fragOffset - case netflow.IPFIX_FIELD_fragmentFlags: - var ipFlags uint32 - DecodeUNumber(v, &ipFlags) - flowMessage.FragmentOffset |= ipFlags - case netflow.NFV9_FIELD_IPV6_FLOW_LABEL: - DecodeUNumber(v, &(flowMessage.Ipv6FlowLabel)) - - case netflow.IPFIX_FIELD_biflowDirection: - DecodeUNumber(v, &(flowMessage.BiFlowDirection)) - - case netflow.NFV9_FIELD_DIRECTION: - DecodeUNumber(v, &(flowMessage.FlowDirection)) - - // MPLS - case netflow.IPFIX_FIELD_mplsTopLabelStackSection: - var mplsLabel uint32 - DecodeUNumber(v, &mplsLabel) - flowMessage.Mpls_1Label = uint32(mplsLabel >> 4) - flowMessage.HasMpls = true - case netflow.IPFIX_FIELD_mplsLabelStackSection2: - var mplsLabel uint32 - DecodeUNumber(v, &mplsLabel) - flowMessage.Mpls_2Label = uint32(mplsLabel >> 4) - case netflow.IPFIX_FIELD_mplsLabelStackSection3: - var mplsLabel uint32 - DecodeUNumber(v, &mplsLabel) - flowMessage.Mpls_3Label = uint32(mplsLabel >> 4) - case netflow.IPFIX_FIELD_mplsTopLabelIPv4Address: - flowMessage.MplsLabelIp = v - case netflow.IPFIX_FIELD_mplsTopLabelIPv6Address: - flowMessage.MplsLabelIp = v - - default: - if version == 9 { - // NetFlow v9 time works with a differential based on router's uptime - switch df.Type { - case netflow.NFV9_FIELD_FIRST_SWITCHED: - var timeFirstSwitched uint32 - DecodeUNumber(v, &timeFirstSwitched) - timeDiff := (uptime - timeFirstSwitched) - flowMessage.TimeFlowStart = uint64(baseTime - timeDiff/1000) - flowMessage.TimeFlowStartMs = uint64(baseTime)*1000 - uint64(timeDiff) - case netflow.NFV9_FIELD_LAST_SWITCHED: - var timeLastSwitched uint32 - DecodeUNumber(v, &timeLastSwitched) - timeDiff := (uptime - timeLastSwitched) - flowMessage.TimeFlowEnd = uint64(baseTime - timeDiff/1000) - flowMessage.TimeFlowEndMs = uint64(baseTime)*1000 - uint64(timeDiff) - } - } else if version == 10 { - switch df.Type { - case netflow.IPFIX_FIELD_flowStartSeconds: - DecodeUNumber(v, &time) - flowMessage.TimeFlowStart = time - flowMessage.TimeFlowStartMs = time * 1000 - case netflow.IPFIX_FIELD_flowStartMilliseconds: - DecodeUNumber(v, &time) - flowMessage.TimeFlowStart = time / 1000 - flowMessage.TimeFlowStartMs = time - case netflow.IPFIX_FIELD_flowStartMicroseconds: - DecodeUNumber(v, &time) - flowMessage.TimeFlowStart = time / 1000000 - flowMessage.TimeFlowStartMs = time / 1000 - case netflow.IPFIX_FIELD_flowStartNanoseconds: - DecodeUNumber(v, &time) - flowMessage.TimeFlowStart = time / 1000000000 - flowMessage.TimeFlowStartMs = time / 1000000 - case netflow.IPFIX_FIELD_flowEndSeconds: - DecodeUNumber(v, &time) - flowMessage.TimeFlowEnd = time - flowMessage.TimeFlowEndMs = time * 1000 - case netflow.IPFIX_FIELD_flowEndMilliseconds: - DecodeUNumber(v, &time) - flowMessage.TimeFlowEnd = time / 1000 - flowMessage.TimeFlowEndMs = time - case netflow.IPFIX_FIELD_flowEndMicroseconds: - DecodeUNumber(v, &time) - flowMessage.TimeFlowEnd = time / 1000000 - flowMessage.TimeFlowEndMs = time / 1000 - case netflow.IPFIX_FIELD_flowEndNanoseconds: - DecodeUNumber(v, &time) - flowMessage.TimeFlowEnd = time / 1000000000 - flowMessage.TimeFlowEndMs = time / 1000000 - case netflow.IPFIX_FIELD_flowStartDeltaMicroseconds: - DecodeUNumber(v, &time) - flowMessage.TimeFlowStart = uint64(baseTime) - time/1000000 - flowMessage.TimeFlowStartMs = uint64(baseTime)*1000 - time/1000 - case netflow.IPFIX_FIELD_flowEndDeltaMicroseconds: - DecodeUNumber(v, &time) - flowMessage.TimeFlowEnd = uint64(baseTime) - time/1000000 - flowMessage.TimeFlowEndMs = uint64(baseTime)*1000 - time/1000 - // RFC7133 - case netflow.IPFIX_FIELD_dataLinkFrameSize: - DecodeUNumber(v, &(flowMessage.Bytes)) - flowMessage.Packets = 1 - case netflow.IPFIX_FIELD_dataLinkFrameSection: - ParseEthernetHeader(flowMessage, v, mapperSFlow) - flowMessage.Packets = 1 - if flowMessage.Bytes == 0 { - flowMessage.Bytes = uint64(len(v)) - } - } - } - } - - } - - return flowMessage -} - -func SearchNetFlowDataSetsRecords(version uint16, baseTime uint32, uptime uint32, dataRecords []netflow.DataRecord, mapperNetFlow *NetFlowMapper, mapperSFlow *SFlowMapper) []*flowmessage.FlowMessage { - var flowMessageSet []*flowmessage.FlowMessage - for _, record := range dataRecords { - fmsg := ConvertNetFlowDataSet(version, baseTime, uptime, record.Values, mapperNetFlow, mapperSFlow) - if fmsg != nil { - flowMessageSet = append(flowMessageSet, fmsg) - } - } - return flowMessageSet -} - -func SearchNetFlowDataSets(version uint16, baseTime uint32, uptime uint32, dataFlowSet []netflow.DataFlowSet, mapperNetFlow *NetFlowMapper, mapperSFlow *SFlowMapper) []*flowmessage.FlowMessage { - var flowMessageSet []*flowmessage.FlowMessage - for _, dataFlowSetItem := range dataFlowSet { - fmsg := SearchNetFlowDataSetsRecords(version, baseTime, uptime, dataFlowSetItem.Records, mapperNetFlow, mapperSFlow) - if fmsg != nil { - flowMessageSet = append(flowMessageSet, fmsg...) - } - } - return flowMessageSet -} - -func SearchNetFlowOptionDataSets(dataFlowSet []netflow.OptionsDataFlowSet) (uint32, bool) { - var samplingRate uint32 - var found bool - for _, dataFlowSetItem := range dataFlowSet { - for _, record := range dataFlowSetItem.Records { - b := NetFlowPopulate(record.OptionsValues, 305, &samplingRate) - if b { - return samplingRate, b - } - b = NetFlowPopulate(record.OptionsValues, 50, &samplingRate) - if b { - return samplingRate, b - } - b = NetFlowPopulate(record.OptionsValues, 34, &samplingRate) - if b { - return samplingRate, b - } - } - } - return samplingRate, found -} - -func SplitNetFlowSets(packetNFv9 netflow.NFv9Packet) ([]netflow.DataFlowSet, []netflow.TemplateFlowSet, []netflow.NFv9OptionsTemplateFlowSet, []netflow.OptionsDataFlowSet) { - var dataFlowSet []netflow.DataFlowSet - var templatesFlowSet []netflow.TemplateFlowSet - var optionsTemplatesFlowSet []netflow.NFv9OptionsTemplateFlowSet - var optionsDataFlowSet []netflow.OptionsDataFlowSet - for _, flowSet := range packetNFv9.FlowSets { - switch tFlowSet := flowSet.(type) { - case netflow.TemplateFlowSet: - templatesFlowSet = append(templatesFlowSet, tFlowSet) - case netflow.NFv9OptionsTemplateFlowSet: - optionsTemplatesFlowSet = append(optionsTemplatesFlowSet, tFlowSet) - case netflow.DataFlowSet: - dataFlowSet = append(dataFlowSet, tFlowSet) - case netflow.OptionsDataFlowSet: - optionsDataFlowSet = append(optionsDataFlowSet, tFlowSet) - } - } - return dataFlowSet, templatesFlowSet, optionsTemplatesFlowSet, optionsDataFlowSet -} - -func SplitIPFIXSets(packetIPFIX netflow.IPFIXPacket) ([]netflow.DataFlowSet, []netflow.TemplateFlowSet, []netflow.IPFIXOptionsTemplateFlowSet, []netflow.OptionsDataFlowSet) { - var dataFlowSet []netflow.DataFlowSet - var templatesFlowSet []netflow.TemplateFlowSet - var optionsTemplatesFlowSet []netflow.IPFIXOptionsTemplateFlowSet - var optionsDataFlowSet []netflow.OptionsDataFlowSet - for _, flowSet := range packetIPFIX.FlowSets { - switch tFlowSet := flowSet.(type) { - case netflow.TemplateFlowSet: - templatesFlowSet = append(templatesFlowSet, tFlowSet) - case netflow.IPFIXOptionsTemplateFlowSet: - optionsTemplatesFlowSet = append(optionsTemplatesFlowSet, tFlowSet) - case netflow.DataFlowSet: - dataFlowSet = append(dataFlowSet, tFlowSet) - case netflow.OptionsDataFlowSet: - optionsDataFlowSet = append(optionsDataFlowSet, tFlowSet) - } - } - return dataFlowSet, templatesFlowSet, optionsTemplatesFlowSet, optionsDataFlowSet -} - -func ProcessMessageNetFlow(msgDec interface{}, samplingRateSys SamplingRateSystem) ([]*flowmessage.FlowMessage, error) { - return ProcessMessageNetFlowConfig(msgDec, samplingRateSys, nil) -} - -// Convert a NetFlow datastructure to a FlowMessage protobuf -// Does not put sampling rate -func ProcessMessageNetFlowConfig(msgDec interface{}, samplingRateSys SamplingRateSystem, config *ProducerConfigMapped) ([]*flowmessage.FlowMessage, error) { - seqnum := uint32(0) - var baseTime uint32 - var uptime uint32 - - var flowMessageSet []*flowmessage.FlowMessage - - switch msgDecConv := msgDec.(type) { - case netflow.NFv9Packet: - dataFlowSet, _, _, optionDataFlowSet := SplitNetFlowSets(msgDecConv) - - seqnum = msgDecConv.SequenceNumber - baseTime = msgDecConv.UnixSeconds - uptime = msgDecConv.SystemUptime - obsDomainId := msgDecConv.SourceId - - var cfg *NetFlowMapper - if config != nil { - cfg = config.NetFlowV9 - } - flowMessageSet = SearchNetFlowDataSets(9, baseTime, uptime, dataFlowSet, cfg, nil) - samplingRate, found := SearchNetFlowOptionDataSets(optionDataFlowSet) - if samplingRateSys != nil { - if found { - samplingRateSys.AddSamplingRate(9, obsDomainId, samplingRate) - } else { - samplingRate, _ = samplingRateSys.GetSamplingRate(9, obsDomainId) - } - } - for _, fmsg := range flowMessageSet { - fmsg.SequenceNum = seqnum - fmsg.SamplingRate = uint64(samplingRate) - } - case netflow.IPFIXPacket: - dataFlowSet, _, _, optionDataFlowSet := SplitIPFIXSets(msgDecConv) - - seqnum = msgDecConv.SequenceNumber - baseTime = msgDecConv.ExportTime - obsDomainId := msgDecConv.ObservationDomainId - - var cfgIpfix *NetFlowMapper - var cfgSflow *SFlowMapper - if config != nil { - cfgIpfix = config.IPFIX - cfgSflow = config.SFlow - } - flowMessageSet = SearchNetFlowDataSets(10, baseTime, uptime, dataFlowSet, cfgIpfix, cfgSflow) - - samplingRate, found := SearchNetFlowOptionDataSets(optionDataFlowSet) - if samplingRateSys != nil { - if found { - samplingRateSys.AddSamplingRate(10, obsDomainId, samplingRate) - } else { - samplingRate, _ = samplingRateSys.GetSamplingRate(10, obsDomainId) - } - } - for _, fmsg := range flowMessageSet { - fmsg.SequenceNum = seqnum - fmsg.SamplingRate = uint64(samplingRate) - fmsg.ObservationDomainId = obsDomainId - } - default: - return flowMessageSet, errors.New("Bad NetFlow/IPFIX version") - } - - return flowMessageSet, nil -} diff --git a/vendor/github.com/netsampler/goflow2/producer/producer_nflegacy.go b/vendor/github.com/netsampler/goflow2/producer/producer_nflegacy.go deleted file mode 100644 index 8acb3eeaa..000000000 --- a/vendor/github.com/netsampler/goflow2/producer/producer_nflegacy.go +++ /dev/null @@ -1,81 +0,0 @@ -package producer - -import ( - "encoding/binary" - "errors" - "net" - - "github.com/netsampler/goflow2/decoders/netflowlegacy" - flowmessage "github.com/netsampler/goflow2/pb" -) - -func ConvertNetFlowLegacyRecord(baseTime uint32, uptime uint32, record netflowlegacy.RecordsNetFlowV5) *flowmessage.FlowMessage { - flowMessage := &flowmessage.FlowMessage{} - - flowMessage.Type = flowmessage.FlowMessage_NETFLOW_V5 - - timeDiffFirst := (uptime - record.First) - timeDiffLast := (uptime - record.Last) - flowMessage.TimeFlowStart = uint64(baseTime - timeDiffFirst/1000) - flowMessage.TimeFlowStartMs = uint64(baseTime)*1000 - uint64(timeDiffFirst) - flowMessage.TimeFlowEnd = uint64(baseTime - timeDiffLast/1000) - flowMessage.TimeFlowEndMs = uint64(baseTime)*1000 - uint64(timeDiffLast) - - v := make(net.IP, 4) - binary.BigEndian.PutUint32(v, record.NextHop) - flowMessage.NextHop = v - v = make(net.IP, 4) - binary.BigEndian.PutUint32(v, record.SrcAddr) - flowMessage.SrcAddr = v - v = make(net.IP, 4) - binary.BigEndian.PutUint32(v, record.DstAddr) - flowMessage.DstAddr = v - - flowMessage.Etype = 0x800 - flowMessage.SrcAs = uint32(record.SrcAS) - flowMessage.DstAs = uint32(record.DstAS) - flowMessage.SrcNet = uint32(record.SrcMask) - flowMessage.DstNet = uint32(record.DstMask) - flowMessage.Proto = uint32(record.Proto) - flowMessage.TcpFlags = uint32(record.TCPFlags) - flowMessage.IpTos = uint32(record.Tos) - flowMessage.InIf = uint32(record.Input) - flowMessage.OutIf = uint32(record.Output) - flowMessage.SrcPort = uint32(record.SrcPort) - flowMessage.DstPort = uint32(record.DstPort) - flowMessage.Packets = uint64(record.DPkts) - flowMessage.Bytes = uint64(record.DOctets) - - return flowMessage -} - -func SearchNetFlowLegacyRecords(baseTime uint32, uptime uint32, dataRecords []netflowlegacy.RecordsNetFlowV5) []*flowmessage.FlowMessage { - var flowMessageSet []*flowmessage.FlowMessage - for _, record := range dataRecords { - fmsg := ConvertNetFlowLegacyRecord(baseTime, uptime, record) - if fmsg != nil { - flowMessageSet = append(flowMessageSet, fmsg) - } - } - return flowMessageSet -} - -func ProcessMessageNetFlowLegacy(msgDec interface{}) ([]*flowmessage.FlowMessage, error) { - switch packet := msgDec.(type) { - case netflowlegacy.PacketNetFlowV5: - seqnum := packet.FlowSequence - samplingRate := packet.SamplingInterval - baseTime := packet.UnixSecs - uptime := packet.SysUptime - - flowMessageSet := SearchNetFlowLegacyRecords(baseTime, uptime, packet.Records) - for _, fmsg := range flowMessageSet { - fmsg.SequenceNum = seqnum - fmsg.SamplingRate = uint64(samplingRate) - } - - return flowMessageSet, nil - default: - return []*flowmessage.FlowMessage{}, errors.New("Bad NetFlow v5 version") - } -} diff --git a/vendor/github.com/netsampler/goflow2/producer/producer_sf.go b/vendor/github.com/netsampler/goflow2/producer/producer_sf.go deleted file mode 100644 index ab949144b..000000000 --- a/vendor/github.com/netsampler/goflow2/producer/producer_sf.go +++ /dev/null @@ -1,349 +0,0 @@ -package producer - -import ( - "encoding/binary" - "errors" - "net" - - "github.com/netsampler/goflow2/decoders/sflow" - flowmessage "github.com/netsampler/goflow2/pb" -) - -func GetSFlowFlowSamples(packet *sflow.Packet) []interface{} { - var flowSamples []interface{} - for _, sample := range packet.Samples { - switch sample.(type) { - case sflow.FlowSample: - flowSamples = append(flowSamples, sample) - case sflow.ExpandedFlowSample: - flowSamples = append(flowSamples, sample) - } - } - return flowSamples -} - -func ParseSampledHeader(flowMessage *flowmessage.FlowMessage, sampledHeader *sflow.SampledHeader) error { - return ParseSampledHeaderConfig(flowMessage, sampledHeader, nil) -} - -func ParseEthernetHeader(flowMessage *flowmessage.FlowMessage, data []byte, config *SFlowMapper) { - var hasMpls bool - var countMpls uint32 - var firstLabelMpls uint32 - var firstTtlMpls uint8 - var secondLabelMpls uint32 - var secondTtlMpls uint8 - var thirdLabelMpls uint32 - var thirdTtlMpls uint8 - var lastLabelMpls uint32 - var lastTtlMpls uint8 - - var nextHeader byte - var tcpflags byte - srcIP := net.IP{} - dstIP := net.IP{} - offset := 14 - - var srcMac uint64 - var dstMac uint64 - - var tos byte - var ttl byte - var identification uint16 - var fragOffset uint16 - var flowLabel uint32 - - var srcPort uint16 - var dstPort uint16 - - for _, configLayer := range GetSFlowConfigLayer(config, 0) { - extracted := GetBytes(data, configLayer.Offset, configLayer.Length) - MapCustom(flowMessage, extracted, configLayer.Destination, configLayer.Endian) - } - - etherType := data[12:14] - - dstMac = binary.BigEndian.Uint64(append([]byte{0, 0}, data[0:6]...)) - srcMac = binary.BigEndian.Uint64(append([]byte{0, 0}, data[6:12]...)) - (*flowMessage).SrcMac = srcMac - (*flowMessage).DstMac = dstMac - - encap := true - iterations := 0 - for encap && iterations <= 1 { - encap = false - - if etherType[0] == 0x81 && etherType[1] == 0x0 { // VLAN 802.1Q - (*flowMessage).VlanId = uint32(binary.BigEndian.Uint16(data[14:16])) - offset += 4 - etherType = data[16:18] - } - - if etherType[0] == 0x88 && etherType[1] == 0x47 { // MPLS - iterateMpls := true - hasMpls = true - for iterateMpls { - if len(data) < offset+5 { - iterateMpls = false - break - } - label := binary.BigEndian.Uint32(append([]byte{0}, data[offset:offset+3]...)) >> 4 - //exp := data[offset+2] > 1 - bottom := data[offset+2] & 1 - mplsTtl := data[offset+3] - offset += 4 - - if bottom == 1 || label <= 15 || offset > len(data) { - if data[offset]&0xf0>>4 == 4 { - etherType = []byte{0x8, 0x0} - } else if data[offset]&0xf0>>4 == 6 { - etherType = []byte{0x86, 0xdd} - } - iterateMpls = false - } - - if countMpls == 0 { - firstLabelMpls = label - firstTtlMpls = mplsTtl - } else if countMpls == 1 { - secondLabelMpls = label - secondTtlMpls = mplsTtl - } else if countMpls == 2 { - thirdLabelMpls = label - thirdTtlMpls = mplsTtl - } else { - lastLabelMpls = label - lastTtlMpls = mplsTtl - } - countMpls++ - } - } - - for _, configLayer := range GetSFlowConfigLayer(config, 3) { - extracted := GetBytes(data, offset*8+configLayer.Offset, configLayer.Length) - MapCustom(flowMessage, extracted, configLayer.Destination, configLayer.Endian) - } - - if etherType[0] == 0x8 && etherType[1] == 0x0 { // IPv4 - if len(data) >= offset+20 { - nextHeader = data[offset+9] - srcIP = data[offset+12 : offset+16] - dstIP = data[offset+16 : offset+20] - tos = data[offset+1] - ttl = data[offset+8] - - identification = binary.BigEndian.Uint16(data[offset+4 : offset+6]) - fragOffset = binary.BigEndian.Uint16(data[offset+6:offset+8]) & 8191 - - offset += 20 - } - } else if etherType[0] == 0x86 && etherType[1] == 0xdd { // IPv6 - if len(data) >= offset+40 { - nextHeader = data[offset+6] - srcIP = data[offset+8 : offset+24] - dstIP = data[offset+24 : offset+40] - - tostmp := uint32(binary.BigEndian.Uint16(data[offset : offset+2])) - tos = uint8(tostmp & 0x0ff0 >> 4) - ttl = data[offset+7] - - flowLabel = binary.BigEndian.Uint32(data[offset : offset+4]) - - offset += 40 - - } - } else if etherType[0] == 0x8 && etherType[1] == 0x6 { // ARP - } /*else { - return errors.New(fmt.Sprintf("Unknown EtherType: %v\n", etherType)) - } */ - - for _, configLayer := range GetSFlowConfigLayer(config, 4) { - extracted := GetBytes(data, offset*8+configLayer.Offset, configLayer.Length) - MapCustom(flowMessage, extracted, configLayer.Destination, configLayer.Endian) - } - - appOffset := 0 - if len(data) >= offset+4 && (nextHeader == 17 || nextHeader == 6) && fragOffset&8191 == 0 { - srcPort = binary.BigEndian.Uint16(data[offset+0 : offset+2]) - dstPort = binary.BigEndian.Uint16(data[offset+2 : offset+4]) - } - - if nextHeader == 17 { - appOffset = 8 - } - - if len(data) > offset+13 && nextHeader == 6 { - tcpflags = data[offset+13] - - appOffset = int(data[13]>>4) * 4 - } - - // ICMP and ICMPv6 - if len(data) >= offset+2 && (nextHeader == 1 || nextHeader == 58) { - (*flowMessage).IcmpType = uint32(data[offset+0]) - (*flowMessage).IcmpCode = uint32(data[offset+1]) - } - - if appOffset > 0 { - for _, configLayer := range GetSFlowConfigLayer(config, 7) { - extracted := GetBytes(data, (offset+appOffset)*8+configLayer.Offset, configLayer.Length) - MapCustom(flowMessage, extracted, configLayer.Destination, configLayer.Endian) - } - } - - iterations++ - } - - (*flowMessage).HasMpls = hasMpls - (*flowMessage).MplsCount = countMpls - (*flowMessage).Mpls_1Label = firstLabelMpls - (*flowMessage).Mpls_1Ttl = uint32(firstTtlMpls) - (*flowMessage).Mpls_2Label = secondLabelMpls - (*flowMessage).Mpls_2Ttl = uint32(secondTtlMpls) - (*flowMessage).Mpls_3Label = thirdLabelMpls - (*flowMessage).Mpls_3Ttl = uint32(thirdTtlMpls) - (*flowMessage).MplsLastLabel = lastLabelMpls - (*flowMessage).MplsLastTtl = uint32(lastTtlMpls) - - (*flowMessage).Etype = uint32(binary.BigEndian.Uint16(etherType[0:2])) - (*flowMessage).Ipv6FlowLabel = flowLabel & 0xFFFFF - - (*flowMessage).SrcPort = uint32(srcPort) - (*flowMessage).DstPort = uint32(dstPort) - - (*flowMessage).SrcAddr = srcIP - (*flowMessage).DstAddr = dstIP - (*flowMessage).Proto = uint32(nextHeader) - (*flowMessage).IpTos = uint32(tos) - (*flowMessage).IpTtl = uint32(ttl) - (*flowMessage).TcpFlags = uint32(tcpflags) - - (*flowMessage).FragmentId = uint32(identification) - (*flowMessage).FragmentOffset = uint32(fragOffset) -} - -func ParseSampledHeaderConfig(flowMessage *flowmessage.FlowMessage, sampledHeader *sflow.SampledHeader, config *SFlowMapper) error { - data := (*sampledHeader).HeaderData - switch (*sampledHeader).Protocol { - case 1: // Ethernet - ParseEthernetHeader(flowMessage, data, config) - } - return nil -} - -func SearchSFlowSamples(samples []interface{}) []*flowmessage.FlowMessage { - return SearchSFlowSamples(samples) -} - -func SearchSFlowSamplesConfig(samples []interface{}, config *SFlowMapper) []*flowmessage.FlowMessage { - var flowMessageSet []*flowmessage.FlowMessage - - for _, flowSample := range samples { - var records []sflow.FlowRecord - - flowMessage := &flowmessage.FlowMessage{} - flowMessage.Type = flowmessage.FlowMessage_SFLOW_5 - - switch flowSample := flowSample.(type) { - case sflow.FlowSample: - records = flowSample.Records - flowMessage.SamplingRate = uint64(flowSample.SamplingRate) - flowMessage.InIf = flowSample.Input - flowMessage.OutIf = flowSample.Output - case sflow.ExpandedFlowSample: - records = flowSample.Records - flowMessage.SamplingRate = uint64(flowSample.SamplingRate) - flowMessage.InIf = flowSample.InputIfValue - flowMessage.OutIf = flowSample.OutputIfValue - } - - ipNh := net.IP{} - ipSrc := net.IP{} - ipDst := net.IP{} - flowMessage.Packets = 1 - for _, record := range records { - switch recordData := record.Data.(type) { - case sflow.SampledHeader: - flowMessage.Bytes = uint64(recordData.FrameLength) - ParseSampledHeaderConfig(flowMessage, &recordData, config) - case sflow.SampledIPv4: - ipSrc = recordData.Base.SrcIP - ipDst = recordData.Base.DstIP - flowMessage.SrcAddr = ipSrc - flowMessage.DstAddr = ipDst - flowMessage.Bytes = uint64(recordData.Base.Length) - flowMessage.Proto = recordData.Base.Protocol - flowMessage.SrcPort = recordData.Base.SrcPort - flowMessage.DstPort = recordData.Base.DstPort - flowMessage.IpTos = recordData.Tos - flowMessage.Etype = 0x800 - case sflow.SampledIPv6: - ipSrc = recordData.Base.SrcIP - ipDst = recordData.Base.DstIP - flowMessage.SrcAddr = ipSrc - flowMessage.DstAddr = ipDst - flowMessage.Bytes = uint64(recordData.Base.Length) - flowMessage.Proto = recordData.Base.Protocol - flowMessage.SrcPort = recordData.Base.SrcPort - flowMessage.DstPort = recordData.Base.DstPort - flowMessage.IpTos = recordData.Priority - flowMessage.Etype = 0x86dd - case sflow.ExtendedRouter: - ipNh = recordData.NextHop - flowMessage.NextHop = ipNh - flowMessage.SrcNet = recordData.SrcMaskLen - flowMessage.DstNet = recordData.DstMaskLen - case sflow.ExtendedGateway: - ipNh = recordData.NextHop - flowMessage.BgpNextHop = ipNh - flowMessage.BgpCommunities = recordData.Communities - flowMessage.AsPath = recordData.ASPath - if len(recordData.ASPath) > 0 { - flowMessage.DstAs = recordData.ASPath[len(recordData.ASPath)-1] - flowMessage.NextHopAs = recordData.ASPath[0] - } else { - flowMessage.DstAs = recordData.AS - } - if recordData.SrcAS > 0 { - flowMessage.SrcAs = recordData.SrcAS - } else { - flowMessage.SrcAs = recordData.AS - } - case sflow.ExtendedSwitch: - flowMessage.SrcVlan = recordData.SrcVlan - flowMessage.DstVlan = recordData.DstVlan - } - } - flowMessageSet = append(flowMessageSet, flowMessage) - } - return flowMessageSet -} - -func ProcessMessageSFlow(msgDec interface{}) ([]*flowmessage.FlowMessage, error) { - return ProcessMessageSFlowConfig(msgDec, nil) -} - -func ProcessMessageSFlowConfig(msgDec interface{}, config *ProducerConfigMapped) ([]*flowmessage.FlowMessage, error) { - switch packet := msgDec.(type) { - case sflow.Packet: - seqnum := packet.SequenceNumber - var agent net.IP - agent = packet.AgentIP - - var cfg *SFlowMapper - if config != nil { - cfg = config.SFlow - } - - flowSamples := GetSFlowFlowSamples(&packet) - flowMessageSet := SearchSFlowSamplesConfig(flowSamples, cfg) - for _, fmsg := range flowMessageSet { - fmsg.SamplerAddress = agent - fmsg.SequenceNum = seqnum - } - - return flowMessageSet, nil - default: - return []*flowmessage.FlowMessage{}, errors.New("Bad sFlow version") - } -} diff --git a/vendor/github.com/netsampler/goflow2/producer/reflect.go b/vendor/github.com/netsampler/goflow2/producer/reflect.go deleted file mode 100644 index 91a2a415c..000000000 --- a/vendor/github.com/netsampler/goflow2/producer/reflect.go +++ /dev/null @@ -1,233 +0,0 @@ -package producer - -import ( - "fmt" - "reflect" - - "github.com/netsampler/goflow2/decoders/netflow" - flowmessage "github.com/netsampler/goflow2/pb" -) - -type EndianType string - -var ( - BigEndian EndianType = "big" - LittleEndian EndianType = "little" -) - -func GetBytes(d []byte, offset int, length int) []byte { - if length == 0 { - return nil - } - leftBytes := offset / 8 - rightBytes := (offset + length) / 8 - if (offset+length)%8 != 0 { - rightBytes += 1 - } - if leftBytes >= len(d) { - return nil - } - if rightBytes > len(d) { - rightBytes = len(d) - } - chunk := make([]byte, rightBytes-leftBytes) - - offsetMod8 := (offset % 8) - shiftAnd := byte(0xff >> (8 - offsetMod8)) - - var shifted byte - for i := range chunk { - j := len(chunk) - 1 - i - cur := d[j+leftBytes] - chunk[j] = (cur << offsetMod8) | shifted - shifted = shiftAnd & cur - } - last := len(chunk) - 1 - shiftAndLast := byte(0xff << ((8 - ((offset + length) % 8)) % 8)) - chunk[last] = chunk[last] & shiftAndLast - return chunk -} - -func IsUInt(k reflect.Kind) bool { - return k == reflect.Uint8 || k == reflect.Uint16 || k == reflect.Uint32 || k == reflect.Uint64 -} - -func IsInt(k reflect.Kind) bool { - return k == reflect.Int8 || k == reflect.Int16 || k == reflect.Int32 || k == reflect.Int64 -} - -func MapCustomNetFlow(flowMessage *flowmessage.FlowMessage, df netflow.DataField, mapper *NetFlowMapper) { - if mapper == nil { - return - } - mapped, ok := mapper.Map(df) - if ok { - v := df.Value.([]byte) - MapCustom(flowMessage, v, mapped.Destination, mapped.Endian) - } -} - -func MapCustom(flowMessage *flowmessage.FlowMessage, v []byte, destination string, endianness EndianType) { - vfm := reflect.ValueOf(flowMessage) - vfm = reflect.Indirect(vfm) - - fieldValue := vfm.FieldByName(destination) - - if fieldValue.IsValid() { - typeDest := fieldValue.Type() - fieldValueAddr := fieldValue.Addr() - - if typeDest.Kind() == reflect.Slice { - - if typeDest.Elem().Kind() == reflect.Uint8 { - fieldValue.SetBytes(v) - } else { - item := reflect.New(typeDest.Elem()) - - if IsUInt(typeDest.Elem().Kind()) { - if endianness == LittleEndian { - DecodeUNumberLE(v, item.Interface()) - } else { - DecodeUNumber(v, item.Interface()) - } - } else if IsUInt(typeDest.Elem().Kind()) { - if endianness == LittleEndian { - DecodeUNumberLE(v, item.Interface()) - } else { - DecodeUNumber(v, item.Interface()) - } - } - - itemi := reflect.Indirect(item) - tmpFieldValue := reflect.Append(fieldValue, itemi) - fieldValue.Set(tmpFieldValue) - } - - } else if fieldValueAddr.IsValid() && IsUInt(typeDest.Kind()) { - if endianness == LittleEndian { - DecodeUNumberLE(v, fieldValueAddr.Interface()) - } else { - DecodeUNumber(v, fieldValueAddr.Interface()) - } - } else if fieldValueAddr.IsValid() && IsInt(typeDest.Kind()) { - if endianness == LittleEndian { - DecodeUNumberLE(v, fieldValueAddr.Interface()) - } else { - DecodeUNumber(v, fieldValueAddr.Interface()) - } - } - } -} - -type NetFlowMapField struct { - PenProvided bool `json:"penprovided" yaml:"penprovided"` - Type uint16 `json:"field" yaml:"field"` - Pen uint32 `json:"pen" yaml:"pen"` - - Destination string `json:"destination" yaml:"destination"` - Endian EndianType `json:"endianness" yaml:"endianness"` - //DestinationLength uint8 `json:"dlen"` // could be used if populating a slice of uint16 that aren't in protobuf -} - -type IPFIXProducerConfig struct { - Mapping []NetFlowMapField `json:"mapping"` - //PacketMapping []SFlowMapField `json:"packet-mapping"` // for embedded frames: use sFlow configuration -} - -type NetFlowV9ProducerConfig struct { - Mapping []NetFlowMapField `json:"mapping"` -} - -type SFlowMapField struct { - Layer int `json:"layer"` - Offset int `json:"offset"` // offset in bits - Length int `json:"length"` // length in bits - - Destination string `json:"destination" yaml:"destination"` - Endian EndianType `json:"endianness" yaml:"endianness"` - //DestinationLength uint8 `json:"dlen"` -} - -type SFlowProducerConfig struct { - Mapping []SFlowMapField `json:"mapping"` -} - -type ProducerConfig struct { - IPFIX IPFIXProducerConfig `json:"ipfix"` - NetFlowV9 NetFlowV9ProducerConfig `json:"netflowv9"` - SFlow SFlowProducerConfig `json:"sflow"` // also used for IPFIX data frames - - // should do a rename map list for when printing -} - -type DataMap struct { - Destination string - Endian EndianType -} - -type NetFlowMapper struct { - data map[string]DataMap // maps field to destination -} - -func (m *NetFlowMapper) Map(field netflow.DataField) (DataMap, bool) { - mapped, found := m.data[fmt.Sprintf("%v-%d-%d", field.PenProvided, field.Pen, field.Type)] - return mapped, found -} - -func MapFieldsNetFlow(fields []NetFlowMapField) *NetFlowMapper { - ret := make(map[string]DataMap) - for _, field := range fields { - ret[fmt.Sprintf("%v-%d-%d", field.PenProvided, field.Pen, field.Type)] = DataMap{Destination: field.Destination, Endian: field.Endian} - } - return &NetFlowMapper{ret} -} - -type DataMapLayer struct { - Offset int - Length int - Destination string - Endian EndianType -} - -type SFlowMapper struct { - data map[int][]DataMapLayer // map layer to list of offsets -} - -func GetSFlowConfigLayer(m *SFlowMapper, layer int) []DataMapLayer { - if m == nil { - return nil - } - return m.data[layer] -} - -func MapFieldsSFlow(fields []SFlowMapField) *SFlowMapper { - ret := make(map[int][]DataMapLayer) - for _, field := range fields { - retLayerEntry := DataMapLayer{ - Offset: field.Offset, - Length: field.Length, - Destination: field.Destination, - Endian: field.Endian, - } - retLayer := ret[field.Layer] - retLayer = append(retLayer, retLayerEntry) - ret[field.Layer] = retLayer - } - return &SFlowMapper{ret} -} - -type ProducerConfigMapped struct { - IPFIX *NetFlowMapper `json:"ipfix"` - NetFlowV9 *NetFlowMapper `json:"netflowv9"` - SFlow *SFlowMapper `json:"sflow"` -} - -func NewProducerConfigMapped(config *ProducerConfig) *ProducerConfigMapped { - newCfg := &ProducerConfigMapped{} - if config != nil { - newCfg.IPFIX = MapFieldsNetFlow(config.IPFIX.Mapping) - newCfg.NetFlowV9 = MapFieldsNetFlow(config.NetFlowV9.Mapping) - newCfg.SFlow = MapFieldsSFlow(config.SFlow.Mapping) - } - return newCfg -} diff --git a/vendor/github.com/spf13/pflag/.editorconfig b/vendor/github.com/spf13/pflag/.editorconfig deleted file mode 100644 index 4492e9f9f..000000000 --- a/vendor/github.com/spf13/pflag/.editorconfig +++ /dev/null @@ -1,12 +0,0 @@ -root = true - -[*] -charset = utf-8 -end_of_line = lf -indent_size = 4 -indent_style = space -insert_final_newline = true -trim_trailing_whitespace = true - -[*.go] -indent_style = tab diff --git a/vendor/github.com/spf13/pflag/.gitignore b/vendor/github.com/spf13/pflag/.gitignore deleted file mode 100644 index c3da29013..000000000 --- a/vendor/github.com/spf13/pflag/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.idea/* - diff --git a/vendor/github.com/spf13/pflag/.golangci.yaml b/vendor/github.com/spf13/pflag/.golangci.yaml deleted file mode 100644 index b274f2484..000000000 --- a/vendor/github.com/spf13/pflag/.golangci.yaml +++ /dev/null @@ -1,4 +0,0 @@ -linters: - disable-all: true - enable: - - nolintlint diff --git a/vendor/github.com/spf13/pflag/.travis.yml b/vendor/github.com/spf13/pflag/.travis.yml deleted file mode 100644 index 00d04cb9b..000000000 --- a/vendor/github.com/spf13/pflag/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -sudo: false - -language: go - -go: - - 1.9.x - - 1.10.x - - 1.11.x - - tip - -matrix: - allow_failures: - - go: tip - -install: - - go get golang.org/x/lint/golint - - export PATH=$GOPATH/bin:$PATH - - go install ./... - -script: - - verify/all.sh -v - - go test ./... diff --git a/vendor/github.com/spf13/pflag/LICENSE b/vendor/github.com/spf13/pflag/LICENSE deleted file mode 100644 index 63ed1cfea..000000000 --- a/vendor/github.com/spf13/pflag/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2012 Alex Ogier. All rights reserved. -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/spf13/pflag/README.md b/vendor/github.com/spf13/pflag/README.md deleted file mode 100644 index 388c4e5ea..000000000 --- a/vendor/github.com/spf13/pflag/README.md +++ /dev/null @@ -1,323 +0,0 @@ -[![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag) -[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/pflag)](https://goreportcard.com/report/github.com/spf13/pflag) -[![GoDoc](https://godoc.org/github.com/spf13/pflag?status.svg)](https://godoc.org/github.com/spf13/pflag) - -## Description - -pflag is a drop-in replacement for Go's flag package, implementing -POSIX/GNU-style --flags. - -pflag is compatible with the [GNU extensions to the POSIX recommendations -for command-line options][1]. For a more precise description, see the -"Command-line flag syntax" section below. - -[1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html - -pflag is available under the same style of BSD license as the Go language, -which can be found in the LICENSE file. - -## Installation - -pflag is available using the standard `go get` command. - -Install by running: - - go get github.com/spf13/pflag - -Run tests by running: - - go test github.com/spf13/pflag - -## Usage - -pflag is a drop-in replacement of Go's native flag package. If you import -pflag under the name "flag" then all code should continue to function -with no changes. - -``` go -import flag "github.com/spf13/pflag" -``` - -There is one exception to this: if you directly instantiate the Flag struct -there is one more field "Shorthand" that you will need to set. -Most code never instantiates this struct directly, and instead uses -functions such as String(), BoolVar(), and Var(), and is therefore -unaffected. - -Define flags using flag.String(), Bool(), Int(), etc. - -This declares an integer flag, -flagname, stored in the pointer ip, with type *int. - -``` go -var ip *int = flag.Int("flagname", 1234, "help message for flagname") -``` - -If you like, you can bind the flag to a variable using the Var() functions. - -``` go -var flagvar int -func init() { - flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") -} -``` - -Or you can create custom flags that satisfy the Value interface (with -pointer receivers) and couple them to flag parsing by - -``` go -flag.Var(&flagVal, "name", "help message for flagname") -``` - -For such flags, the default value is just the initial value of the variable. - -After all flags are defined, call - -``` go -flag.Parse() -``` - -to parse the command line into the defined flags. - -Flags may then be used directly. If you're using the flags themselves, -they are all pointers; if you bind to variables, they're values. - -``` go -fmt.Println("ip has value ", *ip) -fmt.Println("flagvar has value ", flagvar) -``` - -There are helper functions available to get the value stored in a Flag if you have a FlagSet but find -it difficult to keep up with all of the pointers in your code. -If you have a pflag.FlagSet with a flag called 'flagname' of type int you -can use GetInt() to get the int value. But notice that 'flagname' must exist -and it must be an int. GetString("flagname") will fail. - -``` go -i, err := flagset.GetInt("flagname") -``` - -After parsing, the arguments after the flag are available as the -slice flag.Args() or individually as flag.Arg(i). -The arguments are indexed from 0 through flag.NArg()-1. - -The pflag package also defines some new functions that are not in flag, -that give one-letter shorthands for flags. You can use these by appending -'P' to the name of any function that defines a flag. - -``` go -var ip = flag.IntP("flagname", "f", 1234, "help message") -var flagvar bool -func init() { - flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") -} -flag.VarP(&flagVal, "varname", "v", "help message") -``` - -Shorthand letters can be used with single dashes on the command line. -Boolean shorthand flags can be combined with other shorthand flags. - -The default set of command-line flags is controlled by -top-level functions. The FlagSet type allows one to define -independent sets of flags, such as to implement subcommands -in a command-line interface. The methods of FlagSet are -analogous to the top-level functions for the command-line -flag set. - -## Setting no option default values for flags - -After you create a flag it is possible to set the pflag.NoOptDefVal for -the given flag. Doing this changes the meaning of the flag slightly. If -a flag has a NoOptDefVal and the flag is set on the command line without -an option the flag will be set to the NoOptDefVal. For example given: - -``` go -var ip = flag.IntP("flagname", "f", 1234, "help message") -flag.Lookup("flagname").NoOptDefVal = "4321" -``` - -Would result in something like - -| Parsed Arguments | Resulting Value | -| ------------- | ------------- | -| --flagname=1357 | ip=1357 | -| --flagname | ip=4321 | -| [nothing] | ip=1234 | - -## Command line flag syntax - -``` ---flag // boolean flags, or flags with no option default values ---flag x // only on flags without a default value ---flag=x -``` - -Unlike the flag package, a single dash before an option means something -different than a double dash. Single dashes signify a series of shorthand -letters for flags. All but the last shorthand letter must be boolean flags -or a flag with a default value - -``` -// boolean or flags where the 'no option default value' is set --f --f=true --abc -but --b true is INVALID - -// non-boolean and flags without a 'no option default value' --n 1234 --n=1234 --n1234 - -// mixed --abcs "hello" --absd="hello" --abcs1234 -``` - -Flag parsing stops after the terminator "--". Unlike the flag package, -flags can be interspersed with arguments anywhere on the command line -before this terminator. - -Integer flags accept 1234, 0664, 0x1234 and may be negative. -Boolean flags (in their long form) accept 1, 0, t, f, true, false, -TRUE, FALSE, True, False. -Duration flags accept any input valid for time.ParseDuration. - -## Mutating or "Normalizing" Flag names - -It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow. - -**Example #1**: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag - -``` go -func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { - from := []string{"-", "_"} - to := "." - for _, sep := range from { - name = strings.Replace(name, sep, to, -1) - } - return pflag.NormalizedName(name) -} - -myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc) -``` - -**Example #2**: You want to alias two flags. aka --old-flag-name == --new-flag-name - -``` go -func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { - switch name { - case "old-flag-name": - name = "new-flag-name" - break - } - return pflag.NormalizedName(name) -} - -myFlagSet.SetNormalizeFunc(aliasNormalizeFunc) -``` - -## Deprecating a flag or its shorthand -It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used. - -**Example #1**: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead. -```go -// deprecate a flag by specifying its name and a usage message -flags.MarkDeprecated("badflag", "please use --good-flag instead") -``` -This hides "badflag" from help text, and prints `Flag --badflag has been deprecated, please use --good-flag instead` when "badflag" is used. - -**Example #2**: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n". -```go -// deprecate a flag shorthand by specifying its flag name and a usage message -flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only") -``` -This hides the shortname "n" from help text, and prints `Flag shorthand -n has been deprecated, please use --noshorthandflag only` when the shorthand "n" is used. - -Note that usage message is essential here, and it should not be empty. - -## Hidden flags -It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text. - -**Example**: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available. -```go -// hide a flag by specifying its name -flags.MarkHidden("secretFlag") -``` - -## Disable sorting of flags -`pflag` allows you to disable sorting of flags for help and usage message. - -**Example**: -```go -flags.BoolP("verbose", "v", false, "verbose output") -flags.String("coolflag", "yeaah", "it's really cool flag") -flags.Int("usefulflag", 777, "sometimes it's very useful") -flags.SortFlags = false -flags.PrintDefaults() -``` -**Output**: -``` - -v, --verbose verbose output - --coolflag string it's really cool flag (default "yeaah") - --usefulflag int sometimes it's very useful (default 777) -``` - - -## Supporting Go flags when using pflag -In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary -to support flags defined by third-party dependencies (e.g. `golang/glog`). - -**Example**: You want to add the Go flags to the `CommandLine` flagset -```go -import ( - goflag "flag" - flag "github.com/spf13/pflag" -) - -var ip *int = flag.Int("flagname", 1234, "help message for flagname") - -func main() { - flag.CommandLine.AddGoFlagSet(goflag.CommandLine) - flag.Parse() -} -``` - -### Using pflag with go test -`pflag` does not parse the shorthand versions of go test's built-in flags (i.e., those starting with `-test.`). -For more context, see issues [#63](https://github.com/spf13/pflag/issues/63) and [#238](https://github.com/spf13/pflag/issues/238) for more details. - -For example, if you use pflag in your `TestMain` function and call `pflag.Parse()` after defining your custom flags, running a test like this: -```bash -go test /your/tests -run ^YourTest -v --your-test-pflags -``` -will result in the `-v` flag being ignored. This happens because of the way pflag handles flag parsing, skipping over go test's built-in shorthand flags. -To work around this, you can use the `ParseSkippedFlags` function, which ensures that go test's flags are parsed separately using the standard flag package. - -**Example**: You want to parse go test flags that are otherwise ignore by `pflag.Parse()` -```go -import ( - goflag "flag" - flag "github.com/spf13/pflag" -) - -var ip *int = flag.Int("flagname", 1234, "help message for flagname") - -func main() { - flag.CommandLine.AddGoFlagSet(goflag.CommandLine) - flag.ParseSkippedFlags(os.Args[1:], goflag.CommandLine) - flag.Parse() -} -``` - -## More info - -You can see the full reference documentation of the pflag package -[at godoc.org][3], or through go's standard documentation system by -running `godoc -http=:6060` and browsing to -[http://localhost:6060/pkg/github.com/spf13/pflag][2] after -installation. - -[2]: http://localhost:6060/pkg/github.com/spf13/pflag -[3]: http://godoc.org/github.com/spf13/pflag diff --git a/vendor/github.com/spf13/pflag/bool.go b/vendor/github.com/spf13/pflag/bool.go deleted file mode 100644 index c4c5c0bfd..000000000 --- a/vendor/github.com/spf13/pflag/bool.go +++ /dev/null @@ -1,94 +0,0 @@ -package pflag - -import "strconv" - -// optional interface to indicate boolean flags that can be -// supplied without "=value" text -type boolFlag interface { - Value - IsBoolFlag() bool -} - -// -- bool Value -type boolValue bool - -func newBoolValue(val bool, p *bool) *boolValue { - *p = val - return (*boolValue)(p) -} - -func (b *boolValue) Set(s string) error { - v, err := strconv.ParseBool(s) - *b = boolValue(v) - return err -} - -func (b *boolValue) Type() string { - return "bool" -} - -func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) } - -func (b *boolValue) IsBoolFlag() bool { return true } - -func boolConv(sval string) (interface{}, error) { - return strconv.ParseBool(sval) -} - -// GetBool return the bool value of a flag with the given name -func (f *FlagSet) GetBool(name string) (bool, error) { - val, err := f.getFlagType(name, "bool", boolConv) - if err != nil { - return false, err - } - return val.(bool), nil -} - -// BoolVar defines a bool flag with specified name, default value, and usage string. -// The argument p points to a bool variable in which to store the value of the flag. -func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) { - f.BoolVarP(p, name, "", value, usage) -} - -// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) { - flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage) - flag.NoOptDefVal = "true" -} - -// BoolVar defines a bool flag with specified name, default value, and usage string. -// The argument p points to a bool variable in which to store the value of the flag. -func BoolVar(p *bool, name string, value bool, usage string) { - BoolVarP(p, name, "", value, usage) -} - -// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. -func BoolVarP(p *bool, name, shorthand string, value bool, usage string) { - flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage) - flag.NoOptDefVal = "true" -} - -// Bool defines a bool flag with specified name, default value, and usage string. -// The return value is the address of a bool variable that stores the value of the flag. -func (f *FlagSet) Bool(name string, value bool, usage string) *bool { - return f.BoolP(name, "", value, usage) -} - -// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool { - p := new(bool) - f.BoolVarP(p, name, shorthand, value, usage) - return p -} - -// Bool defines a bool flag with specified name, default value, and usage string. -// The return value is the address of a bool variable that stores the value of the flag. -func Bool(name string, value bool, usage string) *bool { - return BoolP(name, "", value, usage) -} - -// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. -func BoolP(name, shorthand string, value bool, usage string) *bool { - b := CommandLine.BoolP(name, shorthand, value, usage) - return b -} diff --git a/vendor/github.com/spf13/pflag/bool_func.go b/vendor/github.com/spf13/pflag/bool_func.go deleted file mode 100644 index 83d77afa8..000000000 --- a/vendor/github.com/spf13/pflag/bool_func.go +++ /dev/null @@ -1,40 +0,0 @@ -package pflag - -// -- func Value -type boolfuncValue func(string) error - -func (f boolfuncValue) Set(s string) error { return f(s) } - -func (f boolfuncValue) Type() string { return "boolfunc" } - -func (f boolfuncValue) String() string { return "" } // same behavior as stdlib 'flag' package - -func (f boolfuncValue) IsBoolFlag() bool { return true } - -// BoolFunc defines a func flag with specified name, callback function and usage string. -// -// The callback function will be called every time "--{name}" (or any form that matches the flag) is parsed -// on the command line. -func (f *FlagSet) BoolFunc(name string, usage string, fn func(string) error) { - f.BoolFuncP(name, "", usage, fn) -} - -// BoolFuncP is like BoolFunc, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolFuncP(name, shorthand string, usage string, fn func(string) error) { - var val Value = boolfuncValue(fn) - flag := f.VarPF(val, name, shorthand, usage) - flag.NoOptDefVal = "true" -} - -// BoolFunc defines a func flag with specified name, callback function and usage string. -// -// The callback function will be called every time "--{name}" (or any form that matches the flag) is parsed -// on the command line. -func BoolFunc(name string, usage string, fn func(string) error) { - CommandLine.BoolFuncP(name, "", usage, fn) -} - -// BoolFuncP is like BoolFunc, but accepts a shorthand letter that can be used after a single dash. -func BoolFuncP(name, shorthand string, usage string, fn func(string) error) { - CommandLine.BoolFuncP(name, shorthand, usage, fn) -} diff --git a/vendor/github.com/spf13/pflag/bool_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go deleted file mode 100644 index 3731370d6..000000000 --- a/vendor/github.com/spf13/pflag/bool_slice.go +++ /dev/null @@ -1,185 +0,0 @@ -package pflag - -import ( - "io" - "strconv" - "strings" -) - -// -- boolSlice Value -type boolSliceValue struct { - value *[]bool - changed bool -} - -func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue { - bsv := new(boolSliceValue) - bsv.value = p - *bsv.value = val - return bsv -} - -// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag. -// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended. -func (s *boolSliceValue) Set(val string) error { - - // remove all quote characters - rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") - - // read flag arguments with CSV parser - boolStrSlice, err := readAsCSV(rmQuote.Replace(val)) - if err != nil && err != io.EOF { - return err - } - - // parse boolean values into slice - out := make([]bool, 0, len(boolStrSlice)) - for _, boolStr := range boolStrSlice { - b, err := strconv.ParseBool(strings.TrimSpace(boolStr)) - if err != nil { - return err - } - out = append(out, b) - } - - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - - s.changed = true - - return nil -} - -// Type returns a string that uniquely represents this flag's type. -func (s *boolSliceValue) Type() string { - return "boolSlice" -} - -// String defines a "native" format for this boolean slice flag value. -func (s *boolSliceValue) String() string { - - boolStrSlice := make([]string, len(*s.value)) - for i, b := range *s.value { - boolStrSlice[i] = strconv.FormatBool(b) - } - - out, _ := writeAsCSV(boolStrSlice) - - return "[" + out + "]" -} - -func (s *boolSliceValue) fromString(val string) (bool, error) { - return strconv.ParseBool(val) -} - -func (s *boolSliceValue) toString(val bool) string { - return strconv.FormatBool(val) -} - -func (s *boolSliceValue) Append(val string) error { - i, err := s.fromString(val) - if err != nil { - return err - } - *s.value = append(*s.value, i) - return nil -} - -func (s *boolSliceValue) Replace(val []string) error { - out := make([]bool, len(val)) - for i, d := range val { - var err error - out[i], err = s.fromString(d) - if err != nil { - return err - } - } - *s.value = out - return nil -} - -func (s *boolSliceValue) GetSlice() []string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = s.toString(d) - } - return out -} - -func boolSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []bool{}, nil - } - ss := strings.Split(val, ",") - out := make([]bool, len(ss)) - for i, t := range ss { - var err error - out[i], err = strconv.ParseBool(t) - if err != nil { - return nil, err - } - } - return out, nil -} - -// GetBoolSlice returns the []bool value of a flag with the given name. -func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) { - val, err := f.getFlagType(name, "boolSlice", boolSliceConv) - if err != nil { - return []bool{}, err - } - return val.([]bool), nil -} - -// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string. -// The argument p points to a []bool variable in which to store the value of the flag. -func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) { - f.VarP(newBoolSliceValue(value, p), name, "", usage) -} - -// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { - f.VarP(newBoolSliceValue(value, p), name, shorthand, usage) -} - -// BoolSliceVar defines a []bool flag with specified name, default value, and usage string. -// The argument p points to a []bool variable in which to store the value of the flag. -func BoolSliceVar(p *[]bool, name string, value []bool, usage string) { - CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage) -} - -// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. -func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { - CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage) -} - -// BoolSlice defines a []bool flag with specified name, default value, and usage string. -// The return value is the address of a []bool variable that stores the value of the flag. -func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool { - p := []bool{} - f.BoolSliceVarP(&p, name, "", value, usage) - return &p -} - -// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { - p := []bool{} - f.BoolSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// BoolSlice defines a []bool flag with specified name, default value, and usage string. -// The return value is the address of a []bool variable that stores the value of the flag. -func BoolSlice(name string, value []bool, usage string) *[]bool { - return CommandLine.BoolSliceP(name, "", value, usage) -} - -// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. -func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { - return CommandLine.BoolSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/bytes.go b/vendor/github.com/spf13/pflag/bytes.go deleted file mode 100644 index 67d530457..000000000 --- a/vendor/github.com/spf13/pflag/bytes.go +++ /dev/null @@ -1,209 +0,0 @@ -package pflag - -import ( - "encoding/base64" - "encoding/hex" - "fmt" - "strings" -) - -// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded -type bytesHexValue []byte - -// String implements pflag.Value.String. -func (bytesHex bytesHexValue) String() string { - return fmt.Sprintf("%X", []byte(bytesHex)) -} - -// Set implements pflag.Value.Set. -func (bytesHex *bytesHexValue) Set(value string) error { - bin, err := hex.DecodeString(strings.TrimSpace(value)) - - if err != nil { - return err - } - - *bytesHex = bin - - return nil -} - -// Type implements pflag.Value.Type. -func (*bytesHexValue) Type() string { - return "bytesHex" -} - -func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue { - *p = val - return (*bytesHexValue)(p) -} - -func bytesHexConv(sval string) (interface{}, error) { - - bin, err := hex.DecodeString(sval) - - if err == nil { - return bin, nil - } - - return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err) -} - -// GetBytesHex return the []byte value of a flag with the given name -func (f *FlagSet) GetBytesHex(name string) ([]byte, error) { - val, err := f.getFlagType(name, "bytesHex", bytesHexConv) - - if err != nil { - return []byte{}, err - } - - return val.([]byte), nil -} - -// BytesHexVar defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) { - f.VarP(newBytesHexValue(value, p), name, "", usage) -} - -// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { - f.VarP(newBytesHexValue(value, p), name, shorthand, usage) -} - -// BytesHexVar defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func BytesHexVar(p *[]byte, name string, value []byte, usage string) { - CommandLine.VarP(newBytesHexValue(value, p), name, "", usage) -} - -// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. -func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { - CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage) -} - -// BytesHex defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesHexVarP(p, name, "", value, usage) - return p -} - -// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesHexVarP(p, name, shorthand, value, usage) - return p -} - -// BytesHex defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func BytesHex(name string, value []byte, usage string) *[]byte { - return CommandLine.BytesHexP(name, "", value, usage) -} - -// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. -func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { - return CommandLine.BytesHexP(name, shorthand, value, usage) -} - -// BytesBase64 adapts []byte for use as a flag. Value of flag is Base64 encoded -type bytesBase64Value []byte - -// String implements pflag.Value.String. -func (bytesBase64 bytesBase64Value) String() string { - return base64.StdEncoding.EncodeToString([]byte(bytesBase64)) -} - -// Set implements pflag.Value.Set. -func (bytesBase64 *bytesBase64Value) Set(value string) error { - bin, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value)) - - if err != nil { - return err - } - - *bytesBase64 = bin - - return nil -} - -// Type implements pflag.Value.Type. -func (*bytesBase64Value) Type() string { - return "bytesBase64" -} - -func newBytesBase64Value(val []byte, p *[]byte) *bytesBase64Value { - *p = val - return (*bytesBase64Value)(p) -} - -func bytesBase64ValueConv(sval string) (interface{}, error) { - - bin, err := base64.StdEncoding.DecodeString(sval) - if err == nil { - return bin, nil - } - - return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err) -} - -// GetBytesBase64 return the []byte value of a flag with the given name -func (f *FlagSet) GetBytesBase64(name string) ([]byte, error) { - val, err := f.getFlagType(name, "bytesBase64", bytesBase64ValueConv) - - if err != nil { - return []byte{}, err - } - - return val.([]byte), nil -} - -// BytesBase64Var defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func (f *FlagSet) BytesBase64Var(p *[]byte, name string, value []byte, usage string) { - f.VarP(newBytesBase64Value(value, p), name, "", usage) -} - -// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) { - f.VarP(newBytesBase64Value(value, p), name, shorthand, usage) -} - -// BytesBase64Var defines an []byte flag with specified name, default value, and usage string. -// The argument p points to an []byte variable in which to store the value of the flag. -func BytesBase64Var(p *[]byte, name string, value []byte, usage string) { - CommandLine.VarP(newBytesBase64Value(value, p), name, "", usage) -} - -// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash. -func BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) { - CommandLine.VarP(newBytesBase64Value(value, p), name, shorthand, usage) -} - -// BytesBase64 defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func (f *FlagSet) BytesBase64(name string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesBase64VarP(p, name, "", value, usage) - return p -} - -// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte { - p := new([]byte) - f.BytesBase64VarP(p, name, shorthand, value, usage) - return p -} - -// BytesBase64 defines an []byte flag with specified name, default value, and usage string. -// The return value is the address of an []byte variable that stores the value of the flag. -func BytesBase64(name string, value []byte, usage string) *[]byte { - return CommandLine.BytesBase64P(name, "", value, usage) -} - -// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash. -func BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte { - return CommandLine.BytesBase64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go deleted file mode 100644 index d49c0143c..000000000 --- a/vendor/github.com/spf13/pflag/count.go +++ /dev/null @@ -1,96 +0,0 @@ -package pflag - -import "strconv" - -// -- count Value -type countValue int - -func newCountValue(val int, p *int) *countValue { - *p = val - return (*countValue)(p) -} - -func (i *countValue) Set(s string) error { - // "+1" means that no specific value was passed, so increment - if s == "+1" { - *i = countValue(*i + 1) - return nil - } - v, err := strconv.ParseInt(s, 0, 0) - *i = countValue(v) - return err -} - -func (i *countValue) Type() string { - return "count" -} - -func (i *countValue) String() string { return strconv.Itoa(int(*i)) } - -func countConv(sval string) (interface{}, error) { - i, err := strconv.Atoi(sval) - if err != nil { - return nil, err - } - return i, nil -} - -// GetCount return the int value of a flag with the given name -func (f *FlagSet) GetCount(name string) (int, error) { - val, err := f.getFlagType(name, "count", countConv) - if err != nil { - return 0, err - } - return val.(int), nil -} - -// CountVar defines a count flag with specified name, default value, and usage string. -// The argument p points to an int variable in which to store the value of the flag. -// A count flag will add 1 to its value every time it is found on the command line -func (f *FlagSet) CountVar(p *int, name string, usage string) { - f.CountVarP(p, name, "", usage) -} - -// CountVarP is like CountVar only take a shorthand for the flag name. -func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) { - flag := f.VarPF(newCountValue(0, p), name, shorthand, usage) - flag.NoOptDefVal = "+1" -} - -// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set -func CountVar(p *int, name string, usage string) { - CommandLine.CountVar(p, name, usage) -} - -// CountVarP is like CountVar only take a shorthand for the flag name. -func CountVarP(p *int, name, shorthand string, usage string) { - CommandLine.CountVarP(p, name, shorthand, usage) -} - -// Count defines a count flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -// A count flag will add 1 to its value every time it is found on the command line -func (f *FlagSet) Count(name string, usage string) *int { - p := new(int) - f.CountVarP(p, name, "", usage) - return p -} - -// CountP is like Count only takes a shorthand for the flag name. -func (f *FlagSet) CountP(name, shorthand string, usage string) *int { - p := new(int) - f.CountVarP(p, name, shorthand, usage) - return p -} - -// Count defines a count flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -// A count flag will add 1 to its value every time it is found on the command line -func Count(name string, usage string) *int { - return CommandLine.CountP(name, "", usage) -} - -// CountP is like Count only takes a shorthand for the flag name. -func CountP(name, shorthand string, usage string) *int { - return CommandLine.CountP(name, shorthand, usage) -} diff --git a/vendor/github.com/spf13/pflag/duration.go b/vendor/github.com/spf13/pflag/duration.go deleted file mode 100644 index e9debef88..000000000 --- a/vendor/github.com/spf13/pflag/duration.go +++ /dev/null @@ -1,86 +0,0 @@ -package pflag - -import ( - "time" -) - -// -- time.Duration Value -type durationValue time.Duration - -func newDurationValue(val time.Duration, p *time.Duration) *durationValue { - *p = val - return (*durationValue)(p) -} - -func (d *durationValue) Set(s string) error { - v, err := time.ParseDuration(s) - *d = durationValue(v) - return err -} - -func (d *durationValue) Type() string { - return "duration" -} - -func (d *durationValue) String() string { return (*time.Duration)(d).String() } - -func durationConv(sval string) (interface{}, error) { - return time.ParseDuration(sval) -} - -// GetDuration return the duration value of a flag with the given name -func (f *FlagSet) GetDuration(name string) (time.Duration, error) { - val, err := f.getFlagType(name, "duration", durationConv) - if err != nil { - return 0, err - } - return val.(time.Duration), nil -} - -// DurationVar defines a time.Duration flag with specified name, default value, and usage string. -// The argument p points to a time.Duration variable in which to store the value of the flag. -func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) { - f.VarP(newDurationValue(value, p), name, "", usage) -} - -// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { - f.VarP(newDurationValue(value, p), name, shorthand, usage) -} - -// DurationVar defines a time.Duration flag with specified name, default value, and usage string. -// The argument p points to a time.Duration variable in which to store the value of the flag. -func DurationVar(p *time.Duration, name string, value time.Duration, usage string) { - CommandLine.VarP(newDurationValue(value, p), name, "", usage) -} - -// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. -func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { - CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage) -} - -// Duration defines a time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a time.Duration variable that stores the value of the flag. -func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration { - p := new(time.Duration) - f.DurationVarP(p, name, "", value, usage) - return p -} - -// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { - p := new(time.Duration) - f.DurationVarP(p, name, shorthand, value, usage) - return p -} - -// Duration defines a time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a time.Duration variable that stores the value of the flag. -func Duration(name string, value time.Duration, usage string) *time.Duration { - return CommandLine.DurationP(name, "", value, usage) -} - -// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. -func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { - return CommandLine.DurationP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/duration_slice.go b/vendor/github.com/spf13/pflag/duration_slice.go deleted file mode 100644 index badadda53..000000000 --- a/vendor/github.com/spf13/pflag/duration_slice.go +++ /dev/null @@ -1,166 +0,0 @@ -package pflag - -import ( - "fmt" - "strings" - "time" -) - -// -- durationSlice Value -type durationSliceValue struct { - value *[]time.Duration - changed bool -} - -func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue { - dsv := new(durationSliceValue) - dsv.value = p - *dsv.value = val - return dsv -} - -func (s *durationSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]time.Duration, len(ss)) - for i, d := range ss { - var err error - out[i], err = time.ParseDuration(d) - if err != nil { - return err - } - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *durationSliceValue) Type() string { - return "durationSlice" -} - -func (s *durationSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%s", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func (s *durationSliceValue) fromString(val string) (time.Duration, error) { - return time.ParseDuration(val) -} - -func (s *durationSliceValue) toString(val time.Duration) string { - return fmt.Sprintf("%s", val) -} - -func (s *durationSliceValue) Append(val string) error { - i, err := s.fromString(val) - if err != nil { - return err - } - *s.value = append(*s.value, i) - return nil -} - -func (s *durationSliceValue) Replace(val []string) error { - out := make([]time.Duration, len(val)) - for i, d := range val { - var err error - out[i], err = s.fromString(d) - if err != nil { - return err - } - } - *s.value = out - return nil -} - -func (s *durationSliceValue) GetSlice() []string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = s.toString(d) - } - return out -} - -func durationSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []time.Duration{}, nil - } - ss := strings.Split(val, ",") - out := make([]time.Duration, len(ss)) - for i, d := range ss { - var err error - out[i], err = time.ParseDuration(d) - if err != nil { - return nil, err - } - - } - return out, nil -} - -// GetDurationSlice returns the []time.Duration value of a flag with the given name -func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) { - val, err := f.getFlagType(name, "durationSlice", durationSliceConv) - if err != nil { - return []time.Duration{}, err - } - return val.([]time.Duration), nil -} - -// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string. -// The argument p points to a []time.Duration variable in which to store the value of the flag. -func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { - f.VarP(newDurationSliceValue(value, p), name, "", usage) -} - -// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { - f.VarP(newDurationSliceValue(value, p), name, shorthand, usage) -} - -// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string. -// The argument p points to a duration[] variable in which to store the value of the flag. -func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { - CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage) -} - -// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. -func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { - CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage) -} - -// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a []time.Duration variable that stores the value of the flag. -func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { - p := []time.Duration{} - f.DurationSliceVarP(&p, name, "", value, usage) - return &p -} - -// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { - p := []time.Duration{} - f.DurationSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. -// The return value is the address of a []time.Duration variable that stores the value of the flag. -func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { - return CommandLine.DurationSliceP(name, "", value, usage) -} - -// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. -func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { - return CommandLine.DurationSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/errors.go b/vendor/github.com/spf13/pflag/errors.go deleted file mode 100644 index ff11b66be..000000000 --- a/vendor/github.com/spf13/pflag/errors.go +++ /dev/null @@ -1,149 +0,0 @@ -package pflag - -import "fmt" - -// notExistErrorMessageType specifies which flavor of "flag does not exist" -// is printed by NotExistError. This allows the related errors to be grouped -// under a single NotExistError struct without making a breaking change to -// the error message text. -type notExistErrorMessageType int - -const ( - flagNotExistMessage notExistErrorMessageType = iota - flagNotDefinedMessage - flagNoSuchFlagMessage - flagUnknownFlagMessage - flagUnknownShorthandFlagMessage -) - -// NotExistError is the error returned when trying to access a flag that -// does not exist in the FlagSet. -type NotExistError struct { - name string - specifiedShorthands string - messageType notExistErrorMessageType -} - -// Error implements error. -func (e *NotExistError) Error() string { - switch e.messageType { - case flagNotExistMessage: - return fmt.Sprintf("flag %q does not exist", e.name) - - case flagNotDefinedMessage: - return fmt.Sprintf("flag accessed but not defined: %s", e.name) - - case flagNoSuchFlagMessage: - return fmt.Sprintf("no such flag -%v", e.name) - - case flagUnknownFlagMessage: - return fmt.Sprintf("unknown flag: --%s", e.name) - - case flagUnknownShorthandFlagMessage: - c := rune(e.name[0]) - return fmt.Sprintf("unknown shorthand flag: %q in -%s", c, e.specifiedShorthands) - } - - panic(fmt.Errorf("unknown flagNotExistErrorMessageType: %v", e.messageType)) -} - -// GetSpecifiedName returns the name of the flag (without dashes) as it -// appeared in the parsed arguments. -func (e *NotExistError) GetSpecifiedName() string { - return e.name -} - -// GetSpecifiedShortnames returns the group of shorthand arguments -// (without dashes) that the flag appeared within. If the flag was not in a -// shorthand group, this will return an empty string. -func (e *NotExistError) GetSpecifiedShortnames() string { - return e.specifiedShorthands -} - -// ValueRequiredError is the error returned when a flag needs an argument but -// no argument was provided. -type ValueRequiredError struct { - flag *Flag - specifiedName string - specifiedShorthands string -} - -// Error implements error. -func (e *ValueRequiredError) Error() string { - if len(e.specifiedShorthands) > 0 { - c := rune(e.specifiedName[0]) - return fmt.Sprintf("flag needs an argument: %q in -%s", c, e.specifiedShorthands) - } - - return fmt.Sprintf("flag needs an argument: --%s", e.specifiedName) -} - -// GetFlag returns the flag for which the error occurred. -func (e *ValueRequiredError) GetFlag() *Flag { - return e.flag -} - -// GetSpecifiedName returns the name of the flag (without dashes) as it -// appeared in the parsed arguments. -func (e *ValueRequiredError) GetSpecifiedName() string { - return e.specifiedName -} - -// GetSpecifiedShortnames returns the group of shorthand arguments -// (without dashes) that the flag appeared within. If the flag was not in a -// shorthand group, this will return an empty string. -func (e *ValueRequiredError) GetSpecifiedShortnames() string { - return e.specifiedShorthands -} - -// InvalidValueError is the error returned when an invalid value is used -// for a flag. -type InvalidValueError struct { - flag *Flag - value string - cause error -} - -// Error implements error. -func (e *InvalidValueError) Error() string { - flag := e.flag - var flagName string - if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { - flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name) - } else { - flagName = fmt.Sprintf("--%s", flag.Name) - } - return fmt.Sprintf("invalid argument %q for %q flag: %v", e.value, flagName, e.cause) -} - -// Unwrap implements errors.Unwrap. -func (e *InvalidValueError) Unwrap() error { - return e.cause -} - -// GetFlag returns the flag for which the error occurred. -func (e *InvalidValueError) GetFlag() *Flag { - return e.flag -} - -// GetValue returns the invalid value that was provided. -func (e *InvalidValueError) GetValue() string { - return e.value -} - -// InvalidSyntaxError is the error returned when a bad flag name is passed on -// the command line. -type InvalidSyntaxError struct { - specifiedFlag string -} - -// Error implements error. -func (e *InvalidSyntaxError) Error() string { - return fmt.Sprintf("bad flag syntax: %s", e.specifiedFlag) -} - -// GetSpecifiedName returns the exact flag (with dashes) as it -// appeared in the parsed arguments. -func (e *InvalidSyntaxError) GetSpecifiedFlag() string { - return e.specifiedFlag -} diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go deleted file mode 100644 index 2fd3c5759..000000000 --- a/vendor/github.com/spf13/pflag/flag.go +++ /dev/null @@ -1,1289 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package pflag is a drop-in replacement for Go's flag package, implementing -POSIX/GNU-style --flags. - -pflag is compatible with the GNU extensions to the POSIX recommendations -for command-line options. See -http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html - -Usage: - -pflag is a drop-in replacement of Go's native flag package. If you import -pflag under the name "flag" then all code should continue to function -with no changes. - - import flag "github.com/spf13/pflag" - -There is one exception to this: if you directly instantiate the Flag struct -there is one more field "Shorthand" that you will need to set. -Most code never instantiates this struct directly, and instead uses -functions such as String(), BoolVar(), and Var(), and is therefore -unaffected. - -Define flags using flag.String(), Bool(), Int(), etc. - -This declares an integer flag, -flagname, stored in the pointer ip, with type *int. - - var ip = flag.Int("flagname", 1234, "help message for flagname") - -If you like, you can bind the flag to a variable using the Var() functions. - - var flagvar int - func init() { - flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") - } - -Or you can create custom flags that satisfy the Value interface (with -pointer receivers) and couple them to flag parsing by - - flag.Var(&flagVal, "name", "help message for flagname") - -For such flags, the default value is just the initial value of the variable. - -After all flags are defined, call - - flag.Parse() - -to parse the command line into the defined flags. - -Flags may then be used directly. If you're using the flags themselves, -they are all pointers; if you bind to variables, they're values. - - fmt.Println("ip has value ", *ip) - fmt.Println("flagvar has value ", flagvar) - -After parsing, the arguments after the flag are available as the -slice flag.Args() or individually as flag.Arg(i). -The arguments are indexed from 0 through flag.NArg()-1. - -The pflag package also defines some new functions that are not in flag, -that give one-letter shorthands for flags. You can use these by appending -'P' to the name of any function that defines a flag. - - var ip = flag.IntP("flagname", "f", 1234, "help message") - var flagvar bool - func init() { - flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") - } - flag.VarP(&flagval, "varname", "v", "help message") - -Shorthand letters can be used with single dashes on the command line. -Boolean shorthand flags can be combined with other shorthand flags. - -Command line flag syntax: - - --flag // boolean flags only - --flag=x - -Unlike the flag package, a single dash before an option means something -different than a double dash. Single dashes signify a series of shorthand -letters for flags. All but the last shorthand letter must be boolean flags. - - // boolean flags - -f - -abc - // non-boolean flags - -n 1234 - -Ifile - // mixed - -abcs "hello" - -abcn1234 - -Flag parsing stops after the terminator "--". Unlike the flag package, -flags can be interspersed with arguments anywhere on the command line -before this terminator. - -Integer flags accept 1234, 0664, 0x1234 and may be negative. -Boolean flags (in their long form) accept 1, 0, t, f, true, false, -TRUE, FALSE, True, False. -Duration flags accept any input valid for time.ParseDuration. - -The default set of command-line flags is controlled by -top-level functions. The FlagSet type allows one to define -independent sets of flags, such as to implement subcommands -in a command-line interface. The methods of FlagSet are -analogous to the top-level functions for the command-line -flag set. -*/ -package pflag - -import ( - "bytes" - "errors" - goflag "flag" - "fmt" - "io" - "os" - "sort" - "strings" -) - -// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined. -var ErrHelp = errors.New("pflag: help requested") - -// ErrorHandling defines how to handle flag parsing errors. -type ErrorHandling int - -const ( - // ContinueOnError will return an err from Parse() if an error is found - ContinueOnError ErrorHandling = iota - // ExitOnError will call os.Exit(2) if an error is found when parsing - ExitOnError - // PanicOnError will panic() if an error is found when parsing flags - PanicOnError -) - -// ParseErrorsAllowlist defines the parsing errors that can be ignored -type ParseErrorsAllowlist struct { - // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags - UnknownFlags bool -} - -// ParseErrorsWhitelist defines the parsing errors that can be ignored. -// -// Deprecated: use [ParseErrorsAllowlist] instead. This type will be removed in a future release. -type ParseErrorsWhitelist = ParseErrorsAllowlist - -// NormalizedName is a flag name that has been normalized according to rules -// for the FlagSet (e.g. making '-' and '_' equivalent). -type NormalizedName string - -// A FlagSet represents a set of defined flags. -type FlagSet struct { - // Usage is the function called when an error occurs while parsing flags. - // The field is a function (not a method) that may be changed to point to - // a custom error handler. - Usage func() - - // SortFlags is used to indicate, if user wants to have sorted flags in - // help/usage messages. - SortFlags bool - - // ParseErrorsAllowlist is used to configure an allowlist of errors - ParseErrorsAllowlist ParseErrorsAllowlist - - // ParseErrorsAllowlist is used to configure an allowlist of errors. - // - // Deprecated: use [FlagSet.ParseErrorsAllowlist] instead. This field will be removed in a future release. - ParseErrorsWhitelist ParseErrorsAllowlist - - name string - parsed bool - actual map[NormalizedName]*Flag - orderedActual []*Flag - sortedActual []*Flag - formal map[NormalizedName]*Flag - orderedFormal []*Flag - sortedFormal []*Flag - shorthands map[byte]*Flag - args []string // arguments after flags - argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no -- - errorHandling ErrorHandling - output io.Writer // nil means stderr; use Output() accessor - interspersed bool // allow interspersed option/non-option args - normalizeNameFunc func(f *FlagSet, name string) NormalizedName - - addedGoFlagSets []*goflag.FlagSet -} - -// A Flag represents the state of a flag. -type Flag struct { - Name string // name as it appears on command line - Shorthand string // one-letter abbreviated flag - Usage string // help message - Value Value // value as set - DefValue string // default value (as text); for usage message - Changed bool // If the user set the value (or if left to default) - NoOptDefVal string // default value (as text); if the flag is on the command line without any options - Deprecated string // If this flag is deprecated, this string is the new or now thing to use - Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text - ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use - Annotations map[string][]string // used by cobra.Command bash autocomple code -} - -// Value is the interface to the dynamic value stored in a flag. -// (The default value is represented as a string.) -type Value interface { - String() string - Set(string) error - Type() string -} - -// SliceValue is a secondary interface to all flags which hold a list -// of values. This allows full control over the value of list flags, -// and avoids complicated marshalling and unmarshalling to csv. -type SliceValue interface { - // Append adds the specified value to the end of the flag value list. - Append(string) error - // Replace will fully overwrite any data currently in the flag value list. - Replace([]string) error - // GetSlice returns the flag value list as an array of strings. - GetSlice() []string -} - -// sortFlags returns the flags as a slice in lexicographical sorted order. -func sortFlags(flags map[NormalizedName]*Flag) []*Flag { - list := make(sort.StringSlice, len(flags)) - i := 0 - for k := range flags { - list[i] = string(k) - i++ - } - list.Sort() - result := make([]*Flag, len(list)) - for i, name := range list { - result[i] = flags[NormalizedName(name)] - } - return result -} - -// SetNormalizeFunc allows you to add a function which can translate flag names. -// Flags added to the FlagSet will be translated and then when anything tries to -// look up the flag that will also be translated. So it would be possible to create -// a flag named "getURL" and have it translated to "geturl". A user could then pass -// "--getUrl" which may also be translated to "geturl" and everything will work. -func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) { - f.normalizeNameFunc = n - f.sortedFormal = f.sortedFormal[:0] - for fname, flag := range f.formal { - nname := f.normalizeFlagName(flag.Name) - if fname == nname { - continue - } - flag.Name = string(nname) - delete(f.formal, fname) - f.formal[nname] = flag - if _, set := f.actual[fname]; set { - delete(f.actual, fname) - f.actual[nname] = flag - } - } -} - -// GetNormalizeFunc returns the previously set NormalizeFunc of a function which -// does no translation, if not set previously. -func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName { - if f.normalizeNameFunc != nil { - return f.normalizeNameFunc - } - return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) } -} - -func (f *FlagSet) normalizeFlagName(name string) NormalizedName { - n := f.GetNormalizeFunc() - return n(f, name) -} - -// Output returns the destination for usage and error messages. os.Stderr is returned if -// output was not set or was set to nil. -func (f *FlagSet) Output() io.Writer { - if f.output == nil { - return os.Stderr - } - return f.output -} - -// Name returns the name of the flag set. -func (f *FlagSet) Name() string { - return f.name -} - -// SetOutput sets the destination for usage and error messages. -// If output is nil, os.Stderr is used. -func (f *FlagSet) SetOutput(output io.Writer) { - f.output = output -} - -// VisitAll visits the flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits all flags, even those not set. -func (f *FlagSet) VisitAll(fn func(*Flag)) { - if len(f.formal) == 0 { - return - } - - var flags []*Flag - if f.SortFlags { - if len(f.formal) != len(f.sortedFormal) { - f.sortedFormal = sortFlags(f.formal) - } - flags = f.sortedFormal - } else { - flags = f.orderedFormal - } - - for _, flag := range flags { - fn(flag) - } -} - -// HasFlags returns a bool to indicate if the FlagSet has any flags defined. -func (f *FlagSet) HasFlags() bool { - return len(f.formal) > 0 -} - -// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags -// that are not hidden. -func (f *FlagSet) HasAvailableFlags() bool { - for _, flag := range f.formal { - if !flag.Hidden { - return true - } - } - return false -} - -// VisitAll visits the command-line flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits all flags, even those not set. -func VisitAll(fn func(*Flag)) { - CommandLine.VisitAll(fn) -} - -// Visit visits the flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits only those flags that have been set. -func (f *FlagSet) Visit(fn func(*Flag)) { - if len(f.actual) == 0 { - return - } - - var flags []*Flag - if f.SortFlags { - if len(f.actual) != len(f.sortedActual) { - f.sortedActual = sortFlags(f.actual) - } - flags = f.sortedActual - } else { - flags = f.orderedActual - } - - for _, flag := range flags { - fn(flag) - } -} - -// Visit visits the command-line flags in lexicographical order or -// in primordial order if f.SortFlags is false, calling fn for each. -// It visits only those flags that have been set. -func Visit(fn func(*Flag)) { - CommandLine.Visit(fn) -} - -// Lookup returns the Flag structure of the named flag, returning nil if none exists. -func (f *FlagSet) Lookup(name string) *Flag { - return f.lookup(f.normalizeFlagName(name)) -} - -// ShorthandLookup returns the Flag structure of the short handed flag, -// returning nil if none exists. -// It panics, if len(name) > 1. -func (f *FlagSet) ShorthandLookup(name string) *Flag { - if name == "" { - return nil - } - if len(name) > 1 { - msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name) - fmt.Fprintf(f.Output(), msg) - panic(msg) - } - c := name[0] - return f.shorthands[c] -} - -// lookup returns the Flag structure of the named flag, returning nil if none exists. -func (f *FlagSet) lookup(name NormalizedName) *Flag { - return f.formal[name] -} - -// func to return a given type for a given flag name -func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) { - flag := f.Lookup(name) - if flag == nil { - err := &NotExistError{name: name, messageType: flagNotDefinedMessage} - return nil, err - } - - if flag.Value.Type() != ftype { - err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type()) - return nil, err - } - - sval := flag.Value.String() - result, err := convFunc(sval) - if err != nil { - return nil, err - } - return result, nil -} - -// ArgsLenAtDash will return the length of f.Args at the moment when a -- was -// found during arg parsing. This allows your program to know which args were -// before the -- and which came after. -func (f *FlagSet) ArgsLenAtDash() int { - return f.argsLenAtDash -} - -// MarkDeprecated indicated that a flag is deprecated in your program. It will -// continue to function but will not show up in help or usage messages. Using -// this flag will also print the given usageMessage. -func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error { - flag := f.Lookup(name) - if flag == nil { - return &NotExistError{name: name, messageType: flagNotExistMessage} - } - if usageMessage == "" { - return fmt.Errorf("deprecated message for flag %q must be set", name) - } - flag.Deprecated = usageMessage - flag.Hidden = true - return nil -} - -// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your -// program. It will continue to function but will not show up in help or usage -// messages. Using this flag will also print the given usageMessage. -func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error { - flag := f.Lookup(name) - if flag == nil { - return &NotExistError{name: name, messageType: flagNotExistMessage} - } - if usageMessage == "" { - return fmt.Errorf("deprecated message for flag %q must be set", name) - } - flag.ShorthandDeprecated = usageMessage - return nil -} - -// MarkHidden sets a flag to 'hidden' in your program. It will continue to -// function but will not show up in help or usage messages. -func (f *FlagSet) MarkHidden(name string) error { - flag := f.Lookup(name) - if flag == nil { - return &NotExistError{name: name, messageType: flagNotExistMessage} - } - flag.Hidden = true - return nil -} - -// Lookup returns the Flag structure of the named command-line flag, -// returning nil if none exists. -func Lookup(name string) *Flag { - return CommandLine.Lookup(name) -} - -// ShorthandLookup returns the Flag structure of the short handed flag, -// returning nil if none exists. -func ShorthandLookup(name string) *Flag { - return CommandLine.ShorthandLookup(name) -} - -// Set sets the value of the named flag. -func (f *FlagSet) Set(name, value string) error { - normalName := f.normalizeFlagName(name) - flag, ok := f.formal[normalName] - if !ok { - return &NotExistError{name: name, messageType: flagNoSuchFlagMessage} - } - - err := flag.Value.Set(value) - if err != nil { - return &InvalidValueError{ - flag: flag, - value: value, - cause: err, - } - } - - if !flag.Changed { - if f.actual == nil { - f.actual = make(map[NormalizedName]*Flag) - } - f.actual[normalName] = flag - f.orderedActual = append(f.orderedActual, flag) - - flag.Changed = true - } - - if flag.Deprecated != "" { - fmt.Fprintf(f.Output(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) - } - return nil -} - -// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet. -// This is sometimes used by spf13/cobra programs which want to generate additional -// bash completion information. -func (f *FlagSet) SetAnnotation(name, key string, values []string) error { - normalName := f.normalizeFlagName(name) - flag, ok := f.formal[normalName] - if !ok { - return &NotExistError{name: name, messageType: flagNoSuchFlagMessage} - } - if flag.Annotations == nil { - flag.Annotations = map[string][]string{} - } - flag.Annotations[key] = values - return nil -} - -// Changed returns true if the flag was explicitly set during Parse() and false -// otherwise -func (f *FlagSet) Changed(name string) bool { - flag := f.Lookup(name) - // If a flag doesn't exist, it wasn't changed.... - if flag == nil { - return false - } - return flag.Changed -} - -// Set sets the value of the named command-line flag. -func Set(name, value string) error { - return CommandLine.Set(name, value) -} - -// PrintDefaults prints, to standard error unless configured -// otherwise, the default values of all defined flags in the set. -func (f *FlagSet) PrintDefaults() { - usages := f.FlagUsages() - fmt.Fprint(f.Output(), usages) -} - -// defaultIsZeroValue returns true if the default value for this flag represents -// a zero value. -func (f *Flag) defaultIsZeroValue() bool { - switch f.Value.(type) { - case boolFlag: - return f.DefValue == "false" || f.DefValue == "" - case *durationValue: - // Beginning in Go 1.7, duration zero values are "0s" - return f.DefValue == "0" || f.DefValue == "0s" - case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value: - return f.DefValue == "0" - case *stringValue: - return f.DefValue == "" - case *ipValue, *ipMaskValue, *ipNetValue: - return f.DefValue == "" - case *intSliceValue, *stringSliceValue, *stringArrayValue: - return f.DefValue == "[]" - default: - switch f.DefValue { - case "false": - return true - case "": - return true - case "": - return true - case "0": - return true - } - return false - } -} - -// UnquoteUsage extracts a back-quoted name from the usage -// string for a flag and returns it and the un-quoted usage. -// Given "a `name` to show" it returns ("name", "a name to show"). -// If there are no back quotes, the name is an educated guess of the -// type of the flag's value, or the empty string if the flag is boolean. -func UnquoteUsage(flag *Flag) (name string, usage string) { - // Look for a back-quoted name, but avoid the strings package. - usage = flag.Usage - for i := 0; i < len(usage); i++ { - if usage[i] == '`' { - for j := i + 1; j < len(usage); j++ { - if usage[j] == '`' { - name = usage[i+1 : j] - usage = usage[:i] + name + usage[j+1:] - return name, usage - } - } - break // Only one back quote; use type name. - } - } - - name = flag.Value.Type() - switch name { - case "bool", "boolfunc": - name = "" - case "func": - name = "value" - case "float64": - name = "float" - case "int64": - name = "int" - case "uint64": - name = "uint" - case "stringSlice": - name = "strings" - case "intSlice": - name = "ints" - case "uintSlice": - name = "uints" - case "boolSlice": - name = "bools" - } - - return -} - -// Splits the string `s` on whitespace into an initial substring up to -// `i` runes in length and the remainder. Will go `slop` over `i` if -// that encompasses the entire string (which allows the caller to -// avoid short orphan words on the final line). -func wrapN(i, slop int, s string) (string, string) { - if i+slop > len(s) { - return s, "" - } - - w := strings.LastIndexAny(s[:i], " \t\n") - if w <= 0 { - return s, "" - } - nlPos := strings.LastIndex(s[:i], "\n") - if nlPos > 0 && nlPos < w { - return s[:nlPos], s[nlPos+1:] - } - return s[:w], s[w+1:] -} - -// Wraps the string `s` to a maximum width `w` with leading indent -// `i`. The first line is not indented (this is assumed to be done by -// caller). Pass `w` == 0 to do no wrapping -func wrap(i, w int, s string) string { - if w == 0 { - return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1) - } - - // space between indent i and end of line width w into which - // we should wrap the text. - wrap := w - i - - var r, l string - - // Not enough space for sensible wrapping. Wrap as a block on - // the next line instead. - if wrap < 24 { - i = 16 - wrap = w - i - r += "\n" + strings.Repeat(" ", i) - } - // If still not enough space then don't even try to wrap. - if wrap < 24 { - return strings.Replace(s, "\n", r, -1) - } - - // Try to avoid short orphan words on the final line, by - // allowing wrapN to go a bit over if that would fit in the - // remainder of the line. - slop := 5 - wrap = wrap - slop - - // Handle first line, which is indented by the caller (or the - // special case above) - l, s = wrapN(wrap, slop, s) - r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1) - - // Now wrap the rest - for s != "" { - var t string - - t, s = wrapN(wrap, slop, s) - r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1) - } - - return r - -} - -// FlagUsagesWrapped returns a string containing the usage information -// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no -// wrapping) -func (f *FlagSet) FlagUsagesWrapped(cols int) string { - buf := new(bytes.Buffer) - - lines := make([]string, 0, len(f.formal)) - - maxlen := 0 - f.VisitAll(func(flag *Flag) { - if flag.Hidden { - return - } - - line := "" - if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { - line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name) - } else { - line = fmt.Sprintf(" --%s", flag.Name) - } - - varname, usage := UnquoteUsage(flag) - if varname != "" { - line += " " + varname - } - if flag.NoOptDefVal != "" { - switch flag.Value.Type() { - case "string": - line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal) - case "bool", "boolfunc": - if flag.NoOptDefVal != "true" { - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - case "count": - if flag.NoOptDefVal != "+1" { - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - default: - line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) - } - } - - // This special character will be replaced with spacing once the - // correct alignment is calculated - line += "\x00" - if len(line) > maxlen { - maxlen = len(line) - } - - line += usage - if !flag.defaultIsZeroValue() { - if flag.Value.Type() == "string" { - line += fmt.Sprintf(" (default %q)", flag.DefValue) - } else { - line += fmt.Sprintf(" (default %s)", flag.DefValue) - } - } - if len(flag.Deprecated) != 0 { - line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated) - } - - lines = append(lines, line) - }) - - for _, line := range lines { - sidx := strings.Index(line, "\x00") - spacing := strings.Repeat(" ", maxlen-sidx) - // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx - fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:])) - } - - return buf.String() -} - -// FlagUsages returns a string containing the usage information for all flags in -// the FlagSet -func (f *FlagSet) FlagUsages() string { - return f.FlagUsagesWrapped(0) -} - -// PrintDefaults prints to standard error the default values of all defined command-line flags. -func PrintDefaults() { - CommandLine.PrintDefaults() -} - -// defaultUsage is the default function to print a usage message. -func defaultUsage(f *FlagSet) { - fmt.Fprintf(f.Output(), "Usage of %s:\n", f.name) - f.PrintDefaults() -} - -// NOTE: Usage is not just defaultUsage(CommandLine) -// because it serves (via godoc flag Usage) as the example -// for how to write your own usage function. - -// Usage prints to standard error a usage message documenting all defined command-line flags. -// The function is a variable that may be changed to point to a custom function. -// By default it prints a simple header and calls PrintDefaults; for details about the -// format of the output and how to control it, see the documentation for PrintDefaults. -var Usage = func() { - fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) - PrintDefaults() -} - -// NFlag returns the number of flags that have been set. -func (f *FlagSet) NFlag() int { return len(f.actual) } - -// NFlag returns the number of command-line flags that have been set. -func NFlag() int { return len(CommandLine.actual) } - -// Arg returns the i'th argument. Arg(0) is the first remaining argument -// after flags have been processed. -func (f *FlagSet) Arg(i int) string { - if i < 0 || i >= len(f.args) { - return "" - } - return f.args[i] -} - -// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument -// after flags have been processed. -func Arg(i int) string { - return CommandLine.Arg(i) -} - -// NArg is the number of arguments remaining after flags have been processed. -func (f *FlagSet) NArg() int { return len(f.args) } - -// NArg is the number of arguments remaining after flags have been processed. -func NArg() int { return len(CommandLine.args) } - -// Args returns the non-flag arguments. -func (f *FlagSet) Args() []string { return f.args } - -// Args returns the non-flag command-line arguments. -func Args() []string { return CommandLine.args } - -// Var defines a flag with the specified name and usage string. The type and -// value of the flag are represented by the first argument, of type Value, which -// typically holds a user-defined implementation of Value. For instance, the -// caller could create a flag that turns a comma-separated string into a slice -// of strings by giving the slice the methods of Value; in particular, Set would -// decompose the comma-separated string into the slice. -func (f *FlagSet) Var(value Value, name string, usage string) { - f.VarP(value, name, "", usage) -} - -// VarPF is like VarP, but returns the flag created -func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag { - // Remember the default value as a string; it won't change. - flag := &Flag{ - Name: name, - Shorthand: shorthand, - Usage: usage, - Value: value, - DefValue: value.String(), - } - f.AddFlag(flag) - return flag -} - -// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) VarP(value Value, name, shorthand, usage string) { - f.VarPF(value, name, shorthand, usage) -} - -// AddFlag will add the flag to the FlagSet -func (f *FlagSet) AddFlag(flag *Flag) { - normalizedFlagName := f.normalizeFlagName(flag.Name) - - _, alreadyThere := f.formal[normalizedFlagName] - if alreadyThere { - msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name) - fmt.Fprintln(f.Output(), msg) - panic(msg) // Happens only if flags are declared with identical names - } - if f.formal == nil { - f.formal = make(map[NormalizedName]*Flag) - } - - flag.Name = string(normalizedFlagName) - f.formal[normalizedFlagName] = flag - f.orderedFormal = append(f.orderedFormal, flag) - - if flag.Shorthand == "" { - return - } - if len(flag.Shorthand) > 1 { - msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand) - fmt.Fprintf(f.Output(), msg) - panic(msg) - } - if f.shorthands == nil { - f.shorthands = make(map[byte]*Flag) - } - c := flag.Shorthand[0] - used, alreadyThere := f.shorthands[c] - if alreadyThere { - msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name) - fmt.Fprintf(f.Output(), msg) - panic(msg) - } - f.shorthands[c] = flag -} - -// AddFlagSet adds one FlagSet to another. If a flag is already present in f -// the flag from newSet will be ignored. -func (f *FlagSet) AddFlagSet(newSet *FlagSet) { - if newSet == nil { - return - } - newSet.VisitAll(func(flag *Flag) { - if f.Lookup(flag.Name) == nil { - f.AddFlag(flag) - } - }) -} - -// Var defines a flag with the specified name and usage string. The type and -// value of the flag are represented by the first argument, of type Value, which -// typically holds a user-defined implementation of Value. For instance, the -// caller could create a flag that turns a comma-separated string into a slice -// of strings by giving the slice the methods of Value; in particular, Set would -// decompose the comma-separated string into the slice. -func Var(value Value, name string, usage string) { - CommandLine.VarP(value, name, "", usage) -} - -// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. -func VarP(value Value, name, shorthand, usage string) { - CommandLine.VarP(value, name, shorthand, usage) -} - -// fail prints an error message and usage message to standard error and -// returns the error. -func (f *FlagSet) fail(err error) error { - if f.errorHandling != ContinueOnError { - f.usage() - } - return err -} - -// usage calls the Usage method for the flag set, or the usage function if -// the flag set is CommandLine. -func (f *FlagSet) usage() { - if f == CommandLine { - Usage() - } else if f.Usage == nil { - defaultUsage(f) - } else { - f.Usage() - } -} - -// --unknown (args will be empty) -// --unknown --next-flag ... (args will be --next-flag ...) -// --unknown arg ... (args will be arg ...) -func stripUnknownFlagValue(args []string) []string { - if len(args) == 0 { - //--unknown - return args - } - - first := args[0] - if len(first) > 0 && first[0] == '-' { - //--unknown --next-flag ... - return args - } - - //--unknown arg ... (args will be arg ...) - if len(args) > 1 { - return args[1:] - } - return nil -} - -func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) { - a = args - name := s[2:] - if len(name) == 0 || name[0] == '-' || name[0] == '=' { - err = f.fail(&InvalidSyntaxError{specifiedFlag: s}) - return - } - - split := strings.SplitN(name, "=", 2) - name = split[0] - flag, exists := f.formal[f.normalizeFlagName(name)] - - if !exists { - switch { - case name == "help": - f.usage() - return a, ErrHelp - case f.ParseErrorsWhitelist.UnknownFlags: - fallthrough - case f.ParseErrorsAllowlist.UnknownFlags: - // --unknown=unknownval arg ... - // we do not want to lose arg in this case - if len(split) >= 2 { - return a, nil - } - - return stripUnknownFlagValue(a), nil - default: - err = f.fail(&NotExistError{name: name, messageType: flagUnknownFlagMessage}) - return - } - } - - var value string - if len(split) == 2 { - // '--flag=arg' - value = split[1] - } else if flag.NoOptDefVal != "" { - // '--flag' (arg was optional) - value = flag.NoOptDefVal - } else if len(a) > 0 { - // '--flag arg' - value = a[0] - a = a[1:] - } else { - // '--flag' (arg was required) - err = f.fail(&ValueRequiredError{ - flag: flag, - specifiedName: name, - }) - return - } - - err = fn(flag, value) - if err != nil { - f.fail(err) - } - return -} - -func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) { - outArgs = args - - if isGotestShorthandFlag(shorthands) { - return - } - - outShorts = shorthands[1:] - c := shorthands[0] - - flag, exists := f.shorthands[c] - if !exists { - switch { - case c == 'h': - f.usage() - err = ErrHelp - return - case f.ParseErrorsWhitelist.UnknownFlags: - fallthrough - case f.ParseErrorsAllowlist.UnknownFlags: - // '-f=arg arg ...' - // we do not want to lose arg in this case - if len(shorthands) > 2 && shorthands[1] == '=' { - outShorts = "" - return - } - - outArgs = stripUnknownFlagValue(outArgs) - return - default: - err = f.fail(&NotExistError{ - name: string(c), - specifiedShorthands: shorthands, - messageType: flagUnknownShorthandFlagMessage, - }) - return - } - } - - var value string - if len(shorthands) > 2 && shorthands[1] == '=' { - // '-f=arg' - value = shorthands[2:] - outShorts = "" - } else if flag.NoOptDefVal != "" { - // '-f' (arg was optional) - value = flag.NoOptDefVal - } else if len(shorthands) > 1 { - // '-farg' - value = shorthands[1:] - outShorts = "" - } else if len(args) > 0 { - // '-f arg' - value = args[0] - outArgs = args[1:] - } else { - // '-f' (arg was required) - err = f.fail(&ValueRequiredError{ - flag: flag, - specifiedName: string(c), - specifiedShorthands: shorthands, - }) - return - } - - if flag.ShorthandDeprecated != "" { - fmt.Fprintf(f.Output(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated) - } - - err = fn(flag, value) - if err != nil { - f.fail(err) - } - return -} - -func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) { - a = args - shorthands := s[1:] - - // "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv"). - for len(shorthands) > 0 { - shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn) - if err != nil { - return - } - } - - return -} - -func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) { - for len(args) > 0 { - s := args[0] - args = args[1:] - if len(s) == 0 || s[0] != '-' || len(s) == 1 { - if !f.interspersed { - f.args = append(f.args, s) - f.args = append(f.args, args...) - return nil - } - f.args = append(f.args, s) - continue - } - - if s[1] == '-' { - if len(s) == 2 { // "--" terminates the flags - f.argsLenAtDash = len(f.args) - f.args = append(f.args, args...) - break - } - args, err = f.parseLongArg(s, args, fn) - } else { - args, err = f.parseShortArg(s, args, fn) - } - if err != nil { - return - } - } - return -} - -// Parse parses flag definitions from the argument list, which should not -// include the command name. Must be called after all flags in the FlagSet -// are defined and before flags are accessed by the program. -// The return value will be ErrHelp if -help was set but not defined. -func (f *FlagSet) Parse(arguments []string) error { - if f.addedGoFlagSets != nil { - for _, goFlagSet := range f.addedGoFlagSets { - goFlagSet.Parse(nil) - } - } - f.parsed = true - - f.args = make([]string, 0, len(arguments)) - - if len(arguments) == 0 { - return nil - } - - set := func(flag *Flag, value string) error { - return f.Set(flag.Name, value) - } - - err := f.parseArgs(arguments, set) - if err != nil { - switch f.errorHandling { - case ContinueOnError: - return err - case ExitOnError: - if err == ErrHelp { - os.Exit(0) - } - fmt.Fprintln(f.Output(), err) - os.Exit(2) - case PanicOnError: - panic(err) - } - } - return nil -} - -type parseFunc func(flag *Flag, value string) error - -// ParseAll parses flag definitions from the argument list, which should not -// include the command name. The arguments for fn are flag and value. Must be -// called after all flags in the FlagSet are defined and before flags are -// accessed by the program. The return value will be ErrHelp if -help was set -// but not defined. -func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error { - f.parsed = true - f.args = make([]string, 0, len(arguments)) - - err := f.parseArgs(arguments, fn) - if err != nil { - switch f.errorHandling { - case ContinueOnError: - return err - case ExitOnError: - if err == ErrHelp { - os.Exit(0) - } - fmt.Fprintln(f.Output(), err) - os.Exit(2) - case PanicOnError: - panic(err) - } - } - return nil -} - -// Parsed reports whether f.Parse has been called. -func (f *FlagSet) Parsed() bool { - return f.parsed -} - -// Parse parses the command-line flags from os.Args[1:]. Must be called -// after all flags are defined and before flags are accessed by the program. -func Parse() { - // Ignore errors; CommandLine is set for ExitOnError. - CommandLine.Parse(os.Args[1:]) -} - -// ParseAll parses the command-line flags from os.Args[1:] and called fn for each. -// The arguments for fn are flag and value. Must be called after all flags are -// defined and before flags are accessed by the program. -func ParseAll(fn func(flag *Flag, value string) error) { - // Ignore errors; CommandLine is set for ExitOnError. - CommandLine.ParseAll(os.Args[1:], fn) -} - -// SetInterspersed sets whether to support interspersed option/non-option arguments. -func SetInterspersed(interspersed bool) { - CommandLine.SetInterspersed(interspersed) -} - -// Parsed returns true if the command-line flags have been parsed. -func Parsed() bool { - return CommandLine.Parsed() -} - -// CommandLine is the default set of command-line flags, parsed from os.Args. -var CommandLine = NewFlagSet(os.Args[0], ExitOnError) - -// NewFlagSet returns a new, empty flag set with the specified name, -// error handling property and SortFlags set to true. -func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet { - f := &FlagSet{ - name: name, - errorHandling: errorHandling, - argsLenAtDash: -1, - interspersed: true, - SortFlags: true, - } - return f -} - -// SetInterspersed sets whether to support interspersed option/non-option arguments. -func (f *FlagSet) SetInterspersed(interspersed bool) { - f.interspersed = interspersed -} - -// Init sets the name and error handling property for a flag set. -// By default, the zero FlagSet uses an empty name and the -// ContinueOnError error handling policy. -func (f *FlagSet) Init(name string, errorHandling ErrorHandling) { - f.name = name - f.errorHandling = errorHandling - f.argsLenAtDash = -1 -} diff --git a/vendor/github.com/spf13/pflag/float32.go b/vendor/github.com/spf13/pflag/float32.go deleted file mode 100644 index a243f81f7..000000000 --- a/vendor/github.com/spf13/pflag/float32.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- float32 Value -type float32Value float32 - -func newFloat32Value(val float32, p *float32) *float32Value { - *p = val - return (*float32Value)(p) -} - -func (f *float32Value) Set(s string) error { - v, err := strconv.ParseFloat(s, 32) - *f = float32Value(v) - return err -} - -func (f *float32Value) Type() string { - return "float32" -} - -func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) } - -func float32Conv(sval string) (interface{}, error) { - v, err := strconv.ParseFloat(sval, 32) - if err != nil { - return 0, err - } - return float32(v), nil -} - -// GetFloat32 return the float32 value of a flag with the given name -func (f *FlagSet) GetFloat32(name string) (float32, error) { - val, err := f.getFlagType(name, "float32", float32Conv) - if err != nil { - return 0, err - } - return val.(float32), nil -} - -// Float32Var defines a float32 flag with specified name, default value, and usage string. -// The argument p points to a float32 variable in which to store the value of the flag. -func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) { - f.VarP(newFloat32Value(value, p), name, "", usage) -} - -// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) { - f.VarP(newFloat32Value(value, p), name, shorthand, usage) -} - -// Float32Var defines a float32 flag with specified name, default value, and usage string. -// The argument p points to a float32 variable in which to store the value of the flag. -func Float32Var(p *float32, name string, value float32, usage string) { - CommandLine.VarP(newFloat32Value(value, p), name, "", usage) -} - -// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. -func Float32VarP(p *float32, name, shorthand string, value float32, usage string) { - CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage) -} - -// Float32 defines a float32 flag with specified name, default value, and usage string. -// The return value is the address of a float32 variable that stores the value of the flag. -func (f *FlagSet) Float32(name string, value float32, usage string) *float32 { - p := new(float32) - f.Float32VarP(p, name, "", value, usage) - return p -} - -// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 { - p := new(float32) - f.Float32VarP(p, name, shorthand, value, usage) - return p -} - -// Float32 defines a float32 flag with specified name, default value, and usage string. -// The return value is the address of a float32 variable that stores the value of the flag. -func Float32(name string, value float32, usage string) *float32 { - return CommandLine.Float32P(name, "", value, usage) -} - -// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. -func Float32P(name, shorthand string, value float32, usage string) *float32 { - return CommandLine.Float32P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/float32_slice.go b/vendor/github.com/spf13/pflag/float32_slice.go deleted file mode 100644 index caa352741..000000000 --- a/vendor/github.com/spf13/pflag/float32_slice.go +++ /dev/null @@ -1,174 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- float32Slice Value -type float32SliceValue struct { - value *[]float32 - changed bool -} - -func newFloat32SliceValue(val []float32, p *[]float32) *float32SliceValue { - isv := new(float32SliceValue) - isv.value = p - *isv.value = val - return isv -} - -func (s *float32SliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]float32, len(ss)) - for i, d := range ss { - var err error - var temp64 float64 - temp64, err = strconv.ParseFloat(d, 32) - if err != nil { - return err - } - out[i] = float32(temp64) - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *float32SliceValue) Type() string { - return "float32Slice" -} - -func (s *float32SliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%f", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func (s *float32SliceValue) fromString(val string) (float32, error) { - t64, err := strconv.ParseFloat(val, 32) - if err != nil { - return 0, err - } - return float32(t64), nil -} - -func (s *float32SliceValue) toString(val float32) string { - return fmt.Sprintf("%f", val) -} - -func (s *float32SliceValue) Append(val string) error { - i, err := s.fromString(val) - if err != nil { - return err - } - *s.value = append(*s.value, i) - return nil -} - -func (s *float32SliceValue) Replace(val []string) error { - out := make([]float32, len(val)) - for i, d := range val { - var err error - out[i], err = s.fromString(d) - if err != nil { - return err - } - } - *s.value = out - return nil -} - -func (s *float32SliceValue) GetSlice() []string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = s.toString(d) - } - return out -} - -func float32SliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []float32{}, nil - } - ss := strings.Split(val, ",") - out := make([]float32, len(ss)) - for i, d := range ss { - var err error - var temp64 float64 - temp64, err = strconv.ParseFloat(d, 32) - if err != nil { - return nil, err - } - out[i] = float32(temp64) - - } - return out, nil -} - -// GetFloat32Slice return the []float32 value of a flag with the given name -func (f *FlagSet) GetFloat32Slice(name string) ([]float32, error) { - val, err := f.getFlagType(name, "float32Slice", float32SliceConv) - if err != nil { - return []float32{}, err - } - return val.([]float32), nil -} - -// Float32SliceVar defines a float32Slice flag with specified name, default value, and usage string. -// The argument p points to a []float32 variable in which to store the value of the flag. -func (f *FlagSet) Float32SliceVar(p *[]float32, name string, value []float32, usage string) { - f.VarP(newFloat32SliceValue(value, p), name, "", usage) -} - -// Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float32SliceVarP(p *[]float32, name, shorthand string, value []float32, usage string) { - f.VarP(newFloat32SliceValue(value, p), name, shorthand, usage) -} - -// Float32SliceVar defines a float32[] flag with specified name, default value, and usage string. -// The argument p points to a float32[] variable in which to store the value of the flag. -func Float32SliceVar(p *[]float32, name string, value []float32, usage string) { - CommandLine.VarP(newFloat32SliceValue(value, p), name, "", usage) -} - -// Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash. -func Float32SliceVarP(p *[]float32, name, shorthand string, value []float32, usage string) { - CommandLine.VarP(newFloat32SliceValue(value, p), name, shorthand, usage) -} - -// Float32Slice defines a []float32 flag with specified name, default value, and usage string. -// The return value is the address of a []float32 variable that stores the value of the flag. -func (f *FlagSet) Float32Slice(name string, value []float32, usage string) *[]float32 { - p := []float32{} - f.Float32SliceVarP(&p, name, "", value, usage) - return &p -} - -// Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float32SliceP(name, shorthand string, value []float32, usage string) *[]float32 { - p := []float32{} - f.Float32SliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// Float32Slice defines a []float32 flag with specified name, default value, and usage string. -// The return value is the address of a []float32 variable that stores the value of the flag. -func Float32Slice(name string, value []float32, usage string) *[]float32 { - return CommandLine.Float32SliceP(name, "", value, usage) -} - -// Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash. -func Float32SliceP(name, shorthand string, value []float32, usage string) *[]float32 { - return CommandLine.Float32SliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/float64.go b/vendor/github.com/spf13/pflag/float64.go deleted file mode 100644 index 04b5492a7..000000000 --- a/vendor/github.com/spf13/pflag/float64.go +++ /dev/null @@ -1,84 +0,0 @@ -package pflag - -import "strconv" - -// -- float64 Value -type float64Value float64 - -func newFloat64Value(val float64, p *float64) *float64Value { - *p = val - return (*float64Value)(p) -} - -func (f *float64Value) Set(s string) error { - v, err := strconv.ParseFloat(s, 64) - *f = float64Value(v) - return err -} - -func (f *float64Value) Type() string { - return "float64" -} - -func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) } - -func float64Conv(sval string) (interface{}, error) { - return strconv.ParseFloat(sval, 64) -} - -// GetFloat64 return the float64 value of a flag with the given name -func (f *FlagSet) GetFloat64(name string) (float64, error) { - val, err := f.getFlagType(name, "float64", float64Conv) - if err != nil { - return 0, err - } - return val.(float64), nil -} - -// Float64Var defines a float64 flag with specified name, default value, and usage string. -// The argument p points to a float64 variable in which to store the value of the flag. -func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) { - f.VarP(newFloat64Value(value, p), name, "", usage) -} - -// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) { - f.VarP(newFloat64Value(value, p), name, shorthand, usage) -} - -// Float64Var defines a float64 flag with specified name, default value, and usage string. -// The argument p points to a float64 variable in which to store the value of the flag. -func Float64Var(p *float64, name string, value float64, usage string) { - CommandLine.VarP(newFloat64Value(value, p), name, "", usage) -} - -// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. -func Float64VarP(p *float64, name, shorthand string, value float64, usage string) { - CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage) -} - -// Float64 defines a float64 flag with specified name, default value, and usage string. -// The return value is the address of a float64 variable that stores the value of the flag. -func (f *FlagSet) Float64(name string, value float64, usage string) *float64 { - p := new(float64) - f.Float64VarP(p, name, "", value, usage) - return p -} - -// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 { - p := new(float64) - f.Float64VarP(p, name, shorthand, value, usage) - return p -} - -// Float64 defines a float64 flag with specified name, default value, and usage string. -// The return value is the address of a float64 variable that stores the value of the flag. -func Float64(name string, value float64, usage string) *float64 { - return CommandLine.Float64P(name, "", value, usage) -} - -// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. -func Float64P(name, shorthand string, value float64, usage string) *float64 { - return CommandLine.Float64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/float64_slice.go b/vendor/github.com/spf13/pflag/float64_slice.go deleted file mode 100644 index 85bf3073d..000000000 --- a/vendor/github.com/spf13/pflag/float64_slice.go +++ /dev/null @@ -1,166 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- float64Slice Value -type float64SliceValue struct { - value *[]float64 - changed bool -} - -func newFloat64SliceValue(val []float64, p *[]float64) *float64SliceValue { - isv := new(float64SliceValue) - isv.value = p - *isv.value = val - return isv -} - -func (s *float64SliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]float64, len(ss)) - for i, d := range ss { - var err error - out[i], err = strconv.ParseFloat(d, 64) - if err != nil { - return err - } - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *float64SliceValue) Type() string { - return "float64Slice" -} - -func (s *float64SliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%f", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func (s *float64SliceValue) fromString(val string) (float64, error) { - return strconv.ParseFloat(val, 64) -} - -func (s *float64SliceValue) toString(val float64) string { - return fmt.Sprintf("%f", val) -} - -func (s *float64SliceValue) Append(val string) error { - i, err := s.fromString(val) - if err != nil { - return err - } - *s.value = append(*s.value, i) - return nil -} - -func (s *float64SliceValue) Replace(val []string) error { - out := make([]float64, len(val)) - for i, d := range val { - var err error - out[i], err = s.fromString(d) - if err != nil { - return err - } - } - *s.value = out - return nil -} - -func (s *float64SliceValue) GetSlice() []string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = s.toString(d) - } - return out -} - -func float64SliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []float64{}, nil - } - ss := strings.Split(val, ",") - out := make([]float64, len(ss)) - for i, d := range ss { - var err error - out[i], err = strconv.ParseFloat(d, 64) - if err != nil { - return nil, err - } - - } - return out, nil -} - -// GetFloat64Slice return the []float64 value of a flag with the given name -func (f *FlagSet) GetFloat64Slice(name string) ([]float64, error) { - val, err := f.getFlagType(name, "float64Slice", float64SliceConv) - if err != nil { - return []float64{}, err - } - return val.([]float64), nil -} - -// Float64SliceVar defines a float64Slice flag with specified name, default value, and usage string. -// The argument p points to a []float64 variable in which to store the value of the flag. -func (f *FlagSet) Float64SliceVar(p *[]float64, name string, value []float64, usage string) { - f.VarP(newFloat64SliceValue(value, p), name, "", usage) -} - -// Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float64SliceVarP(p *[]float64, name, shorthand string, value []float64, usage string) { - f.VarP(newFloat64SliceValue(value, p), name, shorthand, usage) -} - -// Float64SliceVar defines a float64[] flag with specified name, default value, and usage string. -// The argument p points to a float64[] variable in which to store the value of the flag. -func Float64SliceVar(p *[]float64, name string, value []float64, usage string) { - CommandLine.VarP(newFloat64SliceValue(value, p), name, "", usage) -} - -// Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash. -func Float64SliceVarP(p *[]float64, name, shorthand string, value []float64, usage string) { - CommandLine.VarP(newFloat64SliceValue(value, p), name, shorthand, usage) -} - -// Float64Slice defines a []float64 flag with specified name, default value, and usage string. -// The return value is the address of a []float64 variable that stores the value of the flag. -func (f *FlagSet) Float64Slice(name string, value []float64, usage string) *[]float64 { - p := []float64{} - f.Float64SliceVarP(&p, name, "", value, usage) - return &p -} - -// Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Float64SliceP(name, shorthand string, value []float64, usage string) *[]float64 { - p := []float64{} - f.Float64SliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// Float64Slice defines a []float64 flag with specified name, default value, and usage string. -// The return value is the address of a []float64 variable that stores the value of the flag. -func Float64Slice(name string, value []float64, usage string) *[]float64 { - return CommandLine.Float64SliceP(name, "", value, usage) -} - -// Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash. -func Float64SliceP(name, shorthand string, value []float64, usage string) *[]float64 { - return CommandLine.Float64SliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/func.go b/vendor/github.com/spf13/pflag/func.go deleted file mode 100644 index 9f4d88f27..000000000 --- a/vendor/github.com/spf13/pflag/func.go +++ /dev/null @@ -1,37 +0,0 @@ -package pflag - -// -- func Value -type funcValue func(string) error - -func (f funcValue) Set(s string) error { return f(s) } - -func (f funcValue) Type() string { return "func" } - -func (f funcValue) String() string { return "" } // same behavior as stdlib 'flag' package - -// Func defines a func flag with specified name, callback function and usage string. -// -// The callback function will be called every time "--{name}={value}" (or equivalent) is -// parsed on the command line, with "{value}" as an argument. -func (f *FlagSet) Func(name string, usage string, fn func(string) error) { - f.FuncP(name, "", usage, fn) -} - -// FuncP is like Func, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) FuncP(name string, shorthand string, usage string, fn func(string) error) { - var val Value = funcValue(fn) - f.VarP(val, name, shorthand, usage) -} - -// Func defines a func flag with specified name, callback function and usage string. -// -// The callback function will be called every time "--{name}={value}" (or equivalent) is -// parsed on the command line, with "{value}" as an argument. -func Func(name string, usage string, fn func(string) error) { - CommandLine.FuncP(name, "", usage, fn) -} - -// FuncP is like Func, but accepts a shorthand letter that can be used after a single dash. -func FuncP(name, shorthand string, usage string, fn func(string) error) { - CommandLine.FuncP(name, shorthand, usage, fn) -} diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go deleted file mode 100644 index e62eab538..000000000 --- a/vendor/github.com/spf13/pflag/golangflag.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pflag - -import ( - goflag "flag" - "reflect" - "strings" - "time" -) - -// go test flags prefixes -func isGotestFlag(flag string) bool { - return strings.HasPrefix(flag, "-test.") -} - -func isGotestShorthandFlag(flag string) bool { - return strings.HasPrefix(flag, "test.") -} - -// flagValueWrapper implements pflag.Value around a flag.Value. The main -// difference here is the addition of the Type method that returns a string -// name of the type. As this is generally unknown, we approximate that with -// reflection. -type flagValueWrapper struct { - inner goflag.Value - flagType string -} - -// We are just copying the boolFlag interface out of goflag as that is what -// they use to decide if a flag should get "true" when no arg is given. -type goBoolFlag interface { - goflag.Value - IsBoolFlag() bool -} - -func wrapFlagValue(v goflag.Value) Value { - // If the flag.Value happens to also be a pflag.Value, just use it directly. - if pv, ok := v.(Value); ok { - return pv - } - - pv := &flagValueWrapper{ - inner: v, - } - - t := reflect.TypeOf(v) - if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr { - t = t.Elem() - } - - pv.flagType = strings.TrimSuffix(t.Name(), "Value") - return pv -} - -func (v *flagValueWrapper) String() string { - return v.inner.String() -} - -func (v *flagValueWrapper) Set(s string) error { - return v.inner.Set(s) -} - -func (v *flagValueWrapper) Type() string { - return v.flagType -} - -// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag -// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei -// with both `-v` and `--v` in flags. If the golang flag was more than a single -// character (ex: `verbose`) it will only be accessible via `--verbose` -func PFlagFromGoFlag(goflag *goflag.Flag) *Flag { - // Remember the default value as a string; it won't change. - flag := &Flag{ - Name: goflag.Name, - Usage: goflag.Usage, - Value: wrapFlagValue(goflag.Value), - // Looks like golang flags don't set DefValue correctly :-( - //DefValue: goflag.DefValue, - DefValue: goflag.Value.String(), - } - // Ex: if the golang flag was -v, allow both -v and --v to work - if len(flag.Name) == 1 { - flag.Shorthand = flag.Name - } - if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() { - flag.NoOptDefVal = "true" - } - return flag -} - -// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet -func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) { - if f.Lookup(goflag.Name) != nil { - return - } - newflag := PFlagFromGoFlag(goflag) - f.AddFlag(newflag) -} - -// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet -func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) { - if newSet == nil { - return - } - newSet.VisitAll(func(goflag *goflag.Flag) { - f.AddGoFlag(goflag) - }) - if f.addedGoFlagSets == nil { - f.addedGoFlagSets = make([]*goflag.FlagSet, 0) - } - f.addedGoFlagSets = append(f.addedGoFlagSets, newSet) -} - -// CopyToGoFlagSet will add all current flags to the given Go flag set. -// Deprecation remarks get copied into the usage description. -// Whenever possible, a flag gets added for which Go flags shows -// a proper type in the help message. -func (f *FlagSet) CopyToGoFlagSet(newSet *goflag.FlagSet) { - f.VisitAll(func(flag *Flag) { - usage := flag.Usage - if flag.Deprecated != "" { - usage += " (DEPRECATED: " + flag.Deprecated + ")" - } - - switch value := flag.Value.(type) { - case *stringValue: - newSet.StringVar((*string)(value), flag.Name, flag.DefValue, usage) - case *intValue: - newSet.IntVar((*int)(value), flag.Name, *(*int)(value), usage) - case *int64Value: - newSet.Int64Var((*int64)(value), flag.Name, *(*int64)(value), usage) - case *uintValue: - newSet.UintVar((*uint)(value), flag.Name, *(*uint)(value), usage) - case *uint64Value: - newSet.Uint64Var((*uint64)(value), flag.Name, *(*uint64)(value), usage) - case *durationValue: - newSet.DurationVar((*time.Duration)(value), flag.Name, *(*time.Duration)(value), usage) - case *float64Value: - newSet.Float64Var((*float64)(value), flag.Name, *(*float64)(value), usage) - default: - newSet.Var(flag.Value, flag.Name, usage) - } - }) -} - -// ParseSkippedFlags explicitly Parses go test flags (i.e. the one starting with '-test.') with goflag.Parse(), -// since by default those are skipped by pflag.Parse(). -// Typical usage example: `ParseGoTestFlags(os.Args[1:], goflag.CommandLine)` -func ParseSkippedFlags(osArgs []string, goFlagSet *goflag.FlagSet) error { - var skippedFlags []string - for _, f := range osArgs { - if isGotestFlag(f) { - skippedFlags = append(skippedFlags, f) - } - } - return goFlagSet.Parse(skippedFlags) -} - diff --git a/vendor/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go deleted file mode 100644 index 1474b89df..000000000 --- a/vendor/github.com/spf13/pflag/int.go +++ /dev/null @@ -1,84 +0,0 @@ -package pflag - -import "strconv" - -// -- int Value -type intValue int - -func newIntValue(val int, p *int) *intValue { - *p = val - return (*intValue)(p) -} - -func (i *intValue) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - *i = intValue(v) - return err -} - -func (i *intValue) Type() string { - return "int" -} - -func (i *intValue) String() string { return strconv.Itoa(int(*i)) } - -func intConv(sval string) (interface{}, error) { - return strconv.Atoi(sval) -} - -// GetInt return the int value of a flag with the given name -func (f *FlagSet) GetInt(name string) (int, error) { - val, err := f.getFlagType(name, "int", intConv) - if err != nil { - return 0, err - } - return val.(int), nil -} - -// IntVar defines an int flag with specified name, default value, and usage string. -// The argument p points to an int variable in which to store the value of the flag. -func (f *FlagSet) IntVar(p *int, name string, value int, usage string) { - f.VarP(newIntValue(value, p), name, "", usage) -} - -// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) { - f.VarP(newIntValue(value, p), name, shorthand, usage) -} - -// IntVar defines an int flag with specified name, default value, and usage string. -// The argument p points to an int variable in which to store the value of the flag. -func IntVar(p *int, name string, value int, usage string) { - CommandLine.VarP(newIntValue(value, p), name, "", usage) -} - -// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. -func IntVarP(p *int, name, shorthand string, value int, usage string) { - CommandLine.VarP(newIntValue(value, p), name, shorthand, usage) -} - -// Int defines an int flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -func (f *FlagSet) Int(name string, value int, usage string) *int { - p := new(int) - f.IntVarP(p, name, "", value, usage) - return p -} - -// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int { - p := new(int) - f.IntVarP(p, name, shorthand, value, usage) - return p -} - -// Int defines an int flag with specified name, default value, and usage string. -// The return value is the address of an int variable that stores the value of the flag. -func Int(name string, value int, usage string) *int { - return CommandLine.IntP(name, "", value, usage) -} - -// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. -func IntP(name, shorthand string, value int, usage string) *int { - return CommandLine.IntP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int16.go b/vendor/github.com/spf13/pflag/int16.go deleted file mode 100644 index f1a01d05e..000000000 --- a/vendor/github.com/spf13/pflag/int16.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- int16 Value -type int16Value int16 - -func newInt16Value(val int16, p *int16) *int16Value { - *p = val - return (*int16Value)(p) -} - -func (i *int16Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 16) - *i = int16Value(v) - return err -} - -func (i *int16Value) Type() string { - return "int16" -} - -func (i *int16Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int16Conv(sval string) (interface{}, error) { - v, err := strconv.ParseInt(sval, 0, 16) - if err != nil { - return 0, err - } - return int16(v), nil -} - -// GetInt16 returns the int16 value of a flag with the given name -func (f *FlagSet) GetInt16(name string) (int16, error) { - val, err := f.getFlagType(name, "int16", int16Conv) - if err != nil { - return 0, err - } - return val.(int16), nil -} - -// Int16Var defines an int16 flag with specified name, default value, and usage string. -// The argument p points to an int16 variable in which to store the value of the flag. -func (f *FlagSet) Int16Var(p *int16, name string, value int16, usage string) { - f.VarP(newInt16Value(value, p), name, "", usage) -} - -// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int16VarP(p *int16, name, shorthand string, value int16, usage string) { - f.VarP(newInt16Value(value, p), name, shorthand, usage) -} - -// Int16Var defines an int16 flag with specified name, default value, and usage string. -// The argument p points to an int16 variable in which to store the value of the flag. -func Int16Var(p *int16, name string, value int16, usage string) { - CommandLine.VarP(newInt16Value(value, p), name, "", usage) -} - -// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. -func Int16VarP(p *int16, name, shorthand string, value int16, usage string) { - CommandLine.VarP(newInt16Value(value, p), name, shorthand, usage) -} - -// Int16 defines an int16 flag with specified name, default value, and usage string. -// The return value is the address of an int16 variable that stores the value of the flag. -func (f *FlagSet) Int16(name string, value int16, usage string) *int16 { - p := new(int16) - f.Int16VarP(p, name, "", value, usage) - return p -} - -// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int16P(name, shorthand string, value int16, usage string) *int16 { - p := new(int16) - f.Int16VarP(p, name, shorthand, value, usage) - return p -} - -// Int16 defines an int16 flag with specified name, default value, and usage string. -// The return value is the address of an int16 variable that stores the value of the flag. -func Int16(name string, value int16, usage string) *int16 { - return CommandLine.Int16P(name, "", value, usage) -} - -// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. -func Int16P(name, shorthand string, value int16, usage string) *int16 { - return CommandLine.Int16P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int32.go b/vendor/github.com/spf13/pflag/int32.go deleted file mode 100644 index 9b95944f0..000000000 --- a/vendor/github.com/spf13/pflag/int32.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- int32 Value -type int32Value int32 - -func newInt32Value(val int32, p *int32) *int32Value { - *p = val - return (*int32Value)(p) -} - -func (i *int32Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 32) - *i = int32Value(v) - return err -} - -func (i *int32Value) Type() string { - return "int32" -} - -func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int32Conv(sval string) (interface{}, error) { - v, err := strconv.ParseInt(sval, 0, 32) - if err != nil { - return 0, err - } - return int32(v), nil -} - -// GetInt32 return the int32 value of a flag with the given name -func (f *FlagSet) GetInt32(name string) (int32, error) { - val, err := f.getFlagType(name, "int32", int32Conv) - if err != nil { - return 0, err - } - return val.(int32), nil -} - -// Int32Var defines an int32 flag with specified name, default value, and usage string. -// The argument p points to an int32 variable in which to store the value of the flag. -func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) { - f.VarP(newInt32Value(value, p), name, "", usage) -} - -// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) { - f.VarP(newInt32Value(value, p), name, shorthand, usage) -} - -// Int32Var defines an int32 flag with specified name, default value, and usage string. -// The argument p points to an int32 variable in which to store the value of the flag. -func Int32Var(p *int32, name string, value int32, usage string) { - CommandLine.VarP(newInt32Value(value, p), name, "", usage) -} - -// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. -func Int32VarP(p *int32, name, shorthand string, value int32, usage string) { - CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage) -} - -// Int32 defines an int32 flag with specified name, default value, and usage string. -// The return value is the address of an int32 variable that stores the value of the flag. -func (f *FlagSet) Int32(name string, value int32, usage string) *int32 { - p := new(int32) - f.Int32VarP(p, name, "", value, usage) - return p -} - -// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 { - p := new(int32) - f.Int32VarP(p, name, shorthand, value, usage) - return p -} - -// Int32 defines an int32 flag with specified name, default value, and usage string. -// The return value is the address of an int32 variable that stores the value of the flag. -func Int32(name string, value int32, usage string) *int32 { - return CommandLine.Int32P(name, "", value, usage) -} - -// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. -func Int32P(name, shorthand string, value int32, usage string) *int32 { - return CommandLine.Int32P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int32_slice.go b/vendor/github.com/spf13/pflag/int32_slice.go deleted file mode 100644 index ff128ff06..000000000 --- a/vendor/github.com/spf13/pflag/int32_slice.go +++ /dev/null @@ -1,174 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- int32Slice Value -type int32SliceValue struct { - value *[]int32 - changed bool -} - -func newInt32SliceValue(val []int32, p *[]int32) *int32SliceValue { - isv := new(int32SliceValue) - isv.value = p - *isv.value = val - return isv -} - -func (s *int32SliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]int32, len(ss)) - for i, d := range ss { - var err error - var temp64 int64 - temp64, err = strconv.ParseInt(d, 0, 32) - if err != nil { - return err - } - out[i] = int32(temp64) - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *int32SliceValue) Type() string { - return "int32Slice" -} - -func (s *int32SliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%d", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func (s *int32SliceValue) fromString(val string) (int32, error) { - t64, err := strconv.ParseInt(val, 0, 32) - if err != nil { - return 0, err - } - return int32(t64), nil -} - -func (s *int32SliceValue) toString(val int32) string { - return fmt.Sprintf("%d", val) -} - -func (s *int32SliceValue) Append(val string) error { - i, err := s.fromString(val) - if err != nil { - return err - } - *s.value = append(*s.value, i) - return nil -} - -func (s *int32SliceValue) Replace(val []string) error { - out := make([]int32, len(val)) - for i, d := range val { - var err error - out[i], err = s.fromString(d) - if err != nil { - return err - } - } - *s.value = out - return nil -} - -func (s *int32SliceValue) GetSlice() []string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = s.toString(d) - } - return out -} - -func int32SliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []int32{}, nil - } - ss := strings.Split(val, ",") - out := make([]int32, len(ss)) - for i, d := range ss { - var err error - var temp64 int64 - temp64, err = strconv.ParseInt(d, 0, 32) - if err != nil { - return nil, err - } - out[i] = int32(temp64) - - } - return out, nil -} - -// GetInt32Slice return the []int32 value of a flag with the given name -func (f *FlagSet) GetInt32Slice(name string) ([]int32, error) { - val, err := f.getFlagType(name, "int32Slice", int32SliceConv) - if err != nil { - return []int32{}, err - } - return val.([]int32), nil -} - -// Int32SliceVar defines a int32Slice flag with specified name, default value, and usage string. -// The argument p points to a []int32 variable in which to store the value of the flag. -func (f *FlagSet) Int32SliceVar(p *[]int32, name string, value []int32, usage string) { - f.VarP(newInt32SliceValue(value, p), name, "", usage) -} - -// Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int32SliceVarP(p *[]int32, name, shorthand string, value []int32, usage string) { - f.VarP(newInt32SliceValue(value, p), name, shorthand, usage) -} - -// Int32SliceVar defines a int32[] flag with specified name, default value, and usage string. -// The argument p points to a int32[] variable in which to store the value of the flag. -func Int32SliceVar(p *[]int32, name string, value []int32, usage string) { - CommandLine.VarP(newInt32SliceValue(value, p), name, "", usage) -} - -// Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash. -func Int32SliceVarP(p *[]int32, name, shorthand string, value []int32, usage string) { - CommandLine.VarP(newInt32SliceValue(value, p), name, shorthand, usage) -} - -// Int32Slice defines a []int32 flag with specified name, default value, and usage string. -// The return value is the address of a []int32 variable that stores the value of the flag. -func (f *FlagSet) Int32Slice(name string, value []int32, usage string) *[]int32 { - p := []int32{} - f.Int32SliceVarP(&p, name, "", value, usage) - return &p -} - -// Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int32SliceP(name, shorthand string, value []int32, usage string) *[]int32 { - p := []int32{} - f.Int32SliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// Int32Slice defines a []int32 flag with specified name, default value, and usage string. -// The return value is the address of a []int32 variable that stores the value of the flag. -func Int32Slice(name string, value []int32, usage string) *[]int32 { - return CommandLine.Int32SliceP(name, "", value, usage) -} - -// Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash. -func Int32SliceP(name, shorthand string, value []int32, usage string) *[]int32 { - return CommandLine.Int32SliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int64.go b/vendor/github.com/spf13/pflag/int64.go deleted file mode 100644 index 0026d781d..000000000 --- a/vendor/github.com/spf13/pflag/int64.go +++ /dev/null @@ -1,84 +0,0 @@ -package pflag - -import "strconv" - -// -- int64 Value -type int64Value int64 - -func newInt64Value(val int64, p *int64) *int64Value { - *p = val - return (*int64Value)(p) -} - -func (i *int64Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - *i = int64Value(v) - return err -} - -func (i *int64Value) Type() string { - return "int64" -} - -func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int64Conv(sval string) (interface{}, error) { - return strconv.ParseInt(sval, 0, 64) -} - -// GetInt64 return the int64 value of a flag with the given name -func (f *FlagSet) GetInt64(name string) (int64, error) { - val, err := f.getFlagType(name, "int64", int64Conv) - if err != nil { - return 0, err - } - return val.(int64), nil -} - -// Int64Var defines an int64 flag with specified name, default value, and usage string. -// The argument p points to an int64 variable in which to store the value of the flag. -func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) { - f.VarP(newInt64Value(value, p), name, "", usage) -} - -// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) { - f.VarP(newInt64Value(value, p), name, shorthand, usage) -} - -// Int64Var defines an int64 flag with specified name, default value, and usage string. -// The argument p points to an int64 variable in which to store the value of the flag. -func Int64Var(p *int64, name string, value int64, usage string) { - CommandLine.VarP(newInt64Value(value, p), name, "", usage) -} - -// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. -func Int64VarP(p *int64, name, shorthand string, value int64, usage string) { - CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage) -} - -// Int64 defines an int64 flag with specified name, default value, and usage string. -// The return value is the address of an int64 variable that stores the value of the flag. -func (f *FlagSet) Int64(name string, value int64, usage string) *int64 { - p := new(int64) - f.Int64VarP(p, name, "", value, usage) - return p -} - -// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 { - p := new(int64) - f.Int64VarP(p, name, shorthand, value, usage) - return p -} - -// Int64 defines an int64 flag with specified name, default value, and usage string. -// The return value is the address of an int64 variable that stores the value of the flag. -func Int64(name string, value int64, usage string) *int64 { - return CommandLine.Int64P(name, "", value, usage) -} - -// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. -func Int64P(name, shorthand string, value int64, usage string) *int64 { - return CommandLine.Int64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int64_slice.go b/vendor/github.com/spf13/pflag/int64_slice.go deleted file mode 100644 index 25464638f..000000000 --- a/vendor/github.com/spf13/pflag/int64_slice.go +++ /dev/null @@ -1,166 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- int64Slice Value -type int64SliceValue struct { - value *[]int64 - changed bool -} - -func newInt64SliceValue(val []int64, p *[]int64) *int64SliceValue { - isv := new(int64SliceValue) - isv.value = p - *isv.value = val - return isv -} - -func (s *int64SliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]int64, len(ss)) - for i, d := range ss { - var err error - out[i], err = strconv.ParseInt(d, 0, 64) - if err != nil { - return err - } - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *int64SliceValue) Type() string { - return "int64Slice" -} - -func (s *int64SliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%d", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func (s *int64SliceValue) fromString(val string) (int64, error) { - return strconv.ParseInt(val, 0, 64) -} - -func (s *int64SliceValue) toString(val int64) string { - return fmt.Sprintf("%d", val) -} - -func (s *int64SliceValue) Append(val string) error { - i, err := s.fromString(val) - if err != nil { - return err - } - *s.value = append(*s.value, i) - return nil -} - -func (s *int64SliceValue) Replace(val []string) error { - out := make([]int64, len(val)) - for i, d := range val { - var err error - out[i], err = s.fromString(d) - if err != nil { - return err - } - } - *s.value = out - return nil -} - -func (s *int64SliceValue) GetSlice() []string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = s.toString(d) - } - return out -} - -func int64SliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []int64{}, nil - } - ss := strings.Split(val, ",") - out := make([]int64, len(ss)) - for i, d := range ss { - var err error - out[i], err = strconv.ParseInt(d, 0, 64) - if err != nil { - return nil, err - } - - } - return out, nil -} - -// GetInt64Slice return the []int64 value of a flag with the given name -func (f *FlagSet) GetInt64Slice(name string) ([]int64, error) { - val, err := f.getFlagType(name, "int64Slice", int64SliceConv) - if err != nil { - return []int64{}, err - } - return val.([]int64), nil -} - -// Int64SliceVar defines a int64Slice flag with specified name, default value, and usage string. -// The argument p points to a []int64 variable in which to store the value of the flag. -func (f *FlagSet) Int64SliceVar(p *[]int64, name string, value []int64, usage string) { - f.VarP(newInt64SliceValue(value, p), name, "", usage) -} - -// Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int64SliceVarP(p *[]int64, name, shorthand string, value []int64, usage string) { - f.VarP(newInt64SliceValue(value, p), name, shorthand, usage) -} - -// Int64SliceVar defines a int64[] flag with specified name, default value, and usage string. -// The argument p points to a int64[] variable in which to store the value of the flag. -func Int64SliceVar(p *[]int64, name string, value []int64, usage string) { - CommandLine.VarP(newInt64SliceValue(value, p), name, "", usage) -} - -// Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash. -func Int64SliceVarP(p *[]int64, name, shorthand string, value []int64, usage string) { - CommandLine.VarP(newInt64SliceValue(value, p), name, shorthand, usage) -} - -// Int64Slice defines a []int64 flag with specified name, default value, and usage string. -// The return value is the address of a []int64 variable that stores the value of the flag. -func (f *FlagSet) Int64Slice(name string, value []int64, usage string) *[]int64 { - p := []int64{} - f.Int64SliceVarP(&p, name, "", value, usage) - return &p -} - -// Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int64SliceP(name, shorthand string, value []int64, usage string) *[]int64 { - p := []int64{} - f.Int64SliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// Int64Slice defines a []int64 flag with specified name, default value, and usage string. -// The return value is the address of a []int64 variable that stores the value of the flag. -func Int64Slice(name string, value []int64, usage string) *[]int64 { - return CommandLine.Int64SliceP(name, "", value, usage) -} - -// Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash. -func Int64SliceP(name, shorthand string, value []int64, usage string) *[]int64 { - return CommandLine.Int64SliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int8.go b/vendor/github.com/spf13/pflag/int8.go deleted file mode 100644 index 4da92228e..000000000 --- a/vendor/github.com/spf13/pflag/int8.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- int8 Value -type int8Value int8 - -func newInt8Value(val int8, p *int8) *int8Value { - *p = val - return (*int8Value)(p) -} - -func (i *int8Value) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 8) - *i = int8Value(v) - return err -} - -func (i *int8Value) Type() string { - return "int8" -} - -func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) } - -func int8Conv(sval string) (interface{}, error) { - v, err := strconv.ParseInt(sval, 0, 8) - if err != nil { - return 0, err - } - return int8(v), nil -} - -// GetInt8 return the int8 value of a flag with the given name -func (f *FlagSet) GetInt8(name string) (int8, error) { - val, err := f.getFlagType(name, "int8", int8Conv) - if err != nil { - return 0, err - } - return val.(int8), nil -} - -// Int8Var defines an int8 flag with specified name, default value, and usage string. -// The argument p points to an int8 variable in which to store the value of the flag. -func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) { - f.VarP(newInt8Value(value, p), name, "", usage) -} - -// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) { - f.VarP(newInt8Value(value, p), name, shorthand, usage) -} - -// Int8Var defines an int8 flag with specified name, default value, and usage string. -// The argument p points to an int8 variable in which to store the value of the flag. -func Int8Var(p *int8, name string, value int8, usage string) { - CommandLine.VarP(newInt8Value(value, p), name, "", usage) -} - -// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. -func Int8VarP(p *int8, name, shorthand string, value int8, usage string) { - CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage) -} - -// Int8 defines an int8 flag with specified name, default value, and usage string. -// The return value is the address of an int8 variable that stores the value of the flag. -func (f *FlagSet) Int8(name string, value int8, usage string) *int8 { - p := new(int8) - f.Int8VarP(p, name, "", value, usage) - return p -} - -// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 { - p := new(int8) - f.Int8VarP(p, name, shorthand, value, usage) - return p -} - -// Int8 defines an int8 flag with specified name, default value, and usage string. -// The return value is the address of an int8 variable that stores the value of the flag. -func Int8(name string, value int8, usage string) *int8 { - return CommandLine.Int8P(name, "", value, usage) -} - -// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. -func Int8P(name, shorthand string, value int8, usage string) *int8 { - return CommandLine.Int8P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/int_slice.go b/vendor/github.com/spf13/pflag/int_slice.go deleted file mode 100644 index e71c39d91..000000000 --- a/vendor/github.com/spf13/pflag/int_slice.go +++ /dev/null @@ -1,158 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- intSlice Value -type intSliceValue struct { - value *[]int - changed bool -} - -func newIntSliceValue(val []int, p *[]int) *intSliceValue { - isv := new(intSliceValue) - isv.value = p - *isv.value = val - return isv -} - -func (s *intSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]int, len(ss)) - for i, d := range ss { - var err error - out[i], err = strconv.Atoi(d) - if err != nil { - return err - } - - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *intSliceValue) Type() string { - return "intSlice" -} - -func (s *intSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%d", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func (s *intSliceValue) Append(val string) error { - i, err := strconv.Atoi(val) - if err != nil { - return err - } - *s.value = append(*s.value, i) - return nil -} - -func (s *intSliceValue) Replace(val []string) error { - out := make([]int, len(val)) - for i, d := range val { - var err error - out[i], err = strconv.Atoi(d) - if err != nil { - return err - } - } - *s.value = out - return nil -} - -func (s *intSliceValue) GetSlice() []string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = strconv.Itoa(d) - } - return out -} - -func intSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []int{}, nil - } - ss := strings.Split(val, ",") - out := make([]int, len(ss)) - for i, d := range ss { - var err error - out[i], err = strconv.Atoi(d) - if err != nil { - return nil, err - } - - } - return out, nil -} - -// GetIntSlice return the []int value of a flag with the given name -func (f *FlagSet) GetIntSlice(name string) ([]int, error) { - val, err := f.getFlagType(name, "intSlice", intSliceConv) - if err != nil { - return []int{}, err - } - return val.([]int), nil -} - -// IntSliceVar defines a intSlice flag with specified name, default value, and usage string. -// The argument p points to a []int variable in which to store the value of the flag. -func (f *FlagSet) IntSliceVar(p *[]int, name string, value []int, usage string) { - f.VarP(newIntSliceValue(value, p), name, "", usage) -} - -// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { - f.VarP(newIntSliceValue(value, p), name, shorthand, usage) -} - -// IntSliceVar defines a int[] flag with specified name, default value, and usage string. -// The argument p points to a int[] variable in which to store the value of the flag. -func IntSliceVar(p *[]int, name string, value []int, usage string) { - CommandLine.VarP(newIntSliceValue(value, p), name, "", usage) -} - -// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. -func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { - CommandLine.VarP(newIntSliceValue(value, p), name, shorthand, usage) -} - -// IntSlice defines a []int flag with specified name, default value, and usage string. -// The return value is the address of a []int variable that stores the value of the flag. -func (f *FlagSet) IntSlice(name string, value []int, usage string) *[]int { - p := []int{} - f.IntSliceVarP(&p, name, "", value, usage) - return &p -} - -// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IntSliceP(name, shorthand string, value []int, usage string) *[]int { - p := []int{} - f.IntSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// IntSlice defines a []int flag with specified name, default value, and usage string. -// The return value is the address of a []int variable that stores the value of the flag. -func IntSlice(name string, value []int, usage string) *[]int { - return CommandLine.IntSliceP(name, "", value, usage) -} - -// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. -func IntSliceP(name, shorthand string, value []int, usage string) *[]int { - return CommandLine.IntSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go deleted file mode 100644 index 06b8bcb57..000000000 --- a/vendor/github.com/spf13/pflag/ip.go +++ /dev/null @@ -1,97 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strings" -) - -// -- net.IP value -type ipValue net.IP - -func newIPValue(val net.IP, p *net.IP) *ipValue { - *p = val - return (*ipValue)(p) -} - -func (i *ipValue) String() string { return net.IP(*i).String() } -func (i *ipValue) Set(s string) error { - if s == "" { - return nil - } - ip := net.ParseIP(strings.TrimSpace(s)) - if ip == nil { - return fmt.Errorf("failed to parse IP: %q", s) - } - *i = ipValue(ip) - return nil -} - -func (i *ipValue) Type() string { - return "ip" -} - -func ipConv(sval string) (interface{}, error) { - ip := net.ParseIP(sval) - if ip != nil { - return ip, nil - } - return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval) -} - -// GetIP return the net.IP value of a flag with the given name -func (f *FlagSet) GetIP(name string) (net.IP, error) { - val, err := f.getFlagType(name, "ip", ipConv) - if err != nil { - return nil, err - } - return val.(net.IP), nil -} - -// IPVar defines an net.IP flag with specified name, default value, and usage string. -// The argument p points to an net.IP variable in which to store the value of the flag. -func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) { - f.VarP(newIPValue(value, p), name, "", usage) -} - -// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { - f.VarP(newIPValue(value, p), name, shorthand, usage) -} - -// IPVar defines an net.IP flag with specified name, default value, and usage string. -// The argument p points to an net.IP variable in which to store the value of the flag. -func IPVar(p *net.IP, name string, value net.IP, usage string) { - CommandLine.VarP(newIPValue(value, p), name, "", usage) -} - -// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. -func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { - CommandLine.VarP(newIPValue(value, p), name, shorthand, usage) -} - -// IP defines an net.IP flag with specified name, default value, and usage string. -// The return value is the address of an net.IP variable that stores the value of the flag. -func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP { - p := new(net.IP) - f.IPVarP(p, name, "", value, usage) - return p -} - -// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP { - p := new(net.IP) - f.IPVarP(p, name, shorthand, value, usage) - return p -} - -// IP defines an net.IP flag with specified name, default value, and usage string. -// The return value is the address of an net.IP variable that stores the value of the flag. -func IP(name string, value net.IP, usage string) *net.IP { - return CommandLine.IPP(name, "", value, usage) -} - -// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. -func IPP(name, shorthand string, value net.IP, usage string) *net.IP { - return CommandLine.IPP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ip_slice.go b/vendor/github.com/spf13/pflag/ip_slice.go deleted file mode 100644 index 775faae4f..000000000 --- a/vendor/github.com/spf13/pflag/ip_slice.go +++ /dev/null @@ -1,186 +0,0 @@ -package pflag - -import ( - "fmt" - "io" - "net" - "strings" -) - -// -- ipSlice Value -type ipSliceValue struct { - value *[]net.IP - changed bool -} - -func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue { - ipsv := new(ipSliceValue) - ipsv.value = p - *ipsv.value = val - return ipsv -} - -// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag. -// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended. -func (s *ipSliceValue) Set(val string) error { - - // remove all quote characters - rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") - - // read flag arguments with CSV parser - ipStrSlice, err := readAsCSV(rmQuote.Replace(val)) - if err != nil && err != io.EOF { - return err - } - - // parse ip values into slice - out := make([]net.IP, 0, len(ipStrSlice)) - for _, ipStr := range ipStrSlice { - ip := net.ParseIP(strings.TrimSpace(ipStr)) - if ip == nil { - return fmt.Errorf("invalid string being converted to IP address: %s", ipStr) - } - out = append(out, ip) - } - - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - - s.changed = true - - return nil -} - -// Type returns a string that uniquely represents this flag's type. -func (s *ipSliceValue) Type() string { - return "ipSlice" -} - -// String defines a "native" format for this net.IP slice flag value. -func (s *ipSliceValue) String() string { - - ipStrSlice := make([]string, len(*s.value)) - for i, ip := range *s.value { - ipStrSlice[i] = ip.String() - } - - out, _ := writeAsCSV(ipStrSlice) - - return "[" + out + "]" -} - -func (s *ipSliceValue) fromString(val string) (net.IP, error) { - return net.ParseIP(strings.TrimSpace(val)), nil -} - -func (s *ipSliceValue) toString(val net.IP) string { - return val.String() -} - -func (s *ipSliceValue) Append(val string) error { - i, err := s.fromString(val) - if err != nil { - return err - } - *s.value = append(*s.value, i) - return nil -} - -func (s *ipSliceValue) Replace(val []string) error { - out := make([]net.IP, len(val)) - for i, d := range val { - var err error - out[i], err = s.fromString(d) - if err != nil { - return err - } - } - *s.value = out - return nil -} - -func (s *ipSliceValue) GetSlice() []string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = s.toString(d) - } - return out -} - -func ipSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []net.IP{}, nil - } - ss := strings.Split(val, ",") - out := make([]net.IP, len(ss)) - for i, sval := range ss { - ip := net.ParseIP(strings.TrimSpace(sval)) - if ip == nil { - return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval) - } - out[i] = ip - } - return out, nil -} - -// GetIPSlice returns the []net.IP value of a flag with the given name -func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) { - val, err := f.getFlagType(name, "ipSlice", ipSliceConv) - if err != nil { - return []net.IP{}, err - } - return val.([]net.IP), nil -} - -// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string. -// The argument p points to a []net.IP variable in which to store the value of the flag. -func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { - f.VarP(newIPSliceValue(value, p), name, "", usage) -} - -// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { - f.VarP(newIPSliceValue(value, p), name, shorthand, usage) -} - -// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string. -// The argument p points to a []net.IP variable in which to store the value of the flag. -func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { - CommandLine.VarP(newIPSliceValue(value, p), name, "", usage) -} - -// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. -func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { - CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage) -} - -// IPSlice defines a []net.IP flag with specified name, default value, and usage string. -// The return value is the address of a []net.IP variable that stores the value of that flag. -func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP { - p := []net.IP{} - f.IPSliceVarP(&p, name, "", value, usage) - return &p -} - -// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { - p := []net.IP{} - f.IPSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// IPSlice defines a []net.IP flag with specified name, default value, and usage string. -// The return value is the address of a []net.IP variable that stores the value of the flag. -func IPSlice(name string, value []net.IP, usage string) *[]net.IP { - return CommandLine.IPSliceP(name, "", value, usage) -} - -// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. -func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { - return CommandLine.IPSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ipmask.go b/vendor/github.com/spf13/pflag/ipmask.go deleted file mode 100644 index 5bd44bd21..000000000 --- a/vendor/github.com/spf13/pflag/ipmask.go +++ /dev/null @@ -1,122 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strconv" -) - -// -- net.IPMask value -type ipMaskValue net.IPMask - -func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue { - *p = val - return (*ipMaskValue)(p) -} - -func (i *ipMaskValue) String() string { return net.IPMask(*i).String() } -func (i *ipMaskValue) Set(s string) error { - ip := ParseIPv4Mask(s) - if ip == nil { - return fmt.Errorf("failed to parse IP mask: %q", s) - } - *i = ipMaskValue(ip) - return nil -} - -func (i *ipMaskValue) Type() string { - return "ipMask" -} - -// ParseIPv4Mask written in IP form (e.g. 255.255.255.0). -// This function should really belong to the net package. -func ParseIPv4Mask(s string) net.IPMask { - mask := net.ParseIP(s) - if mask == nil { - if len(s) != 8 { - return nil - } - // net.IPMask.String() actually outputs things like ffffff00 - // so write a horrible parser for that as well :-( - m := []int{} - for i := 0; i < 4; i++ { - b := "0x" + s[2*i:2*i+2] - d, err := strconv.ParseInt(b, 0, 0) - if err != nil { - return nil - } - m = append(m, int(d)) - } - s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3]) - mask = net.ParseIP(s) - if mask == nil { - return nil - } - } - return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15]) -} - -func parseIPv4Mask(sval string) (interface{}, error) { - mask := ParseIPv4Mask(sval) - if mask == nil { - return nil, fmt.Errorf("unable to parse %s as net.IPMask", sval) - } - return mask, nil -} - -// GetIPv4Mask return the net.IPv4Mask value of a flag with the given name -func (f *FlagSet) GetIPv4Mask(name string) (net.IPMask, error) { - val, err := f.getFlagType(name, "ipMask", parseIPv4Mask) - if err != nil { - return nil, err - } - return val.(net.IPMask), nil -} - -// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. -// The argument p points to an net.IPMask variable in which to store the value of the flag. -func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { - f.VarP(newIPMaskValue(value, p), name, "", usage) -} - -// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { - f.VarP(newIPMaskValue(value, p), name, shorthand, usage) -} - -// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. -// The argument p points to an net.IPMask variable in which to store the value of the flag. -func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { - CommandLine.VarP(newIPMaskValue(value, p), name, "", usage) -} - -// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. -func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { - CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage) -} - -// IPMask defines an net.IPMask flag with specified name, default value, and usage string. -// The return value is the address of an net.IPMask variable that stores the value of the flag. -func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask { - p := new(net.IPMask) - f.IPMaskVarP(p, name, "", value, usage) - return p -} - -// IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { - p := new(net.IPMask) - f.IPMaskVarP(p, name, shorthand, value, usage) - return p -} - -// IPMask defines an net.IPMask flag with specified name, default value, and usage string. -// The return value is the address of an net.IPMask variable that stores the value of the flag. -func IPMask(name string, value net.IPMask, usage string) *net.IPMask { - return CommandLine.IPMaskP(name, "", value, usage) -} - -// IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash. -func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { - return CommandLine.IPMaskP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ipnet.go b/vendor/github.com/spf13/pflag/ipnet.go deleted file mode 100644 index e2c1b8bcd..000000000 --- a/vendor/github.com/spf13/pflag/ipnet.go +++ /dev/null @@ -1,98 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strings" -) - -// IPNet adapts net.IPNet for use as a flag. -type ipNetValue net.IPNet - -func (ipnet ipNetValue) String() string { - n := net.IPNet(ipnet) - return n.String() -} - -func (ipnet *ipNetValue) Set(value string) error { - _, n, err := net.ParseCIDR(strings.TrimSpace(value)) - if err != nil { - return err - } - *ipnet = ipNetValue(*n) - return nil -} - -func (*ipNetValue) Type() string { - return "ipNet" -} - -func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue { - *p = val - return (*ipNetValue)(p) -} - -func ipNetConv(sval string) (interface{}, error) { - _, n, err := net.ParseCIDR(strings.TrimSpace(sval)) - if err == nil { - return *n, nil - } - return nil, fmt.Errorf("invalid string being converted to IPNet: %s", sval) -} - -// GetIPNet return the net.IPNet value of a flag with the given name -func (f *FlagSet) GetIPNet(name string) (net.IPNet, error) { - val, err := f.getFlagType(name, "ipNet", ipNetConv) - if err != nil { - return net.IPNet{}, err - } - return val.(net.IPNet), nil -} - -// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string. -// The argument p points to an net.IPNet variable in which to store the value of the flag. -func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) { - f.VarP(newIPNetValue(value, p), name, "", usage) -} - -// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { - f.VarP(newIPNetValue(value, p), name, shorthand, usage) -} - -// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string. -// The argument p points to an net.IPNet variable in which to store the value of the flag. -func IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) { - CommandLine.VarP(newIPNetValue(value, p), name, "", usage) -} - -// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. -func IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { - CommandLine.VarP(newIPNetValue(value, p), name, shorthand, usage) -} - -// IPNet defines an net.IPNet flag with specified name, default value, and usage string. -// The return value is the address of an net.IPNet variable that stores the value of the flag. -func (f *FlagSet) IPNet(name string, value net.IPNet, usage string) *net.IPNet { - p := new(net.IPNet) - f.IPNetVarP(p, name, "", value, usage) - return p -} - -// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { - p := new(net.IPNet) - f.IPNetVarP(p, name, shorthand, value, usage) - return p -} - -// IPNet defines an net.IPNet flag with specified name, default value, and usage string. -// The return value is the address of an net.IPNet variable that stores the value of the flag. -func IPNet(name string, value net.IPNet, usage string) *net.IPNet { - return CommandLine.IPNetP(name, "", value, usage) -} - -// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. -func IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { - return CommandLine.IPNetP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/ipnet_slice.go b/vendor/github.com/spf13/pflag/ipnet_slice.go deleted file mode 100644 index c6e89da18..000000000 --- a/vendor/github.com/spf13/pflag/ipnet_slice.go +++ /dev/null @@ -1,147 +0,0 @@ -package pflag - -import ( - "fmt" - "io" - "net" - "strings" -) - -// -- ipNetSlice Value -type ipNetSliceValue struct { - value *[]net.IPNet - changed bool -} - -func newIPNetSliceValue(val []net.IPNet, p *[]net.IPNet) *ipNetSliceValue { - ipnsv := new(ipNetSliceValue) - ipnsv.value = p - *ipnsv.value = val - return ipnsv -} - -// Set converts, and assigns, the comma-separated IPNet argument string representation as the []net.IPNet value of this flag. -// If Set is called on a flag that already has a []net.IPNet assigned, the newly converted values will be appended. -func (s *ipNetSliceValue) Set(val string) error { - - // remove all quote characters - rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") - - // read flag arguments with CSV parser - ipNetStrSlice, err := readAsCSV(rmQuote.Replace(val)) - if err != nil && err != io.EOF { - return err - } - - // parse ip values into slice - out := make([]net.IPNet, 0, len(ipNetStrSlice)) - for _, ipNetStr := range ipNetStrSlice { - _, n, err := net.ParseCIDR(strings.TrimSpace(ipNetStr)) - if err != nil { - return fmt.Errorf("invalid string being converted to CIDR: %s", ipNetStr) - } - out = append(out, *n) - } - - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - - s.changed = true - - return nil -} - -// Type returns a string that uniquely represents this flag's type. -func (s *ipNetSliceValue) Type() string { - return "ipNetSlice" -} - -// String defines a "native" format for this net.IPNet slice flag value. -func (s *ipNetSliceValue) String() string { - - ipNetStrSlice := make([]string, len(*s.value)) - for i, n := range *s.value { - ipNetStrSlice[i] = n.String() - } - - out, _ := writeAsCSV(ipNetStrSlice) - return "[" + out + "]" -} - -func ipNetSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []net.IPNet{}, nil - } - ss := strings.Split(val, ",") - out := make([]net.IPNet, len(ss)) - for i, sval := range ss { - _, n, err := net.ParseCIDR(strings.TrimSpace(sval)) - if err != nil { - return nil, fmt.Errorf("invalid string being converted to CIDR: %s", sval) - } - out[i] = *n - } - return out, nil -} - -// GetIPNetSlice returns the []net.IPNet value of a flag with the given name -func (f *FlagSet) GetIPNetSlice(name string) ([]net.IPNet, error) { - val, err := f.getFlagType(name, "ipNetSlice", ipNetSliceConv) - if err != nil { - return []net.IPNet{}, err - } - return val.([]net.IPNet), nil -} - -// IPNetSliceVar defines a ipNetSlice flag with specified name, default value, and usage string. -// The argument p points to a []net.IPNet variable in which to store the value of the flag. -func (f *FlagSet) IPNetSliceVar(p *[]net.IPNet, name string, value []net.IPNet, usage string) { - f.VarP(newIPNetSliceValue(value, p), name, "", usage) -} - -// IPNetSliceVarP is like IPNetSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPNetSliceVarP(p *[]net.IPNet, name, shorthand string, value []net.IPNet, usage string) { - f.VarP(newIPNetSliceValue(value, p), name, shorthand, usage) -} - -// IPNetSliceVar defines a []net.IPNet flag with specified name, default value, and usage string. -// The argument p points to a []net.IPNet variable in which to store the value of the flag. -func IPNetSliceVar(p *[]net.IPNet, name string, value []net.IPNet, usage string) { - CommandLine.VarP(newIPNetSliceValue(value, p), name, "", usage) -} - -// IPNetSliceVarP is like IPNetSliceVar, but accepts a shorthand letter that can be used after a single dash. -func IPNetSliceVarP(p *[]net.IPNet, name, shorthand string, value []net.IPNet, usage string) { - CommandLine.VarP(newIPNetSliceValue(value, p), name, shorthand, usage) -} - -// IPNetSlice defines a []net.IPNet flag with specified name, default value, and usage string. -// The return value is the address of a []net.IPNet variable that stores the value of that flag. -func (f *FlagSet) IPNetSlice(name string, value []net.IPNet, usage string) *[]net.IPNet { - p := []net.IPNet{} - f.IPNetSliceVarP(&p, name, "", value, usage) - return &p -} - -// IPNetSliceP is like IPNetSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) IPNetSliceP(name, shorthand string, value []net.IPNet, usage string) *[]net.IPNet { - p := []net.IPNet{} - f.IPNetSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// IPNetSlice defines a []net.IPNet flag with specified name, default value, and usage string. -// The return value is the address of a []net.IP variable that stores the value of the flag. -func IPNetSlice(name string, value []net.IPNet, usage string) *[]net.IPNet { - return CommandLine.IPNetSliceP(name, "", value, usage) -} - -// IPNetSliceP is like IPNetSlice, but accepts a shorthand letter that can be used after a single dash. -func IPNetSliceP(name, shorthand string, value []net.IPNet, usage string) *[]net.IPNet { - return CommandLine.IPNetSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go deleted file mode 100644 index 04e0a26ff..000000000 --- a/vendor/github.com/spf13/pflag/string.go +++ /dev/null @@ -1,80 +0,0 @@ -package pflag - -// -- string Value -type stringValue string - -func newStringValue(val string, p *string) *stringValue { - *p = val - return (*stringValue)(p) -} - -func (s *stringValue) Set(val string) error { - *s = stringValue(val) - return nil -} -func (s *stringValue) Type() string { - return "string" -} - -func (s *stringValue) String() string { return string(*s) } - -func stringConv(sval string) (interface{}, error) { - return sval, nil -} - -// GetString return the string value of a flag with the given name -func (f *FlagSet) GetString(name string) (string, error) { - val, err := f.getFlagType(name, "string", stringConv) - if err != nil { - return "", err - } - return val.(string), nil -} - -// StringVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a string variable in which to store the value of the flag. -func (f *FlagSet) StringVar(p *string, name string, value string, usage string) { - f.VarP(newStringValue(value, p), name, "", usage) -} - -// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) { - f.VarP(newStringValue(value, p), name, shorthand, usage) -} - -// StringVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a string variable in which to store the value of the flag. -func StringVar(p *string, name string, value string, usage string) { - CommandLine.VarP(newStringValue(value, p), name, "", usage) -} - -// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. -func StringVarP(p *string, name, shorthand string, value string, usage string) { - CommandLine.VarP(newStringValue(value, p), name, shorthand, usage) -} - -// String defines a string flag with specified name, default value, and usage string. -// The return value is the address of a string variable that stores the value of the flag. -func (f *FlagSet) String(name string, value string, usage string) *string { - p := new(string) - f.StringVarP(p, name, "", value, usage) - return p -} - -// StringP is like String, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string { - p := new(string) - f.StringVarP(p, name, shorthand, value, usage) - return p -} - -// String defines a string flag with specified name, default value, and usage string. -// The return value is the address of a string variable that stores the value of the flag. -func String(name string, value string, usage string) *string { - return CommandLine.StringP(name, "", value, usage) -} - -// StringP is like String, but accepts a shorthand letter that can be used after a single dash. -func StringP(name, shorthand string, value string, usage string) *string { - return CommandLine.StringP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go deleted file mode 100644 index d1ff0a96b..000000000 --- a/vendor/github.com/spf13/pflag/string_array.go +++ /dev/null @@ -1,125 +0,0 @@ -package pflag - -// -- stringArray Value -type stringArrayValue struct { - value *[]string - changed bool -} - -func newStringArrayValue(val []string, p *[]string) *stringArrayValue { - ssv := new(stringArrayValue) - ssv.value = p - *ssv.value = val - return ssv -} - -func (s *stringArrayValue) Set(val string) error { - if !s.changed { - *s.value = []string{val} - s.changed = true - } else { - *s.value = append(*s.value, val) - } - return nil -} - -func (s *stringArrayValue) Append(val string) error { - *s.value = append(*s.value, val) - return nil -} - -func (s *stringArrayValue) Replace(val []string) error { - out := make([]string, len(val)) - for i, d := range val { - out[i] = d - } - *s.value = out - return nil -} - -func (s *stringArrayValue) GetSlice() []string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = d - } - return out -} - -func (s *stringArrayValue) Type() string { - return "stringArray" -} - -func (s *stringArrayValue) String() string { - str, _ := writeAsCSV(*s.value) - return "[" + str + "]" -} - -func stringArrayConv(sval string) (interface{}, error) { - sval = sval[1 : len(sval)-1] - // An empty string would cause a array with one (empty) string - if len(sval) == 0 { - return []string{}, nil - } - return readAsCSV(sval) -} - -// GetStringArray return the []string value of a flag with the given name -func (f *FlagSet) GetStringArray(name string) ([]string, error) { - val, err := f.getFlagType(name, "stringArray", stringArrayConv) - if err != nil { - return []string{}, err - } - return val.([]string), nil -} - -// StringArrayVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the values of the multiple flags. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) { - f.VarP(newStringArrayValue(value, p), name, "", usage) -} - -// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { - f.VarP(newStringArrayValue(value, p), name, shorthand, usage) -} - -// StringArrayVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func StringArrayVar(p *[]string, name string, value []string, usage string) { - CommandLine.VarP(newStringArrayValue(value, p), name, "", usage) -} - -// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. -func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { - CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage) -} - -// StringArray defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string { - p := []string{} - f.StringArrayVarP(&p, name, "", value, usage) - return &p -} - -// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string { - p := []string{} - f.StringArrayVarP(&p, name, shorthand, value, usage) - return &p -} - -// StringArray defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma. Use a StringSlice for that. -func StringArray(name string, value []string, usage string) *[]string { - return CommandLine.StringArrayP(name, "", value, usage) -} - -// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. -func StringArrayP(name, shorthand string, value []string, usage string) *[]string { - return CommandLine.StringArrayP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go deleted file mode 100644 index 3cb2e69db..000000000 --- a/vendor/github.com/spf13/pflag/string_slice.go +++ /dev/null @@ -1,163 +0,0 @@ -package pflag - -import ( - "bytes" - "encoding/csv" - "strings" -) - -// -- stringSlice Value -type stringSliceValue struct { - value *[]string - changed bool -} - -func newStringSliceValue(val []string, p *[]string) *stringSliceValue { - ssv := new(stringSliceValue) - ssv.value = p - *ssv.value = val - return ssv -} - -func readAsCSV(val string) ([]string, error) { - if val == "" { - return []string{}, nil - } - stringReader := strings.NewReader(val) - csvReader := csv.NewReader(stringReader) - return csvReader.Read() -} - -func writeAsCSV(vals []string) (string, error) { - b := &bytes.Buffer{} - w := csv.NewWriter(b) - err := w.Write(vals) - if err != nil { - return "", err - } - w.Flush() - return strings.TrimSuffix(b.String(), "\n"), nil -} - -func (s *stringSliceValue) Set(val string) error { - v, err := readAsCSV(val) - if err != nil { - return err - } - if !s.changed { - *s.value = v - } else { - *s.value = append(*s.value, v...) - } - s.changed = true - return nil -} - -func (s *stringSliceValue) Type() string { - return "stringSlice" -} - -func (s *stringSliceValue) String() string { - str, _ := writeAsCSV(*s.value) - return "[" + str + "]" -} - -func (s *stringSliceValue) Append(val string) error { - *s.value = append(*s.value, val) - return nil -} - -func (s *stringSliceValue) Replace(val []string) error { - *s.value = val - return nil -} - -func (s *stringSliceValue) GetSlice() []string { - return *s.value -} - -func stringSliceConv(sval string) (interface{}, error) { - sval = sval[1 : len(sval)-1] - // An empty string would cause a slice with one (empty) string - if len(sval) == 0 { - return []string{}, nil - } - return readAsCSV(sval) -} - -// GetStringSlice return the []string value of a flag with the given name -func (f *FlagSet) GetStringSlice(name string) ([]string, error) { - val, err := f.getFlagType(name, "stringSlice", stringSliceConv) - if err != nil { - return []string{}, err - } - return val.([]string), nil -} - -// StringSliceVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" --ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) { - f.VarP(newStringSliceValue(value, p), name, "", usage) -} - -// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { - f.VarP(newStringSliceValue(value, p), name, shorthand, usage) -} - -// StringSliceVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a []string variable in which to store the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" --ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func StringSliceVar(p *[]string, name string, value []string, usage string) { - CommandLine.VarP(newStringSliceValue(value, p), name, "", usage) -} - -// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. -func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { - CommandLine.VarP(newStringSliceValue(value, p), name, shorthand, usage) -} - -// StringSlice defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" --ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string { - p := []string{} - f.StringSliceVarP(&p, name, "", value, usage) - return &p -} - -// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage string) *[]string { - p := []string{} - f.StringSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// StringSlice defines a string flag with specified name, default value, and usage string. -// The return value is the address of a []string variable that stores the value of the flag. -// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. -// For example: -// --ss="v1,v2" --ss="v3" -// will result in -// []string{"v1", "v2", "v3"} -func StringSlice(name string, value []string, usage string) *[]string { - return CommandLine.StringSliceP(name, "", value, usage) -} - -// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. -func StringSliceP(name, shorthand string, value []string, usage string) *[]string { - return CommandLine.StringSliceP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string_to_int.go b/vendor/github.com/spf13/pflag/string_to_int.go deleted file mode 100644 index 5ceda3965..000000000 --- a/vendor/github.com/spf13/pflag/string_to_int.go +++ /dev/null @@ -1,149 +0,0 @@ -package pflag - -import ( - "bytes" - "fmt" - "strconv" - "strings" -) - -// -- stringToInt Value -type stringToIntValue struct { - value *map[string]int - changed bool -} - -func newStringToIntValue(val map[string]int, p *map[string]int) *stringToIntValue { - ssv := new(stringToIntValue) - ssv.value = p - *ssv.value = val - return ssv -} - -// Format: a=1,b=2 -func (s *stringToIntValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make(map[string]int, len(ss)) - for _, pair := range ss { - kv := strings.SplitN(pair, "=", 2) - if len(kv) != 2 { - return fmt.Errorf("%s must be formatted as key=value", pair) - } - var err error - out[kv[0]], err = strconv.Atoi(kv[1]) - if err != nil { - return err - } - } - if !s.changed { - *s.value = out - } else { - for k, v := range out { - (*s.value)[k] = v - } - } - s.changed = true - return nil -} - -func (s *stringToIntValue) Type() string { - return "stringToInt" -} - -func (s *stringToIntValue) String() string { - var buf bytes.Buffer - i := 0 - for k, v := range *s.value { - if i > 0 { - buf.WriteRune(',') - } - buf.WriteString(k) - buf.WriteRune('=') - buf.WriteString(strconv.Itoa(v)) - i++ - } - return "[" + buf.String() + "]" -} - -func stringToIntConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // An empty string would cause an empty map - if len(val) == 0 { - return map[string]int{}, nil - } - ss := strings.Split(val, ",") - out := make(map[string]int, len(ss)) - for _, pair := range ss { - kv := strings.SplitN(pair, "=", 2) - if len(kv) != 2 { - return nil, fmt.Errorf("%s must be formatted as key=value", pair) - } - var err error - out[kv[0]], err = strconv.Atoi(kv[1]) - if err != nil { - return nil, err - } - } - return out, nil -} - -// GetStringToInt return the map[string]int value of a flag with the given name -func (f *FlagSet) GetStringToInt(name string) (map[string]int, error) { - val, err := f.getFlagType(name, "stringToInt", stringToIntConv) - if err != nil { - return map[string]int{}, err - } - return val.(map[string]int), nil -} - -// StringToIntVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a map[string]int variable in which to store the values of the multiple flags. -// The value of each argument will not try to be separated by comma -func (f *FlagSet) StringToIntVar(p *map[string]int, name string, value map[string]int, usage string) { - f.VarP(newStringToIntValue(value, p), name, "", usage) -} - -// StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringToIntVarP(p *map[string]int, name, shorthand string, value map[string]int, usage string) { - f.VarP(newStringToIntValue(value, p), name, shorthand, usage) -} - -// StringToIntVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a map[string]int variable in which to store the value of the flag. -// The value of each argument will not try to be separated by comma -func StringToIntVar(p *map[string]int, name string, value map[string]int, usage string) { - CommandLine.VarP(newStringToIntValue(value, p), name, "", usage) -} - -// StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash. -func StringToIntVarP(p *map[string]int, name, shorthand string, value map[string]int, usage string) { - CommandLine.VarP(newStringToIntValue(value, p), name, shorthand, usage) -} - -// StringToInt defines a string flag with specified name, default value, and usage string. -// The return value is the address of a map[string]int variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma -func (f *FlagSet) StringToInt(name string, value map[string]int, usage string) *map[string]int { - p := map[string]int{} - f.StringToIntVarP(&p, name, "", value, usage) - return &p -} - -// StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringToIntP(name, shorthand string, value map[string]int, usage string) *map[string]int { - p := map[string]int{} - f.StringToIntVarP(&p, name, shorthand, value, usage) - return &p -} - -// StringToInt defines a string flag with specified name, default value, and usage string. -// The return value is the address of a map[string]int variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma -func StringToInt(name string, value map[string]int, usage string) *map[string]int { - return CommandLine.StringToIntP(name, "", value, usage) -} - -// StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash. -func StringToIntP(name, shorthand string, value map[string]int, usage string) *map[string]int { - return CommandLine.StringToIntP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string_to_int64.go b/vendor/github.com/spf13/pflag/string_to_int64.go deleted file mode 100644 index a807a04a0..000000000 --- a/vendor/github.com/spf13/pflag/string_to_int64.go +++ /dev/null @@ -1,149 +0,0 @@ -package pflag - -import ( - "bytes" - "fmt" - "strconv" - "strings" -) - -// -- stringToInt64 Value -type stringToInt64Value struct { - value *map[string]int64 - changed bool -} - -func newStringToInt64Value(val map[string]int64, p *map[string]int64) *stringToInt64Value { - ssv := new(stringToInt64Value) - ssv.value = p - *ssv.value = val - return ssv -} - -// Format: a=1,b=2 -func (s *stringToInt64Value) Set(val string) error { - ss := strings.Split(val, ",") - out := make(map[string]int64, len(ss)) - for _, pair := range ss { - kv := strings.SplitN(pair, "=", 2) - if len(kv) != 2 { - return fmt.Errorf("%s must be formatted as key=value", pair) - } - var err error - out[kv[0]], err = strconv.ParseInt(kv[1], 10, 64) - if err != nil { - return err - } - } - if !s.changed { - *s.value = out - } else { - for k, v := range out { - (*s.value)[k] = v - } - } - s.changed = true - return nil -} - -func (s *stringToInt64Value) Type() string { - return "stringToInt64" -} - -func (s *stringToInt64Value) String() string { - var buf bytes.Buffer - i := 0 - for k, v := range *s.value { - if i > 0 { - buf.WriteRune(',') - } - buf.WriteString(k) - buf.WriteRune('=') - buf.WriteString(strconv.FormatInt(v, 10)) - i++ - } - return "[" + buf.String() + "]" -} - -func stringToInt64Conv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // An empty string would cause an empty map - if len(val) == 0 { - return map[string]int64{}, nil - } - ss := strings.Split(val, ",") - out := make(map[string]int64, len(ss)) - for _, pair := range ss { - kv := strings.SplitN(pair, "=", 2) - if len(kv) != 2 { - return nil, fmt.Errorf("%s must be formatted as key=value", pair) - } - var err error - out[kv[0]], err = strconv.ParseInt(kv[1], 10, 64) - if err != nil { - return nil, err - } - } - return out, nil -} - -// GetStringToInt64 return the map[string]int64 value of a flag with the given name -func (f *FlagSet) GetStringToInt64(name string) (map[string]int64, error) { - val, err := f.getFlagType(name, "stringToInt64", stringToInt64Conv) - if err != nil { - return map[string]int64{}, err - } - return val.(map[string]int64), nil -} - -// StringToInt64Var defines a string flag with specified name, default value, and usage string. -// The argument p point64s to a map[string]int64 variable in which to store the values of the multiple flags. -// The value of each argument will not try to be separated by comma -func (f *FlagSet) StringToInt64Var(p *map[string]int64, name string, value map[string]int64, usage string) { - f.VarP(newStringToInt64Value(value, p), name, "", usage) -} - -// StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringToInt64VarP(p *map[string]int64, name, shorthand string, value map[string]int64, usage string) { - f.VarP(newStringToInt64Value(value, p), name, shorthand, usage) -} - -// StringToInt64Var defines a string flag with specified name, default value, and usage string. -// The argument p point64s to a map[string]int64 variable in which to store the value of the flag. -// The value of each argument will not try to be separated by comma -func StringToInt64Var(p *map[string]int64, name string, value map[string]int64, usage string) { - CommandLine.VarP(newStringToInt64Value(value, p), name, "", usage) -} - -// StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash. -func StringToInt64VarP(p *map[string]int64, name, shorthand string, value map[string]int64, usage string) { - CommandLine.VarP(newStringToInt64Value(value, p), name, shorthand, usage) -} - -// StringToInt64 defines a string flag with specified name, default value, and usage string. -// The return value is the address of a map[string]int64 variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma -func (f *FlagSet) StringToInt64(name string, value map[string]int64, usage string) *map[string]int64 { - p := map[string]int64{} - f.StringToInt64VarP(&p, name, "", value, usage) - return &p -} - -// StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringToInt64P(name, shorthand string, value map[string]int64, usage string) *map[string]int64 { - p := map[string]int64{} - f.StringToInt64VarP(&p, name, shorthand, value, usage) - return &p -} - -// StringToInt64 defines a string flag with specified name, default value, and usage string. -// The return value is the address of a map[string]int64 variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma -func StringToInt64(name string, value map[string]int64, usage string) *map[string]int64 { - return CommandLine.StringToInt64P(name, "", value, usage) -} - -// StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash. -func StringToInt64P(name, shorthand string, value map[string]int64, usage string) *map[string]int64 { - return CommandLine.StringToInt64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/string_to_string.go b/vendor/github.com/spf13/pflag/string_to_string.go deleted file mode 100644 index 1d1e3bf91..000000000 --- a/vendor/github.com/spf13/pflag/string_to_string.go +++ /dev/null @@ -1,168 +0,0 @@ -package pflag - -import ( - "bytes" - "encoding/csv" - "fmt" - "sort" - "strings" -) - -// -- stringToString Value -type stringToStringValue struct { - value *map[string]string - changed bool -} - -func newStringToStringValue(val map[string]string, p *map[string]string) *stringToStringValue { - ssv := new(stringToStringValue) - ssv.value = p - *ssv.value = val - return ssv -} - -// Format: a=1,b=2 -func (s *stringToStringValue) Set(val string) error { - var ss []string - n := strings.Count(val, "=") - switch n { - case 0: - return fmt.Errorf("%s must be formatted as key=value", val) - case 1: - ss = append(ss, strings.Trim(val, `"`)) - default: - r := csv.NewReader(strings.NewReader(val)) - var err error - ss, err = r.Read() - if err != nil { - return err - } - } - - out := make(map[string]string, len(ss)) - for _, pair := range ss { - kv := strings.SplitN(pair, "=", 2) - if len(kv) != 2 { - return fmt.Errorf("%s must be formatted as key=value", pair) - } - out[kv[0]] = kv[1] - } - if !s.changed { - *s.value = out - } else { - for k, v := range out { - (*s.value)[k] = v - } - } - s.changed = true - return nil -} - -func (s *stringToStringValue) Type() string { - return "stringToString" -} - -func (s *stringToStringValue) String() string { - keys := make([]string, 0, len(*s.value)) - for k := range *s.value { - keys = append(keys, k) - } - sort.Strings(keys) - - records := make([]string, 0, len(*s.value)>>1) - for _, k := range keys { - v := (*s.value)[k] - records = append(records, k+"="+v) - } - - var buf bytes.Buffer - w := csv.NewWriter(&buf) - if err := w.Write(records); err != nil { - panic(err) - } - w.Flush() - return "[" + strings.TrimSpace(buf.String()) + "]" -} - -func stringToStringConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // An empty string would cause an empty map - if len(val) == 0 { - return map[string]string{}, nil - } - r := csv.NewReader(strings.NewReader(val)) - ss, err := r.Read() - if err != nil { - return nil, err - } - out := make(map[string]string, len(ss)) - for _, pair := range ss { - kv := strings.SplitN(pair, "=", 2) - if len(kv) != 2 { - return nil, fmt.Errorf("%s must be formatted as key=value", pair) - } - out[kv[0]] = kv[1] - } - return out, nil -} - -// GetStringToString return the map[string]string value of a flag with the given name -func (f *FlagSet) GetStringToString(name string) (map[string]string, error) { - val, err := f.getFlagType(name, "stringToString", stringToStringConv) - if err != nil { - return map[string]string{}, err - } - return val.(map[string]string), nil -} - -// StringToStringVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a map[string]string variable in which to store the values of the multiple flags. -// The value of each argument will not try to be separated by comma -func (f *FlagSet) StringToStringVar(p *map[string]string, name string, value map[string]string, usage string) { - f.VarP(newStringToStringValue(value, p), name, "", usage) -} - -// StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringToStringVarP(p *map[string]string, name, shorthand string, value map[string]string, usage string) { - f.VarP(newStringToStringValue(value, p), name, shorthand, usage) -} - -// StringToStringVar defines a string flag with specified name, default value, and usage string. -// The argument p points to a map[string]string variable in which to store the value of the flag. -// The value of each argument will not try to be separated by comma -func StringToStringVar(p *map[string]string, name string, value map[string]string, usage string) { - CommandLine.VarP(newStringToStringValue(value, p), name, "", usage) -} - -// StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash. -func StringToStringVarP(p *map[string]string, name, shorthand string, value map[string]string, usage string) { - CommandLine.VarP(newStringToStringValue(value, p), name, shorthand, usage) -} - -// StringToString defines a string flag with specified name, default value, and usage string. -// The return value is the address of a map[string]string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma -func (f *FlagSet) StringToString(name string, value map[string]string, usage string) *map[string]string { - p := map[string]string{} - f.StringToStringVarP(&p, name, "", value, usage) - return &p -} - -// StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) StringToStringP(name, shorthand string, value map[string]string, usage string) *map[string]string { - p := map[string]string{} - f.StringToStringVarP(&p, name, shorthand, value, usage) - return &p -} - -// StringToString defines a string flag with specified name, default value, and usage string. -// The return value is the address of a map[string]string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma -func StringToString(name string, value map[string]string, usage string) *map[string]string { - return CommandLine.StringToStringP(name, "", value, usage) -} - -// StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash. -func StringToStringP(name, shorthand string, value map[string]string, usage string) *map[string]string { - return CommandLine.StringToStringP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/text.go b/vendor/github.com/spf13/pflag/text.go deleted file mode 100644 index 886d5a3d8..000000000 --- a/vendor/github.com/spf13/pflag/text.go +++ /dev/null @@ -1,81 +0,0 @@ -package pflag - -import ( - "encoding" - "fmt" - "reflect" -) - -// following is copied from go 1.23.4 flag.go -type textValue struct{ p encoding.TextUnmarshaler } - -func newTextValue(val encoding.TextMarshaler, p encoding.TextUnmarshaler) textValue { - ptrVal := reflect.ValueOf(p) - if ptrVal.Kind() != reflect.Ptr { - panic("variable value type must be a pointer") - } - defVal := reflect.ValueOf(val) - if defVal.Kind() == reflect.Ptr { - defVal = defVal.Elem() - } - if defVal.Type() != ptrVal.Type().Elem() { - panic(fmt.Sprintf("default type does not match variable type: %v != %v", defVal.Type(), ptrVal.Type().Elem())) - } - ptrVal.Elem().Set(defVal) - return textValue{p} -} - -func (v textValue) Set(s string) error { - return v.p.UnmarshalText([]byte(s)) -} - -func (v textValue) Get() interface{} { - return v.p -} - -func (v textValue) String() string { - if m, ok := v.p.(encoding.TextMarshaler); ok { - if b, err := m.MarshalText(); err == nil { - return string(b) - } - } - return "" -} - -//end of copy - -func (v textValue) Type() string { - return reflect.ValueOf(v.p).Type().Name() -} - -// GetText set out, which implements encoding.UnmarshalText, to the value of a flag with given name -func (f *FlagSet) GetText(name string, out encoding.TextUnmarshaler) error { - flag := f.Lookup(name) - if flag == nil { - return fmt.Errorf("flag accessed but not defined: %s", name) - } - if flag.Value.Type() != reflect.TypeOf(out).Name() { - return fmt.Errorf("trying to get %s value of flag of type %s", reflect.TypeOf(out).Name(), flag.Value.Type()) - } - return out.UnmarshalText([]byte(flag.Value.String())) -} - -// TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p. -func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string) { - f.VarP(newTextValue(value, p), name, "", usage) -} - -// TextVarP is like TextVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) TextVarP(p encoding.TextUnmarshaler, name, shorthand string, value encoding.TextMarshaler, usage string) { - f.VarP(newTextValue(value, p), name, shorthand, usage) -} - -// TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p. -func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string) { - CommandLine.VarP(newTextValue(value, p), name, "", usage) -} - -// TextVarP is like TextVar, but accepts a shorthand letter that can be used after a single dash. -func TextVarP(p encoding.TextUnmarshaler, name, shorthand string, value encoding.TextMarshaler, usage string) { - CommandLine.VarP(newTextValue(value, p), name, shorthand, usage) -} diff --git a/vendor/github.com/spf13/pflag/time.go b/vendor/github.com/spf13/pflag/time.go deleted file mode 100644 index 3dee42479..000000000 --- a/vendor/github.com/spf13/pflag/time.go +++ /dev/null @@ -1,124 +0,0 @@ -package pflag - -import ( - "fmt" - "strings" - "time" -) - -// TimeValue adapts time.Time for use as a flag. -type timeValue struct { - *time.Time - formats []string -} - -func newTimeValue(val time.Time, p *time.Time, formats []string) *timeValue { - *p = val - return &timeValue{ - Time: p, - formats: formats, - } -} - -// Set time.Time value from string based on accepted formats. -func (d *timeValue) Set(s string) error { - s = strings.TrimSpace(s) - for _, f := range d.formats { - v, err := time.Parse(f, s) - if err != nil { - continue - } - *d.Time = v - return nil - } - - formatsString := "" - for i, f := range d.formats { - if i > 0 { - formatsString += ", " - } - formatsString += fmt.Sprintf("`%s`", f) - } - - return fmt.Errorf("invalid time format `%s` must be one of: %s", s, formatsString) -} - -// Type name for time.Time flags. -func (d *timeValue) Type() string { - return "time" -} - -func (d *timeValue) String() string { - if d.Time.IsZero() { - return "" - } else { - return d.Time.Format(time.RFC3339Nano) - } -} - -// GetTime return the time value of a flag with the given name -func (f *FlagSet) GetTime(name string) (time.Time, error) { - flag := f.Lookup(name) - if flag == nil { - err := fmt.Errorf("flag accessed but not defined: %s", name) - return time.Time{}, err - } - - if flag.Value.Type() != "time" { - err := fmt.Errorf("trying to get %s value of flag of type %s", "time", flag.Value.Type()) - return time.Time{}, err - } - - val, ok := flag.Value.(*timeValue) - if !ok { - return time.Time{}, fmt.Errorf("value %s is not a time", flag.Value) - } - - return *val.Time, nil -} - -// TimeVar defines a time.Time flag with specified name, default value, and usage string. -// The argument p points to a time.Time variable in which to store the value of the flag. -func (f *FlagSet) TimeVar(p *time.Time, name string, value time.Time, formats []string, usage string) { - f.TimeVarP(p, name, "", value, formats, usage) -} - -// TimeVarP is like TimeVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) TimeVarP(p *time.Time, name, shorthand string, value time.Time, formats []string, usage string) { - f.VarP(newTimeValue(value, p, formats), name, shorthand, usage) -} - -// TimeVar defines a time.Time flag with specified name, default value, and usage string. -// The argument p points to a time.Time variable in which to store the value of the flag. -func TimeVar(p *time.Time, name string, value time.Time, formats []string, usage string) { - CommandLine.TimeVarP(p, name, "", value, formats, usage) -} - -// TimeVarP is like TimeVar, but accepts a shorthand letter that can be used after a single dash. -func TimeVarP(p *time.Time, name, shorthand string, value time.Time, formats []string, usage string) { - CommandLine.VarP(newTimeValue(value, p, formats), name, shorthand, usage) -} - -// Time defines a time.Time flag with specified name, default value, and usage string. -// The return value is the address of a time.Time variable that stores the value of the flag. -func (f *FlagSet) Time(name string, value time.Time, formats []string, usage string) *time.Time { - return f.TimeP(name, "", value, formats, usage) -} - -// TimeP is like Time, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) TimeP(name, shorthand string, value time.Time, formats []string, usage string) *time.Time { - p := new(time.Time) - f.TimeVarP(p, name, shorthand, value, formats, usage) - return p -} - -// Time defines a time.Time flag with specified name, default value, and usage string. -// The return value is the address of a time.Time variable that stores the value of the flag. -func Time(name string, value time.Time, formats []string, usage string) *time.Time { - return CommandLine.TimeP(name, "", value, formats, usage) -} - -// TimeP is like Time, but accepts a shorthand letter that can be used after a single dash. -func TimeP(name, shorthand string, value time.Time, formats []string, usage string) *time.Time { - return CommandLine.TimeP(name, shorthand, value, formats, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint.go b/vendor/github.com/spf13/pflag/uint.go deleted file mode 100644 index dcbc2b758..000000000 --- a/vendor/github.com/spf13/pflag/uint.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint Value -type uintValue uint - -func newUintValue(val uint, p *uint) *uintValue { - *p = val - return (*uintValue)(p) -} - -func (i *uintValue) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 64) - *i = uintValue(v) - return err -} - -func (i *uintValue) Type() string { - return "uint" -} - -func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uintConv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 0) - if err != nil { - return 0, err - } - return uint(v), nil -} - -// GetUint return the uint value of a flag with the given name -func (f *FlagSet) GetUint(name string) (uint, error) { - val, err := f.getFlagType(name, "uint", uintConv) - if err != nil { - return 0, err - } - return val.(uint), nil -} - -// UintVar defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) { - f.VarP(newUintValue(value, p), name, "", usage) -} - -// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) { - f.VarP(newUintValue(value, p), name, shorthand, usage) -} - -// UintVar defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func UintVar(p *uint, name string, value uint, usage string) { - CommandLine.VarP(newUintValue(value, p), name, "", usage) -} - -// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. -func UintVarP(p *uint, name, shorthand string, value uint, usage string) { - CommandLine.VarP(newUintValue(value, p), name, shorthand, usage) -} - -// Uint defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func (f *FlagSet) Uint(name string, value uint, usage string) *uint { - p := new(uint) - f.UintVarP(p, name, "", value, usage) - return p -} - -// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint { - p := new(uint) - f.UintVarP(p, name, shorthand, value, usage) - return p -} - -// Uint defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func Uint(name string, value uint, usage string) *uint { - return CommandLine.UintP(name, "", value, usage) -} - -// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. -func UintP(name, shorthand string, value uint, usage string) *uint { - return CommandLine.UintP(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint16.go b/vendor/github.com/spf13/pflag/uint16.go deleted file mode 100644 index 7e9914edd..000000000 --- a/vendor/github.com/spf13/pflag/uint16.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint16 value -type uint16Value uint16 - -func newUint16Value(val uint16, p *uint16) *uint16Value { - *p = val - return (*uint16Value)(p) -} - -func (i *uint16Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 16) - *i = uint16Value(v) - return err -} - -func (i *uint16Value) Type() string { - return "uint16" -} - -func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint16Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 16) - if err != nil { - return 0, err - } - return uint16(v), nil -} - -// GetUint16 return the uint16 value of a flag with the given name -func (f *FlagSet) GetUint16(name string) (uint16, error) { - val, err := f.getFlagType(name, "uint16", uint16Conv) - if err != nil { - return 0, err - } - return val.(uint16), nil -} - -// Uint16Var defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) { - f.VarP(newUint16Value(value, p), name, "", usage) -} - -// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { - f.VarP(newUint16Value(value, p), name, shorthand, usage) -} - -// Uint16Var defines a uint flag with specified name, default value, and usage string. -// The argument p points to a uint variable in which to store the value of the flag. -func Uint16Var(p *uint16, name string, value uint16, usage string) { - CommandLine.VarP(newUint16Value(value, p), name, "", usage) -} - -// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. -func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { - CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage) -} - -// Uint16 defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 { - p := new(uint16) - f.Uint16VarP(p, name, "", value, usage) - return p -} - -// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 { - p := new(uint16) - f.Uint16VarP(p, name, shorthand, value, usage) - return p -} - -// Uint16 defines a uint flag with specified name, default value, and usage string. -// The return value is the address of a uint variable that stores the value of the flag. -func Uint16(name string, value uint16, usage string) *uint16 { - return CommandLine.Uint16P(name, "", value, usage) -} - -// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. -func Uint16P(name, shorthand string, value uint16, usage string) *uint16 { - return CommandLine.Uint16P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint32.go b/vendor/github.com/spf13/pflag/uint32.go deleted file mode 100644 index d8024539b..000000000 --- a/vendor/github.com/spf13/pflag/uint32.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint32 value -type uint32Value uint32 - -func newUint32Value(val uint32, p *uint32) *uint32Value { - *p = val - return (*uint32Value)(p) -} - -func (i *uint32Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 32) - *i = uint32Value(v) - return err -} - -func (i *uint32Value) Type() string { - return "uint32" -} - -func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint32Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 32) - if err != nil { - return 0, err - } - return uint32(v), nil -} - -// GetUint32 return the uint32 value of a flag with the given name -func (f *FlagSet) GetUint32(name string) (uint32, error) { - val, err := f.getFlagType(name, "uint32", uint32Conv) - if err != nil { - return 0, err - } - return val.(uint32), nil -} - -// Uint32Var defines a uint32 flag with specified name, default value, and usage string. -// The argument p points to a uint32 variable in which to store the value of the flag. -func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) { - f.VarP(newUint32Value(value, p), name, "", usage) -} - -// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { - f.VarP(newUint32Value(value, p), name, shorthand, usage) -} - -// Uint32Var defines a uint32 flag with specified name, default value, and usage string. -// The argument p points to a uint32 variable in which to store the value of the flag. -func Uint32Var(p *uint32, name string, value uint32, usage string) { - CommandLine.VarP(newUint32Value(value, p), name, "", usage) -} - -// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. -func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { - CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage) -} - -// Uint32 defines a uint32 flag with specified name, default value, and usage string. -// The return value is the address of a uint32 variable that stores the value of the flag. -func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 { - p := new(uint32) - f.Uint32VarP(p, name, "", value, usage) - return p -} - -// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 { - p := new(uint32) - f.Uint32VarP(p, name, shorthand, value, usage) - return p -} - -// Uint32 defines a uint32 flag with specified name, default value, and usage string. -// The return value is the address of a uint32 variable that stores the value of the flag. -func Uint32(name string, value uint32, usage string) *uint32 { - return CommandLine.Uint32P(name, "", value, usage) -} - -// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. -func Uint32P(name, shorthand string, value uint32, usage string) *uint32 { - return CommandLine.Uint32P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint64.go b/vendor/github.com/spf13/pflag/uint64.go deleted file mode 100644 index f62240f2c..000000000 --- a/vendor/github.com/spf13/pflag/uint64.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint64 Value -type uint64Value uint64 - -func newUint64Value(val uint64, p *uint64) *uint64Value { - *p = val - return (*uint64Value)(p) -} - -func (i *uint64Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 64) - *i = uint64Value(v) - return err -} - -func (i *uint64Value) Type() string { - return "uint64" -} - -func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint64Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 64) - if err != nil { - return 0, err - } - return uint64(v), nil -} - -// GetUint64 return the uint64 value of a flag with the given name -func (f *FlagSet) GetUint64(name string) (uint64, error) { - val, err := f.getFlagType(name, "uint64", uint64Conv) - if err != nil { - return 0, err - } - return val.(uint64), nil -} - -// Uint64Var defines a uint64 flag with specified name, default value, and usage string. -// The argument p points to a uint64 variable in which to store the value of the flag. -func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) { - f.VarP(newUint64Value(value, p), name, "", usage) -} - -// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { - f.VarP(newUint64Value(value, p), name, shorthand, usage) -} - -// Uint64Var defines a uint64 flag with specified name, default value, and usage string. -// The argument p points to a uint64 variable in which to store the value of the flag. -func Uint64Var(p *uint64, name string, value uint64, usage string) { - CommandLine.VarP(newUint64Value(value, p), name, "", usage) -} - -// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. -func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { - CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage) -} - -// Uint64 defines a uint64 flag with specified name, default value, and usage string. -// The return value is the address of a uint64 variable that stores the value of the flag. -func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 { - p := new(uint64) - f.Uint64VarP(p, name, "", value, usage) - return p -} - -// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 { - p := new(uint64) - f.Uint64VarP(p, name, shorthand, value, usage) - return p -} - -// Uint64 defines a uint64 flag with specified name, default value, and usage string. -// The return value is the address of a uint64 variable that stores the value of the flag. -func Uint64(name string, value uint64, usage string) *uint64 { - return CommandLine.Uint64P(name, "", value, usage) -} - -// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. -func Uint64P(name, shorthand string, value uint64, usage string) *uint64 { - return CommandLine.Uint64P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint8.go b/vendor/github.com/spf13/pflag/uint8.go deleted file mode 100644 index bb0e83c1f..000000000 --- a/vendor/github.com/spf13/pflag/uint8.go +++ /dev/null @@ -1,88 +0,0 @@ -package pflag - -import "strconv" - -// -- uint8 Value -type uint8Value uint8 - -func newUint8Value(val uint8, p *uint8) *uint8Value { - *p = val - return (*uint8Value)(p) -} - -func (i *uint8Value) Set(s string) error { - v, err := strconv.ParseUint(s, 0, 8) - *i = uint8Value(v) - return err -} - -func (i *uint8Value) Type() string { - return "uint8" -} - -func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) } - -func uint8Conv(sval string) (interface{}, error) { - v, err := strconv.ParseUint(sval, 0, 8) - if err != nil { - return 0, err - } - return uint8(v), nil -} - -// GetUint8 return the uint8 value of a flag with the given name -func (f *FlagSet) GetUint8(name string) (uint8, error) { - val, err := f.getFlagType(name, "uint8", uint8Conv) - if err != nil { - return 0, err - } - return val.(uint8), nil -} - -// Uint8Var defines a uint8 flag with specified name, default value, and usage string. -// The argument p points to a uint8 variable in which to store the value of the flag. -func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) { - f.VarP(newUint8Value(value, p), name, "", usage) -} - -// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { - f.VarP(newUint8Value(value, p), name, shorthand, usage) -} - -// Uint8Var defines a uint8 flag with specified name, default value, and usage string. -// The argument p points to a uint8 variable in which to store the value of the flag. -func Uint8Var(p *uint8, name string, value uint8, usage string) { - CommandLine.VarP(newUint8Value(value, p), name, "", usage) -} - -// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. -func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { - CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage) -} - -// Uint8 defines a uint8 flag with specified name, default value, and usage string. -// The return value is the address of a uint8 variable that stores the value of the flag. -func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 { - p := new(uint8) - f.Uint8VarP(p, name, "", value, usage) - return p -} - -// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 { - p := new(uint8) - f.Uint8VarP(p, name, shorthand, value, usage) - return p -} - -// Uint8 defines a uint8 flag with specified name, default value, and usage string. -// The return value is the address of a uint8 variable that stores the value of the flag. -func Uint8(name string, value uint8, usage string) *uint8 { - return CommandLine.Uint8P(name, "", value, usage) -} - -// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. -func Uint8P(name, shorthand string, value uint8, usage string) *uint8 { - return CommandLine.Uint8P(name, shorthand, value, usage) -} diff --git a/vendor/github.com/spf13/pflag/uint_slice.go b/vendor/github.com/spf13/pflag/uint_slice.go deleted file mode 100644 index 5fa924835..000000000 --- a/vendor/github.com/spf13/pflag/uint_slice.go +++ /dev/null @@ -1,168 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" -) - -// -- uintSlice Value -type uintSliceValue struct { - value *[]uint - changed bool -} - -func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue { - uisv := new(uintSliceValue) - uisv.value = p - *uisv.value = val - return uisv -} - -func (s *uintSliceValue) Set(val string) error { - ss := strings.Split(val, ",") - out := make([]uint, len(ss)) - for i, d := range ss { - u, err := strconv.ParseUint(d, 10, 0) - if err != nil { - return err - } - out[i] = uint(u) - } - if !s.changed { - *s.value = out - } else { - *s.value = append(*s.value, out...) - } - s.changed = true - return nil -} - -func (s *uintSliceValue) Type() string { - return "uintSlice" -} - -func (s *uintSliceValue) String() string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = fmt.Sprintf("%d", d) - } - return "[" + strings.Join(out, ",") + "]" -} - -func (s *uintSliceValue) fromString(val string) (uint, error) { - t, err := strconv.ParseUint(val, 10, 0) - if err != nil { - return 0, err - } - return uint(t), nil -} - -func (s *uintSliceValue) toString(val uint) string { - return fmt.Sprintf("%d", val) -} - -func (s *uintSliceValue) Append(val string) error { - i, err := s.fromString(val) - if err != nil { - return err - } - *s.value = append(*s.value, i) - return nil -} - -func (s *uintSliceValue) Replace(val []string) error { - out := make([]uint, len(val)) - for i, d := range val { - var err error - out[i], err = s.fromString(d) - if err != nil { - return err - } - } - *s.value = out - return nil -} - -func (s *uintSliceValue) GetSlice() []string { - out := make([]string, len(*s.value)) - for i, d := range *s.value { - out[i] = s.toString(d) - } - return out -} - -func uintSliceConv(val string) (interface{}, error) { - val = strings.Trim(val, "[]") - // Empty string would cause a slice with one (empty) entry - if len(val) == 0 { - return []uint{}, nil - } - ss := strings.Split(val, ",") - out := make([]uint, len(ss)) - for i, d := range ss { - u, err := strconv.ParseUint(d, 10, 0) - if err != nil { - return nil, err - } - out[i] = uint(u) - } - return out, nil -} - -// GetUintSlice returns the []uint value of a flag with the given name. -func (f *FlagSet) GetUintSlice(name string) ([]uint, error) { - val, err := f.getFlagType(name, "uintSlice", uintSliceConv) - if err != nil { - return []uint{}, err - } - return val.([]uint), nil -} - -// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string. -// The argument p points to a []uint variable in which to store the value of the flag. -func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) { - f.VarP(newUintSliceValue(value, p), name, "", usage) -} - -// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { - f.VarP(newUintSliceValue(value, p), name, shorthand, usage) -} - -// UintSliceVar defines a uint[] flag with specified name, default value, and usage string. -// The argument p points to a uint[] variable in which to store the value of the flag. -func UintSliceVar(p *[]uint, name string, value []uint, usage string) { - CommandLine.VarP(newUintSliceValue(value, p), name, "", usage) -} - -// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash. -func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { - CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage) -} - -// UintSlice defines a []uint flag with specified name, default value, and usage string. -// The return value is the address of a []uint variable that stores the value of the flag. -func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint { - p := []uint{} - f.UintSliceVarP(&p, name, "", value, usage) - return &p -} - -// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. -func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { - p := []uint{} - f.UintSliceVarP(&p, name, shorthand, value, usage) - return &p -} - -// UintSlice defines a []uint flag with specified name, default value, and usage string. -// The return value is the address of a []uint variable that stores the value of the flag. -func UintSlice(name string, value []uint, usage string) *[]uint { - return CommandLine.UintSliceP(name, "", value, usage) -} - -// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. -func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { - return CommandLine.UintSliceP(name, shorthand, value, usage) -} diff --git a/vendor/golang.org/x/net/http2/writesched_priority_rfc9218.go b/vendor/golang.org/x/net/http2/writesched_priority_rfc9218.go index cb4cadc32..dfbfc1eb3 100644 --- a/vendor/golang.org/x/net/http2/writesched_priority_rfc9218.go +++ b/vendor/golang.org/x/net/http2/writesched_priority_rfc9218.go @@ -37,6 +37,15 @@ type priorityWriteSchedulerRFC9218 struct { // incremental streams or not, when urgency is the same in a given Pop() // call. prioritizeIncremental bool + + // priorityUpdateBuf is used to buffer the most recent PRIORITY_UPDATE we + // receive per https://www.rfc-editor.org/rfc/rfc9218.html#name-the-priority_update-frame. + priorityUpdateBuf struct { + // streamID being 0 means that the buffer is empty. This is a safe + // assumption as PRIORITY_UPDATE for stream 0 is a PROTOCOL_ERROR. + streamID uint32 + priority PriorityParam + } } func newPriorityWriteSchedulerRFC9218() WriteScheduler { @@ -50,6 +59,10 @@ func (ws *priorityWriteSchedulerRFC9218) OpenStream(streamID uint32, opt OpenStr if ws.streams[streamID].location != nil { panic(fmt.Errorf("stream %d already opened", streamID)) } + if streamID == ws.priorityUpdateBuf.streamID { + ws.priorityUpdateBuf.streamID = 0 + opt.priority = ws.priorityUpdateBuf.priority + } q := ws.queuePool.get() ws.streams[streamID] = streamMetadata{ location: q, @@ -95,6 +108,8 @@ func (ws *priorityWriteSchedulerRFC9218) AdjustStream(streamID uint32, priority metadata := ws.streams[streamID] q, u, i := metadata.location, metadata.priority.urgency, metadata.priority.incremental if q == nil { + ws.priorityUpdateBuf.streamID = streamID + ws.priorityUpdateBuf.priority = priority return } diff --git a/vendor/golang.org/x/sys/plan9/syscall_plan9.go b/vendor/golang.org/x/sys/plan9/syscall_plan9.go index d079d8116..761912237 100644 --- a/vendor/golang.org/x/sys/plan9/syscall_plan9.go +++ b/vendor/golang.org/x/sys/plan9/syscall_plan9.go @@ -19,13 +19,7 @@ import ( // A Note is a string describing a process note. // It implements the os.Signal interface. -type Note string - -func (n Note) Signal() {} - -func (n Note) String() string { - return string(n) -} +type Note = syscall.Note var ( Stdin = 0 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index c1a467017..45476a73c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -593,110 +593,115 @@ const ( ) const ( - NDA_UNSPEC = 0x0 - NDA_DST = 0x1 - NDA_LLADDR = 0x2 - NDA_CACHEINFO = 0x3 - NDA_PROBES = 0x4 - NDA_VLAN = 0x5 - NDA_PORT = 0x6 - NDA_VNI = 0x7 - NDA_IFINDEX = 0x8 - NDA_MASTER = 0x9 - NDA_LINK_NETNSID = 0xa - NDA_SRC_VNI = 0xb - NTF_USE = 0x1 - NTF_SELF = 0x2 - NTF_MASTER = 0x4 - NTF_PROXY = 0x8 - NTF_EXT_LEARNED = 0x10 - NTF_OFFLOADED = 0x20 - NTF_ROUTER = 0x80 - NUD_INCOMPLETE = 0x1 - NUD_REACHABLE = 0x2 - NUD_STALE = 0x4 - NUD_DELAY = 0x8 - NUD_PROBE = 0x10 - NUD_FAILED = 0x20 - NUD_NOARP = 0x40 - NUD_PERMANENT = 0x80 - NUD_NONE = 0x0 - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFA_FLAGS = 0x8 - IFA_RT_PRIORITY = 0x9 - IFA_TARGET_NETNSID = 0xa - IFAL_LABEL = 0x2 - IFAL_ADDRESS = 0x1 - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTA_MARK = 0x10 - RTA_MFC_STATS = 0x11 - RTA_VIA = 0x12 - RTA_NEWDST = 0x13 - RTA_PREF = 0x14 - RTA_ENCAP_TYPE = 0x15 - RTA_ENCAP = 0x16 - RTA_EXPIRES = 0x17 - RTA_PAD = 0x18 - RTA_UID = 0x19 - RTA_TTL_PROPAGATE = 0x1a - RTA_IP_PROTO = 0x1b - RTA_SPORT = 0x1c - RTA_DPORT = 0x1d - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofIfAddrlblmsg = 0xc - SizeofIfaCacheinfo = 0x10 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 - SizeofNdUseroptmsg = 0x10 - SizeofNdMsg = 0xc + NDA_UNSPEC = 0x0 + NDA_DST = 0x1 + NDA_LLADDR = 0x2 + NDA_CACHEINFO = 0x3 + NDA_PROBES = 0x4 + NDA_VLAN = 0x5 + NDA_PORT = 0x6 + NDA_VNI = 0x7 + NDA_IFINDEX = 0x8 + NDA_MASTER = 0x9 + NDA_LINK_NETNSID = 0xa + NDA_SRC_VNI = 0xb + NTF_USE = 0x1 + NTF_SELF = 0x2 + NTF_MASTER = 0x4 + NTF_PROXY = 0x8 + NTF_EXT_LEARNED = 0x10 + NTF_OFFLOADED = 0x20 + NTF_ROUTER = 0x80 + NUD_INCOMPLETE = 0x1 + NUD_REACHABLE = 0x2 + NUD_STALE = 0x4 + NUD_DELAY = 0x8 + NUD_PROBE = 0x10 + NUD_FAILED = 0x20 + NUD_NOARP = 0x40 + NUD_PERMANENT = 0x80 + NUD_NONE = 0x0 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFA_FLAGS = 0x8 + IFA_RT_PRIORITY = 0x9 + IFA_TARGET_NETNSID = 0xa + IFAL_LABEL = 0x2 + IFAL_ADDRESS = 0x1 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTA_MARK = 0x10 + RTA_MFC_STATS = 0x11 + RTA_VIA = 0x12 + RTA_NEWDST = 0x13 + RTA_PREF = 0x14 + RTA_ENCAP_TYPE = 0x15 + RTA_ENCAP = 0x16 + RTA_EXPIRES = 0x17 + RTA_PAD = 0x18 + RTA_UID = 0x19 + RTA_TTL_PROPAGATE = 0x1a + RTA_IP_PROTO = 0x1b + RTA_SPORT = 0x1c + RTA_DPORT = 0x1d + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + PREFIX_UNSPEC = 0x0 + PREFIX_ADDRESS = 0x1 + PREFIX_CACHEINFO = 0x2 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofPrefixmsg = 0xc + SizeofPrefixCacheinfo = 0x8 + SizeofIfAddrmsg = 0x8 + SizeofIfAddrlblmsg = 0xc + SizeofIfaCacheinfo = 0x10 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 + SizeofNdUseroptmsg = 0x10 + SizeofNdMsg = 0xc ) type NlMsghdr struct { @@ -735,6 +740,22 @@ type IfInfomsg struct { Change uint32 } +type Prefixmsg struct { + Family uint8 + Pad1 uint8 + Pad2 uint16 + Ifindex int32 + Type uint8 + Len uint8 + Flags uint8 + Pad3 uint8 +} + +type PrefixCacheinfo struct { + Preferred_time uint32 + Valid_time uint32 +} + type IfAddrmsg struct { Family uint8 Prefixlen uint8 diff --git a/vendor/golang.org/x/sys/windows/aliases.go b/vendor/golang.org/x/sys/windows/aliases.go index 16f90560a..96317966e 100644 --- a/vendor/golang.org/x/sys/windows/aliases.go +++ b/vendor/golang.org/x/sys/windows/aliases.go @@ -8,5 +8,6 @@ package windows import "syscall" +type Signal = syscall.Signal type Errno = syscall.Errno type SysProcAttr = syscall.SysProcAttr diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index 738a9f212..d76643658 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -1490,20 +1490,6 @@ func Getgid() (gid int) { return -1 } func Getegid() (egid int) { return -1 } func Getgroups() (gids []int, err error) { return nil, syscall.EWINDOWS } -type Signal int - -func (s Signal) Signal() {} - -func (s Signal) String() string { - if 0 <= s && int(s) < len(signals) { - str := signals[s] - if str != "" { - return str - } - } - return "signal " + itoa(int(s)) -} - func LoadCreateSymbolicLink() error { return procCreateSymbolicLinkW.Find() } diff --git a/vendor/golang.org/x/term/terminal.go b/vendor/golang.org/x/term/terminal.go index 9255449b9..6ec537cdc 100644 --- a/vendor/golang.org/x/term/terminal.go +++ b/vendor/golang.org/x/term/terminal.go @@ -160,7 +160,9 @@ const ( keyEnd keyDeleteWord keyDeleteLine + keyDelete keyClearScreen + keyTranspose keyPasteStart keyPasteEnd ) @@ -194,6 +196,8 @@ func bytesToKey(b []byte, pasteActive bool) (rune, []byte) { return keyDeleteLine, b[1:] case 12: // ^L return keyClearScreen, b[1:] + case 20: // ^T + return keyTranspose, b[1:] case 23: // ^W return keyDeleteWord, b[1:] case 14: // ^N @@ -228,6 +232,10 @@ func bytesToKey(b []byte, pasteActive bool) (rune, []byte) { } } + if !pasteActive && len(b) >= 4 && b[0] == keyEscape && b[1] == '[' && b[2] == '3' && b[3] == '~' { + return keyDelete, b[4:] + } + if !pasteActive && len(b) >= 6 && b[0] == keyEscape && b[1] == '[' && b[2] == '1' && b[3] == ';' && b[4] == '3' { switch b[5] { case 'C': @@ -590,7 +598,7 @@ func (t *Terminal) handleKey(key rune) (line string, ok bool) { } t.line = t.line[:t.pos] t.moveCursorToPos(t.pos) - case keyCtrlD: + case keyCtrlD, keyDelete: // Erase the character under the current position. // The EOF case when the line is empty is handled in // readLine(). @@ -600,6 +608,24 @@ func (t *Terminal) handleKey(key rune) (line string, ok bool) { } case keyCtrlU: t.eraseNPreviousChars(t.pos) + case keyTranspose: + // This transposes the two characters around the cursor and advances the cursor. Best-effort. + if len(t.line) < 2 || t.pos < 1 { + return + } + swap := t.pos + if swap == len(t.line) { + swap-- // special: at end of line, swap previous two chars + } + t.line[swap-1], t.line[swap] = t.line[swap], t.line[swap-1] + if t.pos < len(t.line) { + t.pos++ + } + if t.echo { + t.moveCursorToPos(swap - 1) + t.writeLine(t.line[swap-1:]) + t.moveCursorToPos(t.pos) + } case keyClearScreen: // Erases the screen and moves the cursor to the home position. t.queue([]rune("\x1b[2J\x1b[H")) diff --git a/vendor/k8s.io/client-go/tools/auth/OWNERS b/vendor/k8s.io/client-go/tools/auth/OWNERS deleted file mode 100644 index c4ea6463d..000000000 --- a/vendor/k8s.io/client-go/tools/auth/OWNERS +++ /dev/null @@ -1,8 +0,0 @@ -# See the OWNERS docs at https://go.k8s.io/owners - -approvers: - - sig-auth-authenticators-approvers -reviewers: - - sig-auth-authenticators-reviewers -labels: - - sig/auth diff --git a/vendor/k8s.io/client-go/tools/auth/clientauth.go b/vendor/k8s.io/client-go/tools/auth/clientauth.go deleted file mode 100644 index 5a256c1c3..000000000 --- a/vendor/k8s.io/client-go/tools/auth/clientauth.go +++ /dev/null @@ -1,125 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/* -Package auth defines a file format for holding authentication -information needed by clients of Kubernetes. Typically, -a Kubernetes cluster will put auth info for the admin in a known -location when it is created, and will (soon) put it in a known -location within a Container's file tree for Containers that -need access to the Kubernetes API. - -Having a defined format allows: - - clients to be implemented in multiple languages - - applications which link clients to be portable across - clusters with different authentication styles (e.g. - some may use SSL Client certs, others may not, etc) - - when the format changes, applications only - need to update this code. - -The file format is json, marshalled from a struct authcfg.Info. - -Client libraries in other languages should use the same format. - -It is not intended to store general preferences, such as default -namespace, output options, etc. CLIs (such as kubectl) and UIs should -develop their own format and may wish to inline the authcfg.Info type. - -The authcfg.Info is just a file format. It is distinct from -client.Config which holds options for creating a client.Client. -Helper functions are provided in this package to fill in a -client.Client from an authcfg.Info. - -Example: - - import ( - "pkg/client" - "pkg/client/auth" - ) - - info, err := auth.LoadFromFile(filename) - if err != nil { - // handle error - } - clientConfig = client.Config{} - clientConfig.Host = "example.com:4901" - clientConfig = info.MergeWithConfig() - client := client.New(clientConfig) - client.Pods(ns).List() -*/ -package auth - -// TODO: need a way to rotate Tokens. Therefore, need a way for client object to be reset when the authcfg is updated. -import ( - "encoding/json" - "os" - - restclient "k8s.io/client-go/rest" -) - -// Info holds Kubernetes API authorization config. It is intended -// to be read/written from a file as a JSON object. -type Info struct { - User string - Password string `datapolicy:"password"` - CAFile string - CertFile string - KeyFile string - BearerToken string `datapolicy:"token"` - Insecure *bool -} - -// LoadFromFile parses an Info object from a file path. -// If the file does not exist, then os.IsNotExist(err) == true -func LoadFromFile(path string) (*Info, error) { - var info Info - if _, err := os.Stat(path); os.IsNotExist(err) { - return nil, err - } - data, err := os.ReadFile(path) - if err != nil { - return nil, err - } - err = json.Unmarshal(data, &info) - if err != nil { - return nil, err - } - return &info, err -} - -// MergeWithConfig returns a copy of a client.Config with values from the Info. -// The fields of client.Config with a corresponding field in the Info are set -// with the value from the Info. -func (info Info) MergeWithConfig(c restclient.Config) (restclient.Config, error) { - var config = c - config.Username = info.User - config.Password = info.Password - config.CAFile = info.CAFile - config.CertFile = info.CertFile - config.KeyFile = info.KeyFile - config.BearerToken = info.BearerToken - if info.Insecure != nil { - config.Insecure = *info.Insecure - } - return config, nil -} - -// Complete returns true if the Kubernetes API authorization info is complete. -func (info Info) Complete() bool { - return len(info.User) > 0 || - len(info.CertFile) > 0 || - len(info.BearerToken) > 0 -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/latest/latest.go b/vendor/k8s.io/client-go/tools/clientcmd/api/latest/latest.go deleted file mode 100644 index c575652b1..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/latest/latest.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package latest - -import ( - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/runtime/serializer/json" - "k8s.io/apimachinery/pkg/runtime/serializer/versioning" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/client-go/tools/clientcmd/api" - "k8s.io/client-go/tools/clientcmd/api/v1" -) - -// Version is the string that represents the current external default version. -const Version = "v1" - -var ExternalVersion = schema.GroupVersion{Group: "", Version: "v1"} - -// OldestVersion is the string that represents the oldest server version supported, -// for client code that wants to hardcode the lowest common denominator. -const OldestVersion = "v1" - -// Versions is the list of versions that are recognized in code. The order provided -// may be assumed to be least feature rich to most feature rich, and clients may -// choose to prefer the latter items in the list over the former items when presented -// with a set of versions to choose. -var Versions = []string{"v1"} - -var ( - Codec runtime.Codec - Scheme *runtime.Scheme -) - -func init() { - Scheme = runtime.NewScheme() - utilruntime.Must(api.AddToScheme(Scheme)) - utilruntime.Must(v1.AddToScheme(Scheme)) - yamlSerializer := json.NewSerializerWithOptions(json.DefaultMetaFactory, Scheme, Scheme, json.SerializerOptions{Yaml: true}) - Codec = versioning.NewDefaultingCodecForScheme( - Scheme, - yamlSerializer, - yamlSerializer, - schema.GroupVersion{Version: Version}, - runtime.InternalGroupVersioner, - ) -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go b/vendor/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go deleted file mode 100644 index 6eee281bc..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "fmt" - "sort" - - "k8s.io/apimachinery/pkg/conversion" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/tools/clientcmd/api" -) - -func Convert_Slice_v1_NamedCluster_To_Map_string_To_Pointer_api_Cluster(in *[]NamedCluster, out *map[string]*api.Cluster, s conversion.Scope) error { - for _, curr := range *in { - newCluster := api.NewCluster() - if err := Convert_v1_Cluster_To_api_Cluster(&curr.Cluster, newCluster, s); err != nil { - return err - } - if *out == nil { - *out = make(map[string]*api.Cluster) - } - if (*out)[curr.Name] == nil { - (*out)[curr.Name] = newCluster - } else { - return fmt.Errorf("error converting *[]NamedCluster into *map[string]*api.Cluster: duplicate name \"%v\" in list: %v", curr.Name, *in) - } - } - return nil -} - -func Convert_Map_string_To_Pointer_api_Cluster_To_Slice_v1_NamedCluster(in *map[string]*api.Cluster, out *[]NamedCluster, s conversion.Scope) error { - allKeys := make([]string, 0, len(*in)) - for key := range *in { - allKeys = append(allKeys, key) - } - sort.Strings(allKeys) - - for _, key := range allKeys { - newCluster := (*in)[key] - oldCluster := Cluster{} - if err := Convert_api_Cluster_To_v1_Cluster(newCluster, &oldCluster, s); err != nil { - return err - } - namedCluster := NamedCluster{key, oldCluster} - *out = append(*out, namedCluster) - } - return nil -} - -func Convert_Slice_v1_NamedAuthInfo_To_Map_string_To_Pointer_api_AuthInfo(in *[]NamedAuthInfo, out *map[string]*api.AuthInfo, s conversion.Scope) error { - for _, curr := range *in { - newAuthInfo := api.NewAuthInfo() - if err := Convert_v1_AuthInfo_To_api_AuthInfo(&curr.AuthInfo, newAuthInfo, s); err != nil { - return err - } - if *out == nil { - *out = make(map[string]*api.AuthInfo) - } - if (*out)[curr.Name] == nil { - (*out)[curr.Name] = newAuthInfo - } else { - return fmt.Errorf("error converting *[]NamedAuthInfo into *map[string]*api.AuthInfo: duplicate name \"%v\" in list: %v", curr.Name, *in) - } - } - return nil -} - -func Convert_Map_string_To_Pointer_api_AuthInfo_To_Slice_v1_NamedAuthInfo(in *map[string]*api.AuthInfo, out *[]NamedAuthInfo, s conversion.Scope) error { - allKeys := make([]string, 0, len(*in)) - for key := range *in { - allKeys = append(allKeys, key) - } - sort.Strings(allKeys) - - for _, key := range allKeys { - newAuthInfo := (*in)[key] - oldAuthInfo := AuthInfo{} - if err := Convert_api_AuthInfo_To_v1_AuthInfo(newAuthInfo, &oldAuthInfo, s); err != nil { - return err - } - namedAuthInfo := NamedAuthInfo{key, oldAuthInfo} - *out = append(*out, namedAuthInfo) - } - return nil -} - -func Convert_Slice_v1_NamedContext_To_Map_string_To_Pointer_api_Context(in *[]NamedContext, out *map[string]*api.Context, s conversion.Scope) error { - for _, curr := range *in { - newContext := api.NewContext() - if err := Convert_v1_Context_To_api_Context(&curr.Context, newContext, s); err != nil { - return err - } - if *out == nil { - *out = make(map[string]*api.Context) - } - if (*out)[curr.Name] == nil { - (*out)[curr.Name] = newContext - } else { - return fmt.Errorf("error converting *[]NamedContext into *map[string]*api.Context: duplicate name \"%v\" in list: %v", curr.Name, *in) - } - } - return nil -} - -func Convert_Map_string_To_Pointer_api_Context_To_Slice_v1_NamedContext(in *map[string]*api.Context, out *[]NamedContext, s conversion.Scope) error { - allKeys := make([]string, 0, len(*in)) - for key := range *in { - allKeys = append(allKeys, key) - } - sort.Strings(allKeys) - - for _, key := range allKeys { - newContext := (*in)[key] - oldContext := Context{} - if err := Convert_api_Context_To_v1_Context(newContext, &oldContext, s); err != nil { - return err - } - namedContext := NamedContext{key, oldContext} - *out = append(*out, namedContext) - } - return nil -} - -func Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object(in *[]NamedExtension, out *map[string]runtime.Object, s conversion.Scope) error { - for _, curr := range *in { - var newExtension runtime.Object - if err := runtime.Convert_runtime_RawExtension_To_runtime_Object(&curr.Extension, &newExtension, s); err != nil { - return err - } - if *out == nil { - *out = make(map[string]runtime.Object) - } - if (*out)[curr.Name] == nil { - (*out)[curr.Name] = newExtension - } else { - return fmt.Errorf("error converting *[]NamedExtension into *map[string]runtime.Object: duplicate name \"%v\" in list: %v", curr.Name, *in) - } - } - return nil -} - -func Convert_Map_string_To_runtime_Object_To_Slice_v1_NamedExtension(in *map[string]runtime.Object, out *[]NamedExtension, s conversion.Scope) error { - allKeys := make([]string, 0, len(*in)) - for key := range *in { - allKeys = append(allKeys, key) - } - sort.Strings(allKeys) - - for _, key := range allKeys { - newExtension := (*in)[key] - oldExtension := runtime.RawExtension{} - if err := runtime.Convert_runtime_Object_To_runtime_RawExtension(&newExtension, &oldExtension, s); err != nil { - return err - } - namedExtension := NamedExtension{key, oldExtension} - *out = append(*out, namedExtension) - } - return nil -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/defaults.go b/vendor/k8s.io/client-go/tools/clientcmd/api/v1/defaults.go deleted file mode 100644 index bf513dc7c..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/defaults.go +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "k8s.io/apimachinery/pkg/runtime" -) - -func addDefaultingFuncs(scheme *runtime.Scheme) error { - return RegisterDefaults(scheme) -} - -func SetDefaults_ExecConfig(exec *ExecConfig) { - if len(exec.InteractiveMode) == 0 { - switch exec.APIVersion { - case "client.authentication.k8s.io/v1beta1", "client.authentication.k8s.io/v1alpha1": - // default to IfAvailableExecInteractiveMode for backwards compatibility - exec.InteractiveMode = IfAvailableExecInteractiveMode - default: - // require other versions to explicitly declare whether they want stdin or not - } - } -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/doc.go b/vendor/k8s.io/client-go/tools/clientcmd/api/v1/doc.go deleted file mode 100644 index 3ccdebc1c..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/doc.go +++ /dev/null @@ -1,21 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// +k8s:conversion-gen=k8s.io/client-go/tools/clientcmd/api -// +k8s:deepcopy-gen=package -// +k8s:defaulter-gen=Kind - -package v1 diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/register.go b/vendor/k8s.io/client-go/tools/clientcmd/api/v1/register.go deleted file mode 100644 index 4a4d4a55f..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/register.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// SchemeGroupVersion is group version used to register these objects -// TODO this should be in the "kubeconfig" group -var SchemeGroupVersion = schema.GroupVersion{Group: "", Version: "v1"} - -var ( - // TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api. - // localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes. - SchemeBuilder runtime.SchemeBuilder - localSchemeBuilder = &SchemeBuilder - AddToScheme = localSchemeBuilder.AddToScheme -) - -func init() { - // We only register manually written functions here. The registration of the - // generated functions takes place in the generated files. The separation - // makes the code compile even when the generated files are missing. - localSchemeBuilder.Register(addKnownTypes, addDefaultingFuncs) -} - -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &Config{}, - ) - return nil -} - -func (obj *Config) GetObjectKind() schema.ObjectKind { return obj } -func (obj *Config) SetGroupVersionKind(gvk schema.GroupVersionKind) { - obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind() -} -func (obj *Config) GroupVersionKind() schema.GroupVersionKind { - return schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind) -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/types.go b/vendor/k8s.io/client-go/tools/clientcmd/api/v1/types.go deleted file mode 100644 index c278817b6..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/types.go +++ /dev/null @@ -1,274 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "k8s.io/apimachinery/pkg/runtime" -) - -// Where possible, json tags match the cli argument names. -// Top level config objects and all values required for proper functioning are not "omitempty". Any truly optional piece of config is allowed to be omitted. - -// Config holds the information needed to build connect to remote kubernetes clusters as a given user -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type Config struct { - // Legacy field from pkg/api/types.go TypeMeta. - // TODO(jlowdermilk): remove this after eliminating downstream dependencies. - // +k8s:conversion-gen=false - // +optional - Kind string `json:"kind,omitempty"` - // Legacy field from pkg/api/types.go TypeMeta. - // TODO(jlowdermilk): remove this after eliminating downstream dependencies. - // +k8s:conversion-gen=false - // +optional - APIVersion string `json:"apiVersion,omitempty"` - // Preferences holds general information to be use for cli interactions - // Deprecated: this field is deprecated in v1.34. It is not used by any of the Kubernetes components. - Preferences Preferences `json:"preferences,omitzero"` - // Clusters is a map of referencable names to cluster configs - Clusters []NamedCluster `json:"clusters"` - // AuthInfos is a map of referencable names to user configs - AuthInfos []NamedAuthInfo `json:"users"` - // Contexts is a map of referencable names to context configs - Contexts []NamedContext `json:"contexts"` - // CurrentContext is the name of the context that you would like to use by default - CurrentContext string `json:"current-context"` - // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields - // +optional - Extensions []NamedExtension `json:"extensions,omitempty"` -} - -// Deprecated: this structure is deprecated in v1.34. It is not used by any of the Kubernetes components. -type Preferences struct { - // +optional - Colors bool `json:"colors,omitempty"` - // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields - // +optional - Extensions []NamedExtension `json:"extensions,omitempty"` -} - -// Cluster contains information about how to communicate with a kubernetes cluster -type Cluster struct { - // Server is the address of the kubernetes cluster (https://hostname:port). - Server string `json:"server"` - // TLSServerName is used to check server certificate. If TLSServerName is empty, the hostname used to contact the server is used. - // +optional - TLSServerName string `json:"tls-server-name,omitempty"` - // InsecureSkipTLSVerify skips the validity check for the server's certificate. This will make your HTTPS connections insecure. - // +optional - InsecureSkipTLSVerify bool `json:"insecure-skip-tls-verify,omitempty"` - // CertificateAuthority is the path to a cert file for the certificate authority. - // +optional - CertificateAuthority string `json:"certificate-authority,omitempty"` - // CertificateAuthorityData contains PEM-encoded certificate authority certificates. Overrides CertificateAuthority - // +optional - CertificateAuthorityData []byte `json:"certificate-authority-data,omitempty"` - // ProxyURL is the URL to the proxy to be used for all requests made by this - // client. URLs with "http", "https", and "socks5" schemes are supported. If - // this configuration is not provided or the empty string, the client - // attempts to construct a proxy configuration from http_proxy and - // https_proxy environment variables. If these environment variables are not - // set, the client does not attempt to proxy requests. - // - // socks5 proxying does not currently support spdy streaming endpoints (exec, - // attach, port forward). - // +optional - ProxyURL string `json:"proxy-url,omitempty"` - // DisableCompression allows client to opt-out of response compression for all requests to the server. This is useful - // to speed up requests (specifically lists) when client-server network bandwidth is ample, by saving time on - // compression (server-side) and decompression (client-side): https://github.com/kubernetes/kubernetes/issues/112296. - // +optional - DisableCompression bool `json:"disable-compression,omitempty"` - // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields - // +optional - Extensions []NamedExtension `json:"extensions,omitempty"` -} - -// AuthInfo contains information that describes identity information. This is use to tell the kubernetes cluster who you are. -type AuthInfo struct { - // ClientCertificate is the path to a client cert file for TLS. - // +optional - ClientCertificate string `json:"client-certificate,omitempty"` - // ClientCertificateData contains PEM-encoded data from a client cert file for TLS. Overrides ClientCertificate - // +optional - ClientCertificateData []byte `json:"client-certificate-data,omitempty"` - // ClientKey is the path to a client key file for TLS. - // +optional - ClientKey string `json:"client-key,omitempty"` - // ClientKeyData contains PEM-encoded data from a client key file for TLS. Overrides ClientKey - // +optional - ClientKeyData []byte `json:"client-key-data,omitempty" datapolicy:"security-key"` - // Token is the bearer token for authentication to the kubernetes cluster. - // +optional - Token string `json:"token,omitempty" datapolicy:"token"` - // TokenFile is a pointer to a file that contains a bearer token (as described above). If both Token and TokenFile are present, - // the TokenFile will be periodically read and the last successfully read value takes precedence over Token. - // +optional - TokenFile string `json:"tokenFile,omitempty"` - // Impersonate is the username to impersonate. The name matches the flag. - // +optional - Impersonate string `json:"as,omitempty"` - // ImpersonateUID is the uid to impersonate. - // +optional - ImpersonateUID string `json:"as-uid,omitempty"` - // ImpersonateGroups is the groups to impersonate. - // +optional - ImpersonateGroups []string `json:"as-groups,omitempty"` - // ImpersonateUserExtra contains additional information for impersonated user. - // +optional - ImpersonateUserExtra map[string][]string `json:"as-user-extra,omitempty"` - // Username is the username for basic authentication to the kubernetes cluster. - // +optional - Username string `json:"username,omitempty"` - // Password is the password for basic authentication to the kubernetes cluster. - // +optional - Password string `json:"password,omitempty" datapolicy:"password"` - // AuthProvider specifies a custom authentication plugin for the kubernetes cluster. - // +optional - AuthProvider *AuthProviderConfig `json:"auth-provider,omitempty"` - // Exec specifies a custom exec-based authentication plugin for the kubernetes cluster. - // +optional - Exec *ExecConfig `json:"exec,omitempty"` - // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields - // +optional - Extensions []NamedExtension `json:"extensions,omitempty"` -} - -// Context is a tuple of references to a cluster (how do I communicate with a kubernetes cluster), a user (how do I identify myself), and a namespace (what subset of resources do I want to work with) -type Context struct { - // Cluster is the name of the cluster for this context - Cluster string `json:"cluster"` - // AuthInfo is the name of the authInfo for this context - AuthInfo string `json:"user"` - // Namespace is the default namespace to use on unspecified requests - // +optional - Namespace string `json:"namespace,omitempty"` - // Extensions holds additional information. This is useful for extenders so that reads and writes don't clobber unknown fields - // +optional - Extensions []NamedExtension `json:"extensions,omitempty"` -} - -// NamedCluster relates nicknames to cluster information -type NamedCluster struct { - // Name is the nickname for this Cluster - Name string `json:"name"` - // Cluster holds the cluster information - Cluster Cluster `json:"cluster"` -} - -// NamedContext relates nicknames to context information -type NamedContext struct { - // Name is the nickname for this Context - Name string `json:"name"` - // Context holds the context information - Context Context `json:"context"` -} - -// NamedAuthInfo relates nicknames to auth information -type NamedAuthInfo struct { - // Name is the nickname for this AuthInfo - Name string `json:"name"` - // AuthInfo holds the auth information - AuthInfo AuthInfo `json:"user"` -} - -// NamedExtension relates nicknames to extension information -type NamedExtension struct { - // Name is the nickname for this Extension - Name string `json:"name"` - // Extension holds the extension information - Extension runtime.RawExtension `json:"extension"` -} - -// AuthProviderConfig holds the configuration for a specified auth provider. -type AuthProviderConfig struct { - Name string `json:"name"` - Config map[string]string `json:"config"` -} - -// ExecConfig specifies a command to provide client credentials. The command is exec'd -// and outputs structured stdout holding credentials. -// -// See the client.authentication.k8s.io API group for specifications of the exact input -// and output format -type ExecConfig struct { - // Command to execute. - Command string `json:"command"` - // Arguments to pass to the command when executing it. - // +optional - Args []string `json:"args"` - // Env defines additional environment variables to expose to the process. These - // are unioned with the host's environment, as well as variables client-go uses - // to pass argument to the plugin. - // +optional - Env []ExecEnvVar `json:"env"` - - // Preferred input version of the ExecInfo. The returned ExecCredentials MUST use - // the same encoding version as the input. - APIVersion string `json:"apiVersion,omitempty"` - - // This text is shown to the user when the executable doesn't seem to be - // present. For example, `brew install foo-cli` might be a good InstallHint for - // foo-cli on Mac OS systems. - InstallHint string `json:"installHint,omitempty"` - - // ProvideClusterInfo determines whether or not to provide cluster information, - // which could potentially contain very large CA data, to this exec plugin as a - // part of the KUBERNETES_EXEC_INFO environment variable. By default, it is set - // to false. Package k8s.io/client-go/tools/auth/exec provides helper methods for - // reading this environment variable. - ProvideClusterInfo bool `json:"provideClusterInfo"` - - // InteractiveMode determines this plugin's relationship with standard input. Valid - // values are "Never" (this exec plugin never uses standard input), "IfAvailable" (this - // exec plugin wants to use standard input if it is available), or "Always" (this exec - // plugin requires standard input to function). See ExecInteractiveMode values for more - // details. - // - // If APIVersion is client.authentication.k8s.io/v1alpha1 or - // client.authentication.k8s.io/v1beta1, then this field is optional and defaults - // to "IfAvailable" when unset. Otherwise, this field is required. - //+optional - InteractiveMode ExecInteractiveMode `json:"interactiveMode,omitempty"` -} - -// ExecEnvVar is used for setting environment variables when executing an exec-based -// credential plugin. -type ExecEnvVar struct { - Name string `json:"name"` - Value string `json:"value"` -} - -// ExecInteractiveMode is a string that describes an exec plugin's relationship with standard input. -type ExecInteractiveMode string - -const ( - // NeverExecInteractiveMode declares that this exec plugin never needs to use standard - // input, and therefore the exec plugin will be run regardless of whether standard input is - // available for user input. - NeverExecInteractiveMode ExecInteractiveMode = "Never" - // IfAvailableExecInteractiveMode declares that this exec plugin would like to use standard input - // if it is available, but can still operate if standard input is not available. Therefore, the - // exec plugin will be run regardless of whether stdin is available for user input. If standard - // input is available for user input, then it will be provided to this exec plugin. - IfAvailableExecInteractiveMode ExecInteractiveMode = "IfAvailable" - // AlwaysExecInteractiveMode declares that this exec plugin requires standard input in order to - // run, and therefore the exec plugin will only be run if standard input is available for user - // input. If standard input is not available for user input, then the exec plugin will not be run - // and an error will be returned by the exec plugin runner. - AlwaysExecInteractiveMode ExecInteractiveMode = "Always" -) diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.conversion.go b/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.conversion.go deleted file mode 100644 index ef1e9b8eb..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.conversion.go +++ /dev/null @@ -1,459 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by conversion-gen. DO NOT EDIT. - -package v1 - -import ( - unsafe "unsafe" - - conversion "k8s.io/apimachinery/pkg/conversion" - runtime "k8s.io/apimachinery/pkg/runtime" - api "k8s.io/client-go/tools/clientcmd/api" -) - -func init() { - localSchemeBuilder.Register(RegisterConversions) -} - -// RegisterConversions adds conversion functions to the given scheme. -// Public to allow building arbitrary schemes. -func RegisterConversions(s *runtime.Scheme) error { - if err := s.AddGeneratedConversionFunc((*AuthInfo)(nil), (*api.AuthInfo)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1_AuthInfo_To_api_AuthInfo(a.(*AuthInfo), b.(*api.AuthInfo), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*api.AuthInfo)(nil), (*AuthInfo)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_api_AuthInfo_To_v1_AuthInfo(a.(*api.AuthInfo), b.(*AuthInfo), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*AuthProviderConfig)(nil), (*api.AuthProviderConfig)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1_AuthProviderConfig_To_api_AuthProviderConfig(a.(*AuthProviderConfig), b.(*api.AuthProviderConfig), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*api.AuthProviderConfig)(nil), (*AuthProviderConfig)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_api_AuthProviderConfig_To_v1_AuthProviderConfig(a.(*api.AuthProviderConfig), b.(*AuthProviderConfig), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*Cluster)(nil), (*api.Cluster)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1_Cluster_To_api_Cluster(a.(*Cluster), b.(*api.Cluster), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*api.Cluster)(nil), (*Cluster)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_api_Cluster_To_v1_Cluster(a.(*api.Cluster), b.(*Cluster), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*Config)(nil), (*api.Config)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1_Config_To_api_Config(a.(*Config), b.(*api.Config), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*api.Config)(nil), (*Config)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_api_Config_To_v1_Config(a.(*api.Config), b.(*Config), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*Context)(nil), (*api.Context)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1_Context_To_api_Context(a.(*Context), b.(*api.Context), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*api.Context)(nil), (*Context)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_api_Context_To_v1_Context(a.(*api.Context), b.(*Context), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*ExecConfig)(nil), (*api.ExecConfig)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1_ExecConfig_To_api_ExecConfig(a.(*ExecConfig), b.(*api.ExecConfig), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*api.ExecConfig)(nil), (*ExecConfig)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_api_ExecConfig_To_v1_ExecConfig(a.(*api.ExecConfig), b.(*ExecConfig), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*ExecEnvVar)(nil), (*api.ExecEnvVar)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1_ExecEnvVar_To_api_ExecEnvVar(a.(*ExecEnvVar), b.(*api.ExecEnvVar), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*api.ExecEnvVar)(nil), (*ExecEnvVar)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_api_ExecEnvVar_To_v1_ExecEnvVar(a.(*api.ExecEnvVar), b.(*ExecEnvVar), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*Preferences)(nil), (*api.Preferences)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_v1_Preferences_To_api_Preferences(a.(*Preferences), b.(*api.Preferences), scope) - }); err != nil { - return err - } - if err := s.AddGeneratedConversionFunc((*api.Preferences)(nil), (*Preferences)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_api_Preferences_To_v1_Preferences(a.(*api.Preferences), b.(*Preferences), scope) - }); err != nil { - return err - } - if err := s.AddConversionFunc((*map[string]*api.AuthInfo)(nil), (*[]NamedAuthInfo)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_Map_string_To_Pointer_api_AuthInfo_To_Slice_v1_NamedAuthInfo(a.(*map[string]*api.AuthInfo), b.(*[]NamedAuthInfo), scope) - }); err != nil { - return err - } - if err := s.AddConversionFunc((*map[string]*api.Cluster)(nil), (*[]NamedCluster)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_Map_string_To_Pointer_api_Cluster_To_Slice_v1_NamedCluster(a.(*map[string]*api.Cluster), b.(*[]NamedCluster), scope) - }); err != nil { - return err - } - if err := s.AddConversionFunc((*map[string]*api.Context)(nil), (*[]NamedContext)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_Map_string_To_Pointer_api_Context_To_Slice_v1_NamedContext(a.(*map[string]*api.Context), b.(*[]NamedContext), scope) - }); err != nil { - return err - } - if err := s.AddConversionFunc((*map[string]runtime.Object)(nil), (*[]NamedExtension)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_Map_string_To_runtime_Object_To_Slice_v1_NamedExtension(a.(*map[string]runtime.Object), b.(*[]NamedExtension), scope) - }); err != nil { - return err - } - if err := s.AddConversionFunc((*[]NamedAuthInfo)(nil), (*map[string]*api.AuthInfo)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_Slice_v1_NamedAuthInfo_To_Map_string_To_Pointer_api_AuthInfo(a.(*[]NamedAuthInfo), b.(*map[string]*api.AuthInfo), scope) - }); err != nil { - return err - } - if err := s.AddConversionFunc((*[]NamedCluster)(nil), (*map[string]*api.Cluster)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_Slice_v1_NamedCluster_To_Map_string_To_Pointer_api_Cluster(a.(*[]NamedCluster), b.(*map[string]*api.Cluster), scope) - }); err != nil { - return err - } - if err := s.AddConversionFunc((*[]NamedContext)(nil), (*map[string]*api.Context)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_Slice_v1_NamedContext_To_Map_string_To_Pointer_api_Context(a.(*[]NamedContext), b.(*map[string]*api.Context), scope) - }); err != nil { - return err - } - if err := s.AddConversionFunc((*[]NamedExtension)(nil), (*map[string]runtime.Object)(nil), func(a, b interface{}, scope conversion.Scope) error { - return Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object(a.(*[]NamedExtension), b.(*map[string]runtime.Object), scope) - }); err != nil { - return err - } - return nil -} - -func autoConvert_v1_AuthInfo_To_api_AuthInfo(in *AuthInfo, out *api.AuthInfo, s conversion.Scope) error { - out.ClientCertificate = in.ClientCertificate - out.ClientCertificateData = *(*[]byte)(unsafe.Pointer(&in.ClientCertificateData)) - out.ClientKey = in.ClientKey - out.ClientKeyData = *(*[]byte)(unsafe.Pointer(&in.ClientKeyData)) - out.Token = in.Token - out.TokenFile = in.TokenFile - out.Impersonate = in.Impersonate - out.ImpersonateUID = in.ImpersonateUID - out.ImpersonateGroups = *(*[]string)(unsafe.Pointer(&in.ImpersonateGroups)) - out.ImpersonateUserExtra = *(*map[string][]string)(unsafe.Pointer(&in.ImpersonateUserExtra)) - out.Username = in.Username - out.Password = in.Password - out.AuthProvider = (*api.AuthProviderConfig)(unsafe.Pointer(in.AuthProvider)) - if in.Exec != nil { - in, out := &in.Exec, &out.Exec - *out = new(api.ExecConfig) - if err := Convert_v1_ExecConfig_To_api_ExecConfig(*in, *out, s); err != nil { - return err - } - } else { - out.Exec = nil - } - if err := Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object(&in.Extensions, &out.Extensions, s); err != nil { - return err - } - return nil -} - -// Convert_v1_AuthInfo_To_api_AuthInfo is an autogenerated conversion function. -func Convert_v1_AuthInfo_To_api_AuthInfo(in *AuthInfo, out *api.AuthInfo, s conversion.Scope) error { - return autoConvert_v1_AuthInfo_To_api_AuthInfo(in, out, s) -} - -func autoConvert_api_AuthInfo_To_v1_AuthInfo(in *api.AuthInfo, out *AuthInfo, s conversion.Scope) error { - // INFO: in.LocationOfOrigin opted out of conversion generation - out.ClientCertificate = in.ClientCertificate - out.ClientCertificateData = *(*[]byte)(unsafe.Pointer(&in.ClientCertificateData)) - out.ClientKey = in.ClientKey - out.ClientKeyData = *(*[]byte)(unsafe.Pointer(&in.ClientKeyData)) - out.Token = in.Token - out.TokenFile = in.TokenFile - out.Impersonate = in.Impersonate - out.ImpersonateUID = in.ImpersonateUID - out.ImpersonateGroups = *(*[]string)(unsafe.Pointer(&in.ImpersonateGroups)) - out.ImpersonateUserExtra = *(*map[string][]string)(unsafe.Pointer(&in.ImpersonateUserExtra)) - out.Username = in.Username - out.Password = in.Password - out.AuthProvider = (*AuthProviderConfig)(unsafe.Pointer(in.AuthProvider)) - if in.Exec != nil { - in, out := &in.Exec, &out.Exec - *out = new(ExecConfig) - if err := Convert_api_ExecConfig_To_v1_ExecConfig(*in, *out, s); err != nil { - return err - } - } else { - out.Exec = nil - } - if err := Convert_Map_string_To_runtime_Object_To_Slice_v1_NamedExtension(&in.Extensions, &out.Extensions, s); err != nil { - return err - } - return nil -} - -// Convert_api_AuthInfo_To_v1_AuthInfo is an autogenerated conversion function. -func Convert_api_AuthInfo_To_v1_AuthInfo(in *api.AuthInfo, out *AuthInfo, s conversion.Scope) error { - return autoConvert_api_AuthInfo_To_v1_AuthInfo(in, out, s) -} - -func autoConvert_v1_AuthProviderConfig_To_api_AuthProviderConfig(in *AuthProviderConfig, out *api.AuthProviderConfig, s conversion.Scope) error { - out.Name = in.Name - out.Config = *(*map[string]string)(unsafe.Pointer(&in.Config)) - return nil -} - -// Convert_v1_AuthProviderConfig_To_api_AuthProviderConfig is an autogenerated conversion function. -func Convert_v1_AuthProviderConfig_To_api_AuthProviderConfig(in *AuthProviderConfig, out *api.AuthProviderConfig, s conversion.Scope) error { - return autoConvert_v1_AuthProviderConfig_To_api_AuthProviderConfig(in, out, s) -} - -func autoConvert_api_AuthProviderConfig_To_v1_AuthProviderConfig(in *api.AuthProviderConfig, out *AuthProviderConfig, s conversion.Scope) error { - out.Name = in.Name - out.Config = *(*map[string]string)(unsafe.Pointer(&in.Config)) - return nil -} - -// Convert_api_AuthProviderConfig_To_v1_AuthProviderConfig is an autogenerated conversion function. -func Convert_api_AuthProviderConfig_To_v1_AuthProviderConfig(in *api.AuthProviderConfig, out *AuthProviderConfig, s conversion.Scope) error { - return autoConvert_api_AuthProviderConfig_To_v1_AuthProviderConfig(in, out, s) -} - -func autoConvert_v1_Cluster_To_api_Cluster(in *Cluster, out *api.Cluster, s conversion.Scope) error { - out.Server = in.Server - out.TLSServerName = in.TLSServerName - out.InsecureSkipTLSVerify = in.InsecureSkipTLSVerify - out.CertificateAuthority = in.CertificateAuthority - out.CertificateAuthorityData = *(*[]byte)(unsafe.Pointer(&in.CertificateAuthorityData)) - out.ProxyURL = in.ProxyURL - out.DisableCompression = in.DisableCompression - if err := Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object(&in.Extensions, &out.Extensions, s); err != nil { - return err - } - return nil -} - -// Convert_v1_Cluster_To_api_Cluster is an autogenerated conversion function. -func Convert_v1_Cluster_To_api_Cluster(in *Cluster, out *api.Cluster, s conversion.Scope) error { - return autoConvert_v1_Cluster_To_api_Cluster(in, out, s) -} - -func autoConvert_api_Cluster_To_v1_Cluster(in *api.Cluster, out *Cluster, s conversion.Scope) error { - // INFO: in.LocationOfOrigin opted out of conversion generation - out.Server = in.Server - out.TLSServerName = in.TLSServerName - out.InsecureSkipTLSVerify = in.InsecureSkipTLSVerify - out.CertificateAuthority = in.CertificateAuthority - out.CertificateAuthorityData = *(*[]byte)(unsafe.Pointer(&in.CertificateAuthorityData)) - out.ProxyURL = in.ProxyURL - out.DisableCompression = in.DisableCompression - if err := Convert_Map_string_To_runtime_Object_To_Slice_v1_NamedExtension(&in.Extensions, &out.Extensions, s); err != nil { - return err - } - return nil -} - -// Convert_api_Cluster_To_v1_Cluster is an autogenerated conversion function. -func Convert_api_Cluster_To_v1_Cluster(in *api.Cluster, out *Cluster, s conversion.Scope) error { - return autoConvert_api_Cluster_To_v1_Cluster(in, out, s) -} - -func autoConvert_v1_Config_To_api_Config(in *Config, out *api.Config, s conversion.Scope) error { - // INFO: in.Kind opted out of conversion generation - // INFO: in.APIVersion opted out of conversion generation - if err := Convert_v1_Preferences_To_api_Preferences(&in.Preferences, &out.Preferences, s); err != nil { - return err - } - if err := Convert_Slice_v1_NamedCluster_To_Map_string_To_Pointer_api_Cluster(&in.Clusters, &out.Clusters, s); err != nil { - return err - } - if err := Convert_Slice_v1_NamedAuthInfo_To_Map_string_To_Pointer_api_AuthInfo(&in.AuthInfos, &out.AuthInfos, s); err != nil { - return err - } - if err := Convert_Slice_v1_NamedContext_To_Map_string_To_Pointer_api_Context(&in.Contexts, &out.Contexts, s); err != nil { - return err - } - out.CurrentContext = in.CurrentContext - if err := Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object(&in.Extensions, &out.Extensions, s); err != nil { - return err - } - return nil -} - -// Convert_v1_Config_To_api_Config is an autogenerated conversion function. -func Convert_v1_Config_To_api_Config(in *Config, out *api.Config, s conversion.Scope) error { - return autoConvert_v1_Config_To_api_Config(in, out, s) -} - -func autoConvert_api_Config_To_v1_Config(in *api.Config, out *Config, s conversion.Scope) error { - // INFO: in.Kind opted out of conversion generation - // INFO: in.APIVersion opted out of conversion generation - if err := Convert_api_Preferences_To_v1_Preferences(&in.Preferences, &out.Preferences, s); err != nil { - return err - } - if err := Convert_Map_string_To_Pointer_api_Cluster_To_Slice_v1_NamedCluster(&in.Clusters, &out.Clusters, s); err != nil { - return err - } - if err := Convert_Map_string_To_Pointer_api_AuthInfo_To_Slice_v1_NamedAuthInfo(&in.AuthInfos, &out.AuthInfos, s); err != nil { - return err - } - if err := Convert_Map_string_To_Pointer_api_Context_To_Slice_v1_NamedContext(&in.Contexts, &out.Contexts, s); err != nil { - return err - } - out.CurrentContext = in.CurrentContext - if err := Convert_Map_string_To_runtime_Object_To_Slice_v1_NamedExtension(&in.Extensions, &out.Extensions, s); err != nil { - return err - } - return nil -} - -// Convert_api_Config_To_v1_Config is an autogenerated conversion function. -func Convert_api_Config_To_v1_Config(in *api.Config, out *Config, s conversion.Scope) error { - return autoConvert_api_Config_To_v1_Config(in, out, s) -} - -func autoConvert_v1_Context_To_api_Context(in *Context, out *api.Context, s conversion.Scope) error { - out.Cluster = in.Cluster - out.AuthInfo = in.AuthInfo - out.Namespace = in.Namespace - if err := Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object(&in.Extensions, &out.Extensions, s); err != nil { - return err - } - return nil -} - -// Convert_v1_Context_To_api_Context is an autogenerated conversion function. -func Convert_v1_Context_To_api_Context(in *Context, out *api.Context, s conversion.Scope) error { - return autoConvert_v1_Context_To_api_Context(in, out, s) -} - -func autoConvert_api_Context_To_v1_Context(in *api.Context, out *Context, s conversion.Scope) error { - // INFO: in.LocationOfOrigin opted out of conversion generation - out.Cluster = in.Cluster - out.AuthInfo = in.AuthInfo - out.Namespace = in.Namespace - if err := Convert_Map_string_To_runtime_Object_To_Slice_v1_NamedExtension(&in.Extensions, &out.Extensions, s); err != nil { - return err - } - return nil -} - -// Convert_api_Context_To_v1_Context is an autogenerated conversion function. -func Convert_api_Context_To_v1_Context(in *api.Context, out *Context, s conversion.Scope) error { - return autoConvert_api_Context_To_v1_Context(in, out, s) -} - -func autoConvert_v1_ExecConfig_To_api_ExecConfig(in *ExecConfig, out *api.ExecConfig, s conversion.Scope) error { - out.Command = in.Command - out.Args = *(*[]string)(unsafe.Pointer(&in.Args)) - out.Env = *(*[]api.ExecEnvVar)(unsafe.Pointer(&in.Env)) - out.APIVersion = in.APIVersion - out.InstallHint = in.InstallHint - out.ProvideClusterInfo = in.ProvideClusterInfo - out.InteractiveMode = api.ExecInteractiveMode(in.InteractiveMode) - return nil -} - -// Convert_v1_ExecConfig_To_api_ExecConfig is an autogenerated conversion function. -func Convert_v1_ExecConfig_To_api_ExecConfig(in *ExecConfig, out *api.ExecConfig, s conversion.Scope) error { - return autoConvert_v1_ExecConfig_To_api_ExecConfig(in, out, s) -} - -func autoConvert_api_ExecConfig_To_v1_ExecConfig(in *api.ExecConfig, out *ExecConfig, s conversion.Scope) error { - out.Command = in.Command - out.Args = *(*[]string)(unsafe.Pointer(&in.Args)) - out.Env = *(*[]ExecEnvVar)(unsafe.Pointer(&in.Env)) - out.APIVersion = in.APIVersion - out.InstallHint = in.InstallHint - out.ProvideClusterInfo = in.ProvideClusterInfo - // INFO: in.Config opted out of conversion generation - out.InteractiveMode = ExecInteractiveMode(in.InteractiveMode) - // INFO: in.StdinUnavailable opted out of conversion generation - // INFO: in.StdinUnavailableMessage opted out of conversion generation - // INFO: in.PluginPolicy opted out of conversion generation - return nil -} - -// Convert_api_ExecConfig_To_v1_ExecConfig is an autogenerated conversion function. -func Convert_api_ExecConfig_To_v1_ExecConfig(in *api.ExecConfig, out *ExecConfig, s conversion.Scope) error { - return autoConvert_api_ExecConfig_To_v1_ExecConfig(in, out, s) -} - -func autoConvert_v1_ExecEnvVar_To_api_ExecEnvVar(in *ExecEnvVar, out *api.ExecEnvVar, s conversion.Scope) error { - out.Name = in.Name - out.Value = in.Value - return nil -} - -// Convert_v1_ExecEnvVar_To_api_ExecEnvVar is an autogenerated conversion function. -func Convert_v1_ExecEnvVar_To_api_ExecEnvVar(in *ExecEnvVar, out *api.ExecEnvVar, s conversion.Scope) error { - return autoConvert_v1_ExecEnvVar_To_api_ExecEnvVar(in, out, s) -} - -func autoConvert_api_ExecEnvVar_To_v1_ExecEnvVar(in *api.ExecEnvVar, out *ExecEnvVar, s conversion.Scope) error { - out.Name = in.Name - out.Value = in.Value - return nil -} - -// Convert_api_ExecEnvVar_To_v1_ExecEnvVar is an autogenerated conversion function. -func Convert_api_ExecEnvVar_To_v1_ExecEnvVar(in *api.ExecEnvVar, out *ExecEnvVar, s conversion.Scope) error { - return autoConvert_api_ExecEnvVar_To_v1_ExecEnvVar(in, out, s) -} - -func autoConvert_v1_Preferences_To_api_Preferences(in *Preferences, out *api.Preferences, s conversion.Scope) error { - out.Colors = in.Colors - if err := Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object(&in.Extensions, &out.Extensions, s); err != nil { - return err - } - return nil -} - -// Convert_v1_Preferences_To_api_Preferences is an autogenerated conversion function. -func Convert_v1_Preferences_To_api_Preferences(in *Preferences, out *api.Preferences, s conversion.Scope) error { - return autoConvert_v1_Preferences_To_api_Preferences(in, out, s) -} - -func autoConvert_api_Preferences_To_v1_Preferences(in *api.Preferences, out *Preferences, s conversion.Scope) error { - out.Colors = in.Colors - if err := Convert_Map_string_To_runtime_Object_To_Slice_v1_NamedExtension(&in.Extensions, &out.Extensions, s); err != nil { - return err - } - return nil -} - -// Convert_api_Preferences_To_v1_Preferences is an autogenerated conversion function. -func Convert_api_Preferences_To_v1_Preferences(in *api.Preferences, out *Preferences, s conversion.Scope) error { - return autoConvert_api_Preferences_To_v1_Preferences(in, out, s) -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.deepcopy.go b/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.deepcopy.go deleted file mode 100644 index 78492598b..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.deepcopy.go +++ /dev/null @@ -1,349 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AuthInfo) DeepCopyInto(out *AuthInfo) { - *out = *in - if in.ClientCertificateData != nil { - in, out := &in.ClientCertificateData, &out.ClientCertificateData - *out = make([]byte, len(*in)) - copy(*out, *in) - } - if in.ClientKeyData != nil { - in, out := &in.ClientKeyData, &out.ClientKeyData - *out = make([]byte, len(*in)) - copy(*out, *in) - } - if in.ImpersonateGroups != nil { - in, out := &in.ImpersonateGroups, &out.ImpersonateGroups - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.ImpersonateUserExtra != nil { - in, out := &in.ImpersonateUserExtra, &out.ImpersonateUserExtra - *out = make(map[string][]string, len(*in)) - for key, val := range *in { - var outVal []string - if val == nil { - (*out)[key] = nil - } else { - in, out := &val, &outVal - *out = make([]string, len(*in)) - copy(*out, *in) - } - (*out)[key] = outVal - } - } - if in.AuthProvider != nil { - in, out := &in.AuthProvider, &out.AuthProvider - *out = new(AuthProviderConfig) - (*in).DeepCopyInto(*out) - } - if in.Exec != nil { - in, out := &in.Exec, &out.Exec - *out = new(ExecConfig) - (*in).DeepCopyInto(*out) - } - if in.Extensions != nil { - in, out := &in.Extensions, &out.Extensions - *out = make([]NamedExtension, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuthInfo. -func (in *AuthInfo) DeepCopy() *AuthInfo { - if in == nil { - return nil - } - out := new(AuthInfo) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AuthProviderConfig) DeepCopyInto(out *AuthProviderConfig) { - *out = *in - if in.Config != nil { - in, out := &in.Config, &out.Config - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuthProviderConfig. -func (in *AuthProviderConfig) DeepCopy() *AuthProviderConfig { - if in == nil { - return nil - } - out := new(AuthProviderConfig) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Cluster) DeepCopyInto(out *Cluster) { - *out = *in - if in.CertificateAuthorityData != nil { - in, out := &in.CertificateAuthorityData, &out.CertificateAuthorityData - *out = make([]byte, len(*in)) - copy(*out, *in) - } - if in.Extensions != nil { - in, out := &in.Extensions, &out.Extensions - *out = make([]NamedExtension, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Cluster. -func (in *Cluster) DeepCopy() *Cluster { - if in == nil { - return nil - } - out := new(Cluster) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Config) DeepCopyInto(out *Config) { - *out = *in - in.Preferences.DeepCopyInto(&out.Preferences) - if in.Clusters != nil { - in, out := &in.Clusters, &out.Clusters - *out = make([]NamedCluster, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.AuthInfos != nil { - in, out := &in.AuthInfos, &out.AuthInfos - *out = make([]NamedAuthInfo, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Contexts != nil { - in, out := &in.Contexts, &out.Contexts - *out = make([]NamedContext, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Extensions != nil { - in, out := &in.Extensions, &out.Extensions - *out = make([]NamedExtension, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Config. -func (in *Config) DeepCopy() *Config { - if in == nil { - return nil - } - out := new(Config) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Config) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Context) DeepCopyInto(out *Context) { - *out = *in - if in.Extensions != nil { - in, out := &in.Extensions, &out.Extensions - *out = make([]NamedExtension, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Context. -func (in *Context) DeepCopy() *Context { - if in == nil { - return nil - } - out := new(Context) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ExecConfig) DeepCopyInto(out *ExecConfig) { - *out = *in - if in.Args != nil { - in, out := &in.Args, &out.Args - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.Env != nil { - in, out := &in.Env, &out.Env - *out = make([]ExecEnvVar, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecConfig. -func (in *ExecConfig) DeepCopy() *ExecConfig { - if in == nil { - return nil - } - out := new(ExecConfig) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ExecEnvVar) DeepCopyInto(out *ExecEnvVar) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExecEnvVar. -func (in *ExecEnvVar) DeepCopy() *ExecEnvVar { - if in == nil { - return nil - } - out := new(ExecEnvVar) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *NamedAuthInfo) DeepCopyInto(out *NamedAuthInfo) { - *out = *in - in.AuthInfo.DeepCopyInto(&out.AuthInfo) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamedAuthInfo. -func (in *NamedAuthInfo) DeepCopy() *NamedAuthInfo { - if in == nil { - return nil - } - out := new(NamedAuthInfo) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *NamedCluster) DeepCopyInto(out *NamedCluster) { - *out = *in - in.Cluster.DeepCopyInto(&out.Cluster) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamedCluster. -func (in *NamedCluster) DeepCopy() *NamedCluster { - if in == nil { - return nil - } - out := new(NamedCluster) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *NamedContext) DeepCopyInto(out *NamedContext) { - *out = *in - in.Context.DeepCopyInto(&out.Context) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamedContext. -func (in *NamedContext) DeepCopy() *NamedContext { - if in == nil { - return nil - } - out := new(NamedContext) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *NamedExtension) DeepCopyInto(out *NamedExtension) { - *out = *in - in.Extension.DeepCopyInto(&out.Extension) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamedExtension. -func (in *NamedExtension) DeepCopy() *NamedExtension { - if in == nil { - return nil - } - out := new(NamedExtension) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Preferences) DeepCopyInto(out *Preferences) { - *out = *in - if in.Extensions != nil { - in, out := &in.Extensions, &out.Extensions - *out = make([]NamedExtension, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Preferences. -func (in *Preferences) DeepCopy() *Preferences { - if in == nil { - return nil - } - out := new(Preferences) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.defaults.go b/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.defaults.go deleted file mode 100644 index 6a57decf6..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/v1/zz_generated.defaults.go +++ /dev/null @@ -1,43 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by defaulter-gen. DO NOT EDIT. - -package v1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// RegisterDefaults adds defaulters functions to the given scheme. -// Public to allow building arbitrary schemes. -// All generated defaulters are covering - they call all nested defaulters. -func RegisterDefaults(scheme *runtime.Scheme) error { - scheme.AddTypeDefaultingFunc(&Config{}, func(obj interface{}) { SetObjectDefaults_Config(obj.(*Config)) }) - return nil -} - -func SetObjectDefaults_Config(in *Config) { - for i := range in.AuthInfos { - a := &in.AuthInfos[i] - if a.AuthInfo.Exec != nil { - SetDefaults_ExecConfig(a.AuthInfo.Exec) - } - } -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/auth_loaders.go b/vendor/k8s.io/client-go/tools/clientcmd/auth_loaders.go deleted file mode 100644 index ce951e88d..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/auth_loaders.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clientcmd - -import ( - "encoding/json" - "fmt" - "io" - "os" - - "golang.org/x/term" - - clientauth "k8s.io/client-go/tools/auth" -) - -// AuthLoaders are used to build clientauth.Info objects. -type AuthLoader interface { - // LoadAuth takes a path to a config file and can then do anything it needs in order to return a valid clientauth.Info - LoadAuth(path string) (*clientauth.Info, error) -} - -// default implementation of an AuthLoader -type defaultAuthLoader struct{} - -// LoadAuth for defaultAuthLoader simply delegates to clientauth.LoadFromFile -func (*defaultAuthLoader) LoadAuth(path string) (*clientauth.Info, error) { - return clientauth.LoadFromFile(path) -} - -type PromptingAuthLoader struct { - reader io.Reader -} - -// LoadAuth parses an AuthInfo object from a file path. It prompts user and creates file if it doesn't exist. -func (a *PromptingAuthLoader) LoadAuth(path string) (*clientauth.Info, error) { - // Prompt for user/pass and write a file if none exists. - if _, err := os.Stat(path); os.IsNotExist(err) { - authPtr, err := a.Prompt() - if err != nil { - return nil, err - } - auth := *authPtr - data, err := json.Marshal(auth) - if err != nil { - return &auth, err - } - err = os.WriteFile(path, data, 0600) - return &auth, err - } - authPtr, err := clientauth.LoadFromFile(path) - if err != nil { - return nil, err - } - return authPtr, nil -} - -// Prompt pulls the user and password from a reader -func (a *PromptingAuthLoader) Prompt() (*clientauth.Info, error) { - var err error - auth := &clientauth.Info{} - auth.User, err = promptForString("Username", a.reader, true) - if err != nil { - return nil, err - } - auth.Password, err = promptForString("Password", nil, false) - if err != nil { - return nil, err - } - return auth, nil -} - -func promptForString(field string, r io.Reader, show bool) (result string, err error) { - fmt.Printf("Please enter %s: ", field) - if show { - _, err = fmt.Fscan(r, &result) - } else { - var data []byte - if term.IsTerminal(int(os.Stdin.Fd())) { - data, err = term.ReadPassword(int(os.Stdin.Fd())) - result = string(data) - } else { - return "", fmt.Errorf("error reading input for %s", field) - } - } - return result, err -} - -// NewPromptingAuthLoader is an AuthLoader that parses an AuthInfo object from a file path. It prompts user and creates file if it doesn't exist. -func NewPromptingAuthLoader(reader io.Reader) *PromptingAuthLoader { - return &PromptingAuthLoader{reader} -} - -// NewDefaultAuthLoader returns a default implementation of an AuthLoader that only reads from a config file -func NewDefaultAuthLoader() AuthLoader { - return &defaultAuthLoader{} -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/client_config.go b/vendor/k8s.io/client-go/tools/clientcmd/client_config.go deleted file mode 100644 index ed35891e5..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/client_config.go +++ /dev/null @@ -1,702 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clientcmd - -import ( - "fmt" - "io" - "net/http" - "net/url" - "os" - "strings" - "unicode" - - restclient "k8s.io/client-go/rest" - clientauth "k8s.io/client-go/tools/auth" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "k8s.io/klog/v2" -) - -const ( - // clusterExtensionKey is reserved in the cluster extensions list for exec plugin config. - clusterExtensionKey = "client.authentication.k8s.io/exec" -) - -var ( - // ClusterDefaults has the same behavior as the old EnvVar and DefaultCluster fields - // DEPRECATED will be replaced - ClusterDefaults = clientcmdapi.Cluster{Server: getDefaultServer()} - // DefaultClientConfig represents the legacy behavior of this package for defaulting - // DEPRECATED will be replace - DefaultClientConfig = DirectClientConfig{*clientcmdapi.NewConfig(), "", &ConfigOverrides{ - ClusterDefaults: ClusterDefaults, - }, nil, NewDefaultClientConfigLoadingRules(), promptedCredentials{}} -) - -// getDefaultServer returns a default setting for DefaultClientConfig -// DEPRECATED -func getDefaultServer() string { - if server := os.Getenv("KUBERNETES_MASTER"); len(server) > 0 { - return server - } - return "http://localhost:8080" -} - -// ClientConfig is used to make it easy to get an api server client -type ClientConfig interface { - // RawConfig returns the merged result of all overrides - RawConfig() (clientcmdapi.Config, error) - // ClientConfig returns a complete client config - ClientConfig() (*restclient.Config, error) - // Namespace returns the namespace resulting from the merged - // result of all overrides and a boolean indicating if it was - // overridden - Namespace() (string, bool, error) - // ConfigAccess returns the rules for loading/persisting the config. - ConfigAccess() ConfigAccess -} - -// OverridingClientConfig is used to enable overrriding the raw KubeConfig -type OverridingClientConfig interface { - ClientConfig - // MergedRawConfig return the RawConfig merged with all overrides. - MergedRawConfig() (clientcmdapi.Config, error) -} - -type PersistAuthProviderConfigForUser func(user string) restclient.AuthProviderConfigPersister - -type promptedCredentials struct { - username string - password string `datapolicy:"password"` -} - -// DirectClientConfig is a ClientConfig interface that is backed by a clientcmdapi.Config, options overrides, and an optional fallbackReader for auth information -type DirectClientConfig struct { - config clientcmdapi.Config - contextName string - overrides *ConfigOverrides - fallbackReader io.Reader - configAccess ConfigAccess - // promptedCredentials store the credentials input by the user - promptedCredentials promptedCredentials -} - -// NewDefaultClientConfig creates a DirectClientConfig using the config.CurrentContext as the context name -func NewDefaultClientConfig(config clientcmdapi.Config, overrides *ConfigOverrides) OverridingClientConfig { - return &DirectClientConfig{config, config.CurrentContext, overrides, nil, NewDefaultClientConfigLoadingRules(), promptedCredentials{}} -} - -// NewNonInteractiveClientConfig creates a DirectClientConfig using the passed context name and does not have a fallback reader for auth information -func NewNonInteractiveClientConfig(config clientcmdapi.Config, contextName string, overrides *ConfigOverrides, configAccess ConfigAccess) OverridingClientConfig { - return &DirectClientConfig{config, contextName, overrides, nil, configAccess, promptedCredentials{}} -} - -// NewInteractiveClientConfig creates a DirectClientConfig using the passed context name and a reader in case auth information is not provided via files or flags -func NewInteractiveClientConfig(config clientcmdapi.Config, contextName string, overrides *ConfigOverrides, fallbackReader io.Reader, configAccess ConfigAccess) OverridingClientConfig { - return &DirectClientConfig{config, contextName, overrides, fallbackReader, configAccess, promptedCredentials{}} -} - -// NewClientConfigFromBytes takes your kubeconfig and gives you back a ClientConfig -func NewClientConfigFromBytes(configBytes []byte) (OverridingClientConfig, error) { - config, err := Load(configBytes) - if err != nil { - return nil, err - } - - return &DirectClientConfig{*config, "", &ConfigOverrides{}, nil, nil, promptedCredentials{}}, nil -} - -// RESTConfigFromKubeConfig is a convenience method to give back a restconfig from your kubeconfig bytes. -// For programmatic access, this is what you want 80% of the time -func RESTConfigFromKubeConfig(configBytes []byte) (*restclient.Config, error) { - clientConfig, err := NewClientConfigFromBytes(configBytes) - if err != nil { - return nil, err - } - return clientConfig.ClientConfig() -} - -func (config *DirectClientConfig) RawConfig() (clientcmdapi.Config, error) { - return config.config, nil -} - -// MergedRawConfig returns the raw kube config merged with the overrides -func (config *DirectClientConfig) MergedRawConfig() (clientcmdapi.Config, error) { - if err := config.ConfirmUsable(); err != nil { - return clientcmdapi.Config{}, err - } - merged := config.config.DeepCopy() - - // set the AuthInfo merged with overrides in the merged config - mergedAuthInfo, err := config.getAuthInfo() - if err != nil { - return clientcmdapi.Config{}, err - } - mergedAuthInfoName, _ := config.getAuthInfoName() - merged.AuthInfos[mergedAuthInfoName] = &mergedAuthInfo - - // set the Context merged with overrides in the merged config - mergedContext, err := config.getContext() - if err != nil { - return clientcmdapi.Config{}, err - } - mergedContextName, _ := config.getContextName() - merged.Contexts[mergedContextName] = &mergedContext - merged.CurrentContext = mergedContextName - - // set the Cluster merged with overrides in the merged config - configClusterInfo, err := config.getCluster() - if err != nil { - return clientcmdapi.Config{}, err - } - configClusterName, _ := config.getClusterName() - merged.Clusters[configClusterName] = &configClusterInfo - return *merged, nil -} - -// ClientConfig implements ClientConfig -func (config *DirectClientConfig) ClientConfig() (*restclient.Config, error) { - // check that getAuthInfo, getContext, and getCluster do not return an error. - // Do this before checking if the current config is usable in the event that an - // AuthInfo, Context, or Cluster config with user-defined names are not found. - // This provides a user with the immediate cause for error if one is found - configAuthInfo, err := config.getAuthInfo() - if err != nil { - return nil, err - } - - _, err = config.getContext() - if err != nil { - return nil, err - } - - configClusterInfo, err := config.getCluster() - if err != nil { - return nil, err - } - - if err := config.ConfirmUsable(); err != nil { - return nil, err - } - - clientConfig := &restclient.Config{} - clientConfig.Host = configClusterInfo.Server - if configClusterInfo.ProxyURL != "" { - u, err := parseProxyURL(configClusterInfo.ProxyURL) - if err != nil { - return nil, err - } - clientConfig.Proxy = http.ProxyURL(u) - } - - clientConfig.DisableCompression = configClusterInfo.DisableCompression - - if config.overrides != nil && len(config.overrides.Timeout) > 0 { - timeout, err := ParseTimeout(config.overrides.Timeout) - if err != nil { - return nil, err - } - clientConfig.Timeout = timeout - } - - if u, err := url.ParseRequestURI(clientConfig.Host); err == nil && u.Opaque == "" && len(u.Path) > 1 { - u.RawQuery = "" - u.Fragment = "" - clientConfig.Host = u.String() - } - if len(configAuthInfo.Impersonate) > 0 { - clientConfig.Impersonate = restclient.ImpersonationConfig{ - UserName: configAuthInfo.Impersonate, - UID: configAuthInfo.ImpersonateUID, - Groups: configAuthInfo.ImpersonateGroups, - Extra: configAuthInfo.ImpersonateUserExtra, - } - } - - // only try to read the auth information if we are secure - if restclient.IsConfigTransportTLS(*clientConfig) { - var err error - var persister restclient.AuthProviderConfigPersister - if config.configAccess != nil { - authInfoName, _ := config.getAuthInfoName() - persister = PersisterForUser(config.configAccess, authInfoName) - } - userAuthPartialConfig, err := config.getUserIdentificationPartialConfig(configAuthInfo, config.fallbackReader, persister, configClusterInfo) - if err != nil { - return nil, err - } - if err := merge(clientConfig, userAuthPartialConfig); err != nil { - return nil, err - } - - serverAuthPartialConfig := getServerIdentificationPartialConfig(configClusterInfo) - if err := merge(clientConfig, serverAuthPartialConfig); err != nil { - return nil, err - } - } - - return clientConfig, nil -} - -// clientauth.Info object contain both user identification and server identification. We want different precedence orders for -// both, so we have to split the objects and merge them separately. - -// getServerIdentificationPartialConfig extracts server identification information from configClusterInfo -// (the final result of command line flags and merged .kubeconfig files). -func getServerIdentificationPartialConfig(configClusterInfo clientcmdapi.Cluster) *restclient.Config { - configClientConfig := &restclient.Config{} - configClientConfig.CAFile = configClusterInfo.CertificateAuthority - configClientConfig.CAData = configClusterInfo.CertificateAuthorityData - configClientConfig.Insecure = configClusterInfo.InsecureSkipTLSVerify - configClientConfig.ServerName = configClusterInfo.TLSServerName - - return configClientConfig -} - -// getUserIdentificationPartialConfig extracts user identification information from configAuthInfo -// (the final result of command line flags and merged .kubeconfig files); -// if the information available there is insufficient, it prompts (if possible) for additional information. -func (config *DirectClientConfig) getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fallbackReader io.Reader, persistAuthConfig restclient.AuthProviderConfigPersister, configClusterInfo clientcmdapi.Cluster) (*restclient.Config, error) { - mergedConfig := &restclient.Config{} - - // blindly overwrite existing values based on precedence - if len(configAuthInfo.Token) > 0 { - mergedConfig.BearerToken = configAuthInfo.Token - mergedConfig.BearerTokenFile = configAuthInfo.TokenFile - } else if len(configAuthInfo.TokenFile) > 0 { - tokenBytes, err := os.ReadFile(configAuthInfo.TokenFile) - if err != nil { - return nil, err - } - mergedConfig.BearerToken = string(tokenBytes) - mergedConfig.BearerTokenFile = configAuthInfo.TokenFile - } - if len(configAuthInfo.Impersonate) > 0 { - mergedConfig.Impersonate = restclient.ImpersonationConfig{ - UserName: configAuthInfo.Impersonate, - UID: configAuthInfo.ImpersonateUID, - Groups: configAuthInfo.ImpersonateGroups, - Extra: configAuthInfo.ImpersonateUserExtra, - } - } - if len(configAuthInfo.ClientCertificate) > 0 || len(configAuthInfo.ClientCertificateData) > 0 { - mergedConfig.CertFile = configAuthInfo.ClientCertificate - mergedConfig.CertData = configAuthInfo.ClientCertificateData - mergedConfig.KeyFile = configAuthInfo.ClientKey - mergedConfig.KeyData = configAuthInfo.ClientKeyData - } - if len(configAuthInfo.Username) > 0 || len(configAuthInfo.Password) > 0 { - mergedConfig.Username = configAuthInfo.Username - mergedConfig.Password = configAuthInfo.Password - } - if configAuthInfo.AuthProvider != nil { - mergedConfig.AuthProvider = configAuthInfo.AuthProvider - mergedConfig.AuthConfigPersister = persistAuthConfig - } - if configAuthInfo.Exec != nil { - mergedConfig.ExecProvider = configAuthInfo.Exec - mergedConfig.ExecProvider.InstallHint = cleanANSIEscapeCodes(mergedConfig.ExecProvider.InstallHint) - mergedConfig.ExecProvider.Config = configClusterInfo.Extensions[clusterExtensionKey] - } - - // if there still isn't enough information to authenticate the user, try prompting - if !canIdentifyUser(*mergedConfig) && (fallbackReader != nil) { - if len(config.promptedCredentials.username) > 0 && len(config.promptedCredentials.password) > 0 { - mergedConfig.Username = config.promptedCredentials.username - mergedConfig.Password = config.promptedCredentials.password - return mergedConfig, nil - } - prompter := NewPromptingAuthLoader(fallbackReader) - promptedAuthInfo, err := prompter.Prompt() - if err != nil { - return nil, err - } - promptedConfig := makeUserIdentificationConfig(*promptedAuthInfo) - previouslyMergedConfig := mergedConfig - mergedConfig = &restclient.Config{} - if err := merge(mergedConfig, promptedConfig); err != nil { - return nil, err - } - if err := merge(mergedConfig, previouslyMergedConfig); err != nil { - return nil, err - } - config.promptedCredentials.username = mergedConfig.Username - config.promptedCredentials.password = mergedConfig.Password - } - - return mergedConfig, nil -} - -// makeUserIdentificationFieldsConfig returns a client.Config capable of being merged for only user identification information -func makeUserIdentificationConfig(info clientauth.Info) *restclient.Config { - config := &restclient.Config{} - config.Username = info.User - config.Password = info.Password - config.CertFile = info.CertFile - config.KeyFile = info.KeyFile - config.BearerToken = info.BearerToken - return config -} - -func canIdentifyUser(config restclient.Config) bool { - return len(config.Username) > 0 || - (len(config.CertFile) > 0 || len(config.CertData) > 0) || - len(config.BearerToken) > 0 || - config.AuthProvider != nil || - config.ExecProvider != nil -} - -// cleanANSIEscapeCodes takes an arbitrary string and ensures that there are no -// ANSI escape sequences that could put the terminal in a weird state (e.g., -// "\e[1m" bolds text) -func cleanANSIEscapeCodes(s string) string { - // spaceControlCharacters includes tab, new line, vertical tab, new page, and - // carriage return. These are in the unicode.Cc category, but that category also - // contains ESC (U+001B) which we don't want. - spaceControlCharacters := unicode.RangeTable{ - R16: []unicode.Range16{ - {Lo: 0x0009, Hi: 0x000D, Stride: 1}, - }, - } - - // Why not make this deny-only (instead of allow-only)? Because unicode.C - // contains newline and tab characters that we want. - allowedRanges := []*unicode.RangeTable{ - unicode.L, - unicode.M, - unicode.N, - unicode.P, - unicode.S, - unicode.Z, - &spaceControlCharacters, - } - builder := strings.Builder{} - for _, roon := range s { - if unicode.IsOneOf(allowedRanges, roon) { - builder.WriteRune(roon) // returns nil error, per go doc - } else { - fmt.Fprintf(&builder, "%U", roon) - } - } - return builder.String() -} - -// Namespace implements ClientConfig -func (config *DirectClientConfig) Namespace() (string, bool, error) { - if config.overrides != nil && config.overrides.Context.Namespace != "" { - // In the event we have an empty config but we do have a namespace override, we should return - // the namespace override instead of having config.ConfirmUsable() return an error. This allows - // things like in-cluster clients to execute `kubectl get pods --namespace=foo` and have the - // --namespace flag honored instead of being ignored. - return config.overrides.Context.Namespace, true, nil - } - - if err := config.ConfirmUsable(); err != nil { - return "", false, err - } - - configContext, err := config.getContext() - if err != nil { - return "", false, err - } - - if len(configContext.Namespace) == 0 { - return "default", false, nil - } - - return configContext.Namespace, false, nil -} - -// ConfigAccess implements ClientConfig -func (config *DirectClientConfig) ConfigAccess() ConfigAccess { - return config.configAccess -} - -// ConfirmUsable looks a particular context and determines if that particular part of the config is useable. There might still be errors in the config, -// but no errors in the sections requested or referenced. It does not return early so that it can find as many errors as possible. -func (config *DirectClientConfig) ConfirmUsable() error { - validationErrors := make([]error, 0) - - var contextName string - if len(config.contextName) != 0 { - contextName = config.contextName - } else { - contextName = config.config.CurrentContext - } - - if len(contextName) > 0 { - _, exists := config.config.Contexts[contextName] - if !exists { - validationErrors = append(validationErrors, &errContextNotFound{contextName}) - } - } - - authInfoName, _ := config.getAuthInfoName() - authInfo, _ := config.getAuthInfo() - validationErrors = append(validationErrors, validateAuthInfo(authInfoName, authInfo)...) - clusterName, _ := config.getClusterName() - cluster, _ := config.getCluster() - validationErrors = append(validationErrors, validateClusterInfo(clusterName, cluster)...) - // when direct client config is specified, and our only error is that no server is defined, we should - // return a standard "no config" error - if len(validationErrors) == 1 && validationErrors[0] == ErrEmptyCluster { - return newErrConfigurationInvalid([]error{ErrEmptyConfig}) - } - return newErrConfigurationInvalid(validationErrors) -} - -// getContextName returns the default, or user-set context name, and a boolean that indicates -// whether the default context name has been overwritten by a user-set flag, or left as its default value -func (config *DirectClientConfig) getContextName() (string, bool) { - if config.overrides != nil && len(config.overrides.CurrentContext) != 0 { - return config.overrides.CurrentContext, true - } - if len(config.contextName) != 0 { - return config.contextName, false - } - - return config.config.CurrentContext, false -} - -// getAuthInfoName returns a string containing the current authinfo name for the current context, -// and a boolean indicating whether the default authInfo name is overwritten by a user-set flag, or -// left as its default value -func (config *DirectClientConfig) getAuthInfoName() (string, bool) { - if config.overrides != nil && len(config.overrides.Context.AuthInfo) != 0 { - return config.overrides.Context.AuthInfo, true - } - context, _ := config.getContext() - return context.AuthInfo, false -} - -// getClusterName returns a string containing the default, or user-set cluster name, and a boolean -// indicating whether the default clusterName has been overwritten by a user-set flag, or left as -// its default value -func (config *DirectClientConfig) getClusterName() (string, bool) { - if config.overrides != nil && len(config.overrides.Context.Cluster) != 0 { - return config.overrides.Context.Cluster, true - } - context, _ := config.getContext() - return context.Cluster, false -} - -// getContext returns the clientcmdapi.Context, or an error if a required context is not found. -func (config *DirectClientConfig) getContext() (clientcmdapi.Context, error) { - contexts := config.config.Contexts - contextName, required := config.getContextName() - - mergedContext := clientcmdapi.NewContext() - if configContext, exists := contexts[contextName]; exists { - if err := merge(mergedContext, configContext); err != nil { - return clientcmdapi.Context{}, err - } - } else if required { - return clientcmdapi.Context{}, fmt.Errorf("context %q does not exist", contextName) - } - if config.overrides != nil { - if err := merge(mergedContext, &config.overrides.Context); err != nil { - return clientcmdapi.Context{}, err - } - } - - return *mergedContext, nil -} - -// getAuthInfo returns the clientcmdapi.AuthInfo, or an error if a required auth info is not found. -func (config *DirectClientConfig) getAuthInfo() (clientcmdapi.AuthInfo, error) { - authInfos := config.config.AuthInfos - authInfoName, required := config.getAuthInfoName() - - mergedAuthInfo := clientcmdapi.NewAuthInfo() - if configAuthInfo, exists := authInfos[authInfoName]; exists { - if err := merge(mergedAuthInfo, configAuthInfo); err != nil { - return clientcmdapi.AuthInfo{}, err - } - } else if required { - return clientcmdapi.AuthInfo{}, fmt.Errorf("auth info %q does not exist", authInfoName) - } - if config.overrides != nil { - if err := merge(mergedAuthInfo, &config.overrides.AuthInfo); err != nil { - return clientcmdapi.AuthInfo{}, err - } - - // Handle ClientKey/ClientKeyData conflict: if override sets ClientKey, also use override's ClientKeyData - // otherwise if original config has ClientKeyData set, - // validation returns error "client-key-data and client-key are both specified " - if len(config.overrides.AuthInfo.ClientKey) > 0 || len(config.overrides.AuthInfo.ClientKeyData) > 0 { - mergedAuthInfo.ClientKey = config.overrides.AuthInfo.ClientKey - mergedAuthInfo.ClientKeyData = config.overrides.AuthInfo.ClientKeyData - } - // Handle ClientCertificate/ClientCertificateData conflict, if override sets ClientCertificate, also use override's ClientCertificateData - // otherwise if original config has ClientCertificateData set, - // validation returns error "client-cert-data and client-cert are both specified " - if len(config.overrides.AuthInfo.ClientCertificate) > 0 || len(config.overrides.AuthInfo.ClientCertificateData) > 0 { - mergedAuthInfo.ClientCertificate = config.overrides.AuthInfo.ClientCertificate - mergedAuthInfo.ClientCertificateData = config.overrides.AuthInfo.ClientCertificateData - } - } - - return *mergedAuthInfo, nil -} - -// getCluster returns the clientcmdapi.Cluster, or an error if a required cluster is not found. -func (config *DirectClientConfig) getCluster() (clientcmdapi.Cluster, error) { - clusterInfos := config.config.Clusters - clusterInfoName, required := config.getClusterName() - - mergedClusterInfo := clientcmdapi.NewCluster() - if config.overrides != nil { - if err := merge(mergedClusterInfo, &config.overrides.ClusterDefaults); err != nil { - return clientcmdapi.Cluster{}, err - } - } - if configClusterInfo, exists := clusterInfos[clusterInfoName]; exists { - if err := merge(mergedClusterInfo, configClusterInfo); err != nil { - return clientcmdapi.Cluster{}, err - } - } else if required { - return clientcmdapi.Cluster{}, fmt.Errorf("cluster %q does not exist", clusterInfoName) - } - if config.overrides != nil { - if err := merge(mergedClusterInfo, &config.overrides.ClusterInfo); err != nil { - return clientcmdapi.Cluster{}, err - } - } - - // * An override of --insecure-skip-tls-verify=true and no accompanying CA/CA data should clear already-set CA/CA data - // otherwise, a kubeconfig containing a CA reference would return an error that "CA and insecure-skip-tls-verify couldn't both be set". - // * An override of --certificate-authority should also override TLS skip settings and CA data, otherwise existing CA data will take precedence. - if config.overrides != nil { - caLen := len(config.overrides.ClusterInfo.CertificateAuthority) - caDataLen := len(config.overrides.ClusterInfo.CertificateAuthorityData) - if config.overrides.ClusterInfo.InsecureSkipTLSVerify || caLen > 0 || caDataLen > 0 { - mergedClusterInfo.InsecureSkipTLSVerify = config.overrides.ClusterInfo.InsecureSkipTLSVerify - mergedClusterInfo.CertificateAuthority = config.overrides.ClusterInfo.CertificateAuthority - mergedClusterInfo.CertificateAuthorityData = config.overrides.ClusterInfo.CertificateAuthorityData - } - - // if the --tls-server-name has been set in overrides, use that value. - // if the --server has been set in overrides, then use the value of --tls-server-name specified on the CLI too. This gives the property - // that setting a --server will effectively clear the KUBECONFIG value of tls-server-name if it is specified on the command line which is - // usually correct. - if config.overrides.ClusterInfo.TLSServerName != "" || config.overrides.ClusterInfo.Server != "" { - mergedClusterInfo.TLSServerName = config.overrides.ClusterInfo.TLSServerName - } - } - - return *mergedClusterInfo, nil -} - -// inClusterClientConfig makes a config that will work from within a kubernetes cluster container environment. -// Can take options overrides for flags explicitly provided to the command inside the cluster container. -type inClusterClientConfig struct { - overrides *ConfigOverrides - inClusterConfigProvider func() (*restclient.Config, error) -} - -var _ ClientConfig = &inClusterClientConfig{} - -func (config *inClusterClientConfig) RawConfig() (clientcmdapi.Config, error) { - return clientcmdapi.Config{}, fmt.Errorf("inCluster environment config doesn't support multiple clusters") -} - -func (config *inClusterClientConfig) ClientConfig() (*restclient.Config, error) { - inClusterConfigProvider := config.inClusterConfigProvider - if inClusterConfigProvider == nil { - inClusterConfigProvider = restclient.InClusterConfig - } - - icc, err := inClusterConfigProvider() - if err != nil { - return nil, err - } - - // in-cluster configs only takes a host, token, or CA file - // if any of them were individually provided, overwrite anything else - if config.overrides != nil { - if server := config.overrides.ClusterInfo.Server; len(server) > 0 { - icc.Host = server - } - if len(config.overrides.AuthInfo.Token) > 0 || len(config.overrides.AuthInfo.TokenFile) > 0 { - icc.BearerToken = config.overrides.AuthInfo.Token - icc.BearerTokenFile = config.overrides.AuthInfo.TokenFile - } - if certificateAuthorityFile := config.overrides.ClusterInfo.CertificateAuthority; len(certificateAuthorityFile) > 0 { - icc.TLSClientConfig.CAFile = certificateAuthorityFile - } - } - - return icc, nil -} - -func (config *inClusterClientConfig) Namespace() (string, bool, error) { - // This way assumes you've set the POD_NAMESPACE environment variable using the downward API. - // This check has to be done first for backwards compatibility with the way InClusterConfig was originally set up - if ns := os.Getenv("POD_NAMESPACE"); ns != "" { - return ns, false, nil - } - - // Fall back to the namespace associated with the service account token, if available - if data, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace"); err == nil { - if ns := strings.TrimSpace(string(data)); len(ns) > 0 { - return ns, false, nil - } - } - - return "default", false, nil -} - -func (config *inClusterClientConfig) ConfigAccess() ConfigAccess { - return NewDefaultClientConfigLoadingRules() -} - -// Possible returns true if loading an inside-kubernetes-cluster is possible. -func (config *inClusterClientConfig) Possible() bool { - fi, err := os.Stat("/var/run/secrets/kubernetes.io/serviceaccount/token") - return os.Getenv("KUBERNETES_SERVICE_HOST") != "" && - os.Getenv("KUBERNETES_SERVICE_PORT") != "" && - err == nil && !fi.IsDir() -} - -// BuildConfigFromFlags is a helper function that builds configs from a master -// url or a kubeconfig filepath. These are passed in as command line flags for cluster -// components. Warnings should reflect this usage. If neither masterUrl or kubeconfigPath -// are passed in we fallback to inClusterConfig. If inClusterConfig fails, we fallback -// to the default config. -func BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*restclient.Config, error) { - if kubeconfigPath == "" && masterUrl == "" { - klog.Warning("Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.") - kubeconfig, err := restclient.InClusterConfig() - if err == nil { - return kubeconfig, nil - } - klog.Warning("error creating inClusterConfig, falling back to default config: ", err) - } - return NewNonInteractiveDeferredLoadingClientConfig( - &ClientConfigLoadingRules{ExplicitPath: kubeconfigPath}, - &ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}}).ClientConfig() -} - -// BuildConfigFromKubeconfigGetter is a helper function that builds configs from a master -// url and a kubeconfigGetter. -func BuildConfigFromKubeconfigGetter(masterUrl string, kubeconfigGetter KubeconfigGetter) (*restclient.Config, error) { - // TODO: We do not need a DeferredLoader here. Refactor code and see if we can use DirectClientConfig here. - cc := NewNonInteractiveDeferredLoadingClientConfig( - &ClientConfigGetter{kubeconfigGetter: kubeconfigGetter}, - &ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}}) - return cc.ClientConfig() -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/config.go b/vendor/k8s.io/client-go/tools/clientcmd/config.go deleted file mode 100644 index 2cd213ccb..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/config.go +++ /dev/null @@ -1,499 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clientcmd - -import ( - "errors" - "os" - "path/filepath" - "reflect" - "sort" - - "k8s.io/klog/v2" - - restclient "k8s.io/client-go/rest" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -// ConfigAccess is used by subcommands and methods in this package to load and modify the appropriate config files -type ConfigAccess interface { - // GetLoadingPrecedence returns the slice of files that should be used for loading and inspecting the config - GetLoadingPrecedence() []string - // GetStartingConfig returns the config that subcommands should being operating against. It may or may not be merged depending on loading rules - GetStartingConfig() (*clientcmdapi.Config, error) - // GetDefaultFilename returns the name of the file you should write into (create if necessary), if you're trying to create a new stanza as opposed to updating an existing one. - GetDefaultFilename() string - // IsExplicitFile indicates whether or not this command is interested in exactly one file. This implementation only ever does that via a flag, but implementations that handle local, global, and flags may have more - IsExplicitFile() bool - // GetExplicitFile returns the particular file this command is operating against. This implementation only ever has one, but implementations that handle local, global, and flags may have more - GetExplicitFile() string -} - -type PathOptions struct { - // GlobalFile is the full path to the file to load as the global (final) option - GlobalFile string - // EnvVar is the env var name that points to the list of kubeconfig files to load - EnvVar string - // ExplicitFileFlag is the name of the flag to use for prompting for the kubeconfig file - ExplicitFileFlag string - - // GlobalFileSubpath is an optional value used for displaying help - GlobalFileSubpath string - - LoadingRules *ClientConfigLoadingRules -} - -var ( - // UseModifyConfigLock ensures that access to kubeconfig file using ModifyConfig method - // is being guarded by a lock file. - // This variable is intentionaly made public so other consumers of this library - // can modify its default behavior, but be caution when disabling it since - // this will make your code not threadsafe. - UseModifyConfigLock = true -) - -func (o *PathOptions) GetEnvVarFiles() []string { - if len(o.EnvVar) == 0 { - return []string{} - } - - envVarValue := os.Getenv(o.EnvVar) - if len(envVarValue) == 0 { - return []string{} - } - - fileList := filepath.SplitList(envVarValue) - // prevent the same path load multiple times - return deduplicate(fileList) -} - -func (o *PathOptions) GetLoadingPrecedence() []string { - if o.IsExplicitFile() { - return []string{o.GetExplicitFile()} - } - - if envVarFiles := o.GetEnvVarFiles(); len(envVarFiles) > 0 { - return envVarFiles - } - return []string{o.GlobalFile} -} - -func (o *PathOptions) GetStartingConfig() (*clientcmdapi.Config, error) { - // don't mutate the original - loadingRules := *o.LoadingRules - loadingRules.Precedence = o.GetLoadingPrecedence() - - clientConfig := NewNonInteractiveDeferredLoadingClientConfig(&loadingRules, &ConfigOverrides{}) - rawConfig, err := clientConfig.RawConfig() - if os.IsNotExist(err) { - return clientcmdapi.NewConfig(), nil - } - if err != nil { - return nil, err - } - - return &rawConfig, nil -} - -func (o *PathOptions) GetDefaultFilename() string { - if o.IsExplicitFile() { - return o.GetExplicitFile() - } - - if envVarFiles := o.GetEnvVarFiles(); len(envVarFiles) > 0 { - if len(envVarFiles) == 1 { - return envVarFiles[0] - } - - // if any of the envvar files already exists, return it - for _, envVarFile := range envVarFiles { - if _, err := os.Stat(envVarFile); err == nil { - return envVarFile - } - } - - // otherwise, return the last one in the list - return envVarFiles[len(envVarFiles)-1] - } - - return o.GlobalFile -} - -func (o *PathOptions) IsExplicitFile() bool { - return len(o.LoadingRules.ExplicitPath) > 0 -} - -func (o *PathOptions) GetExplicitFile() string { - return o.LoadingRules.ExplicitPath -} - -func NewDefaultPathOptions() *PathOptions { - ret := &PathOptions{ - GlobalFile: RecommendedHomeFile, - EnvVar: RecommendedConfigPathEnvVar, - ExplicitFileFlag: RecommendedConfigPathFlag, - - GlobalFileSubpath: filepath.Join(RecommendedHomeDir, RecommendedFileName), - - LoadingRules: NewDefaultClientConfigLoadingRules(), - } - ret.LoadingRules.DoNotResolvePaths = true - - return ret -} - -// ModifyConfig takes a Config object, iterates through Clusters, AuthInfos, and Contexts, uses the LocationOfOrigin if specified or -// uses the default destination file to write the results into. This results in multiple file reads, but it's very easy to follow. -// Preferences and CurrentContext should always be set in the default destination file. Since we can't distinguish between empty and missing values -// (no nil strings), we're forced have separate handling for them. In the kubeconfig cases, newConfig should have at most one difference, -// that means that this code will only write into a single file. If you want to relativizePaths, you must provide a fully qualified path in any -// modified element. -func ModifyConfig(configAccess ConfigAccess, newConfig clientcmdapi.Config, relativizePaths bool) error { - if UseModifyConfigLock { - possibleSources := configAccess.GetLoadingPrecedence() - // sort the possible kubeconfig files so we always "lock" in the same order - // to avoid deadlock (note: this can fail w/ symlinks, but... come on). - sort.Strings(possibleSources) - for _, filename := range possibleSources { - if err := lockFile(filename); err != nil { - return err - } - defer unlockFile(filename) - } - } - - startingConfig, err := configAccess.GetStartingConfig() - if err != nil { - return err - } - - // We need to find all differences, locate their original files, read a partial config to modify only that stanza and write out the file. - // Special case the test for current context and preferences since those always write to the default file. - if reflect.DeepEqual(*startingConfig, newConfig) { - // nothing to do - return nil - } - - if startingConfig.CurrentContext != newConfig.CurrentContext { - if err := writeCurrentContext(configAccess, newConfig.CurrentContext); err != nil { - return err - } - } - - if !reflect.DeepEqual(startingConfig.Preferences, newConfig.Preferences) { - if err := writePreferences(configAccess, newConfig.Preferences); err != nil { - return err - } - } - - // Search every cluster, authInfo, and context. First from new to old for differences, then from old to new for deletions - for key, cluster := range newConfig.Clusters { - startingCluster, exists := startingConfig.Clusters[key] - if !reflect.DeepEqual(cluster, startingCluster) || !exists { - destinationFile := cluster.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite, err := getConfigFromFile(destinationFile) - if err != nil { - return err - } - t := *cluster - - configToWrite.Clusters[key] = &t - configToWrite.Clusters[key].LocationOfOrigin = destinationFile - if relativizePaths { - if err := RelativizeClusterLocalPaths(configToWrite.Clusters[key]); err != nil { - return err - } - } - - if err := WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - // seenConfigs stores a map of config source filenames to computed config objects - seenConfigs := map[string]*clientcmdapi.Config{} - - for key, context := range newConfig.Contexts { - startingContext, exists := startingConfig.Contexts[key] - if !reflect.DeepEqual(context, startingContext) || !exists { - destinationFile := context.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - // we only obtain a fresh config object from its source file - // if we have not seen it already - this prevents us from - // reading and writing to the same number of files repeatedly - // when multiple / all contexts share the same destination file. - configToWrite, seen := seenConfigs[destinationFile] - if !seen { - var err error - configToWrite, err = getConfigFromFile(destinationFile) - if err != nil { - return err - } - seenConfigs[destinationFile] = configToWrite - } - - configToWrite.Contexts[key] = context - } - } - - // actually persist config object changes - for destinationFile, configToWrite := range seenConfigs { - if err := WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - - for key, authInfo := range newConfig.AuthInfos { - startingAuthInfo, exists := startingConfig.AuthInfos[key] - if !reflect.DeepEqual(authInfo, startingAuthInfo) || !exists { - destinationFile := authInfo.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite, err := getConfigFromFile(destinationFile) - if err != nil { - return err - } - t := *authInfo - configToWrite.AuthInfos[key] = &t - configToWrite.AuthInfos[key].LocationOfOrigin = destinationFile - if relativizePaths { - if err := RelativizeAuthInfoLocalPaths(configToWrite.AuthInfos[key]); err != nil { - return err - } - } - - if err := WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - for key, cluster := range startingConfig.Clusters { - if _, exists := newConfig.Clusters[key]; !exists { - destinationFile := cluster.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite, err := getConfigFromFile(destinationFile) - if err != nil { - return err - } - delete(configToWrite.Clusters, key) - - if err := WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - for key, context := range startingConfig.Contexts { - if _, exists := newConfig.Contexts[key]; !exists { - destinationFile := context.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite, err := getConfigFromFile(destinationFile) - if err != nil { - return err - } - delete(configToWrite.Contexts, key) - - if err := WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - for key, authInfo := range startingConfig.AuthInfos { - if _, exists := newConfig.AuthInfos[key]; !exists { - destinationFile := authInfo.LocationOfOrigin - if len(destinationFile) == 0 { - destinationFile = configAccess.GetDefaultFilename() - } - - configToWrite, err := getConfigFromFile(destinationFile) - if err != nil { - return err - } - delete(configToWrite.AuthInfos, key) - - if err := WriteToFile(*configToWrite, destinationFile); err != nil { - return err - } - } - } - - return nil -} - -func PersisterForUser(configAccess ConfigAccess, user string) restclient.AuthProviderConfigPersister { - return &persister{configAccess, user} -} - -type persister struct { - configAccess ConfigAccess - user string -} - -func (p *persister) Persist(config map[string]string) error { - newConfig, err := p.configAccess.GetStartingConfig() - if err != nil { - return err - } - authInfo, ok := newConfig.AuthInfos[p.user] - if ok && authInfo.AuthProvider != nil { - authInfo.AuthProvider.Config = config - return ModifyConfig(p.configAccess, *newConfig, false) - } - return nil -} - -// writeCurrentContext takes three possible paths. -// If newCurrentContext is the same as the startingConfig's current context, then we exit. -// If newCurrentContext has a value, then that value is written into the default destination file. -// If newCurrentContext is empty, then we find the config file that is setting the CurrentContext and clear the value from that file -func writeCurrentContext(configAccess ConfigAccess, newCurrentContext string) error { - if startingConfig, err := configAccess.GetStartingConfig(); err != nil { - return err - } else if startingConfig.CurrentContext == newCurrentContext { - return nil - } - - if configAccess.IsExplicitFile() { - file := configAccess.GetExplicitFile() - currConfig, err := getConfigFromFile(file) - if err != nil { - return err - } - currConfig.CurrentContext = newCurrentContext - if err := WriteToFile(*currConfig, file); err != nil { - return err - } - - return nil - } - - if len(newCurrentContext) > 0 { - destinationFile := configAccess.GetDefaultFilename() - config, err := getConfigFromFile(destinationFile) - if err != nil { - return err - } - config.CurrentContext = newCurrentContext - - if err := WriteToFile(*config, destinationFile); err != nil { - return err - } - - return nil - } - - // we're supposed to be clearing the current context. We need to find the first spot in the chain that is setting it and clear it - for _, file := range configAccess.GetLoadingPrecedence() { - if _, err := os.Stat(file); err == nil { - currConfig, err := getConfigFromFile(file) - if err != nil { - return err - } - - if len(currConfig.CurrentContext) > 0 { - currConfig.CurrentContext = newCurrentContext - if err := WriteToFile(*currConfig, file); err != nil { - return err - } - - return nil - } - } - } - - return errors.New("no config found to write context") -} - -func writePreferences(configAccess ConfigAccess, newPrefs clientcmdapi.Preferences) error { - if startingConfig, err := configAccess.GetStartingConfig(); err != nil { - return err - } else if reflect.DeepEqual(startingConfig.Preferences, newPrefs) { - return nil - } - - if configAccess.IsExplicitFile() { - file := configAccess.GetExplicitFile() - currConfig, err := getConfigFromFile(file) - if err != nil { - return err - } - currConfig.Preferences = newPrefs - if err := WriteToFile(*currConfig, file); err != nil { - return err - } - - return nil - } - - for _, file := range configAccess.GetLoadingPrecedence() { - currConfig, err := getConfigFromFile(file) - if err != nil { - return err - } - - if !reflect.DeepEqual(currConfig.Preferences, newPrefs) { - currConfig.Preferences = newPrefs - if err := WriteToFile(*currConfig, file); err != nil { - return err - } - - return nil - } - } - - return errors.New("no config found to write preferences") -} - -// getConfigFromFile tries to read a kubeconfig file and if it can't, returns an error. One exception, missing files result in empty configs, not an error. -func getConfigFromFile(filename string) (*clientcmdapi.Config, error) { - config, err := LoadFromFile(filename) - if err != nil && !os.IsNotExist(err) { - return nil, err - } - if config == nil { - config = clientcmdapi.NewConfig() - } - return config, nil -} - -// GetConfigFromFileOrDie tries to read a kubeconfig file and if it can't, it calls exit. One exception, missing files result in empty configs, not an exit -func GetConfigFromFileOrDie(filename string) *clientcmdapi.Config { - config, err := getConfigFromFile(filename) - if err != nil { - klog.FatalDepth(1, err) - } - - return config -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/doc.go b/vendor/k8s.io/client-go/tools/clientcmd/doc.go deleted file mode 100644 index c07ace6a5..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/doc.go +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/* -Package clientcmd provides one stop shopping for building a working client from a fixed config, -from a .kubeconfig file, from command line flags, or from any merged combination. - -Sample usage from merged .kubeconfig files (local directory, home directory) - - loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() - // if you want to change the loading rules (which files in which order), you can do so here - - configOverrides := &clientcmd.ConfigOverrides{} - // if you want to change override values or bind them to flags, there are methods to help you - - kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides) - config, err := kubeConfig.ClientConfig() - if err != nil { - // Do something - } - client, err := metav1.New(config) - // ... -*/ -package clientcmd diff --git a/vendor/k8s.io/client-go/tools/clientcmd/flag.go b/vendor/k8s.io/client-go/tools/clientcmd/flag.go deleted file mode 100644 index 8d60d201c..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/flag.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright 2017 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clientcmd - -// transformingStringValue implements pflag.Value to store string values, -// allowing transforming them while being set -type transformingStringValue struct { - target *string - transformer func(string) (string, error) -} - -func newTransformingStringValue(val string, target *string, transformer func(string) (string, error)) *transformingStringValue { - *target = val - return &transformingStringValue{ - target: target, - transformer: transformer, - } -} - -func (t *transformingStringValue) Set(val string) error { - val, err := t.transformer(val) - if err != nil { - return err - } - *t.target = val - return nil -} - -func (t *transformingStringValue) Type() string { - return "string" -} - -func (t *transformingStringValue) String() string { - return string(*t.target) -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/helpers.go b/vendor/k8s.io/client-go/tools/clientcmd/helpers.go deleted file mode 100644 index d7572232a..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/helpers.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright 2016 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clientcmd - -import ( - "fmt" - "net/url" - "strconv" - "time" -) - -// ParseTimeout returns a parsed duration from a string -// A duration string value must be a positive integer, optionally followed by a corresponding time unit (s|m|h). -func ParseTimeout(duration string) (time.Duration, error) { - if i, err := strconv.ParseInt(duration, 10, 64); err == nil && i >= 0 { - return (time.Duration(i) * time.Second), nil - } - if requestTimeout, err := time.ParseDuration(duration); err == nil { - return requestTimeout, nil - } - return 0, fmt.Errorf("Invalid timeout value. Timeout must be a single integer in seconds, or an integer followed by a corresponding time unit (e.g. 1s | 2m | 3h)") -} - -func parseProxyURL(proxyURL string) (*url.URL, error) { - u, err := url.Parse(proxyURL) - if err != nil { - return nil, fmt.Errorf("could not parse: %v", proxyURL) - } - - switch u.Scheme { - case "http", "https", "socks5": - default: - return nil, fmt.Errorf("unsupported scheme %q, must be http, https, or socks5", u.Scheme) - } - return u, nil -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/loader.go b/vendor/k8s.io/client-go/tools/clientcmd/loader.go deleted file mode 100644 index b127e2e08..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/loader.go +++ /dev/null @@ -1,679 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clientcmd - -import ( - "fmt" - "os" - "path/filepath" - "reflect" - goruntime "runtime" - "strings" - - "k8s.io/klog/v2" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - utilerrors "k8s.io/apimachinery/pkg/util/errors" - restclient "k8s.io/client-go/rest" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest" - "k8s.io/client-go/util/homedir" -) - -const ( - RecommendedConfigPathFlag = "kubeconfig" - RecommendedConfigPathEnvVar = "KUBECONFIG" - RecommendedHomeDir = ".kube" - RecommendedFileName = "config" - RecommendedSchemaName = "schema" -) - -var ( - RecommendedConfigDir = filepath.Join(homedir.HomeDir(), RecommendedHomeDir) - RecommendedHomeFile = filepath.Join(RecommendedConfigDir, RecommendedFileName) - RecommendedSchemaFile = filepath.Join(RecommendedConfigDir, RecommendedSchemaName) -) - -// currentMigrationRules returns a map that holds the history of recommended home directories used in previous versions. -// Any future changes to RecommendedHomeFile and related are expected to add a migration rule here, in order to make -// sure existing config files are migrated to their new locations properly. -func currentMigrationRules() map[string]string { - var oldRecommendedHomeFileName string - if goruntime.GOOS == "windows" { - oldRecommendedHomeFileName = RecommendedFileName - } else { - oldRecommendedHomeFileName = ".kubeconfig" - } - return map[string]string{ - RecommendedHomeFile: filepath.Join(os.Getenv("HOME"), RecommendedHomeDir, oldRecommendedHomeFileName), - } -} - -type ClientConfigLoader interface { - ConfigAccess - // IsDefaultConfig returns true if the returned config matches the defaults. - IsDefaultConfig(*restclient.Config) bool - // Load returns the latest config - Load() (*clientcmdapi.Config, error) -} - -type KubeconfigGetter func() (*clientcmdapi.Config, error) - -type ClientConfigGetter struct { - kubeconfigGetter KubeconfigGetter -} - -// ClientConfigGetter implements the ClientConfigLoader interface. -var _ ClientConfigLoader = &ClientConfigGetter{} - -func (g *ClientConfigGetter) Load() (*clientcmdapi.Config, error) { - return g.kubeconfigGetter() -} - -func (g *ClientConfigGetter) GetLoadingPrecedence() []string { - return nil -} -func (g *ClientConfigGetter) GetStartingConfig() (*clientcmdapi.Config, error) { - return g.kubeconfigGetter() -} -func (g *ClientConfigGetter) GetDefaultFilename() string { - return "" -} -func (g *ClientConfigGetter) IsExplicitFile() bool { - return false -} -func (g *ClientConfigGetter) GetExplicitFile() string { - return "" -} -func (g *ClientConfigGetter) IsDefaultConfig(config *restclient.Config) bool { - return false -} - -// ClientConfigLoadingRules is an ExplicitPath and string slice of specific locations that are used for merging together a Config -// Callers can put the chain together however they want, but we'd recommend: -// EnvVarPathFiles if set (a list of files if set) OR the HomeDirectoryPath -// ExplicitPath is special, because if a user specifically requests a certain file be used and error is reported if this file is not present -type ClientConfigLoadingRules struct { - ExplicitPath string - Precedence []string - - // MigrationRules is a map of destination files to source files. If a destination file is not present, then the source file is checked. - // If the source file is present, then it is copied to the destination file BEFORE any further loading happens. - MigrationRules map[string]string - - // DoNotResolvePaths indicates whether or not to resolve paths with respect to the originating files. This is phrased as a negative so - // that a default object that doesn't set this will usually get the behavior it wants. - DoNotResolvePaths bool - - // DefaultClientConfig is an optional field indicating what rules to use to calculate a default configuration. - // This should match the overrides passed in to ClientConfig loader. - DefaultClientConfig ClientConfig - - // WarnIfAllMissing indicates whether the configuration files pointed by KUBECONFIG environment variable are present or not. - // In case of missing files, it warns the user about the missing files. - WarnIfAllMissing bool - - // Warner is the warning log callback to use in case of missing files. - Warner WarningHandler -} - -// WarningHandler allows to set the logging function to use -type WarningHandler func(error) - -func (handler WarningHandler) Warn(err error) { - if handler == nil { - klog.V(1).Info(err) - } else { - handler(err) - } -} - -type MissingConfigError struct { - Missing []string -} - -func (c MissingConfigError) Error() string { - return fmt.Sprintf("Config not found: %s", strings.Join(c.Missing, ", ")) -} - -// ClientConfigLoadingRules implements the ClientConfigLoader interface. -var _ ClientConfigLoader = &ClientConfigLoadingRules{} - -// NewDefaultClientConfigLoadingRules returns a ClientConfigLoadingRules object with default fields filled in. You are not required to -// use this constructor -func NewDefaultClientConfigLoadingRules() *ClientConfigLoadingRules { - chain := []string{} - warnIfAllMissing := false - - envVarFiles := os.Getenv(RecommendedConfigPathEnvVar) - if len(envVarFiles) != 0 { - fileList := filepath.SplitList(envVarFiles) - // prevent the same path load multiple times - chain = append(chain, deduplicate(fileList)...) - warnIfAllMissing = true - - } else { - chain = append(chain, RecommendedHomeFile) - } - - return &ClientConfigLoadingRules{ - Precedence: chain, - MigrationRules: currentMigrationRules(), - WarnIfAllMissing: warnIfAllMissing, - } -} - -// Load starts by running the MigrationRules and then -// takes the loading rules and returns a Config object based on following rules. -// -// if the ExplicitPath, return the unmerged explicit file -// Otherwise, return a merged config based on the Precedence slice -// -// A missing ExplicitPath file produces an error. Empty filenames or other missing files are ignored. -// Read errors or files with non-deserializable content produce errors. -// The first file to set a particular map key wins and map key's value is never changed. -// BUT, if you set a struct value that is NOT contained inside of map, the value WILL be changed. -// This results in some odd looking logic to merge in one direction, merge in the other, and then merge the two. -// It also means that if two files specify a "red-user", only values from the first file's red-user are used. Even -// non-conflicting entries from the second file's "red-user" are discarded. -// Relative paths inside of the .kubeconfig files are resolved against the .kubeconfig file's parent folder -// and only absolute file paths are returned. -func (rules *ClientConfigLoadingRules) Load() (*clientcmdapi.Config, error) { - if err := rules.Migrate(); err != nil { - return nil, err - } - - errlist := []error{} - missingList := []string{} - - kubeConfigFiles := []string{} - - // Make sure a file we were explicitly told to use exists - if len(rules.ExplicitPath) > 0 { - if _, err := os.Stat(rules.ExplicitPath); os.IsNotExist(err) { - return nil, err - } - kubeConfigFiles = append(kubeConfigFiles, rules.ExplicitPath) - - } else { - kubeConfigFiles = append(kubeConfigFiles, rules.Precedence...) - } - - kubeconfigs := []*clientcmdapi.Config{} - // read and cache the config files so that we only look at them once - for _, filename := range kubeConfigFiles { - if len(filename) == 0 { - // no work to do - continue - } - - config, err := LoadFromFile(filename) - - if os.IsNotExist(err) { - // skip missing files - // Add to the missing list to produce a warning - missingList = append(missingList, filename) - continue - } - - if err != nil { - errlist = append(errlist, fmt.Errorf("error loading config file \"%s\": %v", filename, err)) - continue - } - - kubeconfigs = append(kubeconfigs, config) - } - - if rules.WarnIfAllMissing && len(missingList) > 0 && len(kubeconfigs) == 0 { - rules.Warner.Warn(MissingConfigError{Missing: missingList}) - } - - // first merge all of our maps - mapConfig := clientcmdapi.NewConfig() - - for _, kubeconfig := range kubeconfigs { - if err := merge(mapConfig, kubeconfig); err != nil { - return nil, err - } - } - - // merge all of the struct values in the reverse order so that priority is given correctly - // errors are not added to the list the second time - nonMapConfig := clientcmdapi.NewConfig() - for i := len(kubeconfigs) - 1; i >= 0; i-- { - kubeconfig := kubeconfigs[i] - if err := merge(nonMapConfig, kubeconfig); err != nil { - return nil, err - } - } - - // since values are overwritten, but maps values are not, we can merge the non-map config on top of the map config and - // get the values we expect. - config := clientcmdapi.NewConfig() - if err := merge(config, mapConfig); err != nil { - return nil, err - } - if err := merge(config, nonMapConfig); err != nil { - return nil, err - } - - if rules.ResolvePaths() { - if err := ResolveLocalPaths(config); err != nil { - errlist = append(errlist, err) - } - } - return config, utilerrors.NewAggregate(errlist) -} - -// Migrate uses the MigrationRules map. If a destination file is not present, then the source file is checked. -// If the source file is present, then it is copied to the destination file BEFORE any further loading happens. -func (rules *ClientConfigLoadingRules) Migrate() error { - if rules.MigrationRules == nil { - return nil - } - - for destination, source := range rules.MigrationRules { - if _, err := os.Stat(destination); err == nil { - // if the destination already exists, do nothing - continue - } else if os.IsPermission(err) { - // if we can't access the file, skip it - continue - } else if !os.IsNotExist(err) { - // if we had an error other than non-existence, fail - return err - } - - if sourceInfo, err := os.Stat(source); err != nil { - if os.IsNotExist(err) || os.IsPermission(err) { - // if the source file doesn't exist or we can't access it, there's no work to do. - continue - } - - // if we had an error other than non-existence, fail - return err - } else if sourceInfo.IsDir() { - return fmt.Errorf("cannot migrate %v to %v because it is a directory", source, destination) - } - - data, err := os.ReadFile(source) - if err != nil { - return err - } - // destination is created with mode 0666 before umask - err = os.WriteFile(destination, data, 0666) - if err != nil { - return err - } - } - - return nil -} - -// GetLoadingPrecedence implements ConfigAccess -func (rules *ClientConfigLoadingRules) GetLoadingPrecedence() []string { - if len(rules.ExplicitPath) > 0 { - return []string{rules.ExplicitPath} - } - - // Create a copy in case something tries to sort the returned slice. - precedence := make([]string, len(rules.Precedence)) - copy(precedence, rules.Precedence) - return precedence -} - -// GetStartingConfig implements ConfigAccess -func (rules *ClientConfigLoadingRules) GetStartingConfig() (*clientcmdapi.Config, error) { - clientConfig := NewNonInteractiveDeferredLoadingClientConfig(rules, &ConfigOverrides{}) - rawConfig, err := clientConfig.RawConfig() - if os.IsNotExist(err) { - return clientcmdapi.NewConfig(), nil - } - if err != nil { - return nil, err - } - - return &rawConfig, nil -} - -// GetDefaultFilename implements ConfigAccess -func (rules *ClientConfigLoadingRules) GetDefaultFilename() string { - // Explicit file if we have one. - if rules.IsExplicitFile() { - return rules.GetExplicitFile() - } - // Otherwise, first existing file from precedence. - for _, filename := range rules.GetLoadingPrecedence() { - if _, err := os.Stat(filename); err == nil { - return filename - } - } - // If none exists, use the first from precedence. - if len(rules.Precedence) > 0 { - return rules.Precedence[0] - } - return "" -} - -// IsExplicitFile implements ConfigAccess -func (rules *ClientConfigLoadingRules) IsExplicitFile() bool { - return len(rules.ExplicitPath) > 0 -} - -// GetExplicitFile implements ConfigAccess -func (rules *ClientConfigLoadingRules) GetExplicitFile() string { - return rules.ExplicitPath -} - -// IsDefaultConfig returns true if the provided configuration matches the default -func (rules *ClientConfigLoadingRules) IsDefaultConfig(config *restclient.Config) bool { - if rules.DefaultClientConfig == nil { - return false - } - defaultConfig, err := rules.DefaultClientConfig.ClientConfig() - if err != nil { - return false - } - return reflect.DeepEqual(config, defaultConfig) -} - -// LoadFromFile takes a filename and deserializes the contents into Config object -func LoadFromFile(filename string) (*clientcmdapi.Config, error) { - kubeconfigBytes, err := os.ReadFile(filename) - if err != nil { - return nil, err - } - config, err := Load(kubeconfigBytes) - if err != nil { - return nil, err - } - klog.V(6).Infoln("Config loaded from file: ", filename) - - // set LocationOfOrigin on every Cluster, User, and Context - for key, obj := range config.AuthInfos { - obj.LocationOfOrigin = filename - config.AuthInfos[key] = obj - } - for key, obj := range config.Clusters { - obj.LocationOfOrigin = filename - config.Clusters[key] = obj - } - for key, obj := range config.Contexts { - obj.LocationOfOrigin = filename - config.Contexts[key] = obj - } - - if config.AuthInfos == nil { - config.AuthInfos = map[string]*clientcmdapi.AuthInfo{} - } - if config.Clusters == nil { - config.Clusters = map[string]*clientcmdapi.Cluster{} - } - if config.Contexts == nil { - config.Contexts = map[string]*clientcmdapi.Context{} - } - - return config, nil -} - -// Load takes a byte slice and deserializes the contents into Config object. -// Encapsulates deserialization without assuming the source is a file. -func Load(data []byte) (*clientcmdapi.Config, error) { - config := clientcmdapi.NewConfig() - // if there's no data in a file, return the default object instead of failing (DecodeInto reject empty input) - if len(data) == 0 { - return config, nil - } - decoded, _, err := clientcmdlatest.Codec.Decode(data, &schema.GroupVersionKind{Version: clientcmdlatest.Version, Kind: "Config"}, config) - if err != nil { - return nil, err - } - return decoded.(*clientcmdapi.Config), nil -} - -// WriteToFile serializes the config to yaml and writes it out to a file. If not present, it creates the file with the mode 0600. If it is present -// it stomps the contents -func WriteToFile(config clientcmdapi.Config, filename string) error { - content, err := Write(config) - if err != nil { - return err - } - dir := filepath.Dir(filename) - if _, err := os.Stat(dir); os.IsNotExist(err) { - if err = os.MkdirAll(dir, 0755); err != nil { - return err - } - } - - if err := os.WriteFile(filename, content, 0600); err != nil { - return err - } - return nil -} - -func lockFile(filename string) error { - // TODO: find a way to do this with actual file locks. Will - // probably need separate solution for windows and Linux. - - // Make sure the dir exists before we try to create a lock file. - dir := filepath.Dir(filename) - if _, err := os.Stat(dir); os.IsNotExist(err) { - if err = os.MkdirAll(dir, 0755); err != nil { - return err - } - } - f, err := os.OpenFile(lockName(filename), os.O_CREATE|os.O_EXCL, 0) - if err != nil { - return err - } - f.Close() - return nil -} - -func unlockFile(filename string) error { - return os.Remove(lockName(filename)) -} - -func lockName(filename string) string { - return filename + ".lock" -} - -// Write serializes the config to yaml. -// Encapsulates serialization without assuming the destination is a file. -func Write(config clientcmdapi.Config) ([]byte, error) { - return runtime.Encode(clientcmdlatest.Codec, &config) -} - -func (rules ClientConfigLoadingRules) ResolvePaths() bool { - return !rules.DoNotResolvePaths -} - -// ResolveLocalPaths resolves all relative paths in the config object with respect to the stanza's LocationOfOrigin -// this cannot be done directly inside of LoadFromFile because doing so there would make it impossible to load a file without -// modification of its contents. -func ResolveLocalPaths(config *clientcmdapi.Config) error { - for _, cluster := range config.Clusters { - if len(cluster.LocationOfOrigin) == 0 { - continue - } - base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin)) - if err != nil { - return fmt.Errorf("could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err) - } - - if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil { - return err - } - } - for _, authInfo := range config.AuthInfos { - if len(authInfo.LocationOfOrigin) == 0 { - continue - } - base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin)) - if err != nil { - return fmt.Errorf("could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err) - } - - if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil { - return err - } - } - - return nil -} - -// RelativizeClusterLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already -// absolute, but any existing path will be resolved relative to LocationOfOrigin -func RelativizeClusterLocalPaths(cluster *clientcmdapi.Cluster) error { - if len(cluster.LocationOfOrigin) == 0 { - return fmt.Errorf("no location of origin for %s", cluster.Server) - } - base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin)) - if err != nil { - return fmt.Errorf("could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err) - } - - if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil { - return err - } - if err := RelativizePathWithNoBacksteps(GetClusterFileReferences(cluster), base); err != nil { - return err - } - - return nil -} - -// RelativizeAuthInfoLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already -// absolute, but any existing path will be resolved relative to LocationOfOrigin -func RelativizeAuthInfoLocalPaths(authInfo *clientcmdapi.AuthInfo) error { - if len(authInfo.LocationOfOrigin) == 0 { - return fmt.Errorf("no location of origin for %v", authInfo) - } - base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin)) - if err != nil { - return fmt.Errorf("could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err) - } - - if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil { - return err - } - if err := RelativizePathWithNoBacksteps(GetAuthInfoFileReferences(authInfo), base); err != nil { - return err - } - - return nil -} - -func RelativizeConfigPaths(config *clientcmdapi.Config, base string) error { - return RelativizePathWithNoBacksteps(GetConfigFileReferences(config), base) -} - -func ResolveConfigPaths(config *clientcmdapi.Config, base string) error { - return ResolvePaths(GetConfigFileReferences(config), base) -} - -func GetConfigFileReferences(config *clientcmdapi.Config) []*string { - refs := []*string{} - - for _, cluster := range config.Clusters { - refs = append(refs, GetClusterFileReferences(cluster)...) - } - for _, authInfo := range config.AuthInfos { - refs = append(refs, GetAuthInfoFileReferences(authInfo)...) - } - - return refs -} - -func GetClusterFileReferences(cluster *clientcmdapi.Cluster) []*string { - return []*string{&cluster.CertificateAuthority} -} - -func GetAuthInfoFileReferences(authInfo *clientcmdapi.AuthInfo) []*string { - s := []*string{&authInfo.ClientCertificate, &authInfo.ClientKey, &authInfo.TokenFile} - // Only resolve exec command if it isn't PATH based. - if authInfo.Exec != nil && strings.ContainsRune(authInfo.Exec.Command, filepath.Separator) { - s = append(s, &authInfo.Exec.Command) - } - return s -} - -// ResolvePaths updates the given refs to be absolute paths, relative to the given base directory -func ResolvePaths(refs []*string, base string) error { - for _, ref := range refs { - // Don't resolve empty paths - if len(*ref) > 0 { - // Don't resolve absolute paths - if !filepath.IsAbs(*ref) { - *ref = filepath.Join(base, *ref) - } - } - } - return nil -} - -// RelativizePathWithNoBacksteps updates the given refs to be relative paths, relative to the given base directory as long as they do not require backsteps. -// Any path requiring a backstep is left as-is as long it is absolute. Any non-absolute path that can't be relativized produces an error -func RelativizePathWithNoBacksteps(refs []*string, base string) error { - for _, ref := range refs { - // Don't relativize empty paths - if len(*ref) > 0 { - rel, err := MakeRelative(*ref, base) - if err != nil { - return err - } - - // if we have a backstep, don't mess with the path - if strings.HasPrefix(rel, "../") { - if filepath.IsAbs(*ref) { - continue - } - - return fmt.Errorf("%v requires backsteps and is not absolute", *ref) - } - - *ref = rel - } - } - return nil -} - -func MakeRelative(path, base string) (string, error) { - if len(path) > 0 { - rel, err := filepath.Rel(base, path) - if err != nil { - return path, err - } - return rel, nil - } - return path, nil -} - -// deduplicate removes any duplicated values and returns a new slice, keeping the order unchanged -func deduplicate(s []string) []string { - encountered := map[string]bool{} - ret := make([]string, 0) - for i := range s { - if encountered[s[i]] { - continue - } - encountered[s[i]] = true - ret = append(ret, s[i]) - } - return ret -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/merge.go b/vendor/k8s.io/client-go/tools/clientcmd/merge.go deleted file mode 100644 index 3d74e6029..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/merge.go +++ /dev/null @@ -1,121 +0,0 @@ -/* -Copyright 2024 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clientcmd - -import ( - "fmt" - "reflect" - "strings" -) - -// recursively merges src into dst: -// - non-pointer struct fields with any exported fields are recursively merged -// - non-pointer struct fields with only unexported fields prefer src if the field is non-zero -// - maps are shallow merged with src keys taking priority over dst -// - non-zero src fields encountered during recursion that are not maps or structs overwrite and recursion stops -func merge[T any](dst, src *T) error { - if dst == nil { - return fmt.Errorf("cannot merge into nil pointer") - } - if src == nil { - return nil - } - return mergeValues(nil, reflect.ValueOf(dst).Elem(), reflect.ValueOf(src).Elem()) -} - -func mergeValues(fieldNames []string, dst, src reflect.Value) error { - dstType := dst.Type() - // no-op if we can't read the src - if !src.IsValid() { - return nil - } - // sanity check types match - if srcType := src.Type(); dstType != srcType { - return fmt.Errorf("cannot merge mismatched types (%s, %s) at %s", dstType, srcType, strings.Join(fieldNames, ".")) - } - - switch dstType.Kind() { - case reflect.Struct: - if hasExportedField(dstType) { - // recursively merge - for i, n := 0, dstType.NumField(); i < n; i++ { - if err := mergeValues(append(fieldNames, dstType.Field(i).Name), dst.Field(i), src.Field(i)); err != nil { - return err - } - } - } else if dst.CanSet() { - // If all fields are unexported, overwrite with src. - // Using src.IsZero() would make more sense but that's not what mergo did. - dst.Set(src) - } - - case reflect.Map: - if dst.CanSet() && !src.IsZero() { - // initialize dst if needed - if dst.IsZero() { - dst.Set(reflect.MakeMap(dstType)) - } - // shallow-merge overwriting dst keys with src keys - for _, mapKey := range src.MapKeys() { - dst.SetMapIndex(mapKey, src.MapIndex(mapKey)) - } - } - - case reflect.Slice: - if dst.CanSet() && src.Len() > 0 { - // overwrite dst with non-empty src slice - dst.Set(src) - } - - case reflect.Pointer: - if dst.CanSet() && !src.IsZero() { - // overwrite dst with non-zero values for other types - if dstType.Elem().Kind() == reflect.Struct { - // use struct pointer as-is - dst.Set(src) - } else { - // shallow-copy non-struct pointer (interfaces, primitives, etc) - dst.Set(reflect.New(dstType.Elem())) - dst.Elem().Set(src.Elem()) - } - } - - default: - if dst.CanSet() && !src.IsZero() { - // overwrite dst with non-zero values for other types - dst.Set(src) - } - } - - return nil -} - -// hasExportedField returns true if the given type has any exported fields, -// or if it has any anonymous/embedded struct fields with exported fields -func hasExportedField(dstType reflect.Type) bool { - for i, n := 0, dstType.NumField(); i < n; i++ { - field := dstType.Field(i) - if field.Anonymous && field.Type.Kind() == reflect.Struct { - if hasExportedField(dstType.Field(i).Type) { - return true - } - } else if len(field.PkgPath) == 0 { - return true - } - } - return false -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go b/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go deleted file mode 100644 index 0fc2fd0a0..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go +++ /dev/null @@ -1,172 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clientcmd - -import ( - "io" - "sync" - - "k8s.io/klog/v2" - - restclient "k8s.io/client-go/rest" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -// DeferredLoadingClientConfig is a ClientConfig interface that is backed by a client config loader. -// It is used in cases where the loading rules may change after you've instantiated them and you want to be sure that -// the most recent rules are used. This is useful in cases where you bind flags to loading rule parameters before -// the parse happens and you want your calling code to be ignorant of how the values are being mutated to avoid -// passing extraneous information down a call stack -type DeferredLoadingClientConfig struct { - loader ClientConfigLoader - overrides *ConfigOverrides - fallbackReader io.Reader - - clientConfig ClientConfig - loadingLock sync.Mutex - - // provided for testing - icc InClusterConfig -} - -// InClusterConfig abstracts details of whether the client is running in a cluster for testing. -type InClusterConfig interface { - ClientConfig - Possible() bool -} - -// NewNonInteractiveDeferredLoadingClientConfig creates a ClientConfig using the passed context name -func NewNonInteractiveDeferredLoadingClientConfig(loader ClientConfigLoader, overrides *ConfigOverrides) ClientConfig { - return &DeferredLoadingClientConfig{loader: loader, overrides: overrides, icc: &inClusterClientConfig{overrides: overrides}} -} - -// NewInteractiveDeferredLoadingClientConfig creates a ClientConfig using the passed context name and the fallback auth reader -func NewInteractiveDeferredLoadingClientConfig(loader ClientConfigLoader, overrides *ConfigOverrides, fallbackReader io.Reader) ClientConfig { - return &DeferredLoadingClientConfig{loader: loader, overrides: overrides, icc: &inClusterClientConfig{overrides: overrides}, fallbackReader: fallbackReader} -} - -func (config *DeferredLoadingClientConfig) createClientConfig() (ClientConfig, error) { - config.loadingLock.Lock() - defer config.loadingLock.Unlock() - - if config.clientConfig != nil { - return config.clientConfig, nil - } - mergedConfig, err := config.loader.Load() - if err != nil { - return nil, err - } - - var currentContext string - if config.overrides != nil { - currentContext = config.overrides.CurrentContext - } - if config.fallbackReader != nil { - config.clientConfig = NewInteractiveClientConfig(*mergedConfig, currentContext, config.overrides, config.fallbackReader, config.loader) - } else { - config.clientConfig = NewNonInteractiveClientConfig(*mergedConfig, currentContext, config.overrides, config.loader) - } - return config.clientConfig, nil -} - -func (config *DeferredLoadingClientConfig) RawConfig() (clientcmdapi.Config, error) { - mergedConfig, err := config.createClientConfig() - if err != nil { - return clientcmdapi.Config{}, err - } - - return mergedConfig.RawConfig() -} - -// ClientConfig implements ClientConfig -func (config *DeferredLoadingClientConfig) ClientConfig() (*restclient.Config, error) { - mergedClientConfig, err := config.createClientConfig() - if err != nil { - return nil, err - } - - // load the configuration and return on non-empty errors and if the - // content differs from the default config - mergedConfig, err := mergedClientConfig.ClientConfig() - switch { - case err != nil: - if !IsEmptyConfig(err) { - // return on any error except empty config - return nil, err - } - case mergedConfig != nil: - // the configuration is valid, but if this is equal to the defaults we should try - // in-cluster configuration - if !config.loader.IsDefaultConfig(mergedConfig) { - return mergedConfig, nil - } - } - - // check for in-cluster configuration and use it - if config.icc.Possible() { - klog.V(4).Infof("Using in-cluster configuration") - return config.icc.ClientConfig() - } - - // return the result of the merged client config - return mergedConfig, err -} - -// Namespace implements KubeConfig -func (config *DeferredLoadingClientConfig) Namespace() (string, bool, error) { - mergedKubeConfig, err := config.createClientConfig() - if err != nil { - return "", false, err - } - - ns, overridden, err := mergedKubeConfig.Namespace() - // if we get an error and it is not empty config, or if the merged config defined an explicit namespace, or - // if in-cluster config is not possible, return immediately - if (err != nil && !IsEmptyConfig(err)) || overridden || !config.icc.Possible() { - // return on any error except empty config - return ns, overridden, err - } - - if len(ns) > 0 { - // if we got a non-default namespace from the kubeconfig, use it - if ns != "default" { - return ns, false, nil - } - - // if we got a default namespace, determine whether it was explicit or implicit - if raw, err := mergedKubeConfig.RawConfig(); err == nil { - // determine the current context - currentContext := raw.CurrentContext - if config.overrides != nil && len(config.overrides.CurrentContext) > 0 { - currentContext = config.overrides.CurrentContext - } - if context := raw.Contexts[currentContext]; context != nil && len(context.Namespace) > 0 { - return ns, false, nil - } - } - } - - klog.V(4).Infof("Using in-cluster namespace") - - // allow the namespace from the service account token directory to be used. - return config.icc.Namespace() -} - -// ConfigAccess implements ClientConfig -func (config *DeferredLoadingClientConfig) ConfigAccess() ConfigAccess { - return config.loader -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/overrides.go b/vendor/k8s.io/client-go/tools/clientcmd/overrides.go deleted file mode 100644 index 483e51532..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/overrides.go +++ /dev/null @@ -1,263 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clientcmd - -import ( - "strconv" - "strings" - - "github.com/spf13/pflag" - - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -// ConfigOverrides holds values that should override whatever information is pulled from the actual Config object. You can't -// simply use an actual Config object, because Configs hold maps, but overrides are restricted to "at most one" -type ConfigOverrides struct { - AuthInfo clientcmdapi.AuthInfo - // ClusterDefaults are applied before the configured cluster info is loaded. - ClusterDefaults clientcmdapi.Cluster - ClusterInfo clientcmdapi.Cluster - Context clientcmdapi.Context - CurrentContext string - Timeout string -} - -// ConfigOverrideFlags holds the flag names to be used for binding command line flags. Notice that this structure tightly -// corresponds to ConfigOverrides -type ConfigOverrideFlags struct { - AuthOverrideFlags AuthOverrideFlags - ClusterOverrideFlags ClusterOverrideFlags - ContextOverrideFlags ContextOverrideFlags - CurrentContext FlagInfo - Timeout FlagInfo -} - -// AuthOverrideFlags holds the flag names to be used for binding command line flags for AuthInfo objects -type AuthOverrideFlags struct { - ClientCertificate FlagInfo - ClientKey FlagInfo - Token FlagInfo - Impersonate FlagInfo - ImpersonateUID FlagInfo - ImpersonateGroups FlagInfo - Username FlagInfo - Password FlagInfo -} - -// ContextOverrideFlags holds the flag names to be used for binding command line flags for Cluster objects -type ContextOverrideFlags struct { - ClusterName FlagInfo - AuthInfoName FlagInfo - Namespace FlagInfo -} - -// ClusterOverride holds the flag names to be used for binding command line flags for Cluster objects -type ClusterOverrideFlags struct { - APIServer FlagInfo - APIVersion FlagInfo - CertificateAuthority FlagInfo - InsecureSkipTLSVerify FlagInfo - TLSServerName FlagInfo - ProxyURL FlagInfo - DisableCompression FlagInfo -} - -// FlagInfo contains information about how to register a flag. This struct is useful if you want to provide a way for an extender to -// get back a set of recommended flag names, descriptions, and defaults, but allow for customization by an extender. This makes for -// coherent extension, without full prescription -type FlagInfo struct { - // LongName is the long string for a flag. If this is empty, then the flag will not be bound - LongName string - // ShortName is the single character for a flag. If this is empty, then there will be no short flag - ShortName string - // Default is the default value for the flag - Default string - // Description is the description for the flag - Description string -} - -// AddSecretAnnotation add secret flag to Annotation. -func (f FlagInfo) AddSecretAnnotation(flags *pflag.FlagSet) FlagInfo { - flags.SetAnnotation(f.LongName, "classified", []string{"true"}) - return f -} - -// BindStringFlag binds the flag based on the provided info. If LongName == "", nothing is registered -func (f FlagInfo) BindStringFlag(flags *pflag.FlagSet, target *string) FlagInfo { - // you can't register a flag without a long name - if len(f.LongName) > 0 { - flags.StringVarP(target, f.LongName, f.ShortName, f.Default, f.Description) - } - return f -} - -// BindTransformingStringFlag binds the flag based on the provided info. If LongName == "", nothing is registered -func (f FlagInfo) BindTransformingStringFlag(flags *pflag.FlagSet, target *string, transformer func(string) (string, error)) FlagInfo { - // you can't register a flag without a long name - if len(f.LongName) > 0 { - flags.VarP(newTransformingStringValue(f.Default, target, transformer), f.LongName, f.ShortName, f.Description) - } - return f -} - -// BindStringSliceFlag binds the flag based on the provided info. If LongName == "", nothing is registered -func (f FlagInfo) BindStringArrayFlag(flags *pflag.FlagSet, target *[]string) FlagInfo { - // you can't register a flag without a long name - if len(f.LongName) > 0 { - sliceVal := []string{} - if len(f.Default) > 0 { - sliceVal = []string{f.Default} - } - flags.StringArrayVarP(target, f.LongName, f.ShortName, sliceVal, f.Description) - } - return f -} - -// BindBoolFlag binds the flag based on the provided info. If LongName == "", nothing is registered -func (f FlagInfo) BindBoolFlag(flags *pflag.FlagSet, target *bool) FlagInfo { - // you can't register a flag without a long name - if len(f.LongName) > 0 { - // try to parse Default as a bool. If it fails, assume false - boolVal, err := strconv.ParseBool(f.Default) - if err != nil { - boolVal = false - } - - flags.BoolVarP(target, f.LongName, f.ShortName, boolVal, f.Description) - } - return f -} - -const ( - FlagClusterName = "cluster" - FlagAuthInfoName = "user" - FlagContext = "context" - FlagNamespace = "namespace" - FlagAPIServer = "server" - FlagTLSServerName = "tls-server-name" - FlagInsecure = "insecure-skip-tls-verify" - FlagCertFile = "client-certificate" - FlagKeyFile = "client-key" - FlagCAFile = "certificate-authority" - FlagEmbedCerts = "embed-certs" - FlagBearerToken = "token" - FlagImpersonate = "as" - FlagImpersonateUID = "as-uid" - FlagImpersonateGroup = "as-group" - FlagUsername = "username" - FlagPassword = "password" - FlagTimeout = "request-timeout" - FlagProxyURL = "proxy-url" - FlagDisableCompression = "disable-compression" -) - -// RecommendedConfigOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing -func RecommendedConfigOverrideFlags(prefix string) ConfigOverrideFlags { - return ConfigOverrideFlags{ - AuthOverrideFlags: RecommendedAuthOverrideFlags(prefix), - ClusterOverrideFlags: RecommendedClusterOverrideFlags(prefix), - ContextOverrideFlags: RecommendedContextOverrideFlags(prefix), - - CurrentContext: FlagInfo{prefix + FlagContext, "", "", "The name of the kubeconfig context to use"}, - Timeout: FlagInfo{prefix + FlagTimeout, "", "0", "The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests."}, - } -} - -// RecommendedAuthOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing -func RecommendedAuthOverrideFlags(prefix string) AuthOverrideFlags { - return AuthOverrideFlags{ - ClientCertificate: FlagInfo{prefix + FlagCertFile, "", "", "Path to a client certificate file for TLS"}, - ClientKey: FlagInfo{prefix + FlagKeyFile, "", "", "Path to a client key file for TLS"}, - Token: FlagInfo{prefix + FlagBearerToken, "", "", "Bearer token for authentication to the API server"}, - Impersonate: FlagInfo{prefix + FlagImpersonate, "", "", "Username to impersonate for the operation"}, - ImpersonateUID: FlagInfo{prefix + FlagImpersonateUID, "", "", "UID to impersonate for the operation"}, - ImpersonateGroups: FlagInfo{prefix + FlagImpersonateGroup, "", "", "Group to impersonate for the operation, this flag can be repeated to specify multiple groups."}, - Username: FlagInfo{prefix + FlagUsername, "", "", "Username for basic authentication to the API server"}, - Password: FlagInfo{prefix + FlagPassword, "", "", "Password for basic authentication to the API server"}, - } -} - -// RecommendedClusterOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing -func RecommendedClusterOverrideFlags(prefix string) ClusterOverrideFlags { - return ClusterOverrideFlags{ - APIServer: FlagInfo{prefix + FlagAPIServer, "", "", "The address and port of the Kubernetes API server"}, - CertificateAuthority: FlagInfo{prefix + FlagCAFile, "", "", "Path to a cert file for the certificate authority"}, - InsecureSkipTLSVerify: FlagInfo{prefix + FlagInsecure, "", "false", "If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure"}, - TLSServerName: FlagInfo{prefix + FlagTLSServerName, "", "", "If provided, this name will be used to validate server certificate. If this is not provided, hostname used to contact the server is used."}, - ProxyURL: FlagInfo{prefix + FlagProxyURL, "", "", "If provided, this URL will be used to connect via proxy"}, - DisableCompression: FlagInfo{prefix + FlagDisableCompression, "", "", "If true, opt-out of response compression for all requests to the server"}, - } -} - -// RecommendedContextOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing -func RecommendedContextOverrideFlags(prefix string) ContextOverrideFlags { - return ContextOverrideFlags{ - ClusterName: FlagInfo{prefix + FlagClusterName, "", "", "The name of the kubeconfig cluster to use"}, - AuthInfoName: FlagInfo{prefix + FlagAuthInfoName, "", "", "The name of the kubeconfig user to use"}, - Namespace: FlagInfo{prefix + FlagNamespace, "n", "", "If present, the namespace scope for this CLI request"}, - } -} - -// BindOverrideFlags is a convenience method to bind the specified flags to their associated variables -func BindOverrideFlags(overrides *ConfigOverrides, flags *pflag.FlagSet, flagNames ConfigOverrideFlags) { - BindAuthInfoFlags(&overrides.AuthInfo, flags, flagNames.AuthOverrideFlags) - BindClusterFlags(&overrides.ClusterInfo, flags, flagNames.ClusterOverrideFlags) - BindContextFlags(&overrides.Context, flags, flagNames.ContextOverrideFlags) - flagNames.CurrentContext.BindStringFlag(flags, &overrides.CurrentContext) - flagNames.Timeout.BindStringFlag(flags, &overrides.Timeout) -} - -// BindAuthInfoFlags is a convenience method to bind the specified flags to their associated variables -func BindAuthInfoFlags(authInfo *clientcmdapi.AuthInfo, flags *pflag.FlagSet, flagNames AuthOverrideFlags) { - flagNames.ClientCertificate.BindStringFlag(flags, &authInfo.ClientCertificate).AddSecretAnnotation(flags) - flagNames.ClientKey.BindStringFlag(flags, &authInfo.ClientKey).AddSecretAnnotation(flags) - flagNames.Token.BindStringFlag(flags, &authInfo.Token).AddSecretAnnotation(flags) - flagNames.Impersonate.BindStringFlag(flags, &authInfo.Impersonate).AddSecretAnnotation(flags) - flagNames.ImpersonateUID.BindStringFlag(flags, &authInfo.ImpersonateUID).AddSecretAnnotation(flags) - flagNames.ImpersonateGroups.BindStringArrayFlag(flags, &authInfo.ImpersonateGroups).AddSecretAnnotation(flags) - flagNames.Username.BindStringFlag(flags, &authInfo.Username).AddSecretAnnotation(flags) - flagNames.Password.BindStringFlag(flags, &authInfo.Password).AddSecretAnnotation(flags) -} - -// BindClusterFlags is a convenience method to bind the specified flags to their associated variables -func BindClusterFlags(clusterInfo *clientcmdapi.Cluster, flags *pflag.FlagSet, flagNames ClusterOverrideFlags) { - flagNames.APIServer.BindStringFlag(flags, &clusterInfo.Server) - flagNames.CertificateAuthority.BindStringFlag(flags, &clusterInfo.CertificateAuthority) - flagNames.InsecureSkipTLSVerify.BindBoolFlag(flags, &clusterInfo.InsecureSkipTLSVerify) - flagNames.TLSServerName.BindStringFlag(flags, &clusterInfo.TLSServerName) - flagNames.ProxyURL.BindStringFlag(flags, &clusterInfo.ProxyURL) - flagNames.DisableCompression.BindBoolFlag(flags, &clusterInfo.DisableCompression) -} - -// BindFlags is a convenience method to bind the specified flags to their associated variables -func BindContextFlags(contextInfo *clientcmdapi.Context, flags *pflag.FlagSet, flagNames ContextOverrideFlags) { - flagNames.ClusterName.BindStringFlag(flags, &contextInfo.Cluster) - flagNames.AuthInfoName.BindStringFlag(flags, &contextInfo.AuthInfo) - flagNames.Namespace.BindTransformingStringFlag(flags, &contextInfo.Namespace, RemoveNamespacesPrefix) -} - -// RemoveNamespacesPrefix is a transformer that strips "ns/", "namespace/" and "namespaces/" prefixes case-insensitively -func RemoveNamespacesPrefix(value string) (string, error) { - for _, prefix := range []string{"namespaces/", "namespace/", "ns/"} { - if len(value) > len(prefix) && strings.EqualFold(value[0:len(prefix)], prefix) { - value = value[len(prefix):] - break - } - } - return value, nil -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/validation.go b/vendor/k8s.io/client-go/tools/clientcmd/validation.go deleted file mode 100644 index 0389ad6dc..000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/validation.go +++ /dev/null @@ -1,376 +0,0 @@ -/* -Copyright 2014 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clientcmd - -import ( - "errors" - "fmt" - "os" - "reflect" - "strings" - - utilerrors "k8s.io/apimachinery/pkg/util/errors" - "k8s.io/apimachinery/pkg/util/validation" - authexec "k8s.io/client-go/plugin/pkg/client/auth/exec" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -var ( - ErrNoContext = errors.New("no context chosen") - ErrEmptyConfig = NewEmptyConfigError("no configuration has been provided, try setting KUBERNETES_MASTER environment variable") - // message is for consistency with old behavior - ErrEmptyCluster = errors.New("cluster has no server defined") -) - -// NewEmptyConfigError returns an error wrapping the given message which IsEmptyConfig() will recognize as an empty config error -func NewEmptyConfigError(message string) error { - return &errEmptyConfig{message} -} - -type errEmptyConfig struct { - message string -} - -func (e *errEmptyConfig) Error() string { - return e.message -} - -type errContextNotFound struct { - ContextName string -} - -func (e *errContextNotFound) Error() string { - return fmt.Sprintf("context was not found for specified context: %v", e.ContextName) -} - -// IsContextNotFound returns a boolean indicating whether the error is known to -// report that a context was not found -func IsContextNotFound(err error) bool { - if err == nil { - return false - } - if _, ok := err.(*errContextNotFound); ok || err == ErrNoContext { - return true - } - return strings.Contains(err.Error(), "context was not found for specified context") -} - -// IsEmptyConfig returns true if the provided error indicates the provided configuration -// is empty. -func IsEmptyConfig(err error) bool { - switch t := err.(type) { - case errConfigurationInvalid: - if len(t) != 1 { - return false - } - _, ok := t[0].(*errEmptyConfig) - return ok - } - _, ok := err.(*errEmptyConfig) - return ok -} - -// errConfigurationInvalid is a set of errors indicating the configuration is invalid. -type errConfigurationInvalid []error - -// errConfigurationInvalid implements error and Aggregate -var _ error = errConfigurationInvalid{} -var _ utilerrors.Aggregate = errConfigurationInvalid{} - -func newErrConfigurationInvalid(errs []error) error { - switch len(errs) { - case 0: - return nil - default: - return errConfigurationInvalid(errs) - } -} - -// Error implements the error interface -func (e errConfigurationInvalid) Error() string { - return fmt.Sprintf("invalid configuration: %v", utilerrors.NewAggregate(e).Error()) -} - -// Errors implements the utilerrors.Aggregate interface -func (e errConfigurationInvalid) Errors() []error { - return e -} - -// Is implements the utilerrors.Aggregate interface -func (e errConfigurationInvalid) Is(target error) bool { - return e.visit(func(err error) bool { - return errors.Is(err, target) - }) -} - -func (e errConfigurationInvalid) visit(f func(err error) bool) bool { - for _, err := range e { - switch err := err.(type) { - case errConfigurationInvalid: - if match := err.visit(f); match { - return match - } - case utilerrors.Aggregate: - for _, nestedErr := range err.Errors() { - if match := f(nestedErr); match { - return match - } - } - default: - if match := f(err); match { - return match - } - } - } - - return false -} - -// IsConfigurationInvalid returns true if the provided error indicates the configuration is invalid. -func IsConfigurationInvalid(err error) bool { - switch err.(type) { - case *errContextNotFound, errConfigurationInvalid: - return true - } - return IsContextNotFound(err) -} - -// Validate checks for errors in the Config. It does not return early so that it can find as many errors as possible. -func Validate(config clientcmdapi.Config) error { - validationErrors := make([]error, 0) - - if clientcmdapi.IsConfigEmpty(&config) { - return newErrConfigurationInvalid([]error{ErrEmptyConfig}) - } - - if len(config.CurrentContext) != 0 { - if _, exists := config.Contexts[config.CurrentContext]; !exists { - validationErrors = append(validationErrors, &errContextNotFound{config.CurrentContext}) - } - } - - for contextName, context := range config.Contexts { - validationErrors = append(validationErrors, validateContext(contextName, *context, config)...) - } - - for authInfoName, authInfo := range config.AuthInfos { - validationErrors = append(validationErrors, validateAuthInfo(authInfoName, *authInfo)...) - } - - for clusterName, clusterInfo := range config.Clusters { - validationErrors = append(validationErrors, validateClusterInfo(clusterName, *clusterInfo)...) - } - - return newErrConfigurationInvalid(validationErrors) -} - -// ConfirmUsable looks a particular context and determines if that particular part of the config is useable. There might still be errors in the config, -// but no errors in the sections requested or referenced. It does not return early so that it can find as many errors as possible. -func ConfirmUsable(config clientcmdapi.Config, passedContextName string) error { - validationErrors := make([]error, 0) - - if clientcmdapi.IsConfigEmpty(&config) { - return newErrConfigurationInvalid([]error{ErrEmptyConfig}) - } - - var contextName string - if len(passedContextName) != 0 { - contextName = passedContextName - } else { - contextName = config.CurrentContext - } - - if len(contextName) == 0 { - return ErrNoContext - } - - context, exists := config.Contexts[contextName] - if !exists { - validationErrors = append(validationErrors, &errContextNotFound{contextName}) - } - - if exists { - validationErrors = append(validationErrors, validateContext(contextName, *context, config)...) - - // Default to empty users and clusters and let the validation function report an error. - authInfo := config.AuthInfos[context.AuthInfo] - if authInfo == nil { - authInfo = &clientcmdapi.AuthInfo{} - } - validationErrors = append(validationErrors, validateAuthInfo(context.AuthInfo, *authInfo)...) - - cluster := config.Clusters[context.Cluster] - if cluster == nil { - cluster = &clientcmdapi.Cluster{} - } - validationErrors = append(validationErrors, validateClusterInfo(context.Cluster, *cluster)...) - } - - return newErrConfigurationInvalid(validationErrors) -} - -// validateClusterInfo looks for conflicts and errors in the cluster info -func validateClusterInfo(clusterName string, clusterInfo clientcmdapi.Cluster) []error { - validationErrors := make([]error, 0) - - emptyCluster := clientcmdapi.NewCluster() - if reflect.DeepEqual(*emptyCluster, clusterInfo) { - return []error{ErrEmptyCluster} - } - - if len(clusterInfo.Server) == 0 { - if len(clusterName) == 0 { - validationErrors = append(validationErrors, fmt.Errorf("default cluster has no server defined")) - } else { - validationErrors = append(validationErrors, fmt.Errorf("no server found for cluster %q", clusterName)) - } - } - if proxyURL := clusterInfo.ProxyURL; proxyURL != "" { - if _, err := parseProxyURL(proxyURL); err != nil { - validationErrors = append(validationErrors, fmt.Errorf("invalid 'proxy-url' %q for cluster %q: %w", proxyURL, clusterName, err)) - } - } - // Make sure CA data and CA file aren't both specified - if len(clusterInfo.CertificateAuthority) != 0 && len(clusterInfo.CertificateAuthorityData) != 0 { - validationErrors = append(validationErrors, fmt.Errorf("certificate-authority-data and certificate-authority are both specified for %v. certificate-authority-data will override.", clusterName)) - } - if len(clusterInfo.CertificateAuthority) != 0 { - clientCertCA, err := os.Open(clusterInfo.CertificateAuthority) - if err != nil { - validationErrors = append(validationErrors, fmt.Errorf("unable to read certificate-authority %v for %v due to %w", clusterInfo.CertificateAuthority, clusterName, err)) - } else { - defer clientCertCA.Close() - } - } - - return validationErrors -} - -// validateAuthInfo looks for conflicts and errors in the auth info -func validateAuthInfo(authInfoName string, authInfo clientcmdapi.AuthInfo) []error { - validationErrors := make([]error, 0) - - usingAuthPath := false - methods := make([]string, 0, 3) - if len(authInfo.Token) != 0 { - methods = append(methods, "token") - } - if len(authInfo.Username) != 0 || len(authInfo.Password) != 0 { - methods = append(methods, "basicAuth") - } - - if len(authInfo.ClientCertificate) != 0 || len(authInfo.ClientCertificateData) != 0 { - // Make sure cert data and file aren't both specified - if len(authInfo.ClientCertificate) != 0 && len(authInfo.ClientCertificateData) != 0 { - validationErrors = append(validationErrors, fmt.Errorf("client-cert-data and client-cert are both specified for %v. client-cert-data will override.", authInfoName)) - } - // Make sure key data and file aren't both specified - if len(authInfo.ClientKey) != 0 && len(authInfo.ClientKeyData) != 0 { - validationErrors = append(validationErrors, fmt.Errorf("client-key-data and client-key are both specified for %v; client-key-data will override", authInfoName)) - } - // Make sure a key is specified - if len(authInfo.ClientKey) == 0 && len(authInfo.ClientKeyData) == 0 { - validationErrors = append(validationErrors, fmt.Errorf("client-key-data or client-key must be specified for %v to use the clientCert authentication method.", authInfoName)) - } - - if len(authInfo.ClientCertificate) != 0 { - clientCertFile, err := os.Open(authInfo.ClientCertificate) - if err != nil { - validationErrors = append(validationErrors, fmt.Errorf("unable to read client-cert %v for %v due to %w", authInfo.ClientCertificate, authInfoName, err)) - } else { - defer clientCertFile.Close() - } - } - if len(authInfo.ClientKey) != 0 { - clientKeyFile, err := os.Open(authInfo.ClientKey) - if err != nil { - validationErrors = append(validationErrors, fmt.Errorf("unable to read client-key %v for %v due to %w", authInfo.ClientKey, authInfoName, err)) - } else { - defer clientKeyFile.Close() - } - } - } - - if authInfo.Exec != nil { - if authInfo.AuthProvider != nil { - validationErrors = append(validationErrors, fmt.Errorf("authProvider cannot be provided in combination with an exec plugin for %s", authInfoName)) - } - if len(authInfo.Exec.Command) == 0 { - validationErrors = append(validationErrors, fmt.Errorf("command must be specified for %v to use exec authentication plugin", authInfoName)) - } - if len(authInfo.Exec.APIVersion) == 0 { - validationErrors = append(validationErrors, fmt.Errorf("apiVersion must be specified for %v to use exec authentication plugin", authInfoName)) - } - for _, v := range authInfo.Exec.Env { - if len(v.Name) == 0 { - validationErrors = append(validationErrors, fmt.Errorf("env variable name must be specified for %v to use exec authentication plugin", authInfoName)) - } - } - switch authInfo.Exec.InteractiveMode { - case "": - validationErrors = append(validationErrors, fmt.Errorf("interactiveMode must be specified for %v to use exec authentication plugin", authInfoName)) - case clientcmdapi.NeverExecInteractiveMode, clientcmdapi.IfAvailableExecInteractiveMode, clientcmdapi.AlwaysExecInteractiveMode: - // These are valid - default: - validationErrors = append(validationErrors, fmt.Errorf("invalid interactiveMode for %v: %q", authInfoName, authInfo.Exec.InteractiveMode)) - } - - if err := authexec.ValidatePluginPolicy(authInfo.Exec.PluginPolicy); err != nil { - validationErrors = append(validationErrors, fmt.Errorf("allowlist misconfiguration: %w", err)) - } - } - - // authPath also provides information for the client to identify the server, so allow multiple auth methods in that case - if (len(methods) > 1) && (!usingAuthPath) { - validationErrors = append(validationErrors, fmt.Errorf("more than one authentication method found for %v; found %v, only one is allowed", authInfoName, methods)) - } - - // ImpersonateUID, ImpersonateGroups or ImpersonateUserExtra should be requested with a user - if (len(authInfo.ImpersonateUID) > 0 || len(authInfo.ImpersonateGroups) > 0 || len(authInfo.ImpersonateUserExtra) > 0) && (len(authInfo.Impersonate) == 0) { - validationErrors = append(validationErrors, fmt.Errorf("requesting uid, groups or user-extra for %v without impersonating a user", authInfoName)) - } - return validationErrors -} - -// validateContext looks for errors in the context. It is not transitive, so errors in the reference authInfo or cluster configs are not included in this return -func validateContext(contextName string, context clientcmdapi.Context, config clientcmdapi.Config) []error { - validationErrors := make([]error, 0) - - if len(contextName) == 0 { - validationErrors = append(validationErrors, fmt.Errorf("empty context name for %#v is not allowed", context)) - } - - if len(context.AuthInfo) == 0 { - validationErrors = append(validationErrors, fmt.Errorf("user was not specified for context %q", contextName)) - } else if _, exists := config.AuthInfos[context.AuthInfo]; !exists { - validationErrors = append(validationErrors, fmt.Errorf("user %q was not found for context %q", context.AuthInfo, contextName)) - } - - if len(context.Cluster) == 0 { - validationErrors = append(validationErrors, fmt.Errorf("cluster was not specified for context %q", contextName)) - } else if _, exists := config.Clusters[context.Cluster]; !exists { - validationErrors = append(validationErrors, fmt.Errorf("cluster %q was not found for context %q", context.Cluster, contextName)) - } - - if len(context.Namespace) != 0 { - if len(validation.IsDNS1123Label(context.Namespace)) != 0 { - validationErrors = append(validationErrors, fmt.Errorf("namespace %q for context %q does not conform to the kubernetes DNS_LABEL rules", context.Namespace, contextName)) - } - } - - return validationErrors -} diff --git a/vendor/k8s.io/client-go/util/homedir/homedir.go b/vendor/k8s.io/client-go/util/homedir/homedir.go deleted file mode 100644 index 3fdbeb8cf..000000000 --- a/vendor/k8s.io/client-go/util/homedir/homedir.go +++ /dev/null @@ -1,92 +0,0 @@ -/* -Copyright 2016 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package homedir - -import ( - "os" - "path/filepath" - "runtime" -) - -// HomeDir returns the home directory for the current user. -// On Windows: -// 1. the first of %HOME%, %HOMEDRIVE%%HOMEPATH%, %USERPROFILE% containing a `.kube\config` file is returned. -// 2. if none of those locations contain a `.kube\config` file, the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that exists and is writeable is returned. -// 3. if none of those locations are writeable, the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that exists is returned. -// 4. if none of those locations exists, the first of %HOME%, %USERPROFILE%, %HOMEDRIVE%%HOMEPATH% that is set is returned. -func HomeDir() string { - if runtime.GOOS == "windows" { - home := os.Getenv("HOME") - homeDriveHomePath := "" - if homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH"); len(homeDrive) > 0 && len(homePath) > 0 { - homeDriveHomePath = homeDrive + homePath - } - userProfile := os.Getenv("USERPROFILE") - - // Return first of %HOME%, %HOMEDRIVE%/%HOMEPATH%, %USERPROFILE% that contains a `.kube\config` file. - // %HOMEDRIVE%/%HOMEPATH% is preferred over %USERPROFILE% for backwards-compatibility. - for _, p := range []string{home, homeDriveHomePath, userProfile} { - if len(p) == 0 { - continue - } - if _, err := os.Stat(filepath.Join(p, ".kube", "config")); err != nil { - continue - } - return p - } - - firstSetPath := "" - firstExistingPath := "" - - // Prefer %USERPROFILE% over %HOMEDRIVE%/%HOMEPATH% for compatibility with other auth-writing tools - for _, p := range []string{home, userProfile, homeDriveHomePath} { - if len(p) == 0 { - continue - } - if len(firstSetPath) == 0 { - // remember the first path that is set - firstSetPath = p - } - info, err := os.Stat(p) - if err != nil { - continue - } - if len(firstExistingPath) == 0 { - // remember the first path that exists - firstExistingPath = p - } - if info.IsDir() && info.Mode().Perm()&(1<<(uint(7))) != 0 { - // return first path that is writeable - return p - } - } - - // If none are writeable, return first location that exists - if len(firstExistingPath) > 0 { - return firstExistingPath - } - - // If none exist, return first location that is set - if len(firstSetPath) > 0 { - return firstSetPath - } - - // We've got nothing - return "" - } - return os.Getenv("HOME") -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 332418bad..ece44db4e 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -72,7 +72,7 @@ github.com/munnerz/goautoneg # github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f ## explicit github.com/mwitkow/go-conntrack -# github.com/netobserv/flowlogs-pipeline v1.11.0-community +# github.com/netobserv/flowlogs-pipeline v1.11.2-community ## explicit; go 1.25.0 github.com/netobserv/flowlogs-pipeline/pkg/api github.com/netobserv/flowlogs-pipeline/pkg/config @@ -80,15 +80,6 @@ github.com/netobserv/flowlogs-pipeline/pkg/utils # github.com/netobserv/netobserv-ebpf-agent v1.11.2-community ## explicit; go 1.25.0 github.com/netobserv/netobserv-ebpf-agent/pkg/utils -# github.com/netsampler/goflow2 v1.3.7 -## explicit; go 1.18 -github.com/netsampler/goflow2/decoders/netflow -github.com/netsampler/goflow2/decoders/netflow/templates -github.com/netsampler/goflow2/decoders/netflowlegacy -github.com/netsampler/goflow2/decoders/sflow -github.com/netsampler/goflow2/decoders/utils -github.com/netsampler/goflow2/pb -github.com/netsampler/goflow2/producer # github.com/ovn-org/ovn-kubernetes/go-controller v0.0.0-20250227173154-57a2590a1d16 ## explicit; go 1.22.0 github.com/ovn-org/ovn-kubernetes/go-controller/observability-lib/model @@ -122,9 +113,6 @@ github.com/prometheus/procfs/internal/util # github.com/sirupsen/logrus v1.9.4 ## explicit; go 1.17 github.com/sirupsen/logrus -# github.com/spf13/pflag v1.0.10 -## explicit; go 1.12 -github.com/spf13/pflag # github.com/stretchr/objx v0.5.2 ## explicit; go 1.20 github.com/stretchr/objx @@ -143,7 +131,7 @@ go.yaml.in/yaml/v2 # go.yaml.in/yaml/v3 v3.0.4 ## explicit; go 1.16 go.yaml.in/yaml/v3 -# golang.org/x/net v0.48.0 +# golang.org/x/net v0.49.0 ## explicit; go 1.24.0 golang.org/x/net/http/httpguts golang.org/x/net/http/httpproxy @@ -158,15 +146,15 @@ golang.org/x/net/trace golang.org/x/oauth2 golang.org/x/oauth2/clientcredentials golang.org/x/oauth2/internal -# golang.org/x/sys v0.41.0 -## explicit; go 1.24.0 +# golang.org/x/sys v0.42.0 +## explicit; go 1.25.0 golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows -# golang.org/x/term v0.38.0 +# golang.org/x/term v0.39.0 ## explicit; go 1.24.0 golang.org/x/term -# golang.org/x/text v0.32.0 +# golang.org/x/text v0.33.0 ## explicit; go 1.24.0 golang.org/x/text/secure/bidirule golang.org/x/text/transform @@ -456,11 +444,7 @@ k8s.io/client-go/plugin/pkg/client/auth/exec k8s.io/client-go/rest k8s.io/client-go/rest/watch k8s.io/client-go/testing -k8s.io/client-go/tools/auth -k8s.io/client-go/tools/clientcmd k8s.io/client-go/tools/clientcmd/api -k8s.io/client-go/tools/clientcmd/api/latest -k8s.io/client-go/tools/clientcmd/api/v1 k8s.io/client-go/tools/metrics k8s.io/client-go/tools/reference k8s.io/client-go/transport @@ -468,7 +452,6 @@ k8s.io/client-go/util/apply k8s.io/client-go/util/cert k8s.io/client-go/util/connrotation k8s.io/client-go/util/flowcontrol -k8s.io/client-go/util/homedir k8s.io/client-go/util/keyutil k8s.io/client-go/util/workqueue # k8s.io/klog/v2 v2.130.1 From 4588c812437d212cdadaa358f4402c948399442a Mon Sep 17 00:00:00 2001 From: Joel Takvorian Date: Tue, 31 Mar 2026 22:49:04 +0200 Subject: [PATCH 2/4] Manage anyOf filters, url-encode space for loki --- pkg/loki/flow_query.go | 3 +- .../components/drawer/record/record-panel.tsx | 34 +++++++++++++++++++ web/src/utils/columns.ts | 1 + 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/pkg/loki/flow_query.go b/pkg/loki/flow_query.go index d32ccb79c..2b8470ad4 100644 --- a/pkg/loki/flow_query.go +++ b/pkg/loki/flow_query.go @@ -104,7 +104,8 @@ func (q *FlowQueryBuilder) addFilter(filter filters.Match) error { return fmt.Errorf("unauthorized sign in flows request: %s", filter.Values) } - values := strings.Split(filter.Values, ",") + // Space must be url-encoded + values := strings.Split(strings.ReplaceAll(filter.Values, " ", "%20"), ",") // Stream selector labels if q.config.IsLabel(filter.Key) { diff --git a/web/src/components/drawer/record/record-panel.tsx b/web/src/components/drawer/record/record-panel.tsx index 5b1f79336..fe8ab3da8 100644 --- a/web/src/components/drawer/record/record-panel.tsx +++ b/web/src/components/drawer/record/record-panel.tsx @@ -30,6 +30,7 @@ import { Filter, FilterCompare, FilterDefinition, + FilterValue, findFromFilters, removeFromFilters } from '../../../model/filters'; @@ -125,6 +126,8 @@ export const RecordPanel: React.FC = ({ return getGenericFilter(col, (value as number[])[2]); case ColumnsId.flowdirints: return getDirIntsFilter(); + case ColumnsId.tlstypes: + return getGenericAnyOfFilter(col, value as string[]); default: return getGenericFilter(col, value); } @@ -232,6 +235,37 @@ export const RecordPanel: React.FC = ({ }; }, [columns, filterDefinitions, filters, record.fields.IfDirections, record.fields.Interfaces, setFilters, t]); + const getGenericAnyOfFilter = React.useCallback( + (col: Column, values: string[]): RecordFieldFilter | undefined => { + const def = col.quickFilter ? findFilter(filterDefinitions, col.quickFilter) : undefined; + if (!def) { + return undefined; + } + const filterKey = { def: def, compare: FilterCompare.equal }; + const filterValues: FilterValue[] = values.map(v => ({v: v})); + const isDelete = doesIncludeFilter(filters, filterKey, filterValues); + return { + type: 'filter', + onClick: () => { + if (isDelete) { + setFilters(removeFromFilters(filters, filterKey)); + } else { + const newFilters = _.cloneDeep(filters); + const found = findFromFilters(newFilters, filterKey); + if (found) { + found.values = filterValues; + } else { + newFilters.push({ def: def, compare: FilterCompare.equal, values: filterValues }); + } + setFilters(newFilters); + } + }, + isDelete: isDelete + }; + }, + [filterDefinitions, filters, setFilters] + ); + const getGenericFilter = React.useCallback( (col: Column, value: unknown): RecordFieldFilter | undefined => { const def = col.quickFilter ? findFilter(filterDefinitions, col.quickFilter) : undefined; diff --git a/web/src/utils/columns.ts b/web/src/utils/columns.ts index febe9f3ed..5d9b1e0c4 100644 --- a/web/src/utils/columns.ts +++ b/web/src/utils/columns.ts @@ -80,6 +80,7 @@ export enum ColumnsId { ifdirs = 'IfDirections', flowdirints = 'FlowDirInts', udns = 'Udns', + tlstypes = 'TLSTypes', recordtype = 'RecordType', bytesab = 'Bytes_AB', bytesba = 'Bytes_BA', From 4c1158b280a24a1abc89d6fc3f6a45fb03cecaa2 Mon Sep 17 00:00:00 2001 From: Joel Takvorian Date: Tue, 31 Mar 2026 23:05:37 +0200 Subject: [PATCH 3/4] format --- web/src/components/drawer/record/record-panel.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/src/components/drawer/record/record-panel.tsx b/web/src/components/drawer/record/record-panel.tsx index fe8ab3da8..e0c2a7cfb 100644 --- a/web/src/components/drawer/record/record-panel.tsx +++ b/web/src/components/drawer/record/record-panel.tsx @@ -242,7 +242,7 @@ export const RecordPanel: React.FC = ({ return undefined; } const filterKey = { def: def, compare: FilterCompare.equal }; - const filterValues: FilterValue[] = values.map(v => ({v: v})); + const filterValues: FilterValue[] = values.map(v => ({ v: v })); const isDelete = doesIncludeFilter(filters, filterKey, filterValues); return { type: 'filter', From 2fc9198f12b62183fe98d2b1d2e770a1107cf5eb Mon Sep 17 00:00:00 2001 From: Joel Takvorian Date: Wed, 1 Apr 2026 14:07:26 +0200 Subject: [PATCH 4/4] Update sample config --- config/sample-config.yaml | 280 +++++++++++++++++++++++++------------- pkg/loki/flow_query.go | 2 +- 2 files changed, 184 insertions(+), 98 deletions(-) diff --git a/config/sample-config.yaml b/config/sample-config.yaml index 33d619cf5..24f775adf 100644 --- a/config/sample-config.yaml +++ b/config/sample-config.yaml @@ -25,7 +25,7 @@ prometheus: skipTls: true # tokenPath: /tmp/oc-token.txt alertManager: - # url: https://localhost:9094 + # url: https://localhost:9094 metrics: - enabled: false name: netobserv_node_egress_bytes_total @@ -658,7 +658,7 @@ frontend: default: false width: 15 - id: Proto - group: L3 Layer + group: Protocol Info name: Protocol tooltip: The value of the protocol number in the IP packet header field: Proto @@ -666,36 +666,68 @@ frontend: default: true width: 10 - id: Dscp - group: L3 Layer + group: Protocol Info name: DSCP tooltip: The value of the Differentiated Services Code Point field: Dscp filter: dscp + default: false + width: 10 + - id: TCPFlags + group: Protocol Info + name: TCP Flags + tooltip: Logical OR combination of unique TCP flags comprised in the flow, according to RFC-9293, with additional custom values. + field: Flags + filter: tcp_flags + default: false + width: 10 + - id: TLSVersion + group: Protocol Info + name: TLS Version + tooltip: TLS version found in handshake headers + field: TLSVersion + filter: tls_version default: true width: 10 + feature: tlsTracking + - id: TLSCipherSuite + group: Protocol Info + name: TLS Cipher Suite + field: TLSCipherSuite + filter: tls_cipher_suite + width: 15 + feature: tlsTracking + - id: TLSCurve + group: Protocol Info + name: TLS Curve + field: TLSCurve + filter: tls_curve + width: 10 + feature: tlsTracking + - id: TLSTypes + group: Protocol Info + name: TLS Types + tooltip: TLS packet types, such as ClientHello or AppData + field: TLSTypes + filter: tls_types + width: 15 + feature: tlsTracking - id: IcmpType - group: ICMP - name: Type + group: Protocol Info + name: ICMP Type tooltip: The type of the ICMP message field: IcmpType filter: icmp_type default: false width: 10 - id: IcmpCode - group: ICMP - name: Code + group: Protocol Info + name: ICMP Code tooltip: The code of the ICMP message field: IcmpCode filter: icmp_code default: false width: 10 - - id: TCPFlags - name: TCP Flags - tooltip: Logical OR combination of unique TCP flags comprised in the flow, according to RFC-9293, with additional custom values. - field: Flags - filter: tcp_flags - default: false - width: 10 - id: FlowDirection name: Node Direction tooltip: The interpreted direction of the flow observed at the Node observation point. @@ -943,15 +975,16 @@ frontend: - id: cluster_name name: Cluster component: autocomplete - hint: Specify a cluster ID or name. + placeholder: 'E.g: cluster-1, cluster-2' + hint: Add cluster ID or name filter. feature: multiCluster - id: namespace name: Namespace component: autocomplete autoCompleteAddsQuotes: true category: endpoint - placeholder: 'E.g: netobserv' - hint: Specify a single kubernetes name. + placeholder: 'E.g: netobserv, kube-system' + hint: Add kubernetes namespace filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -966,8 +999,8 @@ frontend: component: autocomplete autoCompleteAddsQuotes: true category: source - placeholder: 'E.g: netobserv' - hint: Specify a single kubernetes name. + placeholder: 'E.g: netobserv, kube-system' + hint: Add kubernetes source namespace filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -982,8 +1015,8 @@ frontend: component: autocomplete autoCompleteAddsQuotes: true category: destination - placeholder: 'E.g: netobserv' - hint: Specify a single kubernetes name. + placeholder: 'E.g: netobserv, kube-system' + hint: Add kubernetes destination namespace filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -997,8 +1030,8 @@ frontend: name: Name component: text category: endpoint - placeholder: 'E.g: my-pod' - hint: Specify a single kubernetes name. + placeholder: 'E.g: my-pod, my-service' + hint: Add kubernetes name filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -1012,8 +1045,8 @@ frontend: name: Name component: text category: source - placeholder: 'E.g: my-pod' - hint: Specify a single kubernetes name. + placeholder: 'E.g: my-pod, my-service' + hint: Add kubernetes source name filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -1027,8 +1060,8 @@ frontend: name: Name component: text category: destination - placeholder: 'E.g: my-pod' - hint: Specify a single kubernetes name. + placeholder: 'E.g: my-pod, my-service' + hint: Add kubernetes destination name filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -1043,25 +1076,25 @@ frontend: component: autocomplete autoCompleteAddsQuotes: true category: endpoint - placeholder: 'E.g: Pod, Service' + placeholder: 'E.g: Pod, Service, Deployment' - id: src_kind name: Kind component: autocomplete autoCompleteAddsQuotes: true category: source - placeholder: 'E.g: Pod, Service' + placeholder: 'E.g: Pod, Service, Deployment' - id: dst_kind name: Kind component: autocomplete autoCompleteAddsQuotes: true category: destination - placeholder: 'E.g: Pod, Service' + placeholder: 'E.g: Pod, Service, Deployment' - id: owner_name name: Owner Name component: text category: endpoint - placeholder: 'E.g: my-deployment' - hint: Specify a single kubernetes name. + placeholder: 'E.g: my-deployment, my-daemonset' + hint: Add kubernetes owner name filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -1075,8 +1108,8 @@ frontend: name: Owner Name component: text category: source - placeholder: 'E.g: my-deployment' - hint: Specify a single kubernetes name. + placeholder: 'E.g: my-deployment, my-daemonset' + hint: Add kubernetes source owner name filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -1090,8 +1123,8 @@ frontend: name: Owner Name component: text category: destination - placeholder: 'E.g: my-deployment' - hint: Specify a single kubernetes name. + placeholder: 'E.g: my-deployment, my-daemonset' + hint: Add kubernetes destination owner name filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -1105,44 +1138,50 @@ frontend: name: Zone component: autocomplete category: endpoint - hint: Specify a single zone. + placeholder: 'E.g: zone-1, zone-2' + hint: Add zone filter. feature: zones - id: src_zone name: Zone component: autocomplete category: source - hint: Specify a single zone. + placeholder: 'E.g: zone-1, zone-2' + hint: Add source zone filter. feature: zones - id: dst_zone name: Zone component: autocomplete category: destination - hint: Specify a single zone. + placeholder: 'E.g: zone-1, zone-2' + hint: Add destination zone filter. feature: zones - id: subnet_label name: Subnet Label component: autocomplete category: endpoint - hint: Specify a subnet label, or an empty string to get unmatched sources. + placeholder: 'E.g: Pods, Services, ExternalIP' + hint: Add subnet label filter, or an empty string to get unmatched sources. feature: subnetLabels - id: src_subnet_label name: Subnet Label component: autocomplete category: source - hint: Specify a subnet label, or an empty string to get unmatched sources. + placeholder: 'E.g: Pods, Services, ExternalIP' + hint: Add source subnet label filter, or an empty string to get unmatched sources. feature: subnetLabels - id: dst_subnet_label name: Subnet Label component: autocomplete category: destination - hint: Specify a subnet label, or an empty string to get unmatched destinations. + placeholder: 'E.g: Pods, Services, ExternalIP' + hint: Add destination subnet label filter, or an empty string to get unmatched destinations. feature: subnetLabels - id: resource name: Resource component: autocomplete category: endpoint placeholder: 'E.g: Deployment.example.my-dep or Pod.default.my-pod' - hint: Specify an existing resource from its kind, namespace and name. + hint: Add kubernetes resource filter from its kind, namespace and name. examples: |- Specify a kind, namespace and name from existing: - Select kind first from suggestions @@ -1153,7 +1192,7 @@ frontend: component: autocomplete category: source placeholder: 'E.g: Deployment.example.my-dep or Pod.default.my-pod' - hint: Specify an existing resource from its kind, namespace and name. + hint: Add kubernetes source resource filter from its kind, namespace and name. examples: |- Specify a kind, namespace and name from existing: - Select kind first from suggestions @@ -1164,7 +1203,7 @@ frontend: component: autocomplete category: destination placeholder: 'E.g: Deployment.example.my-dep or Pod.default.my-pod' - hint: Specify an existing resource from its kind, namespace and name. + hint: Add kubernetes destination resource filter from its kind, namespace and name. examples: |- Specify a kind, namespace and name from existing: - Select kind first from suggestions @@ -1174,7 +1213,7 @@ frontend: name: IP component: text category: endpoint - hint: Specify a single IP or range. + hint: Add IP or range filter. placeholder: 'E.g: 192.0.2.0' examples: |- Specify IP following one of these rules: @@ -1185,7 +1224,7 @@ frontend: name: IP component: text category: source - hint: Specify a single IP or range. + hint: Add source IP or range filter. placeholder: 'E.g: 192.0.2.0' examples: |- Specify IP following one of these rules: @@ -1196,7 +1235,7 @@ frontend: name: IP component: text category: destination - hint: Specify a single IP or range. + hint: Add destination IP or range filter. placeholder: 'E.g: 192.0.2.0' examples: |- Specify IP following one of these rules: @@ -1207,8 +1246,8 @@ frontend: name: Port component: autocomplete category: endpoint - hint: Specify a single port number or name. - placeholder: 'E.g: 80' + hint: Add port number or name filter. + placeholder: 'E.g: 80, 21, HTTP, FTP' examples: |- Specify a single port following one of these rules: - A port number like 80, 21 @@ -1218,8 +1257,8 @@ frontend: name: Port component: autocomplete category: source - hint: Specify a single port number or name. - placeholder: 'E.g: 80' + hint: Add source port number or name filter. + placeholder: 'E.g: 80, 21, HTTP, FTP' examples: |- Specify a single port following one of these rules: - A port number like 80, 21 @@ -1229,8 +1268,8 @@ frontend: name: Port component: autocomplete category: destination - hint: Specify a single port number or name. - placeholder: 'E.g: 80' + hint: Add destination port number or name filter. + placeholder: 'E.g: 80, 21, HTTP, FTP' examples: |- Specify a single port following one of these rules: - A port number like 80, 21 @@ -1241,25 +1280,25 @@ frontend: component: text category: endpoint placeholder: 'E.g: 42:01:0A:00:00:01' - hint: Specify a single MAC address. + hint: Add MAC address filter. - id: src_mac name: MAC component: text category: source - placeholder: 'E.g: 42:01:0A:00:00:01' - hint: Specify a single MAC address. + placeholder: 'E.g: 42:01:0A:00:00:01, 42:01:0A:00:00:02' + hint: Add source MAC address filter. - id: dst_mac name: MAC component: text category: destination - placeholder: 'E.g: 42:01:0A:00:00:01' - hint: Specify a single MAC address. + placeholder: 'E.g: 42:01:0A:00:00:01, 42:01:0A:00:00:02' + hint: Add destination MAC address filter. - id: host_address name: Node IP component: text category: endpoint - placeholder: 'E.g: 10.0.0.1' - hint: Specify a single IP or range. + placeholder: 'E.g: 10.0.0.1, 10.0.0.2' + hint: Add node IP or range filter. examples: |- Specify IP following one of these rules: - A single IPv4 or IPv6 address like 192.0.2.0, ::1 @@ -1269,8 +1308,8 @@ frontend: name: Node IP component: text category: source - placeholder: 'E.g: 10.0.0.1' - hint: Specify a single IP or range. + placeholder: 'E.g: 10.0.0.1, 10.0.0.2' + hint: Add source node IP or range filter. examples: |- Specify IP following one of these rules: - A single IPv4 or IPv6 address like 192.0.2.0, ::1 @@ -1280,8 +1319,8 @@ frontend: name: Node IP component: text category: destination - placeholder: 'E.g: 10.0.0.1' - hint: Specify a single IP or range. + placeholder: 'E.g: 10.0.0.1, 10.0.0.2' + hint: Add destination node IP or range filter. examples: |- Specify IP following one of these rules: - A single IPv4 or IPv6 address like 192.0.2.0, ::1 @@ -1291,8 +1330,8 @@ frontend: name: Node Name component: text category: endpoint - placeholder: 'E.g: my-node' - hint: Specify a single kubernetes name. + placeholder: 'E.g: my-node, my-node-2' + hint: Add kubernetes node name filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -1306,8 +1345,8 @@ frontend: name: Node Name component: text category: source - placeholder: 'E.g: my-node' - hint: Specify a single kubernetes name. + placeholder: 'E.g: my-node, my-node-2' + hint: Add kubernetes source node name filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -1321,8 +1360,8 @@ frontend: name: Node Name component: text category: destination - placeholder: 'E.g: my-node' - hint: Specify a single kubernetes name. + placeholder: 'E.g: my-node, my-node-2' + hint: Add kubernetes destination node name filter. examples: |- Specify a single kubernetes name following these rules: - Containing any alphanumeric, hyphen, underscrore or dot character @@ -1336,31 +1375,59 @@ frontend: name: Network Name component: text category: endpoint + hint: Add network name filter. feature: multiNetworks - id: src_network name: Network Name component: text category: source + hint: Add source network name filter. feature: multiNetworks - id: dst_network name: Network Name component: text category: destination + hint: Add destination network name filter. feature: multiNetworks - id: protocol name: Protocol component: autocomplete - placeholder: 'E.g: TCP, UDP' - hint: Specify a single protocol number or name. + placeholder: 'E.g: TCP, UDP, ICMP' + hint: Add protocol number or name filter. examples: |- Specify a single protocol following one of these rules: - A protocol number like 6, 17 - A IANA name like TCP, UDP docUrl: https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml + - id: tls_version + name: TLS version + component: text + placeholder: 'E.g: TLS 1.2' + hint: Specify a version of TLS. + feature: tlsTracking + - id: tls_cipher_suite + name: TLS cipher suite + component: text + placeholder: 'E.g: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256' + hint: Specify a TLS cipher suite. + feature: tlsTracking + - id: tls_curve + name: TLS curve + component: text + placeholder: 'E.g: X25519' + hint: Specify a TLS curve name. + feature: tlsTracking + - id: tls_types + name: TLS packet type + component: text + placeholder: 'E.g: ClientHello, AppData' + hint: Specify a TLS type of packet. + feature: tlsTracking - id: dscp name: DSCP component: autocomplete - hint: Specify a Differentiated Services Code Point number or name. + placeholder: 'E.g: 8, 10, Low-Priority Data, High-Throughput Data' + hint: Add Differentiated Services Code Point number or name filter. examples: |- Specify a Differentiated Services Code Point following one of these rules: - A DSCP number like 8, 10 @@ -1368,51 +1435,54 @@ frontend: - id: icmp_type name: ICMP type component: number - hint: Specify an ICMP type value as integer number. + placeholder: 'E.g: 8, 10' + hint: Add ICMP type value as integer number filter. - id: icmp_code name: ICMP code component: number - hint: Specify an ICMP code value as integer number. + placeholder: 'E.g: 8, 10' + hint: Add ICMP code value as integer number filter. - id: tcp_flags name: TCP flags component: autocomplete - hint: Specify a TCP flags value. + placeholder: 'E.g: SYN_ACK, FIN_ACK, RST_ACK' + hint: Add TCP flags value filter. examples: |- Logical OR combination of unique TCP flags comprised in the flow, according to RFC-9293, with additional custom flags (SYN_ACK, FIN_ACK and RST_ACK). - id: node_direction name: Node Direction component: autocomplete placeholder: 'E.g: Ingress, Egress, Inner' - hint: Specify the interpreted direction of the Flow observed at the Node observation point. + hint: Add the interpreted direction of the Flow observed at the Node observation point filter. - id: flow_layer name: Flow layer component: text placeholder: 'Either infra or app' - hint: Specify the layer of Flow. + hint: Add the layer of Flow filter. - id: interfaces name: Network interfaces component: text placeholder: 'E.g: br-ex, ovn-k8s-mp0' - hint: Specify a network interface. + hint: Add network interface filter. - id: ifdirections name: Interface Directions component: autocomplete placeholder: 'E.g: Ingress, Egress' - hint: Specify the direction of the Flow observed at the network interface observation point. + hint: Add direction of the Flow observed at the network interface observation point filter. - id: udns name: User Defined Network component: autocomplete - hint: Specify a user defined network name. + hint: Add user defined network name filter. feature: udnMapping - id: id name: Conversation Id component: text - hint: Specify a single conversation hash Id. + hint: Add conversation hash Id filter. - id: pkt_drop_state name: Packet drop TCP state component: autocomplete placeholder: 'E.g: ESTABLISHED, SYN_SENT, SYN_RECV' - hint: Specify a single TCP state. + hint: Add TCP state filter. examples: |- Specify a single TCP state name like: - A _LINUX_TCP_STATES_H number like 1, 2, 3 @@ -1423,7 +1493,7 @@ frontend: name: Packet drop latest cause component: autocomplete placeholder: 'E.g: NO_SOCKET, PKT_TOO_SMALL' - hint: Specify a single packet drop cause. + hint: Add packet drop cause filter. examples: |- Specify a single packet drop cause like: - A _LINUX_DROPREASON_CORE_H number like 2, 3, 4 @@ -1433,22 +1503,25 @@ frontend: - id: dns_id name: DNS Id component: number - hint: Specify a single DNS Id. + hint: Add DNS Id filter. feature: dnsTracking - id: dns_name name: DNS Name component: text - hint: Specify a single DNS name. + placeholder: 'E.g: www.example.com, www.example.org' + hint: Add DNS name filter. feature: dnsTracking - id: dns_latency name: DNS Latency component: number - hint: Specify a DNS Latency in miliseconds. + placeholder: 'E.g: 100, 200' + hint: Add DNS Latency in milliseconds filter. feature: dnsTracking - id: dns_flag_response_code name: DNS Response Code component: autocomplete - hint: Specify a single DNS RCODE name. + placeholder: 'E.g: NoError, NXDomain, NotAuth' + hint: Add DNS RCODE name filter. placeholder: 'E.g: NoError, NXDomain, NotAuth' examples: |- Specify a single DNS RCODE name like: @@ -1459,51 +1532,52 @@ frontend: - id: dns_errno name: DNS Error component: autocomplete - hint: Specify a single DNS error number. + hint: Add DNS error number filter. feature: dnsTracking - id: time_flow_rtt name: Flow RTT component: number - hint: Specify a TCP smoothed Round Trip Time in nanoseconds. + hint: Add TCP smoothed Round Trip Time in nanoseconds filter. feature: flowRTT - id: network_events name: Network Events component: text - hint: Specify a single network event. + hint: Add network event filter. feature: networkEvents - id: xlat_zone_id name: Xlat Zone Id component: number + hint: Add Xlat zone ID filter. feature: packetTranslation - id: xlat_src_address name: Xlat source address component: text category: source - hint: Specify a single IP or range. + hint: Add IP or range filter. feature: packetTranslation - id: xlat_dst_address name: Xlat destination address component: text category: destination - hint: Specify a single IP or range. + hint: Add destination IP or range filter. feature: packetTranslation - id: xlat_src_port name: Xlat source port component: autocomplete category: source - hint: Specify a single port number or name. + hint: Add source port number or name filter. feature: packetTranslation - id: xlat_dst_port name: Xlat destination port component: autocomplete category: destination - hint: Specify a single port number or name. + hint: Add destination port number or name filter. feature: packetTranslation - id: ipsec_status name: IPsec Status component: text placeholder: 'E.g: success, error' - hint: Status of the IPsec encryption (on egress, provided by the kernel function xfrm_output) or decryption (on ingress, via xfrm_input). + hint: Add IPsec status filter. feature: ipsec scopes: - id: cluster @@ -1755,6 +1829,18 @@ frontend: - name: Proto type: number description: L4 protocol + - name: TLSVersion + type: string + description: TLS version + - name: TLSTypes + type: string[] + description: TLS message types (bitfield) + - name: TLSCipherSuite + type: string + description: TLS cipher suite + - name: TLSCurve + type: string + description: TLS curve name - name: Dscp type: number description: Differentiated Services Code Point (DSCP) value diff --git a/pkg/loki/flow_query.go b/pkg/loki/flow_query.go index 2b8470ad4..777cc38a7 100644 --- a/pkg/loki/flow_query.go +++ b/pkg/loki/flow_query.go @@ -22,7 +22,7 @@ const ( emptyMatch = `""` ) -// can contains only alphanumeric / '-' / '_' / '.' / ',' / '"' / '*' / ':' / '/' characteres +// can contains only alphanumeric / ' ' / '-' / '_' / '.' / ',' / '"' / '*' / ':' / '/' characteres var filterRegexpValidation = regexp.MustCompile(`^[\w -_.,\"*:/]*$`) // FlowQueryBuilder stores a state to build a LogQL query