commit acc333c40bcf45fb78a0701596a99e93800fe566
parent 627b8eeae6b7e3ad11d2b5b0b3f9f46c4aca055f
Author: Daniele Sluijters <daenney@users.noreply.github.com>
Date: Tue, 17 Jan 2023 21:59:04 +0100
[feature] Inherit resource limits from cgroups (#1336)
When GTS is running in a container runtime which has configured CPU or
memory limits or under an init system that uses cgroups to impose CPU
and memory limits the values the Go runtime sees for GOMAXPROCS and
GOMEMLIMIT are still based on the host resources, not the cgroup.
At least for the throttling middlewares which use GOMAXPROCS to
configure their queue size, this can result in GTS running with values
too big compared to the resources that will actuall be available to it.
This introduces 2 dependencies which can pick up resource contraints
from the current cgroup and tune the Go runtime accordingly. This should
result in the different queues being appropriately sized and in general
more predictable performance. These dependencies are a no-op on
non-Linux systems or if running in a cgroup that doesn't set a limit on
CPU or memory.
The automatic tuning of GOMEMLIMIT can be disabled by either explicitly
setting GOMEMLIMIT yourself or by setting AUTOMEMLIMIT=off. The
automatic tuning of GOMAXPROCS can similarly be counteracted by setting
GOMAXPROCS yourself.
Diffstat:
254 files changed, 63518 insertions(+), 0 deletions(-)
diff --git a/cmd/gotosocial/action/server/server.go b/cmd/gotosocial/action/server/server.go
@@ -33,6 +33,7 @@ import (
apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/middleware"
+ "go.uber.org/automaxprocs/maxprocs"
"github.com/superseriousbusiness/gotosocial/internal/concurrency"
"github.com/superseriousbusiness/gotosocial/internal/config"
@@ -54,10 +55,18 @@ import (
"github.com/superseriousbusiness/gotosocial/internal/transport"
"github.com/superseriousbusiness/gotosocial/internal/typeutils"
"github.com/superseriousbusiness/gotosocial/internal/web"
+
+ // Inherit memory limit if set from cgroup
+ _ "github.com/KimMachineGun/automemlimit"
)
// Start creates and starts a gotosocial server
var Start action.GTSAction = func(ctx context.Context) error {
+ _, err := maxprocs.Set(maxprocs.Logger(log.Errorf))
+ if err != nil {
+ return fmt.Errorf("failed to set CPU limits from cgroup: %s", err)
+ }
+
var state state.State
// Initialize caches
diff --git a/go.mod b/go.mod
@@ -13,6 +13,7 @@ require (
codeberg.org/gruf/go-mutexes v1.1.5
codeberg.org/gruf/go-runners v1.4.0
codeberg.org/gruf/go-store/v2 v2.2.1
+ github.com/KimMachineGun/automemlimit v0.2.4
github.com/abema/go-mp4 v0.9.0
github.com/buckket/go-blurhash v1.1.0
github.com/coreos/go-oidc/v3 v3.5.0
@@ -49,6 +50,7 @@ require (
github.com/uptrace/bun/dialect/sqlitedialect v1.1.9
github.com/wagslane/go-password-validator v0.3.0
github.com/yuin/goldmark v1.5.3
+ go.uber.org/automaxprocs v1.5.1
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90
golang.org/x/exp v0.0.0-20220613132600-b0d781184e0d
golang.org/x/image v0.3.0
@@ -75,7 +77,11 @@ require (
codeberg.org/gruf/go-pools v1.1.0 // indirect
codeberg.org/gruf/go-sched v1.2.0 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
+ github.com/cilium/ebpf v0.4.0 // indirect
+ github.com/containerd/cgroups v1.0.4 // indirect
+ github.com/coreos/go-systemd/v22 v22.3.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
+ github.com/docker/go-units v0.4.0 // indirect
github.com/dsoprea/go-exif/v3 v3.0.0-20210625224831-a6301f85c82b // indirect
github.com/dsoprea/go-iptc v0.0.0-20200610044640-bc9ca208b413 // indirect
github.com/dsoprea/go-logging v0.0.0-20200710184922-b02d349568dd // indirect
@@ -91,6 +97,8 @@ require (
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-xmlfmt/xmlfmt v0.0.0-20211206191508-7fd73a941850 // indirect
github.com/goccy/go-json v0.9.11 // indirect
+ github.com/godbus/dbus/v5 v5.0.4 // indirect
+ github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551 // indirect
github.com/golang/protobuf v1.5.2 // indirect
@@ -118,6 +126,7 @@ require (
github.com/minio/sha256-simd v1.0.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
+ github.com/opencontainers/runtime-spec v1.0.2 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/pkg/errors v0.9.1 // indirect
diff --git a/go.sum b/go.sum
@@ -88,6 +88,8 @@ codeberg.org/gruf/go-store/v2 v2.2.1/go.mod h1:pxdyfSzau8fFs1TfZlyRzhDYvZWLaj1sX
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
+github.com/KimMachineGun/automemlimit v0.2.4 h1:GBty8TK8k0aJer1Pq5/3Vdt2ef+YpLhcqNo+PSD5CoI=
+github.com/KimMachineGun/automemlimit v0.2.4/go.mod h1:38QAnnnNhnFuAIW3+aPlaVUHqzE9buJYZK3m/jsra8E=
github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc=
github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs=
github.com/abema/go-mp4 v0.9.0 h1:WFkzn0J8uYTQ2MIWfgCaFHRB3VDkird5JncIjuuKjGI=
@@ -105,6 +107,8 @@ github.com/cheekybits/is v0.0.0-20150225183255-68e9c0620927/go.mod h1:h/aW8ynjgk
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
+github.com/cilium/ebpf v0.4.0 h1:QlHdikaxALkqWasW8hAC1mfR0jdmvbfaBdBPFmRSglA=
+github.com/cilium/ebpf v0.4.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
@@ -112,10 +116,14 @@ github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnht
github.com/cnf/structhash v0.0.0-20201127153200-e1b16c1ebc08 h1:ox2F0PSMlrAAiAdknSRMDrAr8mfxPCfSZolH+/qQnyQ=
github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ=
+github.com/containerd/cgroups v1.0.4 h1:jN/mbWBEaz+T1pi5OFtnkQ+8qnmEbAr1Oo1FRm5B0dA=
+github.com/containerd/cgroups v1.0.4/go.mod h1:nLNQtsF7Sl2HxNebu77i1R0oDlhiTG+kO4JTrUzo6IA=
github.com/coreos/go-oidc/v3 v3.5.0 h1:VxKtbccHZxs8juq7RdJntSqtXFtde9YpNpGn0yqgEHw=
github.com/coreos/go-oidc/v3 v3.5.0/go.mod h1:ecXRtV4romGPeO6ieExAsUK9cb/3fp9hXNz1tlv8PIM=
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
+github.com/coreos/go-systemd/v22 v22.3.2 h1:D9/bQk5vlXQFZ6Kwuu6zaiXJ9oTPe68++AzAJc1DzSI=
+github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cornelk/hashmap v1.0.8 h1:nv0AWgw02n+iDcawr5It4CjQIAcdMMKRrs10HOJYlrc=
github.com/cornelk/hashmap v1.0.8/go.mod h1:RfZb7JO3RviW/rT6emczVuC/oxpdz4UsSB2LJSclR1k=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
@@ -127,6 +135,8 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
github.com/djherbis/atime v1.1.0/go.mod h1:28OF6Y8s3NQWwacXc5eZTsEsiMzp7LF8MbXE+XJPdBE=
+github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw=
+github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/dsoprea/go-exif/v2 v2.0.0-20200321225314-640175a69fe4/go.mod h1:Lm2lMM2zx8p4a34ZemkaUV95AnMl4ZvLbCUbwOvLC2E=
github.com/dsoprea/go-exif/v3 v3.0.0-20200717053412-08f1b6708903/go.mod h1:0nsO1ce0mh5czxGeLo4+OCZ/C6Eo6ZlMWsz7rH/Gxv8=
github.com/dsoprea/go-exif/v3 v3.0.0-20210428042052-dca55bf8ca15/go.mod h1:cg5SNYKHMmzxsr9X6ZeLh/nfBRHHp5PngtEPcujONtk=
@@ -156,6 +166,7 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7
github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod h1:duJ4Jxv5lDcvg4QuQr0oowTf7dz4/CR8NtyCooz9HL8=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
+github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k=
github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
@@ -207,8 +218,12 @@ github.com/go-xmlfmt/xmlfmt v0.0.0-20211206191508-7fd73a941850/go.mod h1:aUCEOzz
github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/goccy/go-json v0.9.11 h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk=
github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
+github.com/godbus/dbus/v5 v5.0.4 h1:9349emZab16e7zQvpmsbtjc18ykshndd8y2PG3sgJbA=
+github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw=
github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
@@ -371,6 +386,7 @@ github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfV
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
+github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.10.4/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/klauspost/compress v1.10.10/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
@@ -440,6 +456,8 @@ github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108
github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
+github.com/opencontainers/runtime-spec v1.0.2 h1:UfAcuLBJB9Coz72x1hgl8O5RVzTdNiaglX6v2DM6FI0=
+github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0=
github.com/orcaman/writerseeker v0.0.0-20200621085525-1d3f536ff85e h1:s2RNOM/IGdY0Y6qfTeUKhDawdHDpK9RGBdx80qN4Ttw=
github.com/orcaman/writerseeker v0.0.0-20200621085525-1d3f536ff85e/go.mod h1:nBdnFKj15wFbf94Rwfq4m30eAcyY9V/IyKAGQFtqkW0=
github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
@@ -454,6 +472,7 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b h1:aUNXCGgukb4gtY99imuIeoh8Vr0GSwAlYxPAhqZrpFc=
github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b/go.mod h1:wTPjTepVu7uJBYgZ0SdWHQlIas582j6cn2jgk4DDdlg=
@@ -609,6 +628,9 @@ go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
+go.uber.org/automaxprocs v1.5.1 h1:e1YG66Lrk73dn4qhg8WFSvhF0JuFQF0ERIp4rpuV8Qk=
+go.uber.org/automaxprocs v1.5.1/go.mod h1:BF4eumQw0P9GtnuxxovUd06vwm1o18oMzFtK66vU6XU=
+go.uber.org/goleak v1.1.12 h1:gZAh5/EyT/HQwlpkCy6wTpqfH9H8Lz8zbm3dZh+OyzA=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
@@ -789,6 +811,7 @@ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -870,6 +893,7 @@ golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roY
golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
+golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
@@ -878,6 +902,7 @@ golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4f
golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
+golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
diff --git a/vendor/github.com/KimMachineGun/automemlimit/.gitignore b/vendor/github.com/KimMachineGun/automemlimit/.gitignore
@@ -0,0 +1,15 @@
+# Binaries for programs and plugins
+*.exe
+*.exe~
+*.dll
+*.so
+*.dylib
+
+# Test binary, built with `go test -c`
+*.test
+
+# Output of the go coverage tool, specifically when used with LiteIDE
+*.out
+
+# Dependency directories (remove the comment below to include it)
+# vendor/
diff --git a/vendor/github.com/KimMachineGun/automemlimit/LICENSE b/vendor/github.com/KimMachineGun/automemlimit/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2022 Geon Kim
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/vendor/github.com/KimMachineGun/automemlimit/README.md b/vendor/github.com/KimMachineGun/automemlimit/README.md
@@ -0,0 +1,42 @@
+# automemlimit
+
+[![Go Reference](https://pkg.go.dev/badge/github.com/KimMachineGun/automemlimit.svg)](https://pkg.go.dev/github.com/KimMachineGun/automemlimit)
+[![Go Report Card](https://goreportcard.com/badge/github.com/KimMachineGun/automemlimit)](https://goreportcard.com/report/github.com/KimMachineGun/automemlimit)
+[![Test](https://github.com/KimMachineGun/automemlimit/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/KimMachineGun/automemlimit/actions/workflows/test.yml)
+
+Automatically set `GOMEMLIMIT` to match Linux [cgroups(7)](https://man7.org/linux/man-pages/man7/cgroups.7.html) memory limit.
+
+See more details about `GOMEMLIMIT` [here](https://tip.golang.org/doc/gc-guide#Memory_limit).
+
+## Installation
+
+```shell
+go get github.com/KimMachineGun/automemlimit@latest
+```
+
+## Usage
+
+```go
+package main
+
+// By default, it sets `GOMEMLIMIT` to 90% of cgroup's memory limit.
+// You can find more details of its behavior from the doc comment of memlimit.SetGoMemLimitWithEnv.
+import _ "github.com/KimMachineGun/automemlimit"
+```
+
+or
+
+```go
+package main
+
+import "github.com/KimMachineGun/automemlimit/memlimit"
+
+func init() {
+ memlimit.SetGoMemLimitWithEnv()
+ memlimit.SetGoMemLimit(0.9)
+ memlimit.SetGoMemLimitWithProvider(memlimit.Limit(1024*1024), 0.9)
+ memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroup, 0.9)
+ memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroupV1, 0.9)
+ memlimit.SetGoMemLimitWithProvider(memlimit.FromCgroupV2, 0.9)
+}
+```
diff --git a/vendor/github.com/KimMachineGun/automemlimit/automemlimit.go b/vendor/github.com/KimMachineGun/automemlimit/automemlimit.go
@@ -0,0 +1,9 @@
+package automemlimit
+
+import (
+ "github.com/KimMachineGun/automemlimit/memlimit"
+)
+
+func init() {
+ memlimit.SetGoMemLimitWithEnv()
+}
diff --git a/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups.go b/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups.go
@@ -0,0 +1,63 @@
+//go:build linux
+// +build linux
+
+package memlimit
+
+import (
+ "github.com/containerd/cgroups"
+ v2 "github.com/containerd/cgroups/v2"
+)
+
+const (
+ cgroupMountPoint = "/sys/fs/cgroup"
+)
+
+// FromCgroup returns the memory limit based on the cgroups version on this system.
+func FromCgroup() (uint64, error) {
+ switch cgroups.Mode() {
+ case cgroups.Legacy:
+ return FromCgroupV1()
+ case cgroups.Hybrid, cgroups.Unified:
+ return FromCgroupV2()
+ }
+ return 0, ErrNoCgroup
+}
+
+// FromCgroupV1 returns the memory limit from the cgroup v1.
+func FromCgroupV1() (uint64, error) {
+ cg, err := cgroups.Load(cgroups.SingleSubsystem(cgroups.V1, cgroups.Memory), cgroups.RootPath)
+ if err != nil {
+ return 0, err
+ }
+
+ metrics, err := cg.Stat(cgroups.IgnoreNotExist)
+ if err != nil {
+ return 0, err
+ } else if metrics.Memory == nil {
+ return 0, ErrNoLimit
+ }
+
+ return metrics.Memory.HierarchicalMemoryLimit, nil
+}
+
+// FromCgroupV2 returns the memory limit from the cgroup v2.
+func FromCgroupV2() (uint64, error) {
+ path, err := v2.NestedGroupPath("")
+ if err != nil {
+ return 0, err
+ }
+
+ m, err := v2.LoadManager(cgroupMountPoint, path)
+ if err != nil {
+ return 0, err
+ }
+
+ stats, err := m.Stat()
+ if err != nil {
+ return 0, err
+ } else if stats.Memory == nil {
+ return 0, ErrNoLimit
+ }
+
+ return stats.Memory.UsageLimit, nil
+}
diff --git a/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups_unsupported.go b/vendor/github.com/KimMachineGun/automemlimit/memlimit/cgroups_unsupported.go
@@ -0,0 +1,16 @@
+//go:build !linux
+// +build !linux
+
+package memlimit
+
+func FromCgroup() (uint64, error) {
+ return 0, ErrCgroupsNotSupported
+}
+
+func FromCgroupV1() (uint64, error) {
+ return 0, ErrCgroupsNotSupported
+}
+
+func FromCgroupV2() (uint64, error) {
+ return 0, ErrCgroupsNotSupported
+}
diff --git a/vendor/github.com/KimMachineGun/automemlimit/memlimit/memlimit.go b/vendor/github.com/KimMachineGun/automemlimit/memlimit/memlimit.go
@@ -0,0 +1,105 @@
+package memlimit
+
+import (
+ "errors"
+ "io"
+ "log"
+ "math"
+ "os"
+ "runtime/debug"
+ "strconv"
+)
+
+const (
+ envGOMEMLIMIT = "GOMEMLIMIT"
+ envAUTOMEMLIMIT = "AUTOMEMLIMIT"
+ envAUTOMEMLIMIT_DEBUG = "AUTOMEMLIMIT_DEBUG"
+
+ defaultAUTOMEMLIMIT = 0.9
+)
+
+var (
+ // ErrNoLimit is returned when the memory limit is not set.
+ ErrNoLimit = errors.New("memory is not limited")
+ // ErrNoCgroup is returned when the process is not in cgroup.
+ ErrNoCgroup = errors.New("process is not in cgroup")
+ // ErrCgroupsNotSupported is returned when the system does not support cgroups.
+ ErrCgroupsNotSupported = errors.New("cgroups is not supported on this system")
+
+ logger = log.New(io.Discard, "", log.LstdFlags)
+)
+
+// SetGoMemLimitWithEnv sets GOMEMLIMIT with the value from the environment variable.
+// You can configure how much memory of the cgroup's memory limit to set as GOMEMLIMIT
+// through AUTOMEMLIMIT in the half-open range (0.0,1.0].
+//
+// If AUTOMEMLIMIT is not set, it defaults to 0.9. (10% is the headroom for memory sources the Go runtime is unaware of.)
+// If GOMEMLIMIT is already set or AUTOMEMLIMIT=off, this function does nothing.
+func SetGoMemLimitWithEnv() {
+ if os.Getenv(envAUTOMEMLIMIT_DEBUG) == "true" {
+ logger = log.Default()
+ }
+
+ if val, ok := os.LookupEnv(envGOMEMLIMIT); ok {
+ logger.Printf("GOMEMLIMIT is set already, skipping: %s\n", val)
+ return
+ }
+
+ ratio := defaultAUTOMEMLIMIT
+ if val, ok := os.LookupEnv(envAUTOMEMLIMIT); ok {
+ if val == "off" {
+ logger.Printf("AUTOMEMLIMIT is set to off, skipping\n")
+ return
+ }
+ _ratio, err := strconv.ParseFloat(val, 64)
+ if err != nil {
+ logger.Printf("cannot parse AUTOMEMLIMIT: %s\n", val)
+ return
+ }
+ ratio = _ratio
+ }
+ if ratio <= 0 || ratio > 1 {
+ logger.Printf("invalid AUTOMEMLIMIT: %f\n", ratio)
+ return
+ }
+
+ limit, err := SetGoMemLimit(ratio)
+ if err != nil {
+ logger.Printf("failed to set GOMEMLIMIT: %v\n", err)
+ return
+ }
+
+ logger.Printf("GOMEMLIMIT=%d\n", limit)
+}
+
+// SetGoMemLimit sets GOMEMLIMIT with the value from the cgroup's memory limit and given ratio.
+func SetGoMemLimit(ratio float64) (int64, error) {
+ return SetGoMemLimitWithProvider(FromCgroup, ratio)
+}
+
+// Provider is a function that returns the memory limit.
+type Provider func() (uint64, error)
+
+// SetGoMemLimitWithProvider sets GOMEMLIMIT with the value from the given provider and ratio.
+func SetGoMemLimitWithProvider(provider Provider, ratio float64) (int64, error) {
+ limit, err := provider()
+ if err != nil {
+ return 0, err
+ }
+ goMemLimit := cappedFloat2Int(float64(limit) * ratio)
+ debug.SetMemoryLimit(goMemLimit)
+ return goMemLimit, nil
+}
+
+func cappedFloat2Int(f float64) int64 {
+ if f > math.MaxInt64 {
+ return math.MaxInt64
+ }
+ return int64(f)
+}
+// Limit is a helper Provider function that returns the given limit.
+func Limit(limit uint64) func() (uint64, error) {
+ return func() (uint64, error) {
+ return limit, nil
+ }
+}
diff --git a/vendor/github.com/cilium/ebpf/.clang-format b/vendor/github.com/cilium/ebpf/.clang-format
@@ -0,0 +1,17 @@
+---
+Language: Cpp
+BasedOnStyle: LLVM
+AlignAfterOpenBracket: DontAlign
+AlignConsecutiveAssignments: true
+AlignEscapedNewlines: DontAlign
+AlwaysBreakBeforeMultilineStrings: true
+AlwaysBreakTemplateDeclarations: false
+AllowAllParametersOfDeclarationOnNextLine: false
+AllowShortFunctionsOnASingleLine: false
+BreakBeforeBraces: Attach
+IndentWidth: 4
+KeepEmptyLinesAtTheStartOfBlocks: false
+TabWidth: 4
+UseTab: ForContinuationAndIndentation
+ColumnLimit: 1000
+...
diff --git a/vendor/github.com/cilium/ebpf/.gitignore b/vendor/github.com/cilium/ebpf/.gitignore
@@ -0,0 +1,13 @@
+# Binaries for programs and plugins
+*.exe
+*.exe~
+*.dll
+*.so
+*.dylib
+*.o
+
+# Test binary, build with `go test -c`
+*.test
+
+# Output of the go coverage tool, specifically when used with LiteIDE
+*.out
diff --git a/vendor/github.com/cilium/ebpf/ARCHITECTURE.md b/vendor/github.com/cilium/ebpf/ARCHITECTURE.md
@@ -0,0 +1,80 @@
+Architecture of the library
+===
+
+ ELF -> Specifications -> Objects -> Links
+
+ELF
+---
+
+BPF is usually produced by using Clang to compile a subset of C. Clang outputs
+an ELF file which contains program byte code (aka BPF), but also metadata for
+maps used by the program. The metadata follows the conventions set by libbpf
+shipped with the kernel. Certain ELF sections have special meaning
+and contain structures defined by libbpf. Newer versions of clang emit
+additional metadata in BPF Type Format (aka BTF).
+
+The library aims to be compatible with libbpf so that moving from a C toolchain
+to a Go one creates little friction. To that end, the [ELF reader](elf_reader.go)
+is tested against the Linux selftests and avoids introducing custom behaviour
+if possible.
+
+The output of the ELF reader is a `CollectionSpec` which encodes
+all of the information contained in the ELF in a form that is easy to work with
+in Go.
+
+### BTF
+
+The BPF Type Format describes more than just the types used by a BPF program. It
+includes debug aids like which source line corresponds to which instructions and
+what global variables are used.
+
+[BTF parsing](internal/btf/) lives in a separate internal package since exposing
+it would mean an additional maintenance burden, and because the API still
+has sharp corners. The most important concept is the `btf.Type` interface, which
+also describes things that aren't really types like `.rodata` or `.bss` sections.
+`btf.Type`s can form cyclical graphs, which can easily lead to infinite loops if
+one is not careful. Hopefully a safe pattern to work with `btf.Type` emerges as
+we write more code that deals with it.
+
+Specifications
+---
+
+`CollectionSpec`, `ProgramSpec` and `MapSpec` are blueprints for in-kernel
+objects and contain everything necessary to execute the relevant `bpf(2)`
+syscalls. Since the ELF reader outputs a `CollectionSpec` it's possible to
+modify clang-compiled BPF code, for example to rewrite constants. At the same
+time the [asm](asm/) package provides an assembler that can be used to generate
+`ProgramSpec` on the fly.
+
+Creating a spec should never require any privileges or be restricted in any way,
+for example by only allowing programs in native endianness. This ensures that
+the library stays flexible.
+
+Objects
+---
+
+`Program` and `Map` are the result of loading specs into the kernel. Sometimes
+loading a spec will fail because the kernel is too old, or a feature is not
+enabled. There are multiple ways the library deals with that:
+
+* Fallback: older kernels don't allowing naming programs and maps. The library
+ automatically detects support for names, and omits them during load if
+ necessary. This works since name is primarily a debug aid.
+
+* Sentinel error: sometimes it's possible to detect that a feature isn't available.
+ In that case the library will return an error wrapping `ErrNotSupported`.
+ This is also useful to skip tests that can't run on the current kernel.
+
+Once program and map objects are loaded they expose the kernel's low-level API,
+e.g. `NextKey`. Often this API is awkward to use in Go, so there are safer
+wrappers on top of the low-level API, like `MapIterator`. The low-level API is
+useful as an out when our higher-level API doesn't support a particular use case.
+
+Links
+---
+
+BPF can be attached to many different points in the kernel and newer BPF hooks
+tend to use bpf_link to do so. Older hooks unfortunately use a combination of
+syscalls, netlink messages, etc. Adding support for a new link type should not
+pull in large dependencies like netlink, so XDP programs or tracepoints are
+out of scope.
diff --git a/vendor/github.com/cilium/ebpf/CODE_OF_CONDUCT.md b/vendor/github.com/cilium/ebpf/CODE_OF_CONDUCT.md
@@ -0,0 +1,46 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at nathanjsweet at gmail dot com or i at lmb dot io. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
+
+[homepage]: http://contributor-covenant.org
+[version]: http://contributor-covenant.org/version/1/4/
diff --git a/vendor/github.com/cilium/ebpf/CONTRIBUTING.md b/vendor/github.com/cilium/ebpf/CONTRIBUTING.md
@@ -0,0 +1,23 @@
+# How to contribute
+
+Development is on [GitHub](https://github.com/cilium/ebpf) and contributions in
+the form of pull requests and issues reporting bugs or suggesting new features
+are welcome. Please take a look at [the architecture](ARCHITECTURE.md) to get
+a better understanding for the high-level goals.
+
+New features must be accompanied by tests. Before starting work on any large
+feature, please [join](https://cilium.herokuapp.com/) the
+[#libbpf-go](https://cilium.slack.com/messages/libbpf-go) channel on Slack to
+discuss the design first.
+
+When submitting pull requests, consider writing details about what problem you
+are solving and why the proposed approach solves that problem in commit messages
+and/or pull request description to help future library users and maintainers to
+reason about the proposed changes.
+
+## Running the tests
+
+Many of the tests require privileges to set resource limits and load eBPF code.
+The easiest way to obtain these is to run the tests with `sudo`:
+
+ sudo go test ./...
+\ No newline at end of file
diff --git a/vendor/github.com/cilium/ebpf/LICENSE b/vendor/github.com/cilium/ebpf/LICENSE
@@ -0,0 +1,23 @@
+MIT License
+
+Copyright (c) 2017 Nathan Sweet
+Copyright (c) 2018, 2019 Cloudflare
+Copyright (c) 2019 Authors of Cilium
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/vendor/github.com/cilium/ebpf/Makefile b/vendor/github.com/cilium/ebpf/Makefile
@@ -0,0 +1,67 @@
+# The development version of clang is distributed as the 'clang' binary,
+# while stable/released versions have a version number attached.
+# Pin the default clang to a stable version.
+CLANG ?= clang-11
+CFLAGS := -target bpf -O2 -g -Wall -Werror $(CFLAGS)
+
+# Obtain an absolute path to the directory of the Makefile.
+# Assume the Makefile is in the root of the repository.
+REPODIR := $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
+UIDGID := $(shell stat -c '%u:%g' ${REPODIR})
+
+IMAGE := $(shell cat ${REPODIR}/testdata/docker/IMAGE)
+VERSION := $(shell cat ${REPODIR}/testdata/docker/VERSION)
+
+# clang <8 doesn't tag relocs properly (STT_NOTYPE)
+# clang 9 is the first version emitting BTF
+TARGETS := \
+ testdata/loader-clang-7 \
+ testdata/loader-clang-9 \
+ testdata/loader-clang-11 \
+ testdata/invalid_map \
+ testdata/raw_tracepoint \
+ testdata/invalid_map_static \
+ testdata/initialized_btf_map \
+ testdata/strings \
+ internal/btf/testdata/relocs
+
+.PHONY: all clean docker-all docker-shell
+
+.DEFAULT_TARGET = docker-all
+
+# Build all ELF binaries using a Dockerized LLVM toolchain.
+docker-all:
+ docker run --rm --user "${UIDGID}" \
+ -v "${REPODIR}":/ebpf -w /ebpf --env MAKEFLAGS \
+ "${IMAGE}:${VERSION}" \
+ make all
+
+# (debug) Drop the user into a shell inside the Docker container as root.
+docker-shell:
+ docker run --rm -ti \
+ -v "${REPODIR}":/ebpf -w /ebpf \
+ "${IMAGE}:${VERSION}"
+
+clean:
+ -$(RM) testdata/*.elf
+ -$(RM) internal/btf/testdata/*.elf
+
+all: $(addsuffix -el.elf,$(TARGETS)) $(addsuffix -eb.elf,$(TARGETS))
+
+testdata/loader-%-el.elf: testdata/loader.c
+ $* $(CFLAGS) -mlittle-endian -c $< -o $@
+
+testdata/loader-%-eb.elf: testdata/loader.c
+ $* $(CFLAGS) -mbig-endian -c $< -o $@
+
+%-el.elf: %.c
+ $(CLANG) $(CFLAGS) -mlittle-endian -c $< -o $@
+
+%-eb.elf : %.c
+ $(CLANG) $(CFLAGS) -mbig-endian -c $< -o $@
+
+# Usage: make VMLINUX=/path/to/vmlinux vmlinux-btf
+.PHONY: vmlinux-btf
+vmlinux-btf: internal/btf/testdata/vmlinux-btf.gz
+internal/btf/testdata/vmlinux-btf.gz: $(VMLINUX)
+ objcopy --dump-section .BTF=/dev/stdout "$<" /dev/null | gzip > "$@"
diff --git a/vendor/github.com/cilium/ebpf/README.md b/vendor/github.com/cilium/ebpf/README.md
@@ -0,0 +1,54 @@
+# eBPF
+
+[![PkgGoDev](https://pkg.go.dev/badge/github.com/cilium/ebpf)](https://pkg.go.dev/github.com/cilium/ebpf)
+
+eBPF is a pure Go library that provides utilities for loading, compiling, and
+debugging eBPF programs. It has minimal external dependencies and is intended to
+be used in long running processes.
+
+* [asm](https://pkg.go.dev/github.com/cilium/ebpf/asm) contains a basic
+ assembler
+* [link](https://pkg.go.dev/github.com/cilium/ebpf/link) allows attaching eBPF
+ to various hooks
+* [perf](https://pkg.go.dev/github.com/cilium/ebpf/perf) allows reading from a
+ `PERF_EVENT_ARRAY`
+* [cmd/bpf2go](https://pkg.go.dev/github.com/cilium/ebpf/cmd/bpf2go) allows
+ embedding eBPF in Go
+
+The library is maintained by [Cloudflare](https://www.cloudflare.com) and
+[Cilium](https://www.cilium.io). Feel free to
+[join](https://cilium.herokuapp.com/) the
+[#libbpf-go](https://cilium.slack.com/messages/libbpf-go) channel on Slack.
+
+## Current status
+
+The package is production ready, but **the API is explicitly unstable right
+now**. Expect to update your code if you want to follow along.
+
+## Requirements
+
+* A version of Go that is [supported by
+ upstream](https://golang.org/doc/devel/release.html#policy)
+* Linux 4.9, 4.19 or 5.4 (versions in-between should work, but are not tested)
+
+## Useful resources
+
+* [eBPF.io](https://ebpf.io) (recommended)
+* [Cilium eBPF documentation](https://docs.cilium.io/en/latest/bpf/#bpf-guide)
+ (recommended)
+* [Linux documentation on
+ BPF](https://www.kernel.org/doc/html/latest/networking/filter.html)
+* [eBPF features by Linux
+ version](https://github.com/iovisor/bcc/blob/master/docs/kernel-versions.md)
+
+## Regenerating Testdata
+
+Run `make` in the root of this repository to rebuild testdata in all
+subpackages. This requires Docker, as it relies on a standardized build
+environment to keep the build output stable.
+
+The toolchain image build files are kept in [testdata/docker/](testdata/docker/).
+
+## License
+
+MIT
diff --git a/vendor/github.com/cilium/ebpf/asm/alu.go b/vendor/github.com/cilium/ebpf/asm/alu.go
@@ -0,0 +1,149 @@
+package asm
+
+//go:generate stringer -output alu_string.go -type=Source,Endianness,ALUOp
+
+// Source of ALU / ALU64 / Branch operations
+//
+// msb lsb
+// +----+-+---+
+// |op |S|cls|
+// +----+-+---+
+type Source uint8
+
+const sourceMask OpCode = 0x08
+
+// Source bitmask
+const (
+ // InvalidSource is returned by getters when invoked
+ // on non ALU / branch OpCodes.
+ InvalidSource Source = 0xff
+ // ImmSource src is from constant
+ ImmSource Source = 0x00
+ // RegSource src is from register
+ RegSource Source = 0x08
+)
+
+// The Endianness of a byte swap instruction.
+type Endianness uint8
+
+const endianMask = sourceMask
+
+// Endian flags
+const (
+ InvalidEndian Endianness = 0xff
+ // Convert to little endian
+ LE Endianness = 0x00
+ // Convert to big endian
+ BE Endianness = 0x08
+)
+
+// ALUOp are ALU / ALU64 operations
+//
+// msb lsb
+// +----+-+---+
+// |OP |s|cls|
+// +----+-+---+
+type ALUOp uint8
+
+const aluMask OpCode = 0xf0
+
+const (
+ // InvalidALUOp is returned by getters when invoked
+ // on non ALU OpCodes
+ InvalidALUOp ALUOp = 0xff
+ // Add - addition
+ Add ALUOp = 0x00
+ // Sub - subtraction
+ Sub ALUOp = 0x10
+ // Mul - multiplication
+ Mul ALUOp = 0x20
+ // Div - division
+ Div ALUOp = 0x30
+ // Or - bitwise or
+ Or ALUOp = 0x40
+ // And - bitwise and
+ And ALUOp = 0x50
+ // LSh - bitwise shift left
+ LSh ALUOp = 0x60
+ // RSh - bitwise shift right
+ RSh ALUOp = 0x70
+ // Neg - sign/unsign signing bit
+ Neg ALUOp = 0x80
+ // Mod - modulo
+ Mod ALUOp = 0x90
+ // Xor - bitwise xor
+ Xor ALUOp = 0xa0
+ // Mov - move value from one place to another
+ Mov ALUOp = 0xb0
+ // ArSh - arithmatic shift
+ ArSh ALUOp = 0xc0
+ // Swap - endian conversions
+ Swap ALUOp = 0xd0
+)
+
+// HostTo converts from host to another endianness.
+func HostTo(endian Endianness, dst Register, size Size) Instruction {
+ var imm int64
+ switch size {
+ case Half:
+ imm = 16
+ case Word:
+ imm = 32
+ case DWord:
+ imm = 64
+ default:
+ return Instruction{OpCode: InvalidOpCode}
+ }
+
+ return Instruction{
+ OpCode: OpCode(ALUClass).SetALUOp(Swap).SetSource(Source(endian)),
+ Dst: dst,
+ Constant: imm,
+ }
+}
+
+// Op returns the OpCode for an ALU operation with a given source.
+func (op ALUOp) Op(source Source) OpCode {
+ return OpCode(ALU64Class).SetALUOp(op).SetSource(source)
+}
+
+// Reg emits `dst (op) src`.
+func (op ALUOp) Reg(dst, src Register) Instruction {
+ return Instruction{
+ OpCode: op.Op(RegSource),
+ Dst: dst,
+ Src: src,
+ }
+}
+
+// Imm emits `dst (op) value`.
+func (op ALUOp) Imm(dst Register, value int32) Instruction {
+ return Instruction{
+ OpCode: op.Op(ImmSource),
+ Dst: dst,
+ Constant: int64(value),
+ }
+}
+
+// Op32 returns the OpCode for a 32-bit ALU operation with a given source.
+func (op ALUOp) Op32(source Source) OpCode {
+ return OpCode(ALUClass).SetALUOp(op).SetSource(source)
+}
+
+// Reg32 emits `dst (op) src`, zeroing the upper 32 bit of dst.
+func (op ALUOp) Reg32(dst, src Register) Instruction {
+ return Instruction{
+ OpCode: op.Op32(RegSource),
+ Dst: dst,
+ Src: src,
+ }
+}
+
+// Imm32 emits `dst (op) value`, zeroing the upper 32 bit of dst.
+func (op ALUOp) Imm32(dst Register, value int32) Instruction {
+ return Instruction{
+ OpCode: op.Op32(ImmSource),
+ Dst: dst,
+ Constant: int64(value),
+ }
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/alu_string.go b/vendor/github.com/cilium/ebpf/asm/alu_string.go
@@ -0,0 +1,107 @@
+// Code generated by "stringer -output alu_string.go -type=Source,Endianness,ALUOp"; DO NOT EDIT.
+
+package asm
+
+import "strconv"
+
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[InvalidSource-255]
+ _ = x[ImmSource-0]
+ _ = x[RegSource-8]
+}
+
+const (
+ _Source_name_0 = "ImmSource"
+ _Source_name_1 = "RegSource"
+ _Source_name_2 = "InvalidSource"
+)
+
+func (i Source) String() string {
+ switch {
+ case i == 0:
+ return _Source_name_0
+ case i == 8:
+ return _Source_name_1
+ case i == 255:
+ return _Source_name_2
+ default:
+ return "Source(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+}
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[InvalidEndian-255]
+ _ = x[LE-0]
+ _ = x[BE-8]
+}
+
+const (
+ _Endianness_name_0 = "LE"
+ _Endianness_name_1 = "BE"
+ _Endianness_name_2 = "InvalidEndian"
+)
+
+func (i Endianness) String() string {
+ switch {
+ case i == 0:
+ return _Endianness_name_0
+ case i == 8:
+ return _Endianness_name_1
+ case i == 255:
+ return _Endianness_name_2
+ default:
+ return "Endianness(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+}
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[InvalidALUOp-255]
+ _ = x[Add-0]
+ _ = x[Sub-16]
+ _ = x[Mul-32]
+ _ = x[Div-48]
+ _ = x[Or-64]
+ _ = x[And-80]
+ _ = x[LSh-96]
+ _ = x[RSh-112]
+ _ = x[Neg-128]
+ _ = x[Mod-144]
+ _ = x[Xor-160]
+ _ = x[Mov-176]
+ _ = x[ArSh-192]
+ _ = x[Swap-208]
+}
+
+const _ALUOp_name = "AddSubMulDivOrAndLShRShNegModXorMovArShSwapInvalidALUOp"
+
+var _ALUOp_map = map[ALUOp]string{
+ 0: _ALUOp_name[0:3],
+ 16: _ALUOp_name[3:6],
+ 32: _ALUOp_name[6:9],
+ 48: _ALUOp_name[9:12],
+ 64: _ALUOp_name[12:14],
+ 80: _ALUOp_name[14:17],
+ 96: _ALUOp_name[17:20],
+ 112: _ALUOp_name[20:23],
+ 128: _ALUOp_name[23:26],
+ 144: _ALUOp_name[26:29],
+ 160: _ALUOp_name[29:32],
+ 176: _ALUOp_name[32:35],
+ 192: _ALUOp_name[35:39],
+ 208: _ALUOp_name[39:43],
+ 255: _ALUOp_name[43:55],
+}
+
+func (i ALUOp) String() string {
+ if str, ok := _ALUOp_map[i]; ok {
+ return str
+ }
+ return "ALUOp(" + strconv.FormatInt(int64(i), 10) + ")"
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/doc.go b/vendor/github.com/cilium/ebpf/asm/doc.go
@@ -0,0 +1,2 @@
+// Package asm is an assembler for eBPF bytecode.
+package asm
diff --git a/vendor/github.com/cilium/ebpf/asm/func.go b/vendor/github.com/cilium/ebpf/asm/func.go
@@ -0,0 +1,143 @@
+package asm
+
+//go:generate stringer -output func_string.go -type=BuiltinFunc
+
+// BuiltinFunc is a built-in eBPF function.
+type BuiltinFunc int32
+
+// eBPF built-in functions
+//
+// You can renegerate this list using the following gawk script:
+//
+// /FN\(.+\),/ {
+// match($1, /\((.+)\)/, r)
+// split(r[1], p, "_")
+// printf "Fn"
+// for (i in p) {
+// printf "%s%s", toupper(substr(p[i], 1, 1)), substr(p[i], 2)
+// }
+// print ""
+// }
+//
+// The script expects include/uapi/linux/bpf.h as it's input.
+const (
+ FnUnspec BuiltinFunc = iota
+ FnMapLookupElem
+ FnMapUpdateElem
+ FnMapDeleteElem
+ FnProbeRead
+ FnKtimeGetNs
+ FnTracePrintk
+ FnGetPrandomU32
+ FnGetSmpProcessorId
+ FnSkbStoreBytes
+ FnL3CsumReplace
+ FnL4CsumReplace
+ FnTailCall
+ FnCloneRedirect
+ FnGetCurrentPidTgid
+ FnGetCurrentUidGid
+ FnGetCurrentComm
+ FnGetCgroupClassid
+ FnSkbVlanPush
+ FnSkbVlanPop
+ FnSkbGetTunnelKey
+ FnSkbSetTunnelKey
+ FnPerfEventRead
+ FnRedirect
+ FnGetRouteRealm
+ FnPerfEventOutput
+ FnSkbLoadBytes
+ FnGetStackid
+ FnCsumDiff
+ FnSkbGetTunnelOpt
+ FnSkbSetTunnelOpt
+ FnSkbChangeProto
+ FnSkbChangeType
+ FnSkbUnderCgroup
+ FnGetHashRecalc
+ FnGetCurrentTask
+ FnProbeWriteUser
+ FnCurrentTaskUnderCgroup
+ FnSkbChangeTail
+ FnSkbPullData
+ FnCsumUpdate
+ FnSetHashInvalid
+ FnGetNumaNodeId
+ FnSkbChangeHead
+ FnXdpAdjustHead
+ FnProbeReadStr
+ FnGetSocketCookie
+ FnGetSocketUid
+ FnSetHash
+ FnSetsockopt
+ FnSkbAdjustRoom
+ FnRedirectMap
+ FnSkRedirectMap
+ FnSockMapUpdate
+ FnXdpAdjustMeta
+ FnPerfEventReadValue
+ FnPerfProgReadValue
+ FnGetsockopt
+ FnOverrideReturn
+ FnSockOpsCbFlagsSet
+ FnMsgRedirectMap
+ FnMsgApplyBytes
+ FnMsgCorkBytes
+ FnMsgPullData
+ FnBind
+ FnXdpAdjustTail
+ FnSkbGetXfrmState
+ FnGetStack
+ FnSkbLoadBytesRelative
+ FnFibLookup
+ FnSockHashUpdate
+ FnMsgRedirectHash
+ FnSkRedirectHash
+ FnLwtPushEncap
+ FnLwtSeg6StoreBytes
+ FnLwtSeg6AdjustSrh
+ FnLwtSeg6Action
+ FnRcRepeat
+ FnRcKeydown
+ FnSkbCgroupId
+ FnGetCurrentCgroupId
+ FnGetLocalStorage
+ FnSkSelectReuseport
+ FnSkbAncestorCgroupId
+ FnSkLookupTcp
+ FnSkLookupUdp
+ FnSkRelease
+ FnMapPushElem
+ FnMapPopElem
+ FnMapPeekElem
+ FnMsgPushData
+ FnMsgPopData
+ FnRcPointerRel
+ FnSpinLock
+ FnSpinUnlock
+ FnSkFullsock
+ FnTcpSock
+ FnSkbEcnSetCe
+ FnGetListenerSock
+ FnSkcLookupTcp
+ FnTcpCheckSyncookie
+ FnSysctlGetName
+ FnSysctlGetCurrentValue
+ FnSysctlGetNewValue
+ FnSysctlSetNewValue
+ FnStrtol
+ FnStrtoul
+ FnSkStorageGet
+ FnSkStorageDelete
+ FnSendSignal
+ FnTcpGenSyncookie
+)
+
+// Call emits a function call.
+func (fn BuiltinFunc) Call() Instruction {
+ return Instruction{
+ OpCode: OpCode(JumpClass).SetJumpOp(Call),
+ Constant: int64(fn),
+ }
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/func_string.go b/vendor/github.com/cilium/ebpf/asm/func_string.go
@@ -0,0 +1,133 @@
+// Code generated by "stringer -output func_string.go -type=BuiltinFunc"; DO NOT EDIT.
+
+package asm
+
+import "strconv"
+
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[FnUnspec-0]
+ _ = x[FnMapLookupElem-1]
+ _ = x[FnMapUpdateElem-2]
+ _ = x[FnMapDeleteElem-3]
+ _ = x[FnProbeRead-4]
+ _ = x[FnKtimeGetNs-5]
+ _ = x[FnTracePrintk-6]
+ _ = x[FnGetPrandomU32-7]
+ _ = x[FnGetSmpProcessorId-8]
+ _ = x[FnSkbStoreBytes-9]
+ _ = x[FnL3CsumReplace-10]
+ _ = x[FnL4CsumReplace-11]
+ _ = x[FnTailCall-12]
+ _ = x[FnCloneRedirect-13]
+ _ = x[FnGetCurrentPidTgid-14]
+ _ = x[FnGetCurrentUidGid-15]
+ _ = x[FnGetCurrentComm-16]
+ _ = x[FnGetCgroupClassid-17]
+ _ = x[FnSkbVlanPush-18]
+ _ = x[FnSkbVlanPop-19]
+ _ = x[FnSkbGetTunnelKey-20]
+ _ = x[FnSkbSetTunnelKey-21]
+ _ = x[FnPerfEventRead-22]
+ _ = x[FnRedirect-23]
+ _ = x[FnGetRouteRealm-24]
+ _ = x[FnPerfEventOutput-25]
+ _ = x[FnSkbLoadBytes-26]
+ _ = x[FnGetStackid-27]
+ _ = x[FnCsumDiff-28]
+ _ = x[FnSkbGetTunnelOpt-29]
+ _ = x[FnSkbSetTunnelOpt-30]
+ _ = x[FnSkbChangeProto-31]
+ _ = x[FnSkbChangeType-32]
+ _ = x[FnSkbUnderCgroup-33]
+ _ = x[FnGetHashRecalc-34]
+ _ = x[FnGetCurrentTask-35]
+ _ = x[FnProbeWriteUser-36]
+ _ = x[FnCurrentTaskUnderCgroup-37]
+ _ = x[FnSkbChangeTail-38]
+ _ = x[FnSkbPullData-39]
+ _ = x[FnCsumUpdate-40]
+ _ = x[FnSetHashInvalid-41]
+ _ = x[FnGetNumaNodeId-42]
+ _ = x[FnSkbChangeHead-43]
+ _ = x[FnXdpAdjustHead-44]
+ _ = x[FnProbeReadStr-45]
+ _ = x[FnGetSocketCookie-46]
+ _ = x[FnGetSocketUid-47]
+ _ = x[FnSetHash-48]
+ _ = x[FnSetsockopt-49]
+ _ = x[FnSkbAdjustRoom-50]
+ _ = x[FnRedirectMap-51]
+ _ = x[FnSkRedirectMap-52]
+ _ = x[FnSockMapUpdate-53]
+ _ = x[FnXdpAdjustMeta-54]
+ _ = x[FnPerfEventReadValue-55]
+ _ = x[FnPerfProgReadValue-56]
+ _ = x[FnGetsockopt-57]
+ _ = x[FnOverrideReturn-58]
+ _ = x[FnSockOpsCbFlagsSet-59]
+ _ = x[FnMsgRedirectMap-60]
+ _ = x[FnMsgApplyBytes-61]
+ _ = x[FnMsgCorkBytes-62]
+ _ = x[FnMsgPullData-63]
+ _ = x[FnBind-64]
+ _ = x[FnXdpAdjustTail-65]
+ _ = x[FnSkbGetXfrmState-66]
+ _ = x[FnGetStack-67]
+ _ = x[FnSkbLoadBytesRelative-68]
+ _ = x[FnFibLookup-69]
+ _ = x[FnSockHashUpdate-70]
+ _ = x[FnMsgRedirectHash-71]
+ _ = x[FnSkRedirectHash-72]
+ _ = x[FnLwtPushEncap-73]
+ _ = x[FnLwtSeg6StoreBytes-74]
+ _ = x[FnLwtSeg6AdjustSrh-75]
+ _ = x[FnLwtSeg6Action-76]
+ _ = x[FnRcRepeat-77]
+ _ = x[FnRcKeydown-78]
+ _ = x[FnSkbCgroupId-79]
+ _ = x[FnGetCurrentCgroupId-80]
+ _ = x[FnGetLocalStorage-81]
+ _ = x[FnSkSelectReuseport-82]
+ _ = x[FnSkbAncestorCgroupId-83]
+ _ = x[FnSkLookupTcp-84]
+ _ = x[FnSkLookupUdp-85]
+ _ = x[FnSkRelease-86]
+ _ = x[FnMapPushElem-87]
+ _ = x[FnMapPopElem-88]
+ _ = x[FnMapPeekElem-89]
+ _ = x[FnMsgPushData-90]
+ _ = x[FnMsgPopData-91]
+ _ = x[FnRcPointerRel-92]
+ _ = x[FnSpinLock-93]
+ _ = x[FnSpinUnlock-94]
+ _ = x[FnSkFullsock-95]
+ _ = x[FnTcpSock-96]
+ _ = x[FnSkbEcnSetCe-97]
+ _ = x[FnGetListenerSock-98]
+ _ = x[FnSkcLookupTcp-99]
+ _ = x[FnTcpCheckSyncookie-100]
+ _ = x[FnSysctlGetName-101]
+ _ = x[FnSysctlGetCurrentValue-102]
+ _ = x[FnSysctlGetNewValue-103]
+ _ = x[FnSysctlSetNewValue-104]
+ _ = x[FnStrtol-105]
+ _ = x[FnStrtoul-106]
+ _ = x[FnSkStorageGet-107]
+ _ = x[FnSkStorageDelete-108]
+ _ = x[FnSendSignal-109]
+ _ = x[FnTcpGenSyncookie-110]
+}
+
+const _BuiltinFunc_name = "FnUnspecFnMapLookupElemFnMapUpdateElemFnMapDeleteElemFnProbeReadFnKtimeGetNsFnTracePrintkFnGetPrandomU32FnGetSmpProcessorIdFnSkbStoreBytesFnL3CsumReplaceFnL4CsumReplaceFnTailCallFnCloneRedirectFnGetCurrentPidTgidFnGetCurrentUidGidFnGetCurrentCommFnGetCgroupClassidFnSkbVlanPushFnSkbVlanPopFnSkbGetTunnelKeyFnSkbSetTunnelKeyFnPerfEventReadFnRedirectFnGetRouteRealmFnPerfEventOutputFnSkbLoadBytesFnGetStackidFnCsumDiffFnSkbGetTunnelOptFnSkbSetTunnelOptFnSkbChangeProtoFnSkbChangeTypeFnSkbUnderCgroupFnGetHashRecalcFnGetCurrentTaskFnProbeWriteUserFnCurrentTaskUnderCgroupFnSkbChangeTailFnSkbPullDataFnCsumUpdateFnSetHashInvalidFnGetNumaNodeIdFnSkbChangeHeadFnXdpAdjustHeadFnProbeReadStrFnGetSocketCookieFnGetSocketUidFnSetHashFnSetsockoptFnSkbAdjustRoomFnRedirectMapFnSkRedirectMapFnSockMapUpdateFnXdpAdjustMetaFnPerfEventReadValueFnPerfProgReadValueFnGetsockoptFnOverrideReturnFnSockOpsCbFlagsSetFnMsgRedirectMapFnMsgApplyBytesFnMsgCorkBytesFnMsgPullDataFnBindFnXdpAdjustTailFnSkbGetXfrmStateFnGetStackFnSkbLoadBytesRelativeFnFibLookupFnSockHashUpdateFnMsgRedirectHashFnSkRedirectHashFnLwtPushEncapFnLwtSeg6StoreBytesFnLwtSeg6AdjustSrhFnLwtSeg6ActionFnRcRepeatFnRcKeydownFnSkbCgroupIdFnGetCurrentCgroupIdFnGetLocalStorageFnSkSelectReuseportFnSkbAncestorCgroupIdFnSkLookupTcpFnSkLookupUdpFnSkReleaseFnMapPushElemFnMapPopElemFnMapPeekElemFnMsgPushDataFnMsgPopDataFnRcPointerRelFnSpinLockFnSpinUnlockFnSkFullsockFnTcpSockFnSkbEcnSetCeFnGetListenerSockFnSkcLookupTcpFnTcpCheckSyncookieFnSysctlGetNameFnSysctlGetCurrentValueFnSysctlGetNewValueFnSysctlSetNewValueFnStrtolFnStrtoulFnSkStorageGetFnSkStorageDeleteFnSendSignalFnTcpGenSyncookie"
+
+var _BuiltinFunc_index = [...]uint16{0, 8, 23, 38, 53, 64, 76, 89, 104, 123, 138, 153, 168, 178, 193, 212, 230, 246, 264, 277, 289, 306, 323, 338, 348, 363, 380, 394, 406, 416, 433, 450, 466, 481, 497, 512, 528, 544, 568, 583, 596, 608, 624, 639, 654, 669, 683, 700, 714, 723, 735, 750, 763, 778, 793, 808, 828, 847, 859, 875, 894, 910, 925, 939, 952, 958, 973, 990, 1000, 1022, 1033, 1049, 1066, 1082, 1096, 1115, 1133, 1148, 1158, 1169, 1182, 1202, 1219, 1238, 1259, 1272, 1285, 1296, 1309, 1321, 1334, 1347, 1359, 1373, 1383, 1395, 1407, 1416, 1429, 1446, 1460, 1479, 1494, 1517, 1536, 1555, 1563, 1572, 1586, 1603, 1615, 1632}
+
+func (i BuiltinFunc) String() string {
+ if i < 0 || i >= BuiltinFunc(len(_BuiltinFunc_index)-1) {
+ return "BuiltinFunc(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _BuiltinFunc_name[_BuiltinFunc_index[i]:_BuiltinFunc_index[i+1]]
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/instruction.go b/vendor/github.com/cilium/ebpf/asm/instruction.go
@@ -0,0 +1,498 @@
+package asm
+
+import (
+ "crypto/sha1"
+ "encoding/binary"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "strings"
+
+ "github.com/cilium/ebpf/internal/unix"
+)
+
+// InstructionSize is the size of a BPF instruction in bytes
+const InstructionSize = 8
+
+// RawInstructionOffset is an offset in units of raw BPF instructions.
+type RawInstructionOffset uint64
+
+// Bytes returns the offset of an instruction in bytes.
+func (rio RawInstructionOffset) Bytes() uint64 {
+ return uint64(rio) * InstructionSize
+}
+
+// Instruction is a single eBPF instruction.
+type Instruction struct {
+ OpCode OpCode
+ Dst Register
+ Src Register
+ Offset int16
+ Constant int64
+ Reference string
+ Symbol string
+}
+
+// Sym creates a symbol.
+func (ins Instruction) Sym(name string) Instruction {
+ ins.Symbol = name
+ return ins
+}
+
+// Unmarshal decodes a BPF instruction.
+func (ins *Instruction) Unmarshal(r io.Reader, bo binary.ByteOrder) (uint64, error) {
+ var bi bpfInstruction
+ err := binary.Read(r, bo, &bi)
+ if err != nil {
+ return 0, err
+ }
+
+ ins.OpCode = bi.OpCode
+ ins.Offset = bi.Offset
+ ins.Constant = int64(bi.Constant)
+ ins.Dst, ins.Src, err = bi.Registers.Unmarshal(bo)
+ if err != nil {
+ return 0, fmt.Errorf("can't unmarshal registers: %s", err)
+ }
+
+ if !bi.OpCode.isDWordLoad() {
+ return InstructionSize, nil
+ }
+
+ var bi2 bpfInstruction
+ if err := binary.Read(r, bo, &bi2); err != nil {
+ // No Wrap, to avoid io.EOF clash
+ return 0, errors.New("64bit immediate is missing second half")
+ }
+ if bi2.OpCode != 0 || bi2.Offset != 0 || bi2.Registers != 0 {
+ return 0, errors.New("64bit immediate has non-zero fields")
+ }
+ ins.Constant = int64(uint64(uint32(bi2.Constant))<<32 | uint64(uint32(bi.Constant)))
+
+ return 2 * InstructionSize, nil
+}
+
+// Marshal encodes a BPF instruction.
+func (ins Instruction) Marshal(w io.Writer, bo binary.ByteOrder) (uint64, error) {
+ if ins.OpCode == InvalidOpCode {
+ return 0, errors.New("invalid opcode")
+ }
+
+ isDWordLoad := ins.OpCode.isDWordLoad()
+
+ cons := int32(ins.Constant)
+ if isDWordLoad {
+ // Encode least significant 32bit first for 64bit operations.
+ cons = int32(uint32(ins.Constant))
+ }
+
+ regs, err := newBPFRegisters(ins.Dst, ins.Src, bo)
+ if err != nil {
+ return 0, fmt.Errorf("can't marshal registers: %s", err)
+ }
+
+ bpfi := bpfInstruction{
+ ins.OpCode,
+ regs,
+ ins.Offset,
+ cons,
+ }
+
+ if err := binary.Write(w, bo, &bpfi); err != nil {
+ return 0, err
+ }
+
+ if !isDWordLoad {
+ return InstructionSize, nil
+ }
+
+ bpfi = bpfInstruction{
+ Constant: int32(ins.Constant >> 32),
+ }
+
+ if err := binary.Write(w, bo, &bpfi); err != nil {
+ return 0, err
+ }
+
+ return 2 * InstructionSize, nil
+}
+
+// RewriteMapPtr changes an instruction to use a new map fd.
+//
+// Returns an error if the instruction doesn't load a map.
+func (ins *Instruction) RewriteMapPtr(fd int) error {
+ if !ins.OpCode.isDWordLoad() {
+ return fmt.Errorf("%s is not a 64 bit load", ins.OpCode)
+ }
+
+ if ins.Src != PseudoMapFD && ins.Src != PseudoMapValue {
+ return errors.New("not a load from a map")
+ }
+
+ // Preserve the offset value for direct map loads.
+ offset := uint64(ins.Constant) & (math.MaxUint32 << 32)
+ rawFd := uint64(uint32(fd))
+ ins.Constant = int64(offset | rawFd)
+ return nil
+}
+
+func (ins *Instruction) mapPtr() uint32 {
+ return uint32(uint64(ins.Constant) & math.MaxUint32)
+}
+
+// RewriteMapOffset changes the offset of a direct load from a map.
+//
+// Returns an error if the instruction is not a direct load.
+func (ins *Instruction) RewriteMapOffset(offset uint32) error {
+ if !ins.OpCode.isDWordLoad() {
+ return fmt.Errorf("%s is not a 64 bit load", ins.OpCode)
+ }
+
+ if ins.Src != PseudoMapValue {
+ return errors.New("not a direct load from a map")
+ }
+
+ fd := uint64(ins.Constant) & math.MaxUint32
+ ins.Constant = int64(uint64(offset)<<32 | fd)
+ return nil
+}
+
+func (ins *Instruction) mapOffset() uint32 {
+ return uint32(uint64(ins.Constant) >> 32)
+}
+
+// isLoadFromMap returns true if the instruction loads from a map.
+//
+// This covers both loading the map pointer and direct map value loads.
+func (ins *Instruction) isLoadFromMap() bool {
+ return ins.OpCode == LoadImmOp(DWord) && (ins.Src == PseudoMapFD || ins.Src == PseudoMapValue)
+}
+
+// IsFunctionCall returns true if the instruction calls another BPF function.
+//
+// This is not the same thing as a BPF helper call.
+func (ins *Instruction) IsFunctionCall() bool {
+ return ins.OpCode.JumpOp() == Call && ins.Src == PseudoCall
+}
+
+// Format implements fmt.Formatter.
+func (ins Instruction) Format(f fmt.State, c rune) {
+ if c != 'v' {
+ fmt.Fprintf(f, "{UNRECOGNIZED: %c}", c)
+ return
+ }
+
+ op := ins.OpCode
+
+ if op == InvalidOpCode {
+ fmt.Fprint(f, "INVALID")
+ return
+ }
+
+ // Omit trailing space for Exit
+ if op.JumpOp() == Exit {
+ fmt.Fprint(f, op)
+ return
+ }
+
+ if ins.isLoadFromMap() {
+ fd := int32(ins.mapPtr())
+ switch ins.Src {
+ case PseudoMapFD:
+ fmt.Fprintf(f, "LoadMapPtr dst: %s fd: %d", ins.Dst, fd)
+
+ case PseudoMapValue:
+ fmt.Fprintf(f, "LoadMapValue dst: %s, fd: %d off: %d", ins.Dst, fd, ins.mapOffset())
+ }
+
+ goto ref
+ }
+
+ fmt.Fprintf(f, "%v ", op)
+ switch cls := op.Class(); cls {
+ case LdClass, LdXClass, StClass, StXClass:
+ switch op.Mode() {
+ case ImmMode:
+ fmt.Fprintf(f, "dst: %s imm: %d", ins.Dst, ins.Constant)
+ case AbsMode:
+ fmt.Fprintf(f, "imm: %d", ins.Constant)
+ case IndMode:
+ fmt.Fprintf(f, "dst: %s src: %s imm: %d", ins.Dst, ins.Src, ins.Constant)
+ case MemMode:
+ fmt.Fprintf(f, "dst: %s src: %s off: %d imm: %d", ins.Dst, ins.Src, ins.Offset, ins.Constant)
+ case XAddMode:
+ fmt.Fprintf(f, "dst: %s src: %s", ins.Dst, ins.Src)
+ }
+
+ case ALU64Class, ALUClass:
+ fmt.Fprintf(f, "dst: %s ", ins.Dst)
+ if op.ALUOp() == Swap || op.Source() == ImmSource {
+ fmt.Fprintf(f, "imm: %d", ins.Constant)
+ } else {
+ fmt.Fprintf(f, "src: %s", ins.Src)
+ }
+
+ case JumpClass:
+ switch jop := op.JumpOp(); jop {
+ case Call:
+ if ins.Src == PseudoCall {
+ // bpf-to-bpf call
+ fmt.Fprint(f, ins.Constant)
+ } else {
+ fmt.Fprint(f, BuiltinFunc(ins.Constant))
+ }
+
+ default:
+ fmt.Fprintf(f, "dst: %s off: %d ", ins.Dst, ins.Offset)
+ if op.Source() == ImmSource {
+ fmt.Fprintf(f, "imm: %d", ins.Constant)
+ } else {
+ fmt.Fprintf(f, "src: %s", ins.Src)
+ }
+ }
+ }
+
+ref:
+ if ins.Reference != "" {
+ fmt.Fprintf(f, " <%s>", ins.Reference)
+ }
+}
+
+// Instructions is an eBPF program.
+type Instructions []Instruction
+
+func (insns Instructions) String() string {
+ return fmt.Sprint(insns)
+}
+
+// RewriteMapPtr rewrites all loads of a specific map pointer to a new fd.
+//
+// Returns an error if the symbol isn't used, see IsUnreferencedSymbol.
+func (insns Instructions) RewriteMapPtr(symbol string, fd int) error {
+ if symbol == "" {
+ return errors.New("empty symbol")
+ }
+
+ found := false
+ for i := range insns {
+ ins := &insns[i]
+ if ins.Reference != symbol {
+ continue
+ }
+
+ if err := ins.RewriteMapPtr(fd); err != nil {
+ return err
+ }
+
+ found = true
+ }
+
+ if !found {
+ return &unreferencedSymbolError{symbol}
+ }
+
+ return nil
+}
+
+// SymbolOffsets returns the set of symbols and their offset in
+// the instructions.
+func (insns Instructions) SymbolOffsets() (map[string]int, error) {
+ offsets := make(map[string]int)
+
+ for i, ins := range insns {
+ if ins.Symbol == "" {
+ continue
+ }
+
+ if _, ok := offsets[ins.Symbol]; ok {
+ return nil, fmt.Errorf("duplicate symbol %s", ins.Symbol)
+ }
+
+ offsets[ins.Symbol] = i
+ }
+
+ return offsets, nil
+}
+
+// ReferenceOffsets returns the set of references and their offset in
+// the instructions.
+func (insns Instructions) ReferenceOffsets() map[string][]int {
+ offsets := make(map[string][]int)
+
+ for i, ins := range insns {
+ if ins.Reference == "" {
+ continue
+ }
+
+ offsets[ins.Reference] = append(offsets[ins.Reference], i)
+ }
+
+ return offsets
+}
+
+// Format implements fmt.Formatter.
+//
+// You can control indentation of symbols by
+// specifying a width. Setting a precision controls the indentation of
+// instructions.
+// The default character is a tab, which can be overriden by specifying
+// the ' ' space flag.
+func (insns Instructions) Format(f fmt.State, c rune) {
+ if c != 's' && c != 'v' {
+ fmt.Fprintf(f, "{UNKNOWN FORMAT '%c'}", c)
+ return
+ }
+
+ // Precision is better in this case, because it allows
+ // specifying 0 padding easily.
+ padding, ok := f.Precision()
+ if !ok {
+ padding = 1
+ }
+
+ indent := strings.Repeat("\t", padding)
+ if f.Flag(' ') {
+ indent = strings.Repeat(" ", padding)
+ }
+
+ symPadding, ok := f.Width()
+ if !ok {
+ symPadding = padding - 1
+ }
+ if symPadding < 0 {
+ symPadding = 0
+ }
+
+ symIndent := strings.Repeat("\t", symPadding)
+ if f.Flag(' ') {
+ symIndent = strings.Repeat(" ", symPadding)
+ }
+
+ // Guess how many digits we need at most, by assuming that all instructions
+ // are double wide.
+ highestOffset := len(insns) * 2
+ offsetWidth := int(math.Ceil(math.Log10(float64(highestOffset))))
+
+ iter := insns.Iterate()
+ for iter.Next() {
+ if iter.Ins.Symbol != "" {
+ fmt.Fprintf(f, "%s%s:\n", symIndent, iter.Ins.Symbol)
+ }
+ fmt.Fprintf(f, "%s%*d: %v\n", indent, offsetWidth, iter.Offset, iter.Ins)
+ }
+
+ return
+}
+
+// Marshal encodes a BPF program into the kernel format.
+func (insns Instructions) Marshal(w io.Writer, bo binary.ByteOrder) error {
+ for i, ins := range insns {
+ _, err := ins.Marshal(w, bo)
+ if err != nil {
+ return fmt.Errorf("instruction %d: %w", i, err)
+ }
+ }
+ return nil
+}
+
+// Tag calculates the kernel tag for a series of instructions.
+//
+// It mirrors bpf_prog_calc_tag in the kernel and so can be compared
+// to ProgramInfo.Tag to figure out whether a loaded program matches
+// certain instructions.
+func (insns Instructions) Tag(bo binary.ByteOrder) (string, error) {
+ h := sha1.New()
+ for i, ins := range insns {
+ if ins.isLoadFromMap() {
+ ins.Constant = 0
+ }
+ _, err := ins.Marshal(h, bo)
+ if err != nil {
+ return "", fmt.Errorf("instruction %d: %w", i, err)
+ }
+ }
+ return hex.EncodeToString(h.Sum(nil)[:unix.BPF_TAG_SIZE]), nil
+}
+
+// Iterate allows iterating a BPF program while keeping track of
+// various offsets.
+//
+// Modifying the instruction slice will lead to undefined behaviour.
+func (insns Instructions) Iterate() *InstructionIterator {
+ return &InstructionIterator{insns: insns}
+}
+
+// InstructionIterator iterates over a BPF program.
+type InstructionIterator struct {
+ insns Instructions
+ // The instruction in question.
+ Ins *Instruction
+ // The index of the instruction in the original instruction slice.
+ Index int
+ // The offset of the instruction in raw BPF instructions. This accounts
+ // for double-wide instructions.
+ Offset RawInstructionOffset
+}
+
+// Next returns true as long as there are any instructions remaining.
+func (iter *InstructionIterator) Next() bool {
+ if len(iter.insns) == 0 {
+ return false
+ }
+
+ if iter.Ins != nil {
+ iter.Index++
+ iter.Offset += RawInstructionOffset(iter.Ins.OpCode.rawInstructions())
+ }
+ iter.Ins = &iter.insns[0]
+ iter.insns = iter.insns[1:]
+ return true
+}
+
+type bpfInstruction struct {
+ OpCode OpCode
+ Registers bpfRegisters
+ Offset int16
+ Constant int32
+}
+
+type bpfRegisters uint8
+
+func newBPFRegisters(dst, src Register, bo binary.ByteOrder) (bpfRegisters, error) {
+ switch bo {
+ case binary.LittleEndian:
+ return bpfRegisters((src << 4) | (dst & 0xF)), nil
+ case binary.BigEndian:
+ return bpfRegisters((dst << 4) | (src & 0xF)), nil
+ default:
+ return 0, fmt.Errorf("unrecognized ByteOrder %T", bo)
+ }
+}
+
+func (r bpfRegisters) Unmarshal(bo binary.ByteOrder) (dst, src Register, err error) {
+ switch bo {
+ case binary.LittleEndian:
+ return Register(r & 0xF), Register(r >> 4), nil
+ case binary.BigEndian:
+ return Register(r >> 4), Register(r & 0xf), nil
+ default:
+ return 0, 0, fmt.Errorf("unrecognized ByteOrder %T", bo)
+ }
+}
+
+type unreferencedSymbolError struct {
+ symbol string
+}
+
+func (use *unreferencedSymbolError) Error() string {
+ return fmt.Sprintf("unreferenced symbol %s", use.symbol)
+}
+
+// IsUnreferencedSymbol returns true if err was caused by
+// an unreferenced symbol.
+func IsUnreferencedSymbol(err error) bool {
+ _, ok := err.(*unreferencedSymbolError)
+ return ok
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/jump.go b/vendor/github.com/cilium/ebpf/asm/jump.go
@@ -0,0 +1,109 @@
+package asm
+
+//go:generate stringer -output jump_string.go -type=JumpOp
+
+// JumpOp affect control flow.
+//
+// msb lsb
+// +----+-+---+
+// |OP |s|cls|
+// +----+-+---+
+type JumpOp uint8
+
+const jumpMask OpCode = aluMask
+
+const (
+ // InvalidJumpOp is returned by getters when invoked
+ // on non branch OpCodes
+ InvalidJumpOp JumpOp = 0xff
+ // Ja jumps by offset unconditionally
+ Ja JumpOp = 0x00
+ // JEq jumps by offset if r == imm
+ JEq JumpOp = 0x10
+ // JGT jumps by offset if r > imm
+ JGT JumpOp = 0x20
+ // JGE jumps by offset if r >= imm
+ JGE JumpOp = 0x30
+ // JSet jumps by offset if r & imm
+ JSet JumpOp = 0x40
+ // JNE jumps by offset if r != imm
+ JNE JumpOp = 0x50
+ // JSGT jumps by offset if signed r > signed imm
+ JSGT JumpOp = 0x60
+ // JSGE jumps by offset if signed r >= signed imm
+ JSGE JumpOp = 0x70
+ // Call builtin or user defined function from imm
+ Call JumpOp = 0x80
+ // Exit ends execution, with value in r0
+ Exit JumpOp = 0x90
+ // JLT jumps by offset if r < imm
+ JLT JumpOp = 0xa0
+ // JLE jumps by offset if r <= imm
+ JLE JumpOp = 0xb0
+ // JSLT jumps by offset if signed r < signed imm
+ JSLT JumpOp = 0xc0
+ // JSLE jumps by offset if signed r <= signed imm
+ JSLE JumpOp = 0xd0
+)
+
+// Return emits an exit instruction.
+//
+// Requires a return value in R0.
+func Return() Instruction {
+ return Instruction{
+ OpCode: OpCode(JumpClass).SetJumpOp(Exit),
+ }
+}
+
+// Op returns the OpCode for a given jump source.
+func (op JumpOp) Op(source Source) OpCode {
+ return OpCode(JumpClass).SetJumpOp(op).SetSource(source)
+}
+
+// Imm compares dst to value, and adjusts PC by offset if the condition is fulfilled.
+func (op JumpOp) Imm(dst Register, value int32, label string) Instruction {
+ if op == Exit || op == Call || op == Ja {
+ return Instruction{OpCode: InvalidOpCode}
+ }
+
+ return Instruction{
+ OpCode: OpCode(JumpClass).SetJumpOp(op).SetSource(ImmSource),
+ Dst: dst,
+ Offset: -1,
+ Constant: int64(value),
+ Reference: label,
+ }
+}
+
+// Reg compares dst to src, and adjusts PC by offset if the condition is fulfilled.
+func (op JumpOp) Reg(dst, src Register, label string) Instruction {
+ if op == Exit || op == Call || op == Ja {
+ return Instruction{OpCode: InvalidOpCode}
+ }
+
+ return Instruction{
+ OpCode: OpCode(JumpClass).SetJumpOp(op).SetSource(RegSource),
+ Dst: dst,
+ Src: src,
+ Offset: -1,
+ Reference: label,
+ }
+}
+
+// Label adjusts PC to the address of the label.
+func (op JumpOp) Label(label string) Instruction {
+ if op == Call {
+ return Instruction{
+ OpCode: OpCode(JumpClass).SetJumpOp(Call),
+ Src: PseudoCall,
+ Constant: -1,
+ Reference: label,
+ }
+ }
+
+ return Instruction{
+ OpCode: OpCode(JumpClass).SetJumpOp(op),
+ Offset: -1,
+ Reference: label,
+ }
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/jump_string.go b/vendor/github.com/cilium/ebpf/asm/jump_string.go
@@ -0,0 +1,53 @@
+// Code generated by "stringer -output jump_string.go -type=JumpOp"; DO NOT EDIT.
+
+package asm
+
+import "strconv"
+
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[InvalidJumpOp-255]
+ _ = x[Ja-0]
+ _ = x[JEq-16]
+ _ = x[JGT-32]
+ _ = x[JGE-48]
+ _ = x[JSet-64]
+ _ = x[JNE-80]
+ _ = x[JSGT-96]
+ _ = x[JSGE-112]
+ _ = x[Call-128]
+ _ = x[Exit-144]
+ _ = x[JLT-160]
+ _ = x[JLE-176]
+ _ = x[JSLT-192]
+ _ = x[JSLE-208]
+}
+
+const _JumpOp_name = "JaJEqJGTJGEJSetJNEJSGTJSGECallExitJLTJLEJSLTJSLEInvalidJumpOp"
+
+var _JumpOp_map = map[JumpOp]string{
+ 0: _JumpOp_name[0:2],
+ 16: _JumpOp_name[2:5],
+ 32: _JumpOp_name[5:8],
+ 48: _JumpOp_name[8:11],
+ 64: _JumpOp_name[11:15],
+ 80: _JumpOp_name[15:18],
+ 96: _JumpOp_name[18:22],
+ 112: _JumpOp_name[22:26],
+ 128: _JumpOp_name[26:30],
+ 144: _JumpOp_name[30:34],
+ 160: _JumpOp_name[34:37],
+ 176: _JumpOp_name[37:40],
+ 192: _JumpOp_name[40:44],
+ 208: _JumpOp_name[44:48],
+ 255: _JumpOp_name[48:61],
+}
+
+func (i JumpOp) String() string {
+ if str, ok := _JumpOp_map[i]; ok {
+ return str
+ }
+ return "JumpOp(" + strconv.FormatInt(int64(i), 10) + ")"
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/load_store.go b/vendor/github.com/cilium/ebpf/asm/load_store.go
@@ -0,0 +1,204 @@
+package asm
+
+//go:generate stringer -output load_store_string.go -type=Mode,Size
+
+// Mode for load and store operations
+//
+// msb lsb
+// +---+--+---+
+// |MDE|sz|cls|
+// +---+--+---+
+type Mode uint8
+
+const modeMask OpCode = 0xe0
+
+const (
+ // InvalidMode is returned by getters when invoked
+ // on non load / store OpCodes
+ InvalidMode Mode = 0xff
+ // ImmMode - immediate value
+ ImmMode Mode = 0x00
+ // AbsMode - immediate value + offset
+ AbsMode Mode = 0x20
+ // IndMode - indirect (imm+src)
+ IndMode Mode = 0x40
+ // MemMode - load from memory
+ MemMode Mode = 0x60
+ // XAddMode - add atomically across processors.
+ XAddMode Mode = 0xc0
+)
+
+// Size of load and store operations
+//
+// msb lsb
+// +---+--+---+
+// |mde|SZ|cls|
+// +---+--+---+
+type Size uint8
+
+const sizeMask OpCode = 0x18
+
+const (
+ // InvalidSize is returned by getters when invoked
+ // on non load / store OpCodes
+ InvalidSize Size = 0xff
+ // DWord - double word; 64 bits
+ DWord Size = 0x18
+ // Word - word; 32 bits
+ Word Size = 0x00
+ // Half - half-word; 16 bits
+ Half Size = 0x08
+ // Byte - byte; 8 bits
+ Byte Size = 0x10
+)
+
+// Sizeof returns the size in bytes.
+func (s Size) Sizeof() int {
+ switch s {
+ case DWord:
+ return 8
+ case Word:
+ return 4
+ case Half:
+ return 2
+ case Byte:
+ return 1
+ default:
+ return -1
+ }
+}
+
+// LoadMemOp returns the OpCode to load a value of given size from memory.
+func LoadMemOp(size Size) OpCode {
+ return OpCode(LdXClass).SetMode(MemMode).SetSize(size)
+}
+
+// LoadMem emits `dst = *(size *)(src + offset)`.
+func LoadMem(dst, src Register, offset int16, size Size) Instruction {
+ return Instruction{
+ OpCode: LoadMemOp(size),
+ Dst: dst,
+ Src: src,
+ Offset: offset,
+ }
+}
+
+// LoadImmOp returns the OpCode to load an immediate of given size.
+//
+// As of kernel 4.20, only DWord size is accepted.
+func LoadImmOp(size Size) OpCode {
+ return OpCode(LdClass).SetMode(ImmMode).SetSize(size)
+}
+
+// LoadImm emits `dst = (size)value`.
+//
+// As of kernel 4.20, only DWord size is accepted.
+func LoadImm(dst Register, value int64, size Size) Instruction {
+ return Instruction{
+ OpCode: LoadImmOp(size),
+ Dst: dst,
+ Constant: value,
+ }
+}
+
+// LoadMapPtr stores a pointer to a map in dst.
+func LoadMapPtr(dst Register, fd int) Instruction {
+ if fd < 0 {
+ return Instruction{OpCode: InvalidOpCode}
+ }
+
+ return Instruction{
+ OpCode: LoadImmOp(DWord),
+ Dst: dst,
+ Src: PseudoMapFD,
+ Constant: int64(fd),
+ }
+}
+
+// LoadMapValue stores a pointer to the value at a certain offset of a map.
+func LoadMapValue(dst Register, fd int, offset uint32) Instruction {
+ if fd < 0 {
+ return Instruction{OpCode: InvalidOpCode}
+ }
+
+ fdAndOffset := (uint64(offset) << 32) | uint64(uint32(fd))
+ return Instruction{
+ OpCode: LoadImmOp(DWord),
+ Dst: dst,
+ Src: PseudoMapValue,
+ Constant: int64(fdAndOffset),
+ }
+}
+
+// LoadIndOp returns the OpCode for loading a value of given size from an sk_buff.
+func LoadIndOp(size Size) OpCode {
+ return OpCode(LdClass).SetMode(IndMode).SetSize(size)
+}
+
+// LoadInd emits `dst = ntoh(*(size *)(((sk_buff *)R6)->data + src + offset))`.
+func LoadInd(dst, src Register, offset int32, size Size) Instruction {
+ return Instruction{
+ OpCode: LoadIndOp(size),
+ Dst: dst,
+ Src: src,
+ Constant: int64(offset),
+ }
+}
+
+// LoadAbsOp returns the OpCode for loading a value of given size from an sk_buff.
+func LoadAbsOp(size Size) OpCode {
+ return OpCode(LdClass).SetMode(AbsMode).SetSize(size)
+}
+
+// LoadAbs emits `r0 = ntoh(*(size *)(((sk_buff *)R6)->data + offset))`.
+func LoadAbs(offset int32, size Size) Instruction {
+ return Instruction{
+ OpCode: LoadAbsOp(size),
+ Dst: R0,
+ Constant: int64(offset),
+ }
+}
+
+// StoreMemOp returns the OpCode for storing a register of given size in memory.
+func StoreMemOp(size Size) OpCode {
+ return OpCode(StXClass).SetMode(MemMode).SetSize(size)
+}
+
+// StoreMem emits `*(size *)(dst + offset) = src`
+func StoreMem(dst Register, offset int16, src Register, size Size) Instruction {
+ return Instruction{
+ OpCode: StoreMemOp(size),
+ Dst: dst,
+ Src: src,
+ Offset: offset,
+ }
+}
+
+// StoreImmOp returns the OpCode for storing an immediate of given size in memory.
+func StoreImmOp(size Size) OpCode {
+ return OpCode(StClass).SetMode(MemMode).SetSize(size)
+}
+
+// StoreImm emits `*(size *)(dst + offset) = value`.
+func StoreImm(dst Register, offset int16, value int64, size Size) Instruction {
+ return Instruction{
+ OpCode: StoreImmOp(size),
+ Dst: dst,
+ Offset: offset,
+ Constant: value,
+ }
+}
+
+// StoreXAddOp returns the OpCode to atomically add a register to a value in memory.
+func StoreXAddOp(size Size) OpCode {
+ return OpCode(StXClass).SetMode(XAddMode).SetSize(size)
+}
+
+// StoreXAdd atomically adds src to *dst.
+func StoreXAdd(dst, src Register, size Size) Instruction {
+ return Instruction{
+ OpCode: StoreXAddOp(size),
+ Dst: dst,
+ Src: src,
+ }
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/load_store_string.go b/vendor/github.com/cilium/ebpf/asm/load_store_string.go
@@ -0,0 +1,80 @@
+// Code generated by "stringer -output load_store_string.go -type=Mode,Size"; DO NOT EDIT.
+
+package asm
+
+import "strconv"
+
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[InvalidMode-255]
+ _ = x[ImmMode-0]
+ _ = x[AbsMode-32]
+ _ = x[IndMode-64]
+ _ = x[MemMode-96]
+ _ = x[XAddMode-192]
+}
+
+const (
+ _Mode_name_0 = "ImmMode"
+ _Mode_name_1 = "AbsMode"
+ _Mode_name_2 = "IndMode"
+ _Mode_name_3 = "MemMode"
+ _Mode_name_4 = "XAddMode"
+ _Mode_name_5 = "InvalidMode"
+)
+
+func (i Mode) String() string {
+ switch {
+ case i == 0:
+ return _Mode_name_0
+ case i == 32:
+ return _Mode_name_1
+ case i == 64:
+ return _Mode_name_2
+ case i == 96:
+ return _Mode_name_3
+ case i == 192:
+ return _Mode_name_4
+ case i == 255:
+ return _Mode_name_5
+ default:
+ return "Mode(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+}
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[InvalidSize-255]
+ _ = x[DWord-24]
+ _ = x[Word-0]
+ _ = x[Half-8]
+ _ = x[Byte-16]
+}
+
+const (
+ _Size_name_0 = "Word"
+ _Size_name_1 = "Half"
+ _Size_name_2 = "Byte"
+ _Size_name_3 = "DWord"
+ _Size_name_4 = "InvalidSize"
+)
+
+func (i Size) String() string {
+ switch {
+ case i == 0:
+ return _Size_name_0
+ case i == 8:
+ return _Size_name_1
+ case i == 16:
+ return _Size_name_2
+ case i == 24:
+ return _Size_name_3
+ case i == 255:
+ return _Size_name_4
+ default:
+ return "Size(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/opcode.go b/vendor/github.com/cilium/ebpf/asm/opcode.go
@@ -0,0 +1,237 @@
+package asm
+
+import (
+ "fmt"
+ "strings"
+)
+
+//go:generate stringer -output opcode_string.go -type=Class
+
+type encoding int
+
+const (
+ unknownEncoding encoding = iota
+ loadOrStore
+ jumpOrALU
+)
+
+// Class of operations
+//
+// msb lsb
+// +---+--+---+
+// | ?? |CLS|
+// +---+--+---+
+type Class uint8
+
+const classMask OpCode = 0x07
+
+const (
+ // LdClass load memory
+ LdClass Class = 0x00
+ // LdXClass load memory from constant
+ LdXClass Class = 0x01
+ // StClass load register from memory
+ StClass Class = 0x02
+ // StXClass load register from constant
+ StXClass Class = 0x03
+ // ALUClass arithmetic operators
+ ALUClass Class = 0x04
+ // JumpClass jump operators
+ JumpClass Class = 0x05
+ // ALU64Class arithmetic in 64 bit mode
+ ALU64Class Class = 0x07
+)
+
+func (cls Class) encoding() encoding {
+ switch cls {
+ case LdClass, LdXClass, StClass, StXClass:
+ return loadOrStore
+ case ALU64Class, ALUClass, JumpClass:
+ return jumpOrALU
+ default:
+ return unknownEncoding
+ }
+}
+
+// OpCode is a packed eBPF opcode.
+//
+// Its encoding is defined by a Class value:
+//
+// msb lsb
+// +----+-+---+
+// | ???? |CLS|
+// +----+-+---+
+type OpCode uint8
+
+// InvalidOpCode is returned by setters on OpCode
+const InvalidOpCode OpCode = 0xff
+
+// rawInstructions returns the number of BPF instructions required
+// to encode this opcode.
+func (op OpCode) rawInstructions() int {
+ if op.isDWordLoad() {
+ return 2
+ }
+ return 1
+}
+
+func (op OpCode) isDWordLoad() bool {
+ return op == LoadImmOp(DWord)
+}
+
+// Class returns the class of operation.
+func (op OpCode) Class() Class {
+ return Class(op & classMask)
+}
+
+// Mode returns the mode for load and store operations.
+func (op OpCode) Mode() Mode {
+ if op.Class().encoding() != loadOrStore {
+ return InvalidMode
+ }
+ return Mode(op & modeMask)
+}
+
+// Size returns the size for load and store operations.
+func (op OpCode) Size() Size {
+ if op.Class().encoding() != loadOrStore {
+ return InvalidSize
+ }
+ return Size(op & sizeMask)
+}
+
+// Source returns the source for branch and ALU operations.
+func (op OpCode) Source() Source {
+ if op.Class().encoding() != jumpOrALU || op.ALUOp() == Swap {
+ return InvalidSource
+ }
+ return Source(op & sourceMask)
+}
+
+// ALUOp returns the ALUOp.
+func (op OpCode) ALUOp() ALUOp {
+ if op.Class().encoding() != jumpOrALU {
+ return InvalidALUOp
+ }
+ return ALUOp(op & aluMask)
+}
+
+// Endianness returns the Endianness for a byte swap instruction.
+func (op OpCode) Endianness() Endianness {
+ if op.ALUOp() != Swap {
+ return InvalidEndian
+ }
+ return Endianness(op & endianMask)
+}
+
+// JumpOp returns the JumpOp.
+func (op OpCode) JumpOp() JumpOp {
+ if op.Class().encoding() != jumpOrALU {
+ return InvalidJumpOp
+ }
+ return JumpOp(op & jumpMask)
+}
+
+// SetMode sets the mode on load and store operations.
+//
+// Returns InvalidOpCode if op is of the wrong class.
+func (op OpCode) SetMode(mode Mode) OpCode {
+ if op.Class().encoding() != loadOrStore || !valid(OpCode(mode), modeMask) {
+ return InvalidOpCode
+ }
+ return (op & ^modeMask) | OpCode(mode)
+}
+
+// SetSize sets the size on load and store operations.
+//
+// Returns InvalidOpCode if op is of the wrong class.
+func (op OpCode) SetSize(size Size) OpCode {
+ if op.Class().encoding() != loadOrStore || !valid(OpCode(size), sizeMask) {
+ return InvalidOpCode
+ }
+ return (op & ^sizeMask) | OpCode(size)
+}
+
+// SetSource sets the source on jump and ALU operations.
+//
+// Returns InvalidOpCode if op is of the wrong class.
+func (op OpCode) SetSource(source Source) OpCode {
+ if op.Class().encoding() != jumpOrALU || !valid(OpCode(source), sourceMask) {
+ return InvalidOpCode
+ }
+ return (op & ^sourceMask) | OpCode(source)
+}
+
+// SetALUOp sets the ALUOp on ALU operations.
+//
+// Returns InvalidOpCode if op is of the wrong class.
+func (op OpCode) SetALUOp(alu ALUOp) OpCode {
+ class := op.Class()
+ if (class != ALUClass && class != ALU64Class) || !valid(OpCode(alu), aluMask) {
+ return InvalidOpCode
+ }
+ return (op & ^aluMask) | OpCode(alu)
+}
+
+// SetJumpOp sets the JumpOp on jump operations.
+//
+// Returns InvalidOpCode if op is of the wrong class.
+func (op OpCode) SetJumpOp(jump JumpOp) OpCode {
+ if op.Class() != JumpClass || !valid(OpCode(jump), jumpMask) {
+ return InvalidOpCode
+ }
+ return (op & ^jumpMask) | OpCode(jump)
+}
+
+func (op OpCode) String() string {
+ var f strings.Builder
+
+ switch class := op.Class(); class {
+ case LdClass, LdXClass, StClass, StXClass:
+ f.WriteString(strings.TrimSuffix(class.String(), "Class"))
+
+ mode := op.Mode()
+ f.WriteString(strings.TrimSuffix(mode.String(), "Mode"))
+
+ switch op.Size() {
+ case DWord:
+ f.WriteString("DW")
+ case Word:
+ f.WriteString("W")
+ case Half:
+ f.WriteString("H")
+ case Byte:
+ f.WriteString("B")
+ }
+
+ case ALU64Class, ALUClass:
+ f.WriteString(op.ALUOp().String())
+
+ if op.ALUOp() == Swap {
+ // Width for Endian is controlled by Constant
+ f.WriteString(op.Endianness().String())
+ } else {
+ if class == ALUClass {
+ f.WriteString("32")
+ }
+
+ f.WriteString(strings.TrimSuffix(op.Source().String(), "Source"))
+ }
+
+ case JumpClass:
+ f.WriteString(op.JumpOp().String())
+ if jop := op.JumpOp(); jop != Exit && jop != Call {
+ f.WriteString(strings.TrimSuffix(op.Source().String(), "Source"))
+ }
+
+ default:
+ fmt.Fprintf(&f, "OpCode(%#x)", uint8(op))
+ }
+
+ return f.String()
+}
+
+// valid returns true if all bits in value are covered by mask.
+func valid(value, mask OpCode) bool {
+ return value & ^mask == 0
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/opcode_string.go b/vendor/github.com/cilium/ebpf/asm/opcode_string.go
@@ -0,0 +1,38 @@
+// Code generated by "stringer -output opcode_string.go -type=Class"; DO NOT EDIT.
+
+package asm
+
+import "strconv"
+
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[LdClass-0]
+ _ = x[LdXClass-1]
+ _ = x[StClass-2]
+ _ = x[StXClass-3]
+ _ = x[ALUClass-4]
+ _ = x[JumpClass-5]
+ _ = x[ALU64Class-7]
+}
+
+const (
+ _Class_name_0 = "LdClassLdXClassStClassStXClassALUClassJumpClass"
+ _Class_name_1 = "ALU64Class"
+)
+
+var (
+ _Class_index_0 = [...]uint8{0, 7, 15, 22, 30, 38, 47}
+)
+
+func (i Class) String() string {
+ switch {
+ case 0 <= i && i <= 5:
+ return _Class_name_0[_Class_index_0[i]:_Class_index_0[i+1]]
+ case i == 7:
+ return _Class_name_1
+ default:
+ return "Class(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+}
diff --git a/vendor/github.com/cilium/ebpf/asm/register.go b/vendor/github.com/cilium/ebpf/asm/register.go
@@ -0,0 +1,49 @@
+package asm
+
+import (
+ "fmt"
+)
+
+// Register is the source or destination of most operations.
+type Register uint8
+
+// R0 contains return values.
+const R0 Register = 0
+
+// Registers for function arguments.
+const (
+ R1 Register = R0 + 1 + iota
+ R2
+ R3
+ R4
+ R5
+)
+
+// Callee saved registers preserved by function calls.
+const (
+ R6 Register = R5 + 1 + iota
+ R7
+ R8
+ R9
+)
+
+// Read-only frame pointer to access stack.
+const (
+ R10 Register = R9 + 1
+ RFP = R10
+)
+
+// Pseudo registers used by 64bit loads and jumps
+const (
+ PseudoMapFD = R1 // BPF_PSEUDO_MAP_FD
+ PseudoMapValue = R2 // BPF_PSEUDO_MAP_VALUE
+ PseudoCall = R1 // BPF_PSEUDO_CALL
+)
+
+func (r Register) String() string {
+ v := uint8(r)
+ if v == 10 {
+ return "rfp"
+ }
+ return fmt.Sprintf("r%d", v)
+}
diff --git a/vendor/github.com/cilium/ebpf/collection.go b/vendor/github.com/cilium/ebpf/collection.go
@@ -0,0 +1,589 @@
+package ebpf
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "reflect"
+ "strings"
+
+ "github.com/cilium/ebpf/asm"
+ "github.com/cilium/ebpf/internal"
+ "github.com/cilium/ebpf/internal/btf"
+)
+
+// CollectionOptions control loading a collection into the kernel.
+//
+// Maps and Programs are passed to NewMapWithOptions and NewProgramsWithOptions.
+type CollectionOptions struct {
+ Maps MapOptions
+ Programs ProgramOptions
+}
+
+// CollectionSpec describes a collection.
+type CollectionSpec struct {
+ Maps map[string]*MapSpec
+ Programs map[string]*ProgramSpec
+}
+
+// Copy returns a recursive copy of the spec.
+func (cs *CollectionSpec) Copy() *CollectionSpec {
+ if cs == nil {
+ return nil
+ }
+
+ cpy := CollectionSpec{
+ Maps: make(map[string]*MapSpec, len(cs.Maps)),
+ Programs: make(map[string]*ProgramSpec, len(cs.Programs)),
+ }
+
+ for name, spec := range cs.Maps {
+ cpy.Maps[name] = spec.Copy()
+ }
+
+ for name, spec := range cs.Programs {
+ cpy.Programs[name] = spec.Copy()
+ }
+
+ return &cpy
+}
+
+// RewriteMaps replaces all references to specific maps.
+//
+// Use this function to use pre-existing maps instead of creating new ones
+// when calling NewCollection. Any named maps are removed from CollectionSpec.Maps.
+//
+// Returns an error if a named map isn't used in at least one program.
+func (cs *CollectionSpec) RewriteMaps(maps map[string]*Map) error {
+ for symbol, m := range maps {
+ // have we seen a program that uses this symbol / map
+ seen := false
+ fd := m.FD()
+ for progName, progSpec := range cs.Programs {
+ err := progSpec.Instructions.RewriteMapPtr(symbol, fd)
+
+ switch {
+ case err == nil:
+ seen = true
+
+ case asm.IsUnreferencedSymbol(err):
+ // Not all programs need to use the map
+
+ default:
+ return fmt.Errorf("program %s: %w", progName, err)
+ }
+ }
+
+ if !seen {
+ return fmt.Errorf("map %s not referenced by any programs", symbol)
+ }
+
+ // Prevent NewCollection from creating rewritten maps
+ delete(cs.Maps, symbol)
+ }
+
+ return nil
+}
+
+// RewriteConstants replaces the value of multiple constants.
+//
+// The constant must be defined like so in the C program:
+//
+// static volatile const type foobar;
+// static volatile const type foobar = default;
+//
+// Replacement values must be of the same length as the C sizeof(type).
+// If necessary, they are marshalled according to the same rules as
+// map values.
+//
+// From Linux 5.5 the verifier will use constants to eliminate dead code.
+//
+// Returns an error if a constant doesn't exist.
+func (cs *CollectionSpec) RewriteConstants(consts map[string]interface{}) error {
+ rodata := cs.Maps[".rodata"]
+ if rodata == nil {
+ return errors.New("missing .rodata section")
+ }
+
+ if rodata.BTF == nil {
+ return errors.New(".rodata section has no BTF")
+ }
+
+ if n := len(rodata.Contents); n != 1 {
+ return fmt.Errorf("expected one key in .rodata, found %d", n)
+ }
+
+ kv := rodata.Contents[0]
+ value, ok := kv.Value.([]byte)
+ if !ok {
+ return fmt.Errorf("first value in .rodata is %T not []byte", kv.Value)
+ }
+
+ buf := make([]byte, len(value))
+ copy(buf, value)
+
+ err := patchValue(buf, btf.MapValue(rodata.BTF), consts)
+ if err != nil {
+ return err
+ }
+
+ rodata.Contents[0] = MapKV{kv.Key, buf}
+ return nil
+}
+
+// Assign the contents of a CollectionSpec to a struct.
+//
+// This function is a short-cut to manually checking the presence
+// of maps and programs in a collection spec. Consider using bpf2go if this
+// sounds useful.
+//
+// The argument to must be a pointer to a struct. A field of the
+// struct is updated with values from Programs or Maps if it
+// has an `ebpf` tag and its type is *ProgramSpec or *MapSpec.
+// The tag gives the name of the program or map as found in
+// the CollectionSpec.
+//
+// struct {
+// Foo *ebpf.ProgramSpec `ebpf:"xdp_foo"`
+// Bar *ebpf.MapSpec `ebpf:"bar_map"`
+// Ignored int
+// }
+//
+// Returns an error if any of the fields can't be found, or
+// if the same map or program is assigned multiple times.
+func (cs *CollectionSpec) Assign(to interface{}) error {
+ valueOf := func(typ reflect.Type, name string) (reflect.Value, error) {
+ switch typ {
+ case reflect.TypeOf((*ProgramSpec)(nil)):
+ p := cs.Programs[name]
+ if p == nil {
+ return reflect.Value{}, fmt.Errorf("missing program %q", name)
+ }
+ return reflect.ValueOf(p), nil
+ case reflect.TypeOf((*MapSpec)(nil)):
+ m := cs.Maps[name]
+ if m == nil {
+ return reflect.Value{}, fmt.Errorf("missing map %q", name)
+ }
+ return reflect.ValueOf(m), nil
+ default:
+ return reflect.Value{}, fmt.Errorf("unsupported type %s", typ)
+ }
+ }
+
+ return assignValues(to, valueOf)
+}
+
+// LoadAndAssign maps and programs into the kernel and assign them to a struct.
+//
+// This function is a short-cut to manually checking the presence
+// of maps and programs in a collection spec. Consider using bpf2go if this
+// sounds useful.
+//
+// The argument to must be a pointer to a struct. A field of the
+// struct is updated with values from Programs or Maps if it
+// has an `ebpf` tag and its type is *Program or *Map.
+// The tag gives the name of the program or map as found in
+// the CollectionSpec.
+//
+// struct {
+// Foo *ebpf.Program `ebpf:"xdp_foo"`
+// Bar *ebpf.Map `ebpf:"bar_map"`
+// Ignored int
+// }
+//
+// opts may be nil.
+//
+// Returns an error if any of the fields can't be found, or
+// if the same map or program is assigned multiple times.
+func (cs *CollectionSpec) LoadAndAssign(to interface{}, opts *CollectionOptions) error {
+ if opts == nil {
+ opts = &CollectionOptions{}
+ }
+
+ loadMap, loadProgram, done, cleanup := lazyLoadCollection(cs, opts)
+ defer cleanup()
+
+ valueOf := func(typ reflect.Type, name string) (reflect.Value, error) {
+ switch typ {
+ case reflect.TypeOf((*Program)(nil)):
+ p, err := loadProgram(name)
+ if err != nil {
+ return reflect.Value{}, err
+ }
+ return reflect.ValueOf(p), nil
+ case reflect.TypeOf((*Map)(nil)):
+ m, err := loadMap(name)
+ if err != nil {
+ return reflect.Value{}, err
+ }
+ return reflect.ValueOf(m), nil
+ default:
+ return reflect.Value{}, fmt.Errorf("unsupported type %s", typ)
+ }
+ }
+
+ if err := assignValues(to, valueOf); err != nil {
+ return err
+ }
+
+ done()
+ return nil
+}
+
+// Collection is a collection of Programs and Maps associated
+// with their symbols
+type Collection struct {
+ Programs map[string]*Program
+ Maps map[string]*Map
+}
+
+// NewCollection creates a Collection from a specification.
+func NewCollection(spec *CollectionSpec) (*Collection, error) {
+ return NewCollectionWithOptions(spec, CollectionOptions{})
+}
+
+// NewCollectionWithOptions creates a Collection from a specification.
+func NewCollectionWithOptions(spec *CollectionSpec, opts CollectionOptions) (*Collection, error) {
+ loadMap, loadProgram, done, cleanup := lazyLoadCollection(spec, &opts)
+ defer cleanup()
+
+ for mapName := range spec.Maps {
+ _, err := loadMap(mapName)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ for progName := range spec.Programs {
+ _, err := loadProgram(progName)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ maps, progs := done()
+ return &Collection{
+ progs,
+ maps,
+ }, nil
+}
+
+type btfHandleCache map[*btf.Spec]*btf.Handle
+
+func (btfs btfHandleCache) load(spec *btf.Spec) (*btf.Handle, error) {
+ if btfs[spec] != nil {
+ return btfs[spec], nil
+ }
+
+ handle, err := btf.NewHandle(spec)
+ if err != nil {
+ return nil, err
+ }
+
+ btfs[spec] = handle
+ return handle, nil
+}
+
+func (btfs btfHandleCache) close() {
+ for _, handle := range btfs {
+ handle.Close()
+ }
+}
+
+func lazyLoadCollection(coll *CollectionSpec, opts *CollectionOptions) (
+ loadMap func(string) (*Map, error),
+ loadProgram func(string) (*Program, error),
+ done func() (map[string]*Map, map[string]*Program),
+ cleanup func(),
+) {
+ var (
+ maps = make(map[string]*Map)
+ progs = make(map[string]*Program)
+ btfs = make(btfHandleCache)
+ skipMapsAndProgs = false
+ )
+
+ cleanup = func() {
+ btfs.close()
+
+ if skipMapsAndProgs {
+ return
+ }
+
+ for _, m := range maps {
+ m.Close()
+ }
+
+ for _, p := range progs {
+ p.Close()
+ }
+ }
+
+ done = func() (map[string]*Map, map[string]*Program) {
+ skipMapsAndProgs = true
+ return maps, progs
+ }
+
+ loadMap = func(mapName string) (*Map, error) {
+ if m := maps[mapName]; m != nil {
+ return m, nil
+ }
+
+ mapSpec := coll.Maps[mapName]
+ if mapSpec == nil {
+ return nil, fmt.Errorf("missing map %s", mapName)
+ }
+
+ m, err := newMapWithOptions(mapSpec, opts.Maps, btfs)
+ if err != nil {
+ return nil, fmt.Errorf("map %s: %w", mapName, err)
+ }
+
+ maps[mapName] = m
+ return m, nil
+ }
+
+ loadProgram = func(progName string) (*Program, error) {
+ if prog := progs[progName]; prog != nil {
+ return prog, nil
+ }
+
+ progSpec := coll.Programs[progName]
+ if progSpec == nil {
+ return nil, fmt.Errorf("unknown program %s", progName)
+ }
+
+ progSpec = progSpec.Copy()
+
+ // Rewrite any reference to a valid map.
+ for i := range progSpec.Instructions {
+ ins := &progSpec.Instructions[i]
+
+ if ins.OpCode != asm.LoadImmOp(asm.DWord) || ins.Reference == "" {
+ continue
+ }
+
+ if uint32(ins.Constant) != math.MaxUint32 {
+ // Don't overwrite maps already rewritten, users can
+ // rewrite programs in the spec themselves
+ continue
+ }
+
+ m, err := loadMap(ins.Reference)
+ if err != nil {
+ return nil, fmt.Errorf("program %s: %s", progName, err)
+ }
+
+ fd := m.FD()
+ if fd < 0 {
+ return nil, fmt.Errorf("map %s: %w", ins.Reference, internal.ErrClosedFd)
+ }
+ if err := ins.RewriteMapPtr(m.FD()); err != nil {
+ return nil, fmt.Errorf("progam %s: map %s: %w", progName, ins.Reference, err)
+ }
+ }
+
+ prog, err := newProgramWithOptions(progSpec, opts.Programs, btfs)
+ if err != nil {
+ return nil, fmt.Errorf("program %s: %w", progName, err)
+ }
+
+ progs[progName] = prog
+ return prog, nil
+ }
+
+ return
+}
+
+// LoadCollection parses an object file and converts it to a collection.
+func LoadCollection(file string) (*Collection, error) {
+ spec, err := LoadCollectionSpec(file)
+ if err != nil {
+ return nil, err
+ }
+ return NewCollection(spec)
+}
+
+// Close frees all maps and programs associated with the collection.
+//
+// The collection mustn't be used afterwards.
+func (coll *Collection) Close() {
+ for _, prog := range coll.Programs {
+ prog.Close()
+ }
+ for _, m := range coll.Maps {
+ m.Close()
+ }
+}
+
+// DetachMap removes the named map from the Collection.
+//
+// This means that a later call to Close() will not affect this map.
+//
+// Returns nil if no map of that name exists.
+func (coll *Collection) DetachMap(name string) *Map {
+ m := coll.Maps[name]
+ delete(coll.Maps, name)
+ return m
+}
+
+// DetachProgram removes the named program from the Collection.
+//
+// This means that a later call to Close() will not affect this program.
+//
+// Returns nil if no program of that name exists.
+func (coll *Collection) DetachProgram(name string) *Program {
+ p := coll.Programs[name]
+ delete(coll.Programs, name)
+ return p
+}
+
+// Assign the contents of a collection to a struct.
+//
+// Deprecated: use CollectionSpec.Assign instead. It provides the same
+// functionality but creates only the maps and programs requested.
+func (coll *Collection) Assign(to interface{}) error {
+ assignedMaps := make(map[string]struct{})
+ assignedPrograms := make(map[string]struct{})
+ valueOf := func(typ reflect.Type, name string) (reflect.Value, error) {
+ switch typ {
+ case reflect.TypeOf((*Program)(nil)):
+ p := coll.Programs[name]
+ if p == nil {
+ return reflect.Value{}, fmt.Errorf("missing program %q", name)
+ }
+ assignedPrograms[name] = struct{}{}
+ return reflect.ValueOf(p), nil
+ case reflect.TypeOf((*Map)(nil)):
+ m := coll.Maps[name]
+ if m == nil {
+ return reflect.Value{}, fmt.Errorf("missing map %q", name)
+ }
+ assignedMaps[name] = struct{}{}
+ return reflect.ValueOf(m), nil
+ default:
+ return reflect.Value{}, fmt.Errorf("unsupported type %s", typ)
+ }
+ }
+
+ if err := assignValues(to, valueOf); err != nil {
+ return err
+ }
+
+ for name := range assignedPrograms {
+ coll.DetachProgram(name)
+ }
+
+ for name := range assignedMaps {
+ coll.DetachMap(name)
+ }
+
+ return nil
+}
+
+func assignValues(to interface{}, valueOf func(reflect.Type, string) (reflect.Value, error)) error {
+ type structField struct {
+ reflect.StructField
+ value reflect.Value
+ }
+
+ var (
+ fields []structField
+ visitedTypes = make(map[reflect.Type]bool)
+ flattenStruct func(reflect.Value) error
+ )
+
+ flattenStruct = func(structVal reflect.Value) error {
+ structType := structVal.Type()
+ if structType.Kind() != reflect.Struct {
+ return fmt.Errorf("%s is not a struct", structType)
+ }
+
+ if visitedTypes[structType] {
+ return fmt.Errorf("recursion on type %s", structType)
+ }
+
+ for i := 0; i < structType.NumField(); i++ {
+ field := structField{structType.Field(i), structVal.Field(i)}
+
+ name := field.Tag.Get("ebpf")
+ if name != "" {
+ fields = append(fields, field)
+ continue
+ }
+
+ var err error
+ switch field.Type.Kind() {
+ case reflect.Ptr:
+ if field.Type.Elem().Kind() != reflect.Struct {
+ continue
+ }
+
+ if field.value.IsNil() {
+ return fmt.Errorf("nil pointer to %s", structType)
+ }
+
+ err = flattenStruct(field.value.Elem())
+
+ case reflect.Struct:
+ err = flattenStruct(field.value)
+
+ default:
+ continue
+ }
+
+ if err != nil {
+ return fmt.Errorf("field %s: %s", field.Name, err)
+ }
+ }
+
+ return nil
+ }
+
+ toValue := reflect.ValueOf(to)
+ if toValue.Type().Kind() != reflect.Ptr {
+ return fmt.Errorf("%T is not a pointer to struct", to)
+ }
+
+ if toValue.IsNil() {
+ return fmt.Errorf("nil pointer to %T", to)
+ }
+
+ if err := flattenStruct(toValue.Elem()); err != nil {
+ return err
+ }
+
+ type elem struct {
+ // Either *Map or *Program
+ typ reflect.Type
+ name string
+ }
+
+ assignedTo := make(map[elem]string)
+ for _, field := range fields {
+ name := field.Tag.Get("ebpf")
+ if strings.Contains(name, ",") {
+ return fmt.Errorf("field %s: ebpf tag contains a comma", field.Name)
+ }
+
+ e := elem{field.Type, name}
+ if assignedField := assignedTo[e]; assignedField != "" {
+ return fmt.Errorf("field %s: %q was already assigned to %s", field.Name, name, assignedField)
+ }
+
+ value, err := valueOf(field.Type, name)
+ if err != nil {
+ return fmt.Errorf("field %s: %w", field.Name, err)
+ }
+
+ if !field.value.CanSet() {
+ return fmt.Errorf("field %s: can't set value", field.Name)
+ }
+
+ field.value.Set(value)
+ assignedTo[e] = field.Name
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/cilium/ebpf/doc.go b/vendor/github.com/cilium/ebpf/doc.go
@@ -0,0 +1,16 @@
+// Package ebpf is a toolkit for working with eBPF programs.
+//
+// eBPF programs are small snippets of code which are executed directly
+// in a VM in the Linux kernel, which makes them very fast and flexible.
+// Many Linux subsystems now accept eBPF programs. This makes it possible
+// to implement highly application specific logic inside the kernel,
+// without having to modify the actual kernel itself.
+//
+// This package is designed for long-running processes which
+// want to use eBPF to implement part of their application logic. It has no
+// run-time dependencies outside of the library and the Linux kernel itself.
+// eBPF code should be compiled ahead of time using clang, and shipped with
+// your application as any other resource.
+//
+// Use the link subpackage to attach a loaded program to a hook in the kernel.
+package ebpf
diff --git a/vendor/github.com/cilium/ebpf/elf_reader.go b/vendor/github.com/cilium/ebpf/elf_reader.go
@@ -0,0 +1,930 @@
+package ebpf
+
+import (
+ "bufio"
+ "bytes"
+ "debug/elf"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "os"
+ "strings"
+
+ "github.com/cilium/ebpf/asm"
+ "github.com/cilium/ebpf/internal"
+ "github.com/cilium/ebpf/internal/btf"
+ "github.com/cilium/ebpf/internal/unix"
+)
+
+// elfCode is a convenience to reduce the amount of arguments that have to
+// be passed around explicitly. You should treat it's contents as immutable.
+type elfCode struct {
+ *internal.SafeELFFile
+ sections map[elf.SectionIndex]*elfSection
+ license string
+ version uint32
+ btf *btf.Spec
+}
+
+// LoadCollectionSpec parses an ELF file into a CollectionSpec.
+func LoadCollectionSpec(file string) (*CollectionSpec, error) {
+ f, err := os.Open(file)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ spec, err := LoadCollectionSpecFromReader(f)
+ if err != nil {
+ return nil, fmt.Errorf("file %s: %w", file, err)
+ }
+ return spec, nil
+}
+
+// LoadCollectionSpecFromReader parses an ELF file into a CollectionSpec.
+func LoadCollectionSpecFromReader(rd io.ReaderAt) (*CollectionSpec, error) {
+ f, err := internal.NewSafeELFFile(rd)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+
+ var (
+ licenseSection *elf.Section
+ versionSection *elf.Section
+ sections = make(map[elf.SectionIndex]*elfSection)
+ relSections = make(map[elf.SectionIndex]*elf.Section)
+ )
+
+ // This is the target of relocations generated by inline assembly.
+ sections[elf.SHN_UNDEF] = newElfSection(new(elf.Section), undefSection)
+
+ // Collect all the sections we're interested in. This includes relocations
+ // which we parse later.
+ for i, sec := range f.Sections {
+ idx := elf.SectionIndex(i)
+
+ switch {
+ case strings.HasPrefix(sec.Name, "license"):
+ licenseSection = sec
+ case strings.HasPrefix(sec.Name, "version"):
+ versionSection = sec
+ case strings.HasPrefix(sec.Name, "maps"):
+ sections[idx] = newElfSection(sec, mapSection)
+ case sec.Name == ".maps":
+ sections[idx] = newElfSection(sec, btfMapSection)
+ case sec.Name == ".bss" || sec.Name == ".data" || strings.HasPrefix(sec.Name, ".rodata"):
+ sections[idx] = newElfSection(sec, dataSection)
+ case sec.Type == elf.SHT_REL:
+ // Store relocations under the section index of the target
+ relSections[elf.SectionIndex(sec.Info)] = sec
+ case sec.Type == elf.SHT_PROGBITS && (sec.Flags&elf.SHF_EXECINSTR) != 0 && sec.Size > 0:
+ sections[idx] = newElfSection(sec, programSection)
+ }
+ }
+
+ license, err := loadLicense(licenseSection)
+ if err != nil {
+ return nil, fmt.Errorf("load license: %w", err)
+ }
+
+ version, err := loadVersion(versionSection, f.ByteOrder)
+ if err != nil {
+ return nil, fmt.Errorf("load version: %w", err)
+ }
+
+ btfSpec, err := btf.LoadSpecFromReader(rd)
+ if err != nil {
+ return nil, fmt.Errorf("load BTF: %w", err)
+ }
+
+ // Assign symbols to all the sections we're interested in.
+ symbols, err := f.Symbols()
+ if err != nil {
+ return nil, fmt.Errorf("load symbols: %v", err)
+ }
+
+ for _, symbol := range symbols {
+ idx := symbol.Section
+ symType := elf.ST_TYPE(symbol.Info)
+
+ section := sections[idx]
+ if section == nil {
+ continue
+ }
+
+ // Older versions of LLVM don't tag symbols correctly, so keep
+ // all NOTYPE ones.
+ keep := symType == elf.STT_NOTYPE
+ switch section.kind {
+ case mapSection, btfMapSection, dataSection:
+ keep = keep || symType == elf.STT_OBJECT
+ case programSection:
+ keep = keep || symType == elf.STT_FUNC
+ }
+ if !keep || symbol.Name == "" {
+ continue
+ }
+
+ section.symbols[symbol.Value] = symbol
+ }
+
+ ec := &elfCode{
+ SafeELFFile: f,
+ sections: sections,
+ license: license,
+ version: version,
+ btf: btfSpec,
+ }
+
+ // Go through relocation sections, and parse the ones for sections we're
+ // interested in. Make sure that relocations point at valid sections.
+ for idx, relSection := range relSections {
+ section := sections[idx]
+ if section == nil {
+ continue
+ }
+
+ rels, err := ec.loadRelocations(relSection, symbols)
+ if err != nil {
+ return nil, fmt.Errorf("relocation for section %q: %w", section.Name, err)
+ }
+
+ for _, rel := range rels {
+ target := sections[rel.Section]
+ if target == nil {
+ return nil, fmt.Errorf("section %q: reference to %q in section %s: %w", section.Name, rel.Name, rel.Section, ErrNotSupported)
+ }
+
+ if target.Flags&elf.SHF_STRINGS > 0 {
+ return nil, fmt.Errorf("section %q: string %q is not stack allocated: %w", section.Name, rel.Name, ErrNotSupported)
+ }
+
+ target.references++
+ }
+
+ section.relocations = rels
+ }
+
+ // Collect all the various ways to define maps.
+ maps := make(map[string]*MapSpec)
+ if err := ec.loadMaps(maps); err != nil {
+ return nil, fmt.Errorf("load maps: %w", err)
+ }
+
+ if err := ec.loadBTFMaps(maps); err != nil {
+ return nil, fmt.Errorf("load BTF maps: %w", err)
+ }
+
+ if err := ec.loadDataSections(maps); err != nil {
+ return nil, fmt.Errorf("load data sections: %w", err)
+ }
+
+ // Finally, collect programs and link them.
+ progs, err := ec.loadPrograms()
+ if err != nil {
+ return nil, fmt.Errorf("load programs: %w", err)
+ }
+
+ return &CollectionSpec{maps, progs}, nil
+}
+
+func loadLicense(sec *elf.Section) (string, error) {
+ if sec == nil {
+ return "", nil
+ }
+
+ data, err := sec.Data()
+ if err != nil {
+ return "", fmt.Errorf("section %s: %v", sec.Name, err)
+ }
+ return string(bytes.TrimRight(data, "\000")), nil
+}
+
+func loadVersion(sec *elf.Section, bo binary.ByteOrder) (uint32, error) {
+ if sec == nil {
+ return 0, nil
+ }
+
+ var version uint32
+ if err := binary.Read(sec.Open(), bo, &version); err != nil {
+ return 0, fmt.Errorf("section %s: %v", sec.Name, err)
+ }
+ return version, nil
+}
+
+type elfSectionKind int
+
+const (
+ undefSection elfSectionKind = iota
+ mapSection
+ btfMapSection
+ programSection
+ dataSection
+)
+
+type elfSection struct {
+ *elf.Section
+ kind elfSectionKind
+ // Offset from the start of the section to a symbol
+ symbols map[uint64]elf.Symbol
+ // Offset from the start of the section to a relocation, which points at
+ // a symbol in another section.
+ relocations map[uint64]elf.Symbol
+ // The number of relocations pointing at this section.
+ references int
+}
+
+func newElfSection(section *elf.Section, kind elfSectionKind) *elfSection {
+ return &elfSection{
+ section,
+ kind,
+ make(map[uint64]elf.Symbol),
+ make(map[uint64]elf.Symbol),
+ 0,
+ }
+}
+
+func (ec *elfCode) loadPrograms() (map[string]*ProgramSpec, error) {
+ var (
+ progs []*ProgramSpec
+ libs []*ProgramSpec
+ )
+
+ for _, sec := range ec.sections {
+ if sec.kind != programSection {
+ continue
+ }
+
+ if len(sec.symbols) == 0 {
+ return nil, fmt.Errorf("section %v: missing symbols", sec.Name)
+ }
+
+ funcSym, ok := sec.symbols[0]
+ if !ok {
+ return nil, fmt.Errorf("section %v: no label at start", sec.Name)
+ }
+
+ insns, length, err := ec.loadInstructions(sec)
+ if err != nil {
+ return nil, fmt.Errorf("program %s: %w", funcSym.Name, err)
+ }
+
+ progType, attachType, attachTo := getProgType(sec.Name)
+
+ spec := &ProgramSpec{
+ Name: funcSym.Name,
+ Type: progType,
+ AttachType: attachType,
+ AttachTo: attachTo,
+ License: ec.license,
+ KernelVersion: ec.version,
+ Instructions: insns,
+ ByteOrder: ec.ByteOrder,
+ }
+
+ if ec.btf != nil {
+ spec.BTF, err = ec.btf.Program(sec.Name, length)
+ if err != nil && !errors.Is(err, btf.ErrNoExtendedInfo) {
+ return nil, fmt.Errorf("program %s: %w", funcSym.Name, err)
+ }
+ }
+
+ if spec.Type == UnspecifiedProgram {
+ // There is no single name we can use for "library" sections,
+ // since they may contain multiple functions. We'll decode the
+ // labels they contain later on, and then link sections that way.
+ libs = append(libs, spec)
+ } else {
+ progs = append(progs, spec)
+ }
+ }
+
+ res := make(map[string]*ProgramSpec, len(progs))
+ for _, prog := range progs {
+ err := link(prog, libs)
+ if err != nil {
+ return nil, fmt.Errorf("program %s: %w", prog.Name, err)
+ }
+ res[prog.Name] = prog
+ }
+
+ return res, nil
+}
+
+func (ec *elfCode) loadInstructions(section *elfSection) (asm.Instructions, uint64, error) {
+ var (
+ r = bufio.NewReader(section.Open())
+ insns asm.Instructions
+ offset uint64
+ )
+ for {
+ var ins asm.Instruction
+ n, err := ins.Unmarshal(r, ec.ByteOrder)
+ if err == io.EOF {
+ return insns, offset, nil
+ }
+ if err != nil {
+ return nil, 0, fmt.Errorf("offset %d: %w", offset, err)
+ }
+
+ ins.Symbol = section.symbols[offset].Name
+
+ if rel, ok := section.relocations[offset]; ok {
+ if err = ec.relocateInstruction(&ins, rel); err != nil {
+ return nil, 0, fmt.Errorf("offset %d: relocate instruction: %w", offset, err)
+ }
+ }
+
+ insns = append(insns, ins)
+ offset += n
+ }
+}
+
+func (ec *elfCode) relocateInstruction(ins *asm.Instruction, rel elf.Symbol) error {
+ var (
+ typ = elf.ST_TYPE(rel.Info)
+ bind = elf.ST_BIND(rel.Info)
+ name = rel.Name
+ )
+
+ target := ec.sections[rel.Section]
+
+ switch target.kind {
+ case mapSection, btfMapSection:
+ if bind != elf.STB_GLOBAL {
+ return fmt.Errorf("possible erroneous static qualifier on map definition: found reference to %q", name)
+ }
+
+ if typ != elf.STT_OBJECT && typ != elf.STT_NOTYPE {
+ // STT_NOTYPE is generated on clang < 8 which doesn't tag
+ // relocations appropriately.
+ return fmt.Errorf("map load: incorrect relocation type %v", typ)
+ }
+
+ ins.Src = asm.PseudoMapFD
+
+ // Mark the instruction as needing an update when creating the
+ // collection.
+ if err := ins.RewriteMapPtr(-1); err != nil {
+ return err
+ }
+
+ case dataSection:
+ switch typ {
+ case elf.STT_SECTION:
+ if bind != elf.STB_LOCAL {
+ return fmt.Errorf("direct load: %s: unsupported relocation %s", name, bind)
+ }
+
+ case elf.STT_OBJECT:
+ if bind != elf.STB_GLOBAL {
+ return fmt.Errorf("direct load: %s: unsupported relocation %s", name, bind)
+ }
+
+ default:
+ return fmt.Errorf("incorrect relocation type %v for direct map load", typ)
+ }
+
+ // We rely on using the name of the data section as the reference. It
+ // would be nicer to keep the real name in case of an STT_OBJECT, but
+ // it's not clear how to encode that into Instruction.
+ name = target.Name
+
+ // For some reason, clang encodes the offset of the symbol its
+ // section in the first basic BPF instruction, while the kernel
+ // expects it in the second one.
+ ins.Constant <<= 32
+ ins.Src = asm.PseudoMapValue
+
+ // Mark the instruction as needing an update when creating the
+ // collection.
+ if err := ins.RewriteMapPtr(-1); err != nil {
+ return err
+ }
+
+ case programSection:
+ if ins.OpCode.JumpOp() != asm.Call {
+ return fmt.Errorf("not a call instruction: %s", ins)
+ }
+
+ if ins.Src != asm.PseudoCall {
+ return fmt.Errorf("call: %s: incorrect source register", name)
+ }
+
+ switch typ {
+ case elf.STT_NOTYPE, elf.STT_FUNC:
+ if bind != elf.STB_GLOBAL {
+ return fmt.Errorf("call: %s: unsupported binding: %s", name, bind)
+ }
+
+ case elf.STT_SECTION:
+ if bind != elf.STB_LOCAL {
+ return fmt.Errorf("call: %s: unsupported binding: %s", name, bind)
+ }
+
+ // The function we want to call is in the indicated section,
+ // at the offset encoded in the instruction itself. Reverse
+ // the calculation to find the real function we're looking for.
+ // A value of -1 references the first instruction in the section.
+ offset := int64(int32(ins.Constant)+1) * asm.InstructionSize
+ if offset < 0 {
+ return fmt.Errorf("call: %s: invalid offset %d", name, offset)
+ }
+
+ sym, ok := target.symbols[uint64(offset)]
+ if !ok {
+ return fmt.Errorf("call: %s: no symbol at offset %d", name, offset)
+ }
+
+ ins.Constant = -1
+ name = sym.Name
+
+ default:
+ return fmt.Errorf("call: %s: invalid symbol type %s", name, typ)
+ }
+
+ case undefSection:
+ if bind != elf.STB_GLOBAL {
+ return fmt.Errorf("asm relocation: %s: unsupported binding: %s", name, bind)
+ }
+
+ if typ != elf.STT_NOTYPE {
+ return fmt.Errorf("asm relocation: %s: unsupported type %s", name, typ)
+ }
+
+ // There is nothing to do here but set ins.Reference.
+
+ default:
+ return fmt.Errorf("relocation to %q: %w", target.Name, ErrNotSupported)
+ }
+
+ ins.Reference = name
+ return nil
+}
+
+func (ec *elfCode) loadMaps(maps map[string]*MapSpec) error {
+ for _, sec := range ec.sections {
+ if sec.kind != mapSection {
+ continue
+ }
+
+ nSym := len(sec.symbols)
+ if nSym == 0 {
+ return fmt.Errorf("section %v: no symbols", sec.Name)
+ }
+
+ if sec.Size%uint64(nSym) != 0 {
+ return fmt.Errorf("section %v: map descriptors are not of equal size", sec.Name)
+ }
+
+ var (
+ r = bufio.NewReader(sec.Open())
+ size = sec.Size / uint64(nSym)
+ )
+ for i, offset := 0, uint64(0); i < nSym; i, offset = i+1, offset+size {
+ mapSym, ok := sec.symbols[offset]
+ if !ok {
+ return fmt.Errorf("section %s: missing symbol for map at offset %d", sec.Name, offset)
+ }
+
+ if maps[mapSym.Name] != nil {
+ return fmt.Errorf("section %v: map %v already exists", sec.Name, mapSym)
+ }
+
+ lr := io.LimitReader(r, int64(size))
+
+ spec := MapSpec{
+ Name: SanitizeName(mapSym.Name, -1),
+ }
+ switch {
+ case binary.Read(lr, ec.ByteOrder, &spec.Type) != nil:
+ return fmt.Errorf("map %v: missing type", mapSym)
+ case binary.Read(lr, ec.ByteOrder, &spec.KeySize) != nil:
+ return fmt.Errorf("map %v: missing key size", mapSym)
+ case binary.Read(lr, ec.ByteOrder, &spec.ValueSize) != nil:
+ return fmt.Errorf("map %v: missing value size", mapSym)
+ case binary.Read(lr, ec.ByteOrder, &spec.MaxEntries) != nil:
+ return fmt.Errorf("map %v: missing max entries", mapSym)
+ case binary.Read(lr, ec.ByteOrder, &spec.Flags) != nil:
+ return fmt.Errorf("map %v: missing flags", mapSym)
+ }
+
+ if _, err := io.Copy(internal.DiscardZeroes{}, lr); err != nil {
+ return fmt.Errorf("map %v: unknown and non-zero fields in definition", mapSym)
+ }
+
+ maps[mapSym.Name] = &spec
+ }
+ }
+
+ return nil
+}
+
+func (ec *elfCode) loadBTFMaps(maps map[string]*MapSpec) error {
+ for _, sec := range ec.sections {
+ if sec.kind != btfMapSection {
+ continue
+ }
+
+ if ec.btf == nil {
+ return fmt.Errorf("missing BTF")
+ }
+
+ if len(sec.symbols) == 0 {
+ return fmt.Errorf("section %v: no symbols", sec.Name)
+ }
+
+ _, err := io.Copy(internal.DiscardZeroes{}, bufio.NewReader(sec.Open()))
+ if err != nil {
+ return fmt.Errorf("section %v: initializing BTF map definitions: %w", sec.Name, internal.ErrNotSupported)
+ }
+
+ for _, sym := range sec.symbols {
+ name := sym.Name
+ if maps[name] != nil {
+ return fmt.Errorf("section %v: map %v already exists", sec.Name, sym)
+ }
+
+ // A global Var is created by declaring a struct with a 'structure variable',
+ // as is common in eBPF C to declare eBPF maps. For example,
+ // `struct { ... } map_name ...;` emits a global variable `map_name`
+ // with the type of said struct (which can be anonymous).
+ var v btf.Var
+ if err := ec.btf.FindType(name, &v); err != nil {
+ return fmt.Errorf("cannot find global variable '%s' in BTF: %w", name, err)
+ }
+
+ mapStruct, ok := v.Type.(*btf.Struct)
+ if !ok {
+ return fmt.Errorf("expected struct, got %s", v.Type)
+ }
+
+ mapSpec, err := mapSpecFromBTF(name, mapStruct, false, ec.btf)
+ if err != nil {
+ return fmt.Errorf("map %v: %w", name, err)
+ }
+
+ maps[name] = mapSpec
+ }
+ }
+
+ return nil
+}
+
+// mapSpecFromBTF produces a MapSpec based on a btf.Struct def representing
+// a BTF map definition. The name and spec arguments will be copied to the
+// resulting MapSpec, and inner must be true on any resursive invocations.
+func mapSpecFromBTF(name string, def *btf.Struct, inner bool, spec *btf.Spec) (*MapSpec, error) {
+
+ var (
+ key, value btf.Type
+ keySize, valueSize uint32
+ mapType, flags, maxEntries uint32
+ pinType PinType
+ innerMapSpec *MapSpec
+ err error
+ )
+
+ for i, member := range def.Members {
+ switch member.Name {
+ case "type":
+ mapType, err = uintFromBTF(member.Type)
+ if err != nil {
+ return nil, fmt.Errorf("can't get type: %w", err)
+ }
+
+ case "map_flags":
+ flags, err = uintFromBTF(member.Type)
+ if err != nil {
+ return nil, fmt.Errorf("can't get BTF map flags: %w", err)
+ }
+
+ case "max_entries":
+ maxEntries, err = uintFromBTF(member.Type)
+ if err != nil {
+ return nil, fmt.Errorf("can't get BTF map max entries: %w", err)
+ }
+
+ case "key":
+ if keySize != 0 {
+ return nil, errors.New("both key and key_size given")
+ }
+
+ pk, ok := member.Type.(*btf.Pointer)
+ if !ok {
+ return nil, fmt.Errorf("key type is not a pointer: %T", member.Type)
+ }
+
+ key = pk.Target
+
+ size, err := btf.Sizeof(pk.Target)
+ if err != nil {
+ return nil, fmt.Errorf("can't get size of BTF key: %w", err)
+ }
+
+ keySize = uint32(size)
+
+ case "value":
+ if valueSize != 0 {
+ return nil, errors.New("both value and value_size given")
+ }
+
+ vk, ok := member.Type.(*btf.Pointer)
+ if !ok {
+ return nil, fmt.Errorf("value type is not a pointer: %T", member.Type)
+ }
+
+ value = vk.Target
+
+ size, err := btf.Sizeof(vk.Target)
+ if err != nil {
+ return nil, fmt.Errorf("can't get size of BTF value: %w", err)
+ }
+
+ valueSize = uint32(size)
+
+ case "key_size":
+ // Key needs to be nil and keySize needs to be 0 for key_size to be
+ // considered a valid member.
+ if key != nil || keySize != 0 {
+ return nil, errors.New("both key and key_size given")
+ }
+
+ keySize, err = uintFromBTF(member.Type)
+ if err != nil {
+ return nil, fmt.Errorf("can't get BTF key size: %w", err)
+ }
+
+ case "value_size":
+ // Value needs to be nil and valueSize needs to be 0 for value_size to be
+ // considered a valid member.
+ if value != nil || valueSize != 0 {
+ return nil, errors.New("both value and value_size given")
+ }
+
+ valueSize, err = uintFromBTF(member.Type)
+ if err != nil {
+ return nil, fmt.Errorf("can't get BTF value size: %w", err)
+ }
+
+ case "pinning":
+ if inner {
+ return nil, errors.New("inner maps can't be pinned")
+ }
+
+ pinning, err := uintFromBTF(member.Type)
+ if err != nil {
+ return nil, fmt.Errorf("can't get pinning: %w", err)
+ }
+
+ pinType = PinType(pinning)
+
+ case "values":
+ // The 'values' field in BTF map definitions is used for declaring map
+ // value types that are references to other BPF objects, like other maps
+ // or programs. It is always expected to be an array of pointers.
+ if i != len(def.Members)-1 {
+ return nil, errors.New("'values' must be the last member in a BTF map definition")
+ }
+
+ if valueSize != 0 && valueSize != 4 {
+ return nil, errors.New("value_size must be 0 or 4")
+ }
+ valueSize = 4
+
+ valueType, err := resolveBTFArrayMacro(member.Type)
+ if err != nil {
+ return nil, fmt.Errorf("can't resolve type of member 'values': %w", err)
+ }
+
+ switch t := valueType.(type) {
+ case *btf.Struct:
+ // The values member pointing to an array of structs means we're expecting
+ // a map-in-map declaration.
+ if MapType(mapType) != ArrayOfMaps && MapType(mapType) != HashOfMaps {
+ return nil, errors.New("outer map needs to be an array or a hash of maps")
+ }
+ if inner {
+ return nil, fmt.Errorf("nested inner maps are not supported")
+ }
+
+ // This inner map spec is used as a map template, but it needs to be
+ // created as a traditional map before it can be used to do so.
+ // libbpf names the inner map template '<outer_name>.inner', but we
+ // opted for _inner to simplify validation logic. (dots only supported
+ // on kernels 5.2 and up)
+ // Pass the BTF spec from the parent object, since both parent and
+ // child must be created from the same BTF blob (on kernels that support BTF).
+ innerMapSpec, err = mapSpecFromBTF(name+"_inner", t, true, spec)
+ if err != nil {
+ return nil, fmt.Errorf("can't parse BTF map definition of inner map: %w", err)
+ }
+
+ default:
+ return nil, fmt.Errorf("unsupported value type %q in 'values' field", t)
+ }
+
+ default:
+ return nil, fmt.Errorf("unrecognized field %s in BTF map definition", member.Name)
+ }
+ }
+
+ bm := btf.NewMap(spec, key, value)
+
+ return &MapSpec{
+ Name: SanitizeName(name, -1),
+ Type: MapType(mapType),
+ KeySize: keySize,
+ ValueSize: valueSize,
+ MaxEntries: maxEntries,
+ Flags: flags,
+ BTF: &bm,
+ Pinning: pinType,
+ InnerMap: innerMapSpec,
+ }, nil
+}
+
+// uintFromBTF resolves the __uint macro, which is a pointer to a sized
+// array, e.g. for int (*foo)[10], this function will return 10.
+func uintFromBTF(typ btf.Type) (uint32, error) {
+ ptr, ok := typ.(*btf.Pointer)
+ if !ok {
+ return 0, fmt.Errorf("not a pointer: %v", typ)
+ }
+
+ arr, ok := ptr.Target.(*btf.Array)
+ if !ok {
+ return 0, fmt.Errorf("not a pointer to array: %v", typ)
+ }
+
+ return arr.Nelems, nil
+}
+
+// resolveBTFArrayMacro resolves the __array macro, which declares an array
+// of pointers to a given type. This function returns the target Type of
+// the pointers in the array.
+func resolveBTFArrayMacro(typ btf.Type) (btf.Type, error) {
+ arr, ok := typ.(*btf.Array)
+ if !ok {
+ return nil, fmt.Errorf("not an array: %v", typ)
+ }
+
+ ptr, ok := arr.Type.(*btf.Pointer)
+ if !ok {
+ return nil, fmt.Errorf("not an array of pointers: %v", typ)
+ }
+
+ return ptr.Target, nil
+}
+
+func (ec *elfCode) loadDataSections(maps map[string]*MapSpec) error {
+ for _, sec := range ec.sections {
+ if sec.kind != dataSection {
+ continue
+ }
+
+ if sec.references == 0 {
+ // Prune data sections which are not referenced by any
+ // instructions.
+ continue
+ }
+
+ if ec.btf == nil {
+ return errors.New("data sections require BTF, make sure all consts are marked as static")
+ }
+
+ btfMap, err := ec.btf.Datasec(sec.Name)
+ if err != nil {
+ return err
+ }
+
+ data, err := sec.Data()
+ if err != nil {
+ return fmt.Errorf("data section %s: can't get contents: %w", sec.Name, err)
+ }
+
+ if uint64(len(data)) > math.MaxUint32 {
+ return fmt.Errorf("data section %s: contents exceed maximum size", sec.Name)
+ }
+
+ mapSpec := &MapSpec{
+ Name: SanitizeName(sec.Name, -1),
+ Type: Array,
+ KeySize: 4,
+ ValueSize: uint32(len(data)),
+ MaxEntries: 1,
+ Contents: []MapKV{{uint32(0), data}},
+ BTF: btfMap,
+ }
+
+ switch sec.Name {
+ case ".rodata":
+ mapSpec.Flags = unix.BPF_F_RDONLY_PROG
+ mapSpec.Freeze = true
+ case ".bss":
+ // The kernel already zero-initializes the map
+ mapSpec.Contents = nil
+ }
+
+ maps[sec.Name] = mapSpec
+ }
+ return nil
+}
+
+func getProgType(sectionName string) (ProgramType, AttachType, string) {
+ types := map[string]struct {
+ progType ProgramType
+ attachType AttachType
+ }{
+ // From https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/lib/bpf/libbpf.c
+ "socket": {SocketFilter, AttachNone},
+ "seccomp": {SocketFilter, AttachNone},
+ "kprobe/": {Kprobe, AttachNone},
+ "uprobe/": {Kprobe, AttachNone},
+ "kretprobe/": {Kprobe, AttachNone},
+ "uretprobe/": {Kprobe, AttachNone},
+ "tracepoint/": {TracePoint, AttachNone},
+ "raw_tracepoint/": {RawTracepoint, AttachNone},
+ "xdp": {XDP, AttachNone},
+ "perf_event": {PerfEvent, AttachNone},
+ "lwt_in": {LWTIn, AttachNone},
+ "lwt_out": {LWTOut, AttachNone},
+ "lwt_xmit": {LWTXmit, AttachNone},
+ "lwt_seg6local": {LWTSeg6Local, AttachNone},
+ "sockops": {SockOps, AttachCGroupSockOps},
+ "sk_skb/stream_parser": {SkSKB, AttachSkSKBStreamParser},
+ "sk_skb/stream_verdict": {SkSKB, AttachSkSKBStreamParser},
+ "sk_msg": {SkMsg, AttachSkSKBStreamVerdict},
+ "lirc_mode2": {LircMode2, AttachLircMode2},
+ "flow_dissector": {FlowDissector, AttachFlowDissector},
+ "iter/": {Tracing, AttachTraceIter},
+ "sk_lookup/": {SkLookup, AttachSkLookup},
+ "lsm/": {LSM, AttachLSMMac},
+
+ "cgroup_skb/ingress": {CGroupSKB, AttachCGroupInetIngress},
+ "cgroup_skb/egress": {CGroupSKB, AttachCGroupInetEgress},
+ "cgroup/dev": {CGroupDevice, AttachCGroupDevice},
+ "cgroup/skb": {CGroupSKB, AttachNone},
+ "cgroup/sock": {CGroupSock, AttachCGroupInetSockCreate},
+ "cgroup/post_bind4": {CGroupSock, AttachCGroupInet4PostBind},
+ "cgroup/post_bind6": {CGroupSock, AttachCGroupInet6PostBind},
+ "cgroup/bind4": {CGroupSockAddr, AttachCGroupInet4Bind},
+ "cgroup/bind6": {CGroupSockAddr, AttachCGroupInet6Bind},
+ "cgroup/connect4": {CGroupSockAddr, AttachCGroupInet4Connect},
+ "cgroup/connect6": {CGroupSockAddr, AttachCGroupInet6Connect},
+ "cgroup/sendmsg4": {CGroupSockAddr, AttachCGroupUDP4Sendmsg},
+ "cgroup/sendmsg6": {CGroupSockAddr, AttachCGroupUDP6Sendmsg},
+ "cgroup/recvmsg4": {CGroupSockAddr, AttachCGroupUDP4Recvmsg},
+ "cgroup/recvmsg6": {CGroupSockAddr, AttachCGroupUDP6Recvmsg},
+ "cgroup/sysctl": {CGroupSysctl, AttachCGroupSysctl},
+ "cgroup/getsockopt": {CGroupSockopt, AttachCGroupGetsockopt},
+ "cgroup/setsockopt": {CGroupSockopt, AttachCGroupSetsockopt},
+ "classifier": {SchedCLS, AttachNone},
+ "action": {SchedACT, AttachNone},
+ }
+
+ for prefix, t := range types {
+ if !strings.HasPrefix(sectionName, prefix) {
+ continue
+ }
+
+ if !strings.HasSuffix(prefix, "/") {
+ return t.progType, t.attachType, ""
+ }
+
+ return t.progType, t.attachType, sectionName[len(prefix):]
+ }
+
+ return UnspecifiedProgram, AttachNone, ""
+}
+
+func (ec *elfCode) loadRelocations(sec *elf.Section, symbols []elf.Symbol) (map[uint64]elf.Symbol, error) {
+ rels := make(map[uint64]elf.Symbol)
+
+ if sec.Entsize < 16 {
+ return nil, fmt.Errorf("section %s: relocations are less than 16 bytes", sec.Name)
+ }
+
+ r := bufio.NewReader(sec.Open())
+ for off := uint64(0); off < sec.Size; off += sec.Entsize {
+ ent := io.LimitReader(r, int64(sec.Entsize))
+
+ var rel elf.Rel64
+ if binary.Read(ent, ec.ByteOrder, &rel) != nil {
+ return nil, fmt.Errorf("can't parse relocation at offset %v", off)
+ }
+
+ symNo := int(elf.R_SYM64(rel.Info) - 1)
+ if symNo >= len(symbols) {
+ return nil, fmt.Errorf("offset %d: symbol %d doesn't exist", off, symNo)
+ }
+
+ symbol := symbols[symNo]
+ rels[rel.Off] = symbol
+ }
+
+ return rels, nil
+}
diff --git a/vendor/github.com/cilium/ebpf/elf_reader_fuzz.go b/vendor/github.com/cilium/ebpf/elf_reader_fuzz.go
@@ -0,0 +1,21 @@
+// +build gofuzz
+
+// Use with https://github.com/dvyukov/go-fuzz
+
+package ebpf
+
+import "bytes"
+
+func FuzzLoadCollectionSpec(data []byte) int {
+ spec, err := LoadCollectionSpecFromReader(bytes.NewReader(data))
+ if err != nil {
+ if spec != nil {
+ panic("spec is not nil")
+ }
+ return 0
+ }
+ if spec == nil {
+ panic("spec is nil")
+ }
+ return 1
+}
diff --git a/vendor/github.com/cilium/ebpf/info.go b/vendor/github.com/cilium/ebpf/info.go
@@ -0,0 +1,239 @@
+package ebpf
+
+import (
+ "bufio"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/cilium/ebpf/internal"
+)
+
+// MapInfo describes a map.
+type MapInfo struct {
+ Type MapType
+ id MapID
+ KeySize uint32
+ ValueSize uint32
+ MaxEntries uint32
+ Flags uint32
+ // Name as supplied by user space at load time.
+ Name string
+}
+
+func newMapInfoFromFd(fd *internal.FD) (*MapInfo, error) {
+ info, err := bpfGetMapInfoByFD(fd)
+ if errors.Is(err, syscall.EINVAL) {
+ return newMapInfoFromProc(fd)
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ return &MapInfo{
+ MapType(info.map_type),
+ MapID(info.id),
+ info.key_size,
+ info.value_size,
+ info.max_entries,
+ info.map_flags,
+ // name is available from 4.15.
+ internal.CString(info.name[:]),
+ }, nil
+}
+
+func newMapInfoFromProc(fd *internal.FD) (*MapInfo, error) {
+ var mi MapInfo
+ err := scanFdInfo(fd, map[string]interface{}{
+ "map_type": &mi.Type,
+ "key_size": &mi.KeySize,
+ "value_size": &mi.ValueSize,
+ "max_entries": &mi.MaxEntries,
+ "map_flags": &mi.Flags,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &mi, nil
+}
+
+// ID returns the map ID.
+//
+// Available from 4.13.
+//
+// The bool return value indicates whether this optional field is available.
+func (mi *MapInfo) ID() (MapID, bool) {
+ return mi.id, mi.id > 0
+}
+
+// programStats holds statistics of a program.
+type programStats struct {
+ // Total accumulated runtime of the program ins ns.
+ runtime time.Duration
+ // Total number of times the program was called.
+ runCount uint64
+}
+
+// ProgramInfo describes a program.
+type ProgramInfo struct {
+ Type ProgramType
+ id ProgramID
+ // Truncated hash of the BPF bytecode.
+ Tag string
+ // Name as supplied by user space at load time.
+ Name string
+
+ stats *programStats
+}
+
+func newProgramInfoFromFd(fd *internal.FD) (*ProgramInfo, error) {
+ info, err := bpfGetProgInfoByFD(fd)
+ if errors.Is(err, syscall.EINVAL) {
+ return newProgramInfoFromProc(fd)
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ return &ProgramInfo{
+ Type: ProgramType(info.prog_type),
+ id: ProgramID(info.id),
+ // tag is available if the kernel supports BPF_PROG_GET_INFO_BY_FD.
+ Tag: hex.EncodeToString(info.tag[:]),
+ // name is available from 4.15.
+ Name: internal.CString(info.name[:]),
+ stats: &programStats{
+ runtime: time.Duration(info.run_time_ns),
+ runCount: info.run_cnt,
+ },
+ }, nil
+}
+
+func newProgramInfoFromProc(fd *internal.FD) (*ProgramInfo, error) {
+ var info ProgramInfo
+ err := scanFdInfo(fd, map[string]interface{}{
+ "prog_type": &info.Type,
+ "prog_tag": &info.Tag,
+ })
+ if errors.Is(err, errMissingFields) {
+ return nil, &internal.UnsupportedFeatureError{
+ Name: "reading program info from /proc/self/fdinfo",
+ MinimumVersion: internal.Version{4, 10, 0},
+ }
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ return &info, nil
+}
+
+// ID returns the program ID.
+//
+// Available from 4.13.
+//
+// The bool return value indicates whether this optional field is available.
+func (pi *ProgramInfo) ID() (ProgramID, bool) {
+ return pi.id, pi.id > 0
+}
+
+// RunCount returns the total number of times the program was called.
+//
+// Can return 0 if the collection of statistics is not enabled. See EnableStats().
+// The bool return value indicates whether this optional field is available.
+func (pi *ProgramInfo) RunCount() (uint64, bool) {
+ if pi.stats != nil {
+ return pi.stats.runCount, true
+ }
+ return 0, false
+}
+
+// Runtime returns the total accumulated runtime of the program.
+//
+// Can return 0 if the collection of statistics is not enabled. See EnableStats().
+// The bool return value indicates whether this optional field is available.
+func (pi *ProgramInfo) Runtime() (time.Duration, bool) {
+ if pi.stats != nil {
+ return pi.stats.runtime, true
+ }
+ return time.Duration(0), false
+}
+
+func scanFdInfo(fd *internal.FD, fields map[string]interface{}) error {
+ raw, err := fd.Value()
+ if err != nil {
+ return err
+ }
+
+ fh, err := os.Open(fmt.Sprintf("/proc/self/fdinfo/%d", raw))
+ if err != nil {
+ return err
+ }
+ defer fh.Close()
+
+ if err := scanFdInfoReader(fh, fields); err != nil {
+ return fmt.Errorf("%s: %w", fh.Name(), err)
+ }
+ return nil
+}
+
+var errMissingFields = errors.New("missing fields")
+
+func scanFdInfoReader(r io.Reader, fields map[string]interface{}) error {
+ var (
+ scanner = bufio.NewScanner(r)
+ scanned int
+ )
+
+ for scanner.Scan() {
+ parts := strings.SplitN(scanner.Text(), "\t", 2)
+ if len(parts) != 2 {
+ continue
+ }
+
+ name := strings.TrimSuffix(parts[0], ":")
+ field, ok := fields[string(name)]
+ if !ok {
+ continue
+ }
+
+ if n, err := fmt.Sscanln(parts[1], field); err != nil || n != 1 {
+ return fmt.Errorf("can't parse field %s: %v", name, err)
+ }
+
+ scanned++
+ }
+
+ if err := scanner.Err(); err != nil {
+ return err
+ }
+
+ if scanned != len(fields) {
+ return errMissingFields
+ }
+
+ return nil
+}
+
+// EnableStats starts the measuring of the runtime
+// and run counts of eBPF programs.
+//
+// Collecting statistics can have an impact on the performance.
+//
+// Requires at least 5.8.
+func EnableStats(which uint32) (io.Closer, error) {
+ attr := internal.BPFEnableStatsAttr{
+ StatsType: which,
+ }
+
+ fd, err := internal.BPFEnableStats(&attr)
+ if err != nil {
+ return nil, err
+ }
+ return fd, nil
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/btf/btf.go b/vendor/github.com/cilium/ebpf/internal/btf/btf.go
@@ -0,0 +1,791 @@
+package btf
+
+import (
+ "bytes"
+ "debug/elf"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "math"
+ "os"
+ "reflect"
+ "sync"
+ "unsafe"
+
+ "github.com/cilium/ebpf/internal"
+ "github.com/cilium/ebpf/internal/unix"
+)
+
+const btfMagic = 0xeB9F
+
+// Errors returned by BTF functions.
+var (
+ ErrNotSupported = internal.ErrNotSupported
+ ErrNotFound = errors.New("not found")
+ ErrNoExtendedInfo = errors.New("no extended info")
+)
+
+// Spec represents decoded BTF.
+type Spec struct {
+ rawTypes []rawType
+ strings stringTable
+ types []Type
+ namedTypes map[string][]namedType
+ funcInfos map[string]extInfo
+ lineInfos map[string]extInfo
+ coreRelos map[string]bpfCoreRelos
+ byteOrder binary.ByteOrder
+}
+
+type btfHeader struct {
+ Magic uint16
+ Version uint8
+ Flags uint8
+ HdrLen uint32
+
+ TypeOff uint32
+ TypeLen uint32
+ StringOff uint32
+ StringLen uint32
+}
+
+// LoadSpecFromReader reads BTF sections from an ELF.
+//
+// Returns a nil Spec and no error if no BTF was present.
+func LoadSpecFromReader(rd io.ReaderAt) (*Spec, error) {
+ file, err := internal.NewSafeELFFile(rd)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+
+ btfSection, btfExtSection, sectionSizes, err := findBtfSections(file)
+ if err != nil {
+ return nil, err
+ }
+
+ if btfSection == nil {
+ return nil, nil
+ }
+
+ symbols, err := file.Symbols()
+ if err != nil {
+ return nil, fmt.Errorf("can't read symbols: %v", err)
+ }
+
+ variableOffsets := make(map[variable]uint32)
+ for _, symbol := range symbols {
+ if idx := symbol.Section; idx >= elf.SHN_LORESERVE && idx <= elf.SHN_HIRESERVE {
+ // Ignore things like SHN_ABS
+ continue
+ }
+
+ if int(symbol.Section) >= len(file.Sections) {
+ return nil, fmt.Errorf("symbol %s: invalid section %d", symbol.Name, symbol.Section)
+ }
+
+ secName := file.Sections[symbol.Section].Name
+ if _, ok := sectionSizes[secName]; !ok {
+ continue
+ }
+
+ if symbol.Value > math.MaxUint32 {
+ return nil, fmt.Errorf("section %s: symbol %s: size exceeds maximum", secName, symbol.Name)
+ }
+
+ variableOffsets[variable{secName, symbol.Name}] = uint32(symbol.Value)
+ }
+
+ spec, err := loadNakedSpec(btfSection.Open(), file.ByteOrder, sectionSizes, variableOffsets)
+ if err != nil {
+ return nil, err
+ }
+
+ if btfExtSection == nil {
+ return spec, nil
+ }
+
+ spec.funcInfos, spec.lineInfos, spec.coreRelos, err = parseExtInfos(btfExtSection.Open(), file.ByteOrder, spec.strings)
+ if err != nil {
+ return nil, fmt.Errorf("can't read ext info: %w", err)
+ }
+
+ return spec, nil
+}
+
+func findBtfSections(file *internal.SafeELFFile) (*elf.Section, *elf.Section, map[string]uint32, error) {
+ var (
+ btfSection *elf.Section
+ btfExtSection *elf.Section
+ sectionSizes = make(map[string]uint32)
+ )
+
+ for _, sec := range file.Sections {
+ switch sec.Name {
+ case ".BTF":
+ btfSection = sec
+ case ".BTF.ext":
+ btfExtSection = sec
+ default:
+ if sec.Type != elf.SHT_PROGBITS && sec.Type != elf.SHT_NOBITS {
+ break
+ }
+
+ if sec.Size > math.MaxUint32 {
+ return nil, nil, nil, fmt.Errorf("section %s exceeds maximum size", sec.Name)
+ }
+
+ sectionSizes[sec.Name] = uint32(sec.Size)
+ }
+ }
+ return btfSection, btfExtSection, sectionSizes, nil
+}
+
+func loadSpecFromVmlinux(rd io.ReaderAt) (*Spec, error) {
+ file, err := internal.NewSafeELFFile(rd)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+
+ btfSection, _, _, err := findBtfSections(file)
+ if err != nil {
+ return nil, fmt.Errorf(".BTF ELF section: %s", err)
+ }
+ if btfSection == nil {
+ return nil, fmt.Errorf("unable to find .BTF ELF section")
+ }
+ return loadNakedSpec(btfSection.Open(), file.ByteOrder, nil, nil)
+}
+
+func loadNakedSpec(btf io.ReadSeeker, bo binary.ByteOrder, sectionSizes map[string]uint32, variableOffsets map[variable]uint32) (*Spec, error) {
+ rawTypes, rawStrings, err := parseBTF(btf, bo)
+ if err != nil {
+ return nil, err
+ }
+
+ err = fixupDatasec(rawTypes, rawStrings, sectionSizes, variableOffsets)
+ if err != nil {
+ return nil, err
+ }
+
+ types, typesByName, err := inflateRawTypes(rawTypes, rawStrings)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Spec{
+ rawTypes: rawTypes,
+ namedTypes: typesByName,
+ types: types,
+ strings: rawStrings,
+ byteOrder: bo,
+ }, nil
+}
+
+var kernelBTF struct {
+ sync.Mutex
+ *Spec
+}
+
+// LoadKernelSpec returns the current kernel's BTF information.
+//
+// Requires a >= 5.5 kernel with CONFIG_DEBUG_INFO_BTF enabled. Returns
+// ErrNotSupported if BTF is not enabled.
+func LoadKernelSpec() (*Spec, error) {
+ kernelBTF.Lock()
+ defer kernelBTF.Unlock()
+
+ if kernelBTF.Spec != nil {
+ return kernelBTF.Spec, nil
+ }
+
+ var err error
+ kernelBTF.Spec, err = loadKernelSpec()
+ return kernelBTF.Spec, err
+}
+
+func loadKernelSpec() (*Spec, error) {
+ release, err := unix.KernelRelease()
+ if err != nil {
+ return nil, fmt.Errorf("can't read kernel release number: %w", err)
+ }
+
+ fh, err := os.Open("/sys/kernel/btf/vmlinux")
+ if err == nil {
+ defer fh.Close()
+
+ return loadNakedSpec(fh, internal.NativeEndian, nil, nil)
+ }
+
+ // use same list of locations as libbpf
+ // https://github.com/libbpf/libbpf/blob/9a3a42608dbe3731256a5682a125ac1e23bced8f/src/btf.c#L3114-L3122
+ locations := []string{
+ "/boot/vmlinux-%s",
+ "/lib/modules/%s/vmlinux-%[1]s",
+ "/lib/modules/%s/build/vmlinux",
+ "/usr/lib/modules/%s/kernel/vmlinux",
+ "/usr/lib/debug/boot/vmlinux-%s",
+ "/usr/lib/debug/boot/vmlinux-%s.debug",
+ "/usr/lib/debug/lib/modules/%s/vmlinux",
+ }
+
+ for _, loc := range locations {
+ path := fmt.Sprintf(loc, release)
+
+ fh, err := os.Open(path)
+ if err != nil {
+ continue
+ }
+ defer fh.Close()
+
+ return loadSpecFromVmlinux(fh)
+ }
+
+ return nil, fmt.Errorf("no BTF for kernel version %s: %w", release, internal.ErrNotSupported)
+}
+
+func parseBTF(btf io.ReadSeeker, bo binary.ByteOrder) ([]rawType, stringTable, error) {
+ rawBTF, err := ioutil.ReadAll(btf)
+ if err != nil {
+ return nil, nil, fmt.Errorf("can't read BTF: %v", err)
+ }
+
+ rd := bytes.NewReader(rawBTF)
+
+ var header btfHeader
+ if err := binary.Read(rd, bo, &header); err != nil {
+ return nil, nil, fmt.Errorf("can't read header: %v", err)
+ }
+
+ if header.Magic != btfMagic {
+ return nil, nil, fmt.Errorf("incorrect magic value %v", header.Magic)
+ }
+
+ if header.Version != 1 {
+ return nil, nil, fmt.Errorf("unexpected version %v", header.Version)
+ }
+
+ if header.Flags != 0 {
+ return nil, nil, fmt.Errorf("unsupported flags %v", header.Flags)
+ }
+
+ remainder := int64(header.HdrLen) - int64(binary.Size(&header))
+ if remainder < 0 {
+ return nil, nil, errors.New("header is too short")
+ }
+
+ if _, err := io.CopyN(internal.DiscardZeroes{}, rd, remainder); err != nil {
+ return nil, nil, fmt.Errorf("header padding: %v", err)
+ }
+
+ if _, err := rd.Seek(int64(header.HdrLen+header.StringOff), io.SeekStart); err != nil {
+ return nil, nil, fmt.Errorf("can't seek to start of string section: %v", err)
+ }
+
+ rawStrings, err := readStringTable(io.LimitReader(rd, int64(header.StringLen)))
+ if err != nil {
+ return nil, nil, fmt.Errorf("can't read type names: %w", err)
+ }
+
+ if _, err := rd.Seek(int64(header.HdrLen+header.TypeOff), io.SeekStart); err != nil {
+ return nil, nil, fmt.Errorf("can't seek to start of type section: %v", err)
+ }
+
+ rawTypes, err := readTypes(io.LimitReader(rd, int64(header.TypeLen)), bo)
+ if err != nil {
+ return nil, nil, fmt.Errorf("can't read types: %w", err)
+ }
+
+ return rawTypes, rawStrings, nil
+}
+
+type variable struct {
+ section string
+ name string
+}
+
+func fixupDatasec(rawTypes []rawType, rawStrings stringTable, sectionSizes map[string]uint32, variableOffsets map[variable]uint32) error {
+ for i, rawType := range rawTypes {
+ if rawType.Kind() != kindDatasec {
+ continue
+ }
+
+ name, err := rawStrings.Lookup(rawType.NameOff)
+ if err != nil {
+ return err
+ }
+
+ if name == ".kconfig" || name == ".ksyms" {
+ return fmt.Errorf("reference to %s: %w", name, ErrNotSupported)
+ }
+
+ if rawTypes[i].SizeType != 0 {
+ continue
+ }
+
+ size, ok := sectionSizes[name]
+ if !ok {
+ return fmt.Errorf("data section %s: missing size", name)
+ }
+
+ rawTypes[i].SizeType = size
+
+ secinfos := rawType.data.([]btfVarSecinfo)
+ for j, secInfo := range secinfos {
+ id := int(secInfo.Type - 1)
+ if id >= len(rawTypes) {
+ return fmt.Errorf("data section %s: invalid type id %d for variable %d", name, id, j)
+ }
+
+ varName, err := rawStrings.Lookup(rawTypes[id].NameOff)
+ if err != nil {
+ return fmt.Errorf("data section %s: can't get name for type %d: %w", name, id, err)
+ }
+
+ offset, ok := variableOffsets[variable{name, varName}]
+ if !ok {
+ return fmt.Errorf("data section %s: missing offset for variable %s", name, varName)
+ }
+
+ secinfos[j].Offset = offset
+ }
+ }
+
+ return nil
+}
+
+type marshalOpts struct {
+ ByteOrder binary.ByteOrder
+ StripFuncLinkage bool
+}
+
+func (s *Spec) marshal(opts marshalOpts) ([]byte, error) {
+ var (
+ buf bytes.Buffer
+ header = new(btfHeader)
+ headerLen = binary.Size(header)
+ )
+
+ // Reserve space for the header. We have to write it last since
+ // we don't know the size of the type section yet.
+ _, _ = buf.Write(make([]byte, headerLen))
+
+ // Write type section, just after the header.
+ for _, raw := range s.rawTypes {
+ switch {
+ case opts.StripFuncLinkage && raw.Kind() == kindFunc:
+ raw.SetLinkage(linkageStatic)
+ }
+
+ if err := raw.Marshal(&buf, opts.ByteOrder); err != nil {
+ return nil, fmt.Errorf("can't marshal BTF: %w", err)
+ }
+ }
+
+ typeLen := uint32(buf.Len() - headerLen)
+
+ // Write string section after type section.
+ _, _ = buf.Write(s.strings)
+
+ // Fill out the header, and write it out.
+ header = &btfHeader{
+ Magic: btfMagic,
+ Version: 1,
+ Flags: 0,
+ HdrLen: uint32(headerLen),
+ TypeOff: 0,
+ TypeLen: typeLen,
+ StringOff: typeLen,
+ StringLen: uint32(len(s.strings)),
+ }
+
+ raw := buf.Bytes()
+ err := binary.Write(sliceWriter(raw[:headerLen]), opts.ByteOrder, header)
+ if err != nil {
+ return nil, fmt.Errorf("can't write header: %v", err)
+ }
+
+ return raw, nil
+}
+
+type sliceWriter []byte
+
+func (sw sliceWriter) Write(p []byte) (int, error) {
+ if len(p) != len(sw) {
+ return 0, errors.New("size doesn't match")
+ }
+
+ return copy(sw, p), nil
+}
+
+// Program finds the BTF for a specific section.
+//
+// Length is the number of bytes in the raw BPF instruction stream.
+//
+// Returns an error which may wrap ErrNoExtendedInfo if the Spec doesn't
+// contain extended BTF info.
+func (s *Spec) Program(name string, length uint64) (*Program, error) {
+ if length == 0 {
+ return nil, errors.New("length musn't be zero")
+ }
+
+ if s.funcInfos == nil && s.lineInfos == nil && s.coreRelos == nil {
+ return nil, fmt.Errorf("BTF for section %s: %w", name, ErrNoExtendedInfo)
+ }
+
+ funcInfos, funcOK := s.funcInfos[name]
+ lineInfos, lineOK := s.lineInfos[name]
+ coreRelos, coreOK := s.coreRelos[name]
+
+ if !funcOK && !lineOK && !coreOK {
+ return nil, fmt.Errorf("no extended BTF info for section %s", name)
+ }
+
+ return &Program{s, length, funcInfos, lineInfos, coreRelos}, nil
+}
+
+// Datasec returns the BTF required to create maps which represent data sections.
+func (s *Spec) Datasec(name string) (*Map, error) {
+ var datasec Datasec
+ if err := s.FindType(name, &datasec); err != nil {
+ return nil, fmt.Errorf("data section %s: can't get BTF: %w", name, err)
+ }
+
+ m := NewMap(s, &Void{}, &datasec)
+ return &m, nil
+}
+
+// FindType searches for a type with a specific name.
+//
+// hint determines the type of the returned Type.
+//
+// Returns an error wrapping ErrNotFound if no matching
+// type exists in spec.
+func (s *Spec) FindType(name string, typ Type) error {
+ var (
+ wanted = reflect.TypeOf(typ)
+ candidate Type
+ )
+
+ for _, typ := range s.namedTypes[essentialName(name)] {
+ if reflect.TypeOf(typ) != wanted {
+ continue
+ }
+
+ // Match against the full name, not just the essential one.
+ if typ.name() != name {
+ continue
+ }
+
+ if candidate != nil {
+ return fmt.Errorf("type %s: multiple candidates for %T", name, typ)
+ }
+
+ candidate = typ
+ }
+
+ if candidate == nil {
+ return fmt.Errorf("type %s: %w", name, ErrNotFound)
+ }
+
+ value := reflect.Indirect(reflect.ValueOf(copyType(candidate)))
+ reflect.Indirect(reflect.ValueOf(typ)).Set(value)
+ return nil
+}
+
+// Handle is a reference to BTF loaded into the kernel.
+type Handle struct {
+ fd *internal.FD
+}
+
+// NewHandle loads BTF into the kernel.
+//
+// Returns ErrNotSupported if BTF is not supported.
+func NewHandle(spec *Spec) (*Handle, error) {
+ if err := haveBTF(); err != nil {
+ return nil, err
+ }
+
+ if spec.byteOrder != internal.NativeEndian {
+ return nil, fmt.Errorf("can't load %s BTF on %s", spec.byteOrder, internal.NativeEndian)
+ }
+
+ btf, err := spec.marshal(marshalOpts{
+ ByteOrder: internal.NativeEndian,
+ StripFuncLinkage: haveFuncLinkage() != nil,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("can't marshal BTF: %w", err)
+ }
+
+ if uint64(len(btf)) > math.MaxUint32 {
+ return nil, errors.New("BTF exceeds the maximum size")
+ }
+
+ attr := &bpfLoadBTFAttr{
+ btf: internal.NewSlicePointer(btf),
+ btfSize: uint32(len(btf)),
+ }
+
+ fd, err := bpfLoadBTF(attr)
+ if err != nil {
+ logBuf := make([]byte, 64*1024)
+ attr.logBuf = internal.NewSlicePointer(logBuf)
+ attr.btfLogSize = uint32(len(logBuf))
+ attr.btfLogLevel = 1
+ _, logErr := bpfLoadBTF(attr)
+ return nil, internal.ErrorWithLog(err, logBuf, logErr)
+ }
+
+ return &Handle{fd}, nil
+}
+
+// Close destroys the handle.
+//
+// Subsequent calls to FD will return an invalid value.
+func (h *Handle) Close() error {
+ return h.fd.Close()
+}
+
+// FD returns the file descriptor for the handle.
+func (h *Handle) FD() int {
+ value, err := h.fd.Value()
+ if err != nil {
+ return -1
+ }
+
+ return int(value)
+}
+
+// Map is the BTF for a map.
+type Map struct {
+ spec *Spec
+ key, value Type
+}
+
+// NewMap returns a new Map containing the given values.
+// The key and value arguments are initialized to Void if nil values are given.
+func NewMap(spec *Spec, key Type, value Type) Map {
+ if key == nil {
+ key = &Void{}
+ }
+ if value == nil {
+ value = &Void{}
+ }
+
+ return Map{
+ spec: spec,
+ key: key,
+ value: value,
+ }
+}
+
+// MapSpec should be a method on Map, but is a free function
+// to hide it from users of the ebpf package.
+func MapSpec(m *Map) *Spec {
+ return m.spec
+}
+
+// MapKey should be a method on Map, but is a free function
+// to hide it from users of the ebpf package.
+func MapKey(m *Map) Type {
+ return m.key
+}
+
+// MapValue should be a method on Map, but is a free function
+// to hide it from users of the ebpf package.
+func MapValue(m *Map) Type {
+ return m.value
+}
+
+// Program is the BTF information for a stream of instructions.
+type Program struct {
+ spec *Spec
+ length uint64
+ funcInfos, lineInfos extInfo
+ coreRelos bpfCoreRelos
+}
+
+// ProgramSpec returns the Spec needed for loading function and line infos into the kernel.
+//
+// This is a free function instead of a method to hide it from users
+// of package ebpf.
+func ProgramSpec(s *Program) *Spec {
+ return s.spec
+}
+
+// ProgramAppend the information from other to the Program.
+//
+// This is a free function instead of a method to hide it from users
+// of package ebpf.
+func ProgramAppend(s, other *Program) error {
+ funcInfos, err := s.funcInfos.append(other.funcInfos, s.length)
+ if err != nil {
+ return fmt.Errorf("func infos: %w", err)
+ }
+
+ lineInfos, err := s.lineInfos.append(other.lineInfos, s.length)
+ if err != nil {
+ return fmt.Errorf("line infos: %w", err)
+ }
+
+ s.funcInfos = funcInfos
+ s.lineInfos = lineInfos
+ s.coreRelos = s.coreRelos.append(other.coreRelos, s.length)
+ s.length += other.length
+ return nil
+}
+
+// ProgramFuncInfos returns the binary form of BTF function infos.
+//
+// This is a free function instead of a method to hide it from users
+// of package ebpf.
+func ProgramFuncInfos(s *Program) (recordSize uint32, bytes []byte, err error) {
+ bytes, err = s.funcInfos.MarshalBinary()
+ if err != nil {
+ return 0, nil, err
+ }
+
+ return s.funcInfos.recordSize, bytes, nil
+}
+
+// ProgramLineInfos returns the binary form of BTF line infos.
+//
+// This is a free function instead of a method to hide it from users
+// of package ebpf.
+func ProgramLineInfos(s *Program) (recordSize uint32, bytes []byte, err error) {
+ bytes, err = s.lineInfos.MarshalBinary()
+ if err != nil {
+ return 0, nil, err
+ }
+
+ return s.lineInfos.recordSize, bytes, nil
+}
+
+// ProgramRelocations returns the CO-RE relocations required to adjust the
+// program to the target.
+//
+// This is a free function instead of a method to hide it from users
+// of package ebpf.
+func ProgramRelocations(s *Program, target *Spec) (map[uint64]Relocation, error) {
+ if len(s.coreRelos) == 0 {
+ return nil, nil
+ }
+
+ return coreRelocate(s.spec, target, s.coreRelos)
+}
+
+type bpfLoadBTFAttr struct {
+ btf internal.Pointer
+ logBuf internal.Pointer
+ btfSize uint32
+ btfLogSize uint32
+ btfLogLevel uint32
+}
+
+func bpfLoadBTF(attr *bpfLoadBTFAttr) (*internal.FD, error) {
+ fd, err := internal.BPF(internal.BPF_BTF_LOAD, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ if err != nil {
+ return nil, err
+ }
+
+ return internal.NewFD(uint32(fd)), nil
+}
+
+func marshalBTF(types interface{}, strings []byte, bo binary.ByteOrder) []byte {
+ const minHeaderLength = 24
+
+ typesLen := uint32(binary.Size(types))
+ header := btfHeader{
+ Magic: btfMagic,
+ Version: 1,
+ HdrLen: minHeaderLength,
+ TypeOff: 0,
+ TypeLen: typesLen,
+ StringOff: typesLen,
+ StringLen: uint32(len(strings)),
+ }
+
+ buf := new(bytes.Buffer)
+ _ = binary.Write(buf, bo, &header)
+ _ = binary.Write(buf, bo, types)
+ buf.Write(strings)
+
+ return buf.Bytes()
+}
+
+var haveBTF = internal.FeatureTest("BTF", "5.1", func() error {
+ var (
+ types struct {
+ Integer btfType
+ Var btfType
+ btfVar struct{ Linkage uint32 }
+ }
+ strings = []byte{0, 'a', 0}
+ )
+
+ // We use a BTF_KIND_VAR here, to make sure that
+ // the kernel understands BTF at least as well as we
+ // do. BTF_KIND_VAR was introduced ~5.1.
+ types.Integer.SetKind(kindPointer)
+ types.Var.NameOff = 1
+ types.Var.SetKind(kindVar)
+ types.Var.SizeType = 1
+
+ btf := marshalBTF(&types, strings, internal.NativeEndian)
+
+ fd, err := bpfLoadBTF(&bpfLoadBTFAttr{
+ btf: internal.NewSlicePointer(btf),
+ btfSize: uint32(len(btf)),
+ })
+ if errors.Is(err, unix.EINVAL) || errors.Is(err, unix.EPERM) {
+ // Treat both EINVAL and EPERM as not supported: loading the program
+ // might still succeed without BTF.
+ return internal.ErrNotSupported
+ }
+ if err != nil {
+ return err
+ }
+
+ fd.Close()
+ return nil
+})
+
+var haveFuncLinkage = internal.FeatureTest("BTF func linkage", "5.6", func() error {
+ if err := haveBTF(); err != nil {
+ return err
+ }
+
+ var (
+ types struct {
+ FuncProto btfType
+ Func btfType
+ }
+ strings = []byte{0, 'a', 0}
+ )
+
+ types.FuncProto.SetKind(kindFuncProto)
+ types.Func.SetKind(kindFunc)
+ types.Func.SizeType = 1 // aka FuncProto
+ types.Func.NameOff = 1
+ types.Func.SetLinkage(linkageGlobal)
+
+ btf := marshalBTF(&types, strings, internal.NativeEndian)
+
+ fd, err := bpfLoadBTF(&bpfLoadBTFAttr{
+ btf: internal.NewSlicePointer(btf),
+ btfSize: uint32(len(btf)),
+ })
+ if errors.Is(err, unix.EINVAL) {
+ return internal.ErrNotSupported
+ }
+ if err != nil {
+ return err
+ }
+
+ fd.Close()
+ return nil
+})
diff --git a/vendor/github.com/cilium/ebpf/internal/btf/btf_types.go b/vendor/github.com/cilium/ebpf/internal/btf/btf_types.go
@@ -0,0 +1,269 @@
+package btf
+
+import (
+ "encoding/binary"
+ "fmt"
+ "io"
+)
+
+// btfKind describes a Type.
+type btfKind uint8
+
+// Equivalents of the BTF_KIND_* constants.
+const (
+ kindUnknown btfKind = iota
+ kindInt
+ kindPointer
+ kindArray
+ kindStruct
+ kindUnion
+ kindEnum
+ kindForward
+ kindTypedef
+ kindVolatile
+ kindConst
+ kindRestrict
+ // Added ~4.20
+ kindFunc
+ kindFuncProto
+ // Added ~5.1
+ kindVar
+ kindDatasec
+)
+
+type btfFuncLinkage uint8
+
+const (
+ linkageStatic btfFuncLinkage = iota
+ linkageGlobal
+ linkageExtern
+)
+
+const (
+ btfTypeKindShift = 24
+ btfTypeKindLen = 4
+ btfTypeVlenShift = 0
+ btfTypeVlenMask = 16
+ btfTypeKindFlagShift = 31
+ btfTypeKindFlagMask = 1
+)
+
+// btfType is equivalent to struct btf_type in Documentation/bpf/btf.rst.
+type btfType struct {
+ NameOff uint32
+ /* "info" bits arrangement
+ * bits 0-15: vlen (e.g. # of struct's members), linkage
+ * bits 16-23: unused
+ * bits 24-27: kind (e.g. int, ptr, array...etc)
+ * bits 28-30: unused
+ * bit 31: kind_flag, currently used by
+ * struct, union and fwd
+ */
+ Info uint32
+ /* "size" is used by INT, ENUM, STRUCT and UNION.
+ * "size" tells the size of the type it is describing.
+ *
+ * "type" is used by PTR, TYPEDEF, VOLATILE, CONST, RESTRICT,
+ * FUNC and FUNC_PROTO.
+ * "type" is a type_id referring to another type.
+ */
+ SizeType uint32
+}
+
+func (k btfKind) String() string {
+ switch k {
+ case kindUnknown:
+ return "Unknown"
+ case kindInt:
+ return "Integer"
+ case kindPointer:
+ return "Pointer"
+ case kindArray:
+ return "Array"
+ case kindStruct:
+ return "Struct"
+ case kindUnion:
+ return "Union"
+ case kindEnum:
+ return "Enumeration"
+ case kindForward:
+ return "Forward"
+ case kindTypedef:
+ return "Typedef"
+ case kindVolatile:
+ return "Volatile"
+ case kindConst:
+ return "Const"
+ case kindRestrict:
+ return "Restrict"
+ case kindFunc:
+ return "Function"
+ case kindFuncProto:
+ return "Function Proto"
+ case kindVar:
+ return "Variable"
+ case kindDatasec:
+ return "Section"
+ default:
+ return fmt.Sprintf("Unknown (%d)", k)
+ }
+}
+
+func mask(len uint32) uint32 {
+ return (1 << len) - 1
+}
+
+func (bt *btfType) info(len, shift uint32) uint32 {
+ return (bt.Info >> shift) & mask(len)
+}
+
+func (bt *btfType) setInfo(value, len, shift uint32) {
+ bt.Info &^= mask(len) << shift
+ bt.Info |= (value & mask(len)) << shift
+}
+
+func (bt *btfType) Kind() btfKind {
+ return btfKind(bt.info(btfTypeKindLen, btfTypeKindShift))
+}
+
+func (bt *btfType) SetKind(kind btfKind) {
+ bt.setInfo(uint32(kind), btfTypeKindLen, btfTypeKindShift)
+}
+
+func (bt *btfType) Vlen() int {
+ return int(bt.info(btfTypeVlenMask, btfTypeVlenShift))
+}
+
+func (bt *btfType) SetVlen(vlen int) {
+ bt.setInfo(uint32(vlen), btfTypeVlenMask, btfTypeVlenShift)
+}
+
+func (bt *btfType) KindFlag() bool {
+ return bt.info(btfTypeKindFlagMask, btfTypeKindFlagShift) == 1
+}
+
+func (bt *btfType) Linkage() btfFuncLinkage {
+ return btfFuncLinkage(bt.info(btfTypeVlenMask, btfTypeVlenShift))
+}
+
+func (bt *btfType) SetLinkage(linkage btfFuncLinkage) {
+ bt.setInfo(uint32(linkage), btfTypeVlenMask, btfTypeVlenShift)
+}
+
+func (bt *btfType) Type() TypeID {
+ // TODO: Panic here if wrong kind?
+ return TypeID(bt.SizeType)
+}
+
+func (bt *btfType) Size() uint32 {
+ // TODO: Panic here if wrong kind?
+ return bt.SizeType
+}
+
+type rawType struct {
+ btfType
+ data interface{}
+}
+
+func (rt *rawType) Marshal(w io.Writer, bo binary.ByteOrder) error {
+ if err := binary.Write(w, bo, &rt.btfType); err != nil {
+ return err
+ }
+
+ if rt.data == nil {
+ return nil
+ }
+
+ return binary.Write(w, bo, rt.data)
+}
+
+type btfArray struct {
+ Type TypeID
+ IndexType TypeID
+ Nelems uint32
+}
+
+type btfMember struct {
+ NameOff uint32
+ Type TypeID
+ Offset uint32
+}
+
+type btfVarSecinfo struct {
+ Type TypeID
+ Offset uint32
+ Size uint32
+}
+
+type btfVariable struct {
+ Linkage uint32
+}
+
+type btfEnum struct {
+ NameOff uint32
+ Val int32
+}
+
+type btfParam struct {
+ NameOff uint32
+ Type TypeID
+}
+
+func readTypes(r io.Reader, bo binary.ByteOrder) ([]rawType, error) {
+ var (
+ header btfType
+ types []rawType
+ )
+
+ for id := TypeID(1); ; id++ {
+ if err := binary.Read(r, bo, &header); err == io.EOF {
+ return types, nil
+ } else if err != nil {
+ return nil, fmt.Errorf("can't read type info for id %v: %v", id, err)
+ }
+
+ var data interface{}
+ switch header.Kind() {
+ case kindInt:
+ data = new(uint32)
+ case kindPointer:
+ case kindArray:
+ data = new(btfArray)
+ case kindStruct:
+ fallthrough
+ case kindUnion:
+ data = make([]btfMember, header.Vlen())
+ case kindEnum:
+ data = make([]btfEnum, header.Vlen())
+ case kindForward:
+ case kindTypedef:
+ case kindVolatile:
+ case kindConst:
+ case kindRestrict:
+ case kindFunc:
+ case kindFuncProto:
+ data = make([]btfParam, header.Vlen())
+ case kindVar:
+ data = new(btfVariable)
+ case kindDatasec:
+ data = make([]btfVarSecinfo, header.Vlen())
+ default:
+ return nil, fmt.Errorf("type id %v: unknown kind: %v", id, header.Kind())
+ }
+
+ if data == nil {
+ types = append(types, rawType{header, nil})
+ continue
+ }
+
+ if err := binary.Read(r, bo, data); err != nil {
+ return nil, fmt.Errorf("type id %d: kind %v: can't read %T: %v", id, header.Kind(), data, err)
+ }
+
+ types = append(types, rawType{header, data})
+ }
+}
+
+func intEncoding(raw uint32) (IntEncoding, uint32, byte) {
+ return IntEncoding((raw & 0x0f000000) >> 24), (raw & 0x00ff0000) >> 16, byte(raw & 0x000000ff)
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/btf/core.go b/vendor/github.com/cilium/ebpf/internal/btf/core.go
@@ -0,0 +1,388 @@
+package btf
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "strconv"
+ "strings"
+)
+
+// Code in this file is derived from libbpf, which is available under a BSD
+// 2-Clause license.
+
+// Relocation describes a CO-RE relocation.
+type Relocation struct {
+ Current uint32
+ New uint32
+}
+
+func (r Relocation) equal(other Relocation) bool {
+ return r.Current == other.Current && r.New == other.New
+}
+
+// coreReloKind is the type of CO-RE relocation
+type coreReloKind uint32
+
+const (
+ reloFieldByteOffset coreReloKind = iota /* field byte offset */
+ reloFieldByteSize /* field size in bytes */
+ reloFieldExists /* field existence in target kernel */
+ reloFieldSigned /* field signedness (0 - unsigned, 1 - signed) */
+ reloFieldLShiftU64 /* bitfield-specific left bitshift */
+ reloFieldRShiftU64 /* bitfield-specific right bitshift */
+ reloTypeIDLocal /* type ID in local BPF object */
+ reloTypeIDTarget /* type ID in target kernel */
+ reloTypeExists /* type existence in target kernel */
+ reloTypeSize /* type size in bytes */
+ reloEnumvalExists /* enum value existence in target kernel */
+ reloEnumvalValue /* enum value integer value */
+)
+
+func (k coreReloKind) String() string {
+ switch k {
+ case reloFieldByteOffset:
+ return "byte_off"
+ case reloFieldByteSize:
+ return "byte_sz"
+ case reloFieldExists:
+ return "field_exists"
+ case reloFieldSigned:
+ return "signed"
+ case reloFieldLShiftU64:
+ return "lshift_u64"
+ case reloFieldRShiftU64:
+ return "rshift_u64"
+ case reloTypeIDLocal:
+ return "local_type_id"
+ case reloTypeIDTarget:
+ return "target_type_id"
+ case reloTypeExists:
+ return "type_exists"
+ case reloTypeSize:
+ return "type_size"
+ case reloEnumvalExists:
+ return "enumval_exists"
+ case reloEnumvalValue:
+ return "enumval_value"
+ default:
+ return "unknown"
+ }
+}
+
+func coreRelocate(local, target *Spec, coreRelos bpfCoreRelos) (map[uint64]Relocation, error) {
+ if target == nil {
+ var err error
+ target, err = loadKernelSpec()
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ if local.byteOrder != target.byteOrder {
+ return nil, fmt.Errorf("can't relocate %s against %s", local.byteOrder, target.byteOrder)
+ }
+
+ relocations := make(map[uint64]Relocation, len(coreRelos))
+ for _, relo := range coreRelos {
+ accessorStr, err := local.strings.Lookup(relo.AccessStrOff)
+ if err != nil {
+ return nil, err
+ }
+
+ accessor, err := parseCoreAccessor(accessorStr)
+ if err != nil {
+ return nil, fmt.Errorf("accessor %q: %s", accessorStr, err)
+ }
+
+ if int(relo.TypeID) >= len(local.types) {
+ return nil, fmt.Errorf("invalid type id %d", relo.TypeID)
+ }
+
+ typ := local.types[relo.TypeID]
+
+ if relo.ReloKind == reloTypeIDLocal {
+ relocations[uint64(relo.InsnOff)] = Relocation{
+ uint32(typ.ID()),
+ uint32(typ.ID()),
+ }
+ continue
+ }
+
+ named, ok := typ.(namedType)
+ if !ok || named.name() == "" {
+ return nil, fmt.Errorf("relocate anonymous type %s: %w", typ.String(), ErrNotSupported)
+ }
+
+ name := essentialName(named.name())
+ res, err := coreCalculateRelocation(typ, target.namedTypes[name], relo.ReloKind, accessor)
+ if err != nil {
+ return nil, fmt.Errorf("relocate %s: %w", name, err)
+ }
+
+ relocations[uint64(relo.InsnOff)] = res
+ }
+
+ return relocations, nil
+}
+
+var errAmbiguousRelocation = errors.New("ambiguous relocation")
+
+func coreCalculateRelocation(local Type, targets []namedType, kind coreReloKind, localAccessor coreAccessor) (Relocation, error) {
+ var relos []Relocation
+ var matches []Type
+ for _, target := range targets {
+ switch kind {
+ case reloTypeIDTarget:
+ if localAccessor[0] != 0 {
+ return Relocation{}, fmt.Errorf("%s: unexpected non-zero accessor", kind)
+ }
+
+ if compat, err := coreAreTypesCompatible(local, target); err != nil {
+ return Relocation{}, fmt.Errorf("%s: %s", kind, err)
+ } else if !compat {
+ continue
+ }
+
+ relos = append(relos, Relocation{uint32(target.ID()), uint32(target.ID())})
+
+ default:
+ return Relocation{}, fmt.Errorf("relocation %s: %w", kind, ErrNotSupported)
+ }
+ matches = append(matches, target)
+ }
+
+ if len(relos) == 0 {
+ // TODO: Add switch for existence checks like reloEnumvalExists here.
+
+ // TODO: This might have to be poisoned.
+ return Relocation{}, fmt.Errorf("no relocation found, tried %v", targets)
+ }
+
+ relo := relos[0]
+ for _, altRelo := range relos[1:] {
+ if !altRelo.equal(relo) {
+ return Relocation{}, fmt.Errorf("multiple types %v match: %w", matches, errAmbiguousRelocation)
+ }
+ }
+
+ return relo, nil
+}
+
+/* coreAccessor contains a path through a struct. It contains at least one index.
+ *
+ * The interpretation depends on the kind of the relocation. The following is
+ * taken from struct bpf_core_relo in libbpf_internal.h:
+ *
+ * - for field-based relocations, string encodes an accessed field using
+ * a sequence of field and array indices, separated by colon (:). It's
+ * conceptually very close to LLVM's getelementptr ([0]) instruction's
+ * arguments for identifying offset to a field.
+ * - for type-based relocations, strings is expected to be just "0";
+ * - for enum value-based relocations, string contains an index of enum
+ * value within its enum type;
+ *
+ * Example to provide a better feel.
+ *
+ * struct sample {
+ * int a;
+ * struct {
+ * int b[10];
+ * };
+ * };
+ *
+ * struct sample s = ...;
+ * int x = &s->a; // encoded as "0:0" (a is field #0)
+ * int y = &s->b[5]; // encoded as "0:1:0:5" (anon struct is field #1,
+ * // b is field #0 inside anon struct, accessing elem #5)
+ * int z = &s[10]->b; // encoded as "10:1" (ptr is used as an array)
+ */
+type coreAccessor []int
+
+func parseCoreAccessor(accessor string) (coreAccessor, error) {
+ if accessor == "" {
+ return nil, fmt.Errorf("empty accessor")
+ }
+
+ var result coreAccessor
+ parts := strings.Split(accessor, ":")
+ for _, part := range parts {
+ // 31 bits to avoid overflowing int on 32 bit platforms.
+ index, err := strconv.ParseUint(part, 10, 31)
+ if err != nil {
+ return nil, fmt.Errorf("accessor index %q: %s", part, err)
+ }
+
+ result = append(result, int(index))
+ }
+
+ return result, nil
+}
+
+/* The comment below is from bpf_core_types_are_compat in libbpf.c:
+ *
+ * Check local and target types for compatibility. This check is used for
+ * type-based CO-RE relocations and follow slightly different rules than
+ * field-based relocations. This function assumes that root types were already
+ * checked for name match. Beyond that initial root-level name check, names
+ * are completely ignored. Compatibility rules are as follows:
+ * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
+ * kind should match for local and target types (i.e., STRUCT is not
+ * compatible with UNION);
+ * - for ENUMs, the size is ignored;
+ * - for INT, size and signedness are ignored;
+ * - for ARRAY, dimensionality is ignored, element types are checked for
+ * compatibility recursively;
+ * - CONST/VOLATILE/RESTRICT modifiers are ignored;
+ * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
+ * - FUNC_PROTOs are compatible if they have compatible signature: same
+ * number of input args and compatible return and argument types.
+ * These rules are not set in stone and probably will be adjusted as we get
+ * more experience with using BPF CO-RE relocations.
+ */
+func coreAreTypesCompatible(localType Type, targetType Type) (bool, error) {
+ var (
+ localTs, targetTs typeDeque
+ l, t = &localType, &targetType
+ depth = 0
+ )
+
+ for ; l != nil && t != nil; l, t = localTs.shift(), targetTs.shift() {
+ if depth >= maxTypeDepth {
+ return false, errors.New("types are nested too deep")
+ }
+
+ localType = skipQualifierAndTypedef(*l)
+ targetType = skipQualifierAndTypedef(*t)
+
+ if reflect.TypeOf(localType) != reflect.TypeOf(targetType) {
+ return false, nil
+ }
+
+ switch lv := (localType).(type) {
+ case *Void, *Struct, *Union, *Enum, *Fwd:
+ // Nothing to do here
+
+ case *Int:
+ tv := targetType.(*Int)
+ if lv.isBitfield() || tv.isBitfield() {
+ return false, nil
+ }
+
+ case *Pointer, *Array:
+ depth++
+ localType.walk(&localTs)
+ targetType.walk(&targetTs)
+
+ case *FuncProto:
+ tv := targetType.(*FuncProto)
+ if len(lv.Params) != len(tv.Params) {
+ return false, nil
+ }
+
+ depth++
+ localType.walk(&localTs)
+ targetType.walk(&targetTs)
+
+ default:
+ return false, fmt.Errorf("unsupported type %T", localType)
+ }
+ }
+
+ if l != nil {
+ return false, fmt.Errorf("dangling local type %T", *l)
+ }
+
+ if t != nil {
+ return false, fmt.Errorf("dangling target type %T", *t)
+ }
+
+ return true, nil
+}
+
+/* The comment below is from bpf_core_fields_are_compat in libbpf.c:
+ *
+ * Check two types for compatibility for the purpose of field access
+ * relocation. const/volatile/restrict and typedefs are skipped to ensure we
+ * are relocating semantically compatible entities:
+ * - any two STRUCTs/UNIONs are compatible and can be mixed;
+ * - any two FWDs are compatible, if their names match (modulo flavor suffix);
+ * - any two PTRs are always compatible;
+ * - for ENUMs, names should be the same (ignoring flavor suffix) or at
+ * least one of enums should be anonymous;
+ * - for ENUMs, check sizes, names are ignored;
+ * - for INT, size and signedness are ignored;
+ * - for ARRAY, dimensionality is ignored, element types are checked for
+ * compatibility recursively;
+ * - everything else shouldn't be ever a target of relocation.
+ * These rules are not set in stone and probably will be adjusted as we get
+ * more experience with using BPF CO-RE relocations.
+ */
+func coreAreMembersCompatible(localType Type, targetType Type) (bool, error) {
+ doNamesMatch := func(a, b string) bool {
+ if a == "" || b == "" {
+ // allow anonymous and named type to match
+ return true
+ }
+
+ return essentialName(a) == essentialName(b)
+ }
+
+ for depth := 0; depth <= maxTypeDepth; depth++ {
+ localType = skipQualifierAndTypedef(localType)
+ targetType = skipQualifierAndTypedef(targetType)
+
+ _, lok := localType.(composite)
+ _, tok := targetType.(composite)
+ if lok && tok {
+ return true, nil
+ }
+
+ if reflect.TypeOf(localType) != reflect.TypeOf(targetType) {
+ return false, nil
+ }
+
+ switch lv := localType.(type) {
+ case *Pointer:
+ return true, nil
+
+ case *Enum:
+ tv := targetType.(*Enum)
+ return doNamesMatch(lv.name(), tv.name()), nil
+
+ case *Fwd:
+ tv := targetType.(*Fwd)
+ return doNamesMatch(lv.name(), tv.name()), nil
+
+ case *Int:
+ tv := targetType.(*Int)
+ return !lv.isBitfield() && !tv.isBitfield(), nil
+
+ case *Array:
+ tv := targetType.(*Array)
+
+ localType = lv.Type
+ targetType = tv.Type
+
+ default:
+ return false, fmt.Errorf("unsupported type %T", localType)
+ }
+ }
+
+ return false, errors.New("types are nested too deep")
+}
+
+func skipQualifierAndTypedef(typ Type) Type {
+ result := typ
+ for depth := 0; depth <= maxTypeDepth; depth++ {
+ switch v := (result).(type) {
+ case qualifier:
+ result = v.qualify()
+ case *Typedef:
+ result = v.Type
+ default:
+ return result
+ }
+ }
+ return typ
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/btf/doc.go b/vendor/github.com/cilium/ebpf/internal/btf/doc.go
@@ -0,0 +1,8 @@
+// Package btf handles data encoded according to the BPF Type Format.
+//
+// The canonical documentation lives in the Linux kernel repository and is
+// available at https://www.kernel.org/doc/html/latest/bpf/btf.html
+//
+// The API is very much unstable. You should only use this via the main
+// ebpf library.
+package btf
diff --git a/vendor/github.com/cilium/ebpf/internal/btf/ext_info.go b/vendor/github.com/cilium/ebpf/internal/btf/ext_info.go
@@ -0,0 +1,281 @@
+package btf
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+
+ "github.com/cilium/ebpf/asm"
+ "github.com/cilium/ebpf/internal"
+)
+
+type btfExtHeader struct {
+ Magic uint16
+ Version uint8
+ Flags uint8
+ HdrLen uint32
+
+ FuncInfoOff uint32
+ FuncInfoLen uint32
+ LineInfoOff uint32
+ LineInfoLen uint32
+}
+
+type btfExtCoreHeader struct {
+ CoreReloOff uint32
+ CoreReloLen uint32
+}
+
+func parseExtInfos(r io.ReadSeeker, bo binary.ByteOrder, strings stringTable) (funcInfo, lineInfo map[string]extInfo, coreRelos map[string]bpfCoreRelos, err error) {
+ var header btfExtHeader
+ var coreHeader btfExtCoreHeader
+ if err := binary.Read(r, bo, &header); err != nil {
+ return nil, nil, nil, fmt.Errorf("can't read header: %v", err)
+ }
+
+ if header.Magic != btfMagic {
+ return nil, nil, nil, fmt.Errorf("incorrect magic value %v", header.Magic)
+ }
+
+ if header.Version != 1 {
+ return nil, nil, nil, fmt.Errorf("unexpected version %v", header.Version)
+ }
+
+ if header.Flags != 0 {
+ return nil, nil, nil, fmt.Errorf("unsupported flags %v", header.Flags)
+ }
+
+ remainder := int64(header.HdrLen) - int64(binary.Size(&header))
+ if remainder < 0 {
+ return nil, nil, nil, errors.New("header is too short")
+ }
+
+ coreHdrSize := int64(binary.Size(&coreHeader))
+ if remainder >= coreHdrSize {
+ if err := binary.Read(r, bo, &coreHeader); err != nil {
+ return nil, nil, nil, fmt.Errorf("can't read CO-RE relocation header: %v", err)
+ }
+ remainder -= coreHdrSize
+ }
+
+ // Of course, the .BTF.ext header has different semantics than the
+ // .BTF ext header. We need to ignore non-null values.
+ _, err = io.CopyN(ioutil.Discard, r, remainder)
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("header padding: %v", err)
+ }
+
+ if _, err := r.Seek(int64(header.HdrLen+header.FuncInfoOff), io.SeekStart); err != nil {
+ return nil, nil, nil, fmt.Errorf("can't seek to function info section: %v", err)
+ }
+
+ buf := bufio.NewReader(io.LimitReader(r, int64(header.FuncInfoLen)))
+ funcInfo, err = parseExtInfo(buf, bo, strings)
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("function info: %w", err)
+ }
+
+ if _, err := r.Seek(int64(header.HdrLen+header.LineInfoOff), io.SeekStart); err != nil {
+ return nil, nil, nil, fmt.Errorf("can't seek to line info section: %v", err)
+ }
+
+ buf = bufio.NewReader(io.LimitReader(r, int64(header.LineInfoLen)))
+ lineInfo, err = parseExtInfo(buf, bo, strings)
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("line info: %w", err)
+ }
+
+ if coreHeader.CoreReloOff > 0 && coreHeader.CoreReloLen > 0 {
+ if _, err := r.Seek(int64(header.HdrLen+coreHeader.CoreReloOff), io.SeekStart); err != nil {
+ return nil, nil, nil, fmt.Errorf("can't seek to CO-RE relocation section: %v", err)
+ }
+
+ coreRelos, err = parseExtInfoRelos(io.LimitReader(r, int64(coreHeader.CoreReloLen)), bo, strings)
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("CO-RE relocation info: %w", err)
+ }
+ }
+
+ return funcInfo, lineInfo, coreRelos, nil
+}
+
+type btfExtInfoSec struct {
+ SecNameOff uint32
+ NumInfo uint32
+}
+
+type extInfoRecord struct {
+ InsnOff uint64
+ Opaque []byte
+}
+
+type extInfo struct {
+ recordSize uint32
+ records []extInfoRecord
+}
+
+func (ei extInfo) append(other extInfo, offset uint64) (extInfo, error) {
+ if other.recordSize != ei.recordSize {
+ return extInfo{}, fmt.Errorf("ext_info record size mismatch, want %d (got %d)", ei.recordSize, other.recordSize)
+ }
+
+ records := make([]extInfoRecord, 0, len(ei.records)+len(other.records))
+ records = append(records, ei.records...)
+ for _, info := range other.records {
+ records = append(records, extInfoRecord{
+ InsnOff: info.InsnOff + offset,
+ Opaque: info.Opaque,
+ })
+ }
+ return extInfo{ei.recordSize, records}, nil
+}
+
+func (ei extInfo) MarshalBinary() ([]byte, error) {
+ if len(ei.records) == 0 {
+ return nil, nil
+ }
+
+ buf := bytes.NewBuffer(make([]byte, 0, int(ei.recordSize)*len(ei.records)))
+ for _, info := range ei.records {
+ // The kernel expects offsets in number of raw bpf instructions,
+ // while the ELF tracks it in bytes.
+ insnOff := uint32(info.InsnOff / asm.InstructionSize)
+ if err := binary.Write(buf, internal.NativeEndian, insnOff); err != nil {
+ return nil, fmt.Errorf("can't write instruction offset: %v", err)
+ }
+
+ buf.Write(info.Opaque)
+ }
+
+ return buf.Bytes(), nil
+}
+
+func parseExtInfo(r io.Reader, bo binary.ByteOrder, strings stringTable) (map[string]extInfo, error) {
+ const maxRecordSize = 256
+
+ var recordSize uint32
+ if err := binary.Read(r, bo, &recordSize); err != nil {
+ return nil, fmt.Errorf("can't read record size: %v", err)
+ }
+
+ if recordSize < 4 {
+ // Need at least insnOff
+ return nil, errors.New("record size too short")
+ }
+ if recordSize > maxRecordSize {
+ return nil, fmt.Errorf("record size %v exceeds %v", recordSize, maxRecordSize)
+ }
+
+ result := make(map[string]extInfo)
+ for {
+ secName, infoHeader, err := parseExtInfoHeader(r, bo, strings)
+ if errors.Is(err, io.EOF) {
+ return result, nil
+ }
+
+ var records []extInfoRecord
+ for i := uint32(0); i < infoHeader.NumInfo; i++ {
+ var byteOff uint32
+ if err := binary.Read(r, bo, &byteOff); err != nil {
+ return nil, fmt.Errorf("section %v: can't read extended info offset: %v", secName, err)
+ }
+
+ buf := make([]byte, int(recordSize-4))
+ if _, err := io.ReadFull(r, buf); err != nil {
+ return nil, fmt.Errorf("section %v: can't read record: %v", secName, err)
+ }
+
+ if byteOff%asm.InstructionSize != 0 {
+ return nil, fmt.Errorf("section %v: offset %v is not aligned with instruction size", secName, byteOff)
+ }
+
+ records = append(records, extInfoRecord{uint64(byteOff), buf})
+ }
+
+ result[secName] = extInfo{
+ recordSize,
+ records,
+ }
+ }
+}
+
+// bpfCoreRelo matches `struct bpf_core_relo` from the kernel
+type bpfCoreRelo struct {
+ InsnOff uint32
+ TypeID TypeID
+ AccessStrOff uint32
+ ReloKind coreReloKind
+}
+
+type bpfCoreRelos []bpfCoreRelo
+
+// append two slices of extInfoRelo to each other. The InsnOff of b are adjusted
+// by offset.
+func (r bpfCoreRelos) append(other bpfCoreRelos, offset uint64) bpfCoreRelos {
+ result := make([]bpfCoreRelo, 0, len(r)+len(other))
+ result = append(result, r...)
+ for _, relo := range other {
+ relo.InsnOff += uint32(offset)
+ result = append(result, relo)
+ }
+ return result
+}
+
+var extInfoReloSize = binary.Size(bpfCoreRelo{})
+
+func parseExtInfoRelos(r io.Reader, bo binary.ByteOrder, strings stringTable) (map[string]bpfCoreRelos, error) {
+ var recordSize uint32
+ if err := binary.Read(r, bo, &recordSize); err != nil {
+ return nil, fmt.Errorf("read record size: %v", err)
+ }
+
+ if recordSize != uint32(extInfoReloSize) {
+ return nil, fmt.Errorf("expected record size %d, got %d", extInfoReloSize, recordSize)
+ }
+
+ result := make(map[string]bpfCoreRelos)
+ for {
+ secName, infoHeader, err := parseExtInfoHeader(r, bo, strings)
+ if errors.Is(err, io.EOF) {
+ return result, nil
+ }
+
+ var relos []bpfCoreRelo
+ for i := uint32(0); i < infoHeader.NumInfo; i++ {
+ var relo bpfCoreRelo
+ if err := binary.Read(r, bo, &relo); err != nil {
+ return nil, fmt.Errorf("section %v: read record: %v", secName, err)
+ }
+
+ if relo.InsnOff%asm.InstructionSize != 0 {
+ return nil, fmt.Errorf("section %v: offset %v is not aligned with instruction size", secName, relo.InsnOff)
+ }
+
+ relos = append(relos, relo)
+ }
+
+ result[secName] = relos
+ }
+}
+
+func parseExtInfoHeader(r io.Reader, bo binary.ByteOrder, strings stringTable) (string, *btfExtInfoSec, error) {
+ var infoHeader btfExtInfoSec
+ if err := binary.Read(r, bo, &infoHeader); err != nil {
+ return "", nil, fmt.Errorf("read ext info header: %w", err)
+ }
+
+ secName, err := strings.Lookup(infoHeader.SecNameOff)
+ if err != nil {
+ return "", nil, fmt.Errorf("get section name: %w", err)
+ }
+
+ if infoHeader.NumInfo == 0 {
+ return "", nil, fmt.Errorf("section %s has zero records", secName)
+ }
+
+ return secName, &infoHeader, nil
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/btf/fuzz.go b/vendor/github.com/cilium/ebpf/internal/btf/fuzz.go
@@ -0,0 +1,49 @@
+// +build gofuzz
+
+// Use with https://github.com/dvyukov/go-fuzz
+
+package btf
+
+import (
+ "bytes"
+ "encoding/binary"
+
+ "github.com/cilium/ebpf/internal"
+)
+
+func FuzzSpec(data []byte) int {
+ if len(data) < binary.Size(btfHeader{}) {
+ return -1
+ }
+
+ spec, err := loadNakedSpec(bytes.NewReader(data), internal.NativeEndian, nil, nil)
+ if err != nil {
+ if spec != nil {
+ panic("spec is not nil")
+ }
+ return 0
+ }
+ if spec == nil {
+ panic("spec is nil")
+ }
+ return 1
+}
+
+func FuzzExtInfo(data []byte) int {
+ if len(data) < binary.Size(btfExtHeader{}) {
+ return -1
+ }
+
+ table := stringTable("\x00foo\x00barfoo\x00")
+ info, err := parseExtInfo(bytes.NewReader(data), internal.NativeEndian, table)
+ if err != nil {
+ if info != nil {
+ panic("info is not nil")
+ }
+ return 0
+ }
+ if info == nil {
+ panic("info is nil")
+ }
+ return 1
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/btf/strings.go b/vendor/github.com/cilium/ebpf/internal/btf/strings.go
@@ -0,0 +1,60 @@
+package btf
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+)
+
+type stringTable []byte
+
+func readStringTable(r io.Reader) (stringTable, error) {
+ contents, err := ioutil.ReadAll(r)
+ if err != nil {
+ return nil, fmt.Errorf("can't read string table: %v", err)
+ }
+
+ if len(contents) < 1 {
+ return nil, errors.New("string table is empty")
+ }
+
+ if contents[0] != '\x00' {
+ return nil, errors.New("first item in string table is non-empty")
+ }
+
+ if contents[len(contents)-1] != '\x00' {
+ return nil, errors.New("string table isn't null terminated")
+ }
+
+ return stringTable(contents), nil
+}
+
+func (st stringTable) Lookup(offset uint32) (string, error) {
+ if int64(offset) > int64(^uint(0)>>1) {
+ return "", fmt.Errorf("offset %d overflows int", offset)
+ }
+
+ pos := int(offset)
+ if pos >= len(st) {
+ return "", fmt.Errorf("offset %d is out of bounds", offset)
+ }
+
+ if pos > 0 && st[pos-1] != '\x00' {
+ return "", fmt.Errorf("offset %d isn't start of a string", offset)
+ }
+
+ str := st[pos:]
+ end := bytes.IndexByte(str, '\x00')
+ if end == -1 {
+ return "", fmt.Errorf("offset %d isn't null terminated", offset)
+ }
+
+ return string(str[:end]), nil
+}
+
+func (st stringTable) LookupName(offset uint32) (Name, error) {
+ str, err := st.Lookup(offset)
+ return Name(str), err
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/btf/types.go b/vendor/github.com/cilium/ebpf/internal/btf/types.go
@@ -0,0 +1,871 @@
+package btf
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "strings"
+)
+
+const maxTypeDepth = 32
+
+// TypeID identifies a type in a BTF section.
+type TypeID uint32
+
+// ID implements part of the Type interface.
+func (tid TypeID) ID() TypeID {
+ return tid
+}
+
+// Type represents a type described by BTF.
+type Type interface {
+ ID() TypeID
+
+ String() string
+
+ // Make a copy of the type, without copying Type members.
+ copy() Type
+
+ // Enumerate all nested Types. Repeated calls must visit nested
+ // types in the same order.
+ walk(*typeDeque)
+}
+
+// namedType is a type with a name.
+//
+// Most named types simply embed Name.
+type namedType interface {
+ Type
+ name() string
+}
+
+// Name identifies a type.
+//
+// Anonymous types have an empty name.
+type Name string
+
+func (n Name) name() string {
+ return string(n)
+}
+
+// Void is the unit type of BTF.
+type Void struct{}
+
+func (v *Void) ID() TypeID { return 0 }
+func (v *Void) String() string { return "void#0" }
+func (v *Void) size() uint32 { return 0 }
+func (v *Void) copy() Type { return (*Void)(nil) }
+func (v *Void) walk(*typeDeque) {}
+
+type IntEncoding byte
+
+const (
+ Signed IntEncoding = 1 << iota
+ Char
+ Bool
+)
+
+// Int is an integer of a given length.
+type Int struct {
+ TypeID
+ Name
+
+ // The size of the integer in bytes.
+ Size uint32
+ Encoding IntEncoding
+ // Offset is the starting bit offset. Currently always 0.
+ // See https://www.kernel.org/doc/html/latest/bpf/btf.html#btf-kind-int
+ Offset uint32
+ Bits byte
+}
+
+var _ namedType = (*Int)(nil)
+
+func (i *Int) String() string {
+ var s strings.Builder
+
+ switch {
+ case i.Encoding&Char != 0:
+ s.WriteString("char")
+ case i.Encoding&Bool != 0:
+ s.WriteString("bool")
+ default:
+ if i.Encoding&Signed == 0 {
+ s.WriteRune('u')
+ }
+ s.WriteString("int")
+ fmt.Fprintf(&s, "%d", i.Size*8)
+ }
+
+ fmt.Fprintf(&s, "#%d", i.TypeID)
+
+ if i.Bits > 0 {
+ fmt.Fprintf(&s, "[bits=%d]", i.Bits)
+ }
+
+ return s.String()
+}
+
+func (i *Int) size() uint32 { return i.Size }
+func (i *Int) walk(*typeDeque) {}
+func (i *Int) copy() Type {
+ cpy := *i
+ return &cpy
+}
+
+func (i *Int) isBitfield() bool {
+ return i.Offset > 0
+}
+
+// Pointer is a pointer to another type.
+type Pointer struct {
+ TypeID
+ Target Type
+}
+
+func (p *Pointer) String() string {
+ return fmt.Sprintf("pointer#%d[target=#%d]", p.TypeID, p.Target.ID())
+}
+
+func (p *Pointer) size() uint32 { return 8 }
+func (p *Pointer) walk(tdq *typeDeque) { tdq.push(&p.Target) }
+func (p *Pointer) copy() Type {
+ cpy := *p
+ return &cpy
+}
+
+// Array is an array with a fixed number of elements.
+type Array struct {
+ TypeID
+ Type Type
+ Nelems uint32
+}
+
+func (arr *Array) String() string {
+ return fmt.Sprintf("array#%d[type=#%d n=%d]", arr.TypeID, arr.Type.ID(), arr.Nelems)
+}
+
+func (arr *Array) walk(tdq *typeDeque) { tdq.push(&arr.Type) }
+func (arr *Array) copy() Type {
+ cpy := *arr
+ return &cpy
+}
+
+// Struct is a compound type of consecutive members.
+type Struct struct {
+ TypeID
+ Name
+ // The size of the struct including padding, in bytes
+ Size uint32
+ Members []Member
+}
+
+func (s *Struct) String() string {
+ return fmt.Sprintf("struct#%d[%q]", s.TypeID, s.Name)
+}
+
+func (s *Struct) size() uint32 { return s.Size }
+
+func (s *Struct) walk(tdq *typeDeque) {
+ for i := range s.Members {
+ tdq.push(&s.Members[i].Type)
+ }
+}
+
+func (s *Struct) copy() Type {
+ cpy := *s
+ cpy.Members = make([]Member, len(s.Members))
+ copy(cpy.Members, s.Members)
+ return &cpy
+}
+
+func (s *Struct) members() []Member {
+ return s.Members
+}
+
+// Union is a compound type where members occupy the same memory.
+type Union struct {
+ TypeID
+ Name
+ // The size of the union including padding, in bytes.
+ Size uint32
+ Members []Member
+}
+
+func (u *Union) String() string {
+ return fmt.Sprintf("union#%d[%q]", u.TypeID, u.Name)
+}
+
+func (u *Union) size() uint32 { return u.Size }
+
+func (u *Union) walk(tdq *typeDeque) {
+ for i := range u.Members {
+ tdq.push(&u.Members[i].Type)
+ }
+}
+
+func (u *Union) copy() Type {
+ cpy := *u
+ cpy.Members = make([]Member, len(u.Members))
+ copy(cpy.Members, u.Members)
+ return &cpy
+}
+
+func (u *Union) members() []Member {
+ return u.Members
+}
+
+type composite interface {
+ members() []Member
+}
+
+var (
+ _ composite = (*Struct)(nil)
+ _ composite = (*Union)(nil)
+)
+
+// Member is part of a Struct or Union.
+//
+// It is not a valid Type.
+type Member struct {
+ Name
+ Type Type
+ // Offset is the bit offset of this member
+ Offset uint32
+ BitfieldSize uint32
+}
+
+// Enum lists possible values.
+type Enum struct {
+ TypeID
+ Name
+ Values []EnumValue
+}
+
+func (e *Enum) String() string {
+ return fmt.Sprintf("enum#%d[%q]", e.TypeID, e.Name)
+}
+
+// EnumValue is part of an Enum
+//
+// Is is not a valid Type
+type EnumValue struct {
+ Name
+ Value int32
+}
+
+func (e *Enum) size() uint32 { return 4 }
+func (e *Enum) walk(*typeDeque) {}
+func (e *Enum) copy() Type {
+ cpy := *e
+ cpy.Values = make([]EnumValue, len(e.Values))
+ copy(cpy.Values, e.Values)
+ return &cpy
+}
+
+// FwdKind is the type of forward declaration.
+type FwdKind int
+
+// Valid types of forward declaration.
+const (
+ FwdStruct FwdKind = iota
+ FwdUnion
+)
+
+func (fk FwdKind) String() string {
+ switch fk {
+ case FwdStruct:
+ return "struct"
+ case FwdUnion:
+ return "union"
+ default:
+ return fmt.Sprintf("%T(%d)", fk, int(fk))
+ }
+}
+
+// Fwd is a forward declaration of a Type.
+type Fwd struct {
+ TypeID
+ Name
+ Kind FwdKind
+}
+
+func (f *Fwd) String() string {
+ return fmt.Sprintf("fwd#%d[%s %q]", f.TypeID, f.Kind, f.Name)
+}
+
+func (f *Fwd) walk(*typeDeque) {}
+func (f *Fwd) copy() Type {
+ cpy := *f
+ return &cpy
+}
+
+// Typedef is an alias of a Type.
+type Typedef struct {
+ TypeID
+ Name
+ Type Type
+}
+
+func (td *Typedef) String() string {
+ return fmt.Sprintf("typedef#%d[%q #%d]", td.TypeID, td.Name, td.Type.ID())
+}
+
+func (td *Typedef) walk(tdq *typeDeque) { tdq.push(&td.Type) }
+func (td *Typedef) copy() Type {
+ cpy := *td
+ return &cpy
+}
+
+// Volatile is a qualifier.
+type Volatile struct {
+ TypeID
+ Type Type
+}
+
+func (v *Volatile) String() string {
+ return fmt.Sprintf("volatile#%d[#%d]", v.TypeID, v.Type.ID())
+}
+
+func (v *Volatile) qualify() Type { return v.Type }
+func (v *Volatile) walk(tdq *typeDeque) { tdq.push(&v.Type) }
+func (v *Volatile) copy() Type {
+ cpy := *v
+ return &cpy
+}
+
+// Const is a qualifier.
+type Const struct {
+ TypeID
+ Type Type
+}
+
+func (c *Const) String() string {
+ return fmt.Sprintf("const#%d[#%d]", c.TypeID, c.Type.ID())
+}
+
+func (c *Const) qualify() Type { return c.Type }
+func (c *Const) walk(tdq *typeDeque) { tdq.push(&c.Type) }
+func (c *Const) copy() Type {
+ cpy := *c
+ return &cpy
+}
+
+// Restrict is a qualifier.
+type Restrict struct {
+ TypeID
+ Type Type
+}
+
+func (r *Restrict) String() string {
+ return fmt.Sprintf("restrict#%d[#%d]", r.TypeID, r.Type.ID())
+}
+
+func (r *Restrict) qualify() Type { return r.Type }
+func (r *Restrict) walk(tdq *typeDeque) { tdq.push(&r.Type) }
+func (r *Restrict) copy() Type {
+ cpy := *r
+ return &cpy
+}
+
+// Func is a function definition.
+type Func struct {
+ TypeID
+ Name
+ Type Type
+}
+
+func (f *Func) String() string {
+ return fmt.Sprintf("func#%d[%q proto=#%d]", f.TypeID, f.Name, f.Type.ID())
+}
+
+func (f *Func) walk(tdq *typeDeque) { tdq.push(&f.Type) }
+func (f *Func) copy() Type {
+ cpy := *f
+ return &cpy
+}
+
+// FuncProto is a function declaration.
+type FuncProto struct {
+ TypeID
+ Return Type
+ Params []FuncParam
+}
+
+func (fp *FuncProto) String() string {
+ var s strings.Builder
+ fmt.Fprintf(&s, "proto#%d[", fp.TypeID)
+ for _, param := range fp.Params {
+ fmt.Fprintf(&s, "%q=#%d, ", param.Name, param.Type.ID())
+ }
+ fmt.Fprintf(&s, "return=#%d]", fp.Return.ID())
+ return s.String()
+}
+
+func (fp *FuncProto) walk(tdq *typeDeque) {
+ tdq.push(&fp.Return)
+ for i := range fp.Params {
+ tdq.push(&fp.Params[i].Type)
+ }
+}
+
+func (fp *FuncProto) copy() Type {
+ cpy := *fp
+ cpy.Params = make([]FuncParam, len(fp.Params))
+ copy(cpy.Params, fp.Params)
+ return &cpy
+}
+
+type FuncParam struct {
+ Name
+ Type Type
+}
+
+// Var is a global variable.
+type Var struct {
+ TypeID
+ Name
+ Type Type
+}
+
+func (v *Var) String() string {
+ // TODO: Linkage
+ return fmt.Sprintf("var#%d[%q]", v.TypeID, v.Name)
+}
+
+func (v *Var) walk(tdq *typeDeque) { tdq.push(&v.Type) }
+func (v *Var) copy() Type {
+ cpy := *v
+ return &cpy
+}
+
+// Datasec is a global program section containing data.
+type Datasec struct {
+ TypeID
+ Name
+ Size uint32
+ Vars []VarSecinfo
+}
+
+func (ds *Datasec) String() string {
+ return fmt.Sprintf("section#%d[%q]", ds.TypeID, ds.Name)
+}
+
+func (ds *Datasec) size() uint32 { return ds.Size }
+
+func (ds *Datasec) walk(tdq *typeDeque) {
+ for i := range ds.Vars {
+ tdq.push(&ds.Vars[i].Type)
+ }
+}
+
+func (ds *Datasec) copy() Type {
+ cpy := *ds
+ cpy.Vars = make([]VarSecinfo, len(ds.Vars))
+ copy(cpy.Vars, ds.Vars)
+ return &cpy
+}
+
+// VarSecinfo describes variable in a Datasec
+//
+// It is not a valid Type.
+type VarSecinfo struct {
+ Type Type
+ Offset uint32
+ Size uint32
+}
+
+type sizer interface {
+ size() uint32
+}
+
+var (
+ _ sizer = (*Int)(nil)
+ _ sizer = (*Pointer)(nil)
+ _ sizer = (*Struct)(nil)
+ _ sizer = (*Union)(nil)
+ _ sizer = (*Enum)(nil)
+ _ sizer = (*Datasec)(nil)
+)
+
+type qualifier interface {
+ qualify() Type
+}
+
+var (
+ _ qualifier = (*Const)(nil)
+ _ qualifier = (*Restrict)(nil)
+ _ qualifier = (*Volatile)(nil)
+)
+
+// Sizeof returns the size of a type in bytes.
+//
+// Returns an error if the size can't be computed.
+func Sizeof(typ Type) (int, error) {
+ var (
+ n = int64(1)
+ elem int64
+ )
+
+ for i := 0; i < maxTypeDepth; i++ {
+ switch v := typ.(type) {
+ case *Array:
+ if n > 0 && int64(v.Nelems) > math.MaxInt64/n {
+ return 0, errors.New("overflow")
+ }
+
+ // Arrays may be of zero length, which allows
+ // n to be zero as well.
+ n *= int64(v.Nelems)
+ typ = v.Type
+ continue
+
+ case sizer:
+ elem = int64(v.size())
+
+ case *Typedef:
+ typ = v.Type
+ continue
+
+ case qualifier:
+ typ = v.qualify()
+ continue
+
+ default:
+ return 0, fmt.Errorf("unrecognized type %T", typ)
+ }
+
+ if n > 0 && elem > math.MaxInt64/n {
+ return 0, errors.New("overflow")
+ }
+
+ size := n * elem
+ if int64(int(size)) != size {
+ return 0, errors.New("overflow")
+ }
+
+ return int(size), nil
+ }
+
+ return 0, errors.New("exceeded type depth")
+}
+
+// copy a Type recursively.
+//
+// typ may form a cycle.
+func copyType(typ Type) Type {
+ var (
+ copies = make(map[Type]Type)
+ work typeDeque
+ )
+
+ for t := &typ; t != nil; t = work.pop() {
+ // *t is the identity of the type.
+ if cpy := copies[*t]; cpy != nil {
+ *t = cpy
+ continue
+ }
+
+ cpy := (*t).copy()
+ copies[*t] = cpy
+ *t = cpy
+
+ // Mark any nested types for copying.
+ cpy.walk(&work)
+ }
+
+ return typ
+}
+
+// typeDeque keeps track of pointers to types which still
+// need to be visited.
+type typeDeque struct {
+ types []*Type
+ read, write uint64
+ mask uint64
+}
+
+// push adds a type to the stack.
+func (dq *typeDeque) push(t *Type) {
+ if dq.write-dq.read < uint64(len(dq.types)) {
+ dq.types[dq.write&dq.mask] = t
+ dq.write++
+ return
+ }
+
+ new := len(dq.types) * 2
+ if new == 0 {
+ new = 8
+ }
+
+ types := make([]*Type, new)
+ pivot := dq.read & dq.mask
+ n := copy(types, dq.types[pivot:])
+ n += copy(types[n:], dq.types[:pivot])
+ types[n] = t
+
+ dq.types = types
+ dq.mask = uint64(new) - 1
+ dq.read, dq.write = 0, uint64(n+1)
+}
+
+// shift returns the first element or null.
+func (dq *typeDeque) shift() *Type {
+ if dq.read == dq.write {
+ return nil
+ }
+
+ index := dq.read & dq.mask
+ t := dq.types[index]
+ dq.types[index] = nil
+ dq.read++
+ return t
+}
+
+// pop returns the last element or null.
+func (dq *typeDeque) pop() *Type {
+ if dq.read == dq.write {
+ return nil
+ }
+
+ dq.write--
+ index := dq.write & dq.mask
+ t := dq.types[index]
+ dq.types[index] = nil
+ return t
+}
+
+// all returns all elements.
+//
+// The deque is empty after calling this method.
+func (dq *typeDeque) all() []*Type {
+ length := dq.write - dq.read
+ types := make([]*Type, 0, length)
+ for t := dq.shift(); t != nil; t = dq.shift() {
+ types = append(types, t)
+ }
+ return types
+}
+
+// inflateRawTypes takes a list of raw btf types linked via type IDs, and turns
+// it into a graph of Types connected via pointers.
+//
+// Returns a map of named types (so, where NameOff is non-zero) and a slice of types
+// indexed by TypeID. Since BTF ignores compilation units, multiple types may share
+// the same name. A Type may form a cyclic graph by pointing at itself.
+func inflateRawTypes(rawTypes []rawType, rawStrings stringTable) (types []Type, namedTypes map[string][]namedType, err error) {
+ type fixupDef struct {
+ id TypeID
+ expectedKind btfKind
+ typ *Type
+ }
+
+ var fixups []fixupDef
+ fixup := func(id TypeID, expectedKind btfKind, typ *Type) {
+ fixups = append(fixups, fixupDef{id, expectedKind, typ})
+ }
+
+ convertMembers := func(raw []btfMember, kindFlag bool) ([]Member, error) {
+ // NB: The fixup below relies on pre-allocating this array to
+ // work, since otherwise append might re-allocate members.
+ members := make([]Member, 0, len(raw))
+ for i, btfMember := range raw {
+ name, err := rawStrings.LookupName(btfMember.NameOff)
+ if err != nil {
+ return nil, fmt.Errorf("can't get name for member %d: %w", i, err)
+ }
+ m := Member{
+ Name: name,
+ Offset: btfMember.Offset,
+ }
+ if kindFlag {
+ m.BitfieldSize = btfMember.Offset >> 24
+ m.Offset &= 0xffffff
+ }
+ members = append(members, m)
+ }
+ for i := range members {
+ fixup(raw[i].Type, kindUnknown, &members[i].Type)
+ }
+ return members, nil
+ }
+
+ types = make([]Type, 0, len(rawTypes))
+ types = append(types, (*Void)(nil))
+ namedTypes = make(map[string][]namedType)
+
+ for i, raw := range rawTypes {
+ var (
+ // Void is defined to always be type ID 0, and is thus
+ // omitted from BTF.
+ id = TypeID(i + 1)
+ typ Type
+ )
+
+ name, err := rawStrings.LookupName(raw.NameOff)
+ if err != nil {
+ return nil, nil, fmt.Errorf("get name for type id %d: %w", id, err)
+ }
+
+ switch raw.Kind() {
+ case kindInt:
+ encoding, offset, bits := intEncoding(*raw.data.(*uint32))
+ typ = &Int{id, name, raw.Size(), encoding, offset, bits}
+
+ case kindPointer:
+ ptr := &Pointer{id, nil}
+ fixup(raw.Type(), kindUnknown, &ptr.Target)
+ typ = ptr
+
+ case kindArray:
+ btfArr := raw.data.(*btfArray)
+
+ // IndexType is unused according to btf.rst.
+ // Don't make it available right now.
+ arr := &Array{id, nil, btfArr.Nelems}
+ fixup(btfArr.Type, kindUnknown, &arr.Type)
+ typ = arr
+
+ case kindStruct:
+ members, err := convertMembers(raw.data.([]btfMember), raw.KindFlag())
+ if err != nil {
+ return nil, nil, fmt.Errorf("struct %s (id %d): %w", name, id, err)
+ }
+ typ = &Struct{id, name, raw.Size(), members}
+
+ case kindUnion:
+ members, err := convertMembers(raw.data.([]btfMember), raw.KindFlag())
+ if err != nil {
+ return nil, nil, fmt.Errorf("union %s (id %d): %w", name, id, err)
+ }
+ typ = &Union{id, name, raw.Size(), members}
+
+ case kindEnum:
+ rawvals := raw.data.([]btfEnum)
+ vals := make([]EnumValue, 0, len(rawvals))
+ for i, btfVal := range rawvals {
+ name, err := rawStrings.LookupName(btfVal.NameOff)
+ if err != nil {
+ return nil, nil, fmt.Errorf("get name for enum value %d: %s", i, err)
+ }
+ vals = append(vals, EnumValue{
+ Name: name,
+ Value: btfVal.Val,
+ })
+ }
+ typ = &Enum{id, name, vals}
+
+ case kindForward:
+ if raw.KindFlag() {
+ typ = &Fwd{id, name, FwdUnion}
+ } else {
+ typ = &Fwd{id, name, FwdStruct}
+ }
+
+ case kindTypedef:
+ typedef := &Typedef{id, name, nil}
+ fixup(raw.Type(), kindUnknown, &typedef.Type)
+ typ = typedef
+
+ case kindVolatile:
+ volatile := &Volatile{id, nil}
+ fixup(raw.Type(), kindUnknown, &volatile.Type)
+ typ = volatile
+
+ case kindConst:
+ cnst := &Const{id, nil}
+ fixup(raw.Type(), kindUnknown, &cnst.Type)
+ typ = cnst
+
+ case kindRestrict:
+ restrict := &Restrict{id, nil}
+ fixup(raw.Type(), kindUnknown, &restrict.Type)
+ typ = restrict
+
+ case kindFunc:
+ fn := &Func{id, name, nil}
+ fixup(raw.Type(), kindFuncProto, &fn.Type)
+ typ = fn
+
+ case kindFuncProto:
+ rawparams := raw.data.([]btfParam)
+ params := make([]FuncParam, 0, len(rawparams))
+ for i, param := range rawparams {
+ name, err := rawStrings.LookupName(param.NameOff)
+ if err != nil {
+ return nil, nil, fmt.Errorf("get name for func proto parameter %d: %s", i, err)
+ }
+ params = append(params, FuncParam{
+ Name: name,
+ })
+ }
+ for i := range params {
+ fixup(rawparams[i].Type, kindUnknown, ¶ms[i].Type)
+ }
+
+ fp := &FuncProto{id, nil, params}
+ fixup(raw.Type(), kindUnknown, &fp.Return)
+ typ = fp
+
+ case kindVar:
+ v := &Var{id, name, nil}
+ fixup(raw.Type(), kindUnknown, &v.Type)
+ typ = v
+
+ case kindDatasec:
+ btfVars := raw.data.([]btfVarSecinfo)
+ vars := make([]VarSecinfo, 0, len(btfVars))
+ for _, btfVar := range btfVars {
+ vars = append(vars, VarSecinfo{
+ Offset: btfVar.Offset,
+ Size: btfVar.Size,
+ })
+ }
+ for i := range vars {
+ fixup(btfVars[i].Type, kindVar, &vars[i].Type)
+ }
+ typ = &Datasec{id, name, raw.SizeType, vars}
+
+ default:
+ return nil, nil, fmt.Errorf("type id %d: unknown kind: %v", id, raw.Kind())
+ }
+
+ types = append(types, typ)
+
+ if named, ok := typ.(namedType); ok {
+ if name := essentialName(named.name()); name != "" {
+ namedTypes[name] = append(namedTypes[name], named)
+ }
+ }
+ }
+
+ for _, fixup := range fixups {
+ i := int(fixup.id)
+ if i >= len(types) {
+ return nil, nil, fmt.Errorf("reference to invalid type id: %d", fixup.id)
+ }
+
+ // Default void (id 0) to unknown
+ rawKind := kindUnknown
+ if i > 0 {
+ rawKind = rawTypes[i-1].Kind()
+ }
+
+ if expected := fixup.expectedKind; expected != kindUnknown && rawKind != expected {
+ return nil, nil, fmt.Errorf("expected type id %d to have kind %s, found %s", fixup.id, expected, rawKind)
+ }
+
+ *fixup.typ = types[i]
+ }
+
+ return types, namedTypes, nil
+}
+
+// essentialName returns name without a ___ suffix.
+func essentialName(name string) string {
+ lastIdx := strings.LastIndex(name, "___")
+ if lastIdx > 0 {
+ return name[:lastIdx]
+ }
+ return name
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/cpu.go b/vendor/github.com/cilium/ebpf/internal/cpu.go
@@ -0,0 +1,62 @@
+package internal
+
+import (
+ "fmt"
+ "io/ioutil"
+ "strings"
+ "sync"
+)
+
+var sysCPU struct {
+ once sync.Once
+ err error
+ num int
+}
+
+// PossibleCPUs returns the max number of CPUs a system may possibly have
+// Logical CPU numbers must be of the form 0-n
+func PossibleCPUs() (int, error) {
+ sysCPU.once.Do(func() {
+ sysCPU.num, sysCPU.err = parseCPUsFromFile("/sys/devices/system/cpu/possible")
+ })
+
+ return sysCPU.num, sysCPU.err
+}
+
+func parseCPUsFromFile(path string) (int, error) {
+ spec, err := ioutil.ReadFile(path)
+ if err != nil {
+ return 0, err
+ }
+
+ n, err := parseCPUs(string(spec))
+ if err != nil {
+ return 0, fmt.Errorf("can't parse %s: %v", path, err)
+ }
+
+ return n, nil
+}
+
+// parseCPUs parses the number of cpus from a string produced
+// by bitmap_list_string() in the Linux kernel.
+// Multiple ranges are rejected, since they can't be unified
+// into a single number.
+// This is the format of /sys/devices/system/cpu/possible, it
+// is not suitable for /sys/devices/system/cpu/online, etc.
+func parseCPUs(spec string) (int, error) {
+ if strings.Trim(spec, "\n") == "0" {
+ return 1, nil
+ }
+
+ var low, high int
+ n, err := fmt.Sscanf(spec, "%d-%d\n", &low, &high)
+ if n != 2 || err != nil {
+ return 0, fmt.Errorf("invalid format: %s", spec)
+ }
+ if low != 0 {
+ return 0, fmt.Errorf("CPU spec doesn't start at zero: %s", spec)
+ }
+
+ // cpus is 0 indexed
+ return high + 1, nil
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/elf.go b/vendor/github.com/cilium/ebpf/internal/elf.go
@@ -0,0 +1,52 @@
+package internal
+
+import (
+ "debug/elf"
+ "fmt"
+ "io"
+)
+
+type SafeELFFile struct {
+ *elf.File
+}
+
+// NewSafeELFFile reads an ELF safely.
+//
+// Any panic during parsing is turned into an error. This is necessary since
+// there are a bunch of unfixed bugs in debug/elf.
+//
+// https://github.com/golang/go/issues?q=is%3Aissue+is%3Aopen+debug%2Felf+in%3Atitle
+func NewSafeELFFile(r io.ReaderAt) (safe *SafeELFFile, err error) {
+ defer func() {
+ r := recover()
+ if r == nil {
+ return
+ }
+
+ safe = nil
+ err = fmt.Errorf("reading ELF file panicked: %s", r)
+ }()
+
+ file, err := elf.NewFile(r)
+ if err != nil {
+ return nil, err
+ }
+
+ return &SafeELFFile{file}, nil
+}
+
+// Symbols is the safe version of elf.File.Symbols.
+func (se *SafeELFFile) Symbols() (syms []elf.Symbol, err error) {
+ defer func() {
+ r := recover()
+ if r == nil {
+ return
+ }
+
+ syms = nil
+ err = fmt.Errorf("reading ELF symbols panicked: %s", r)
+ }()
+
+ syms, err = se.File.Symbols()
+ return
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/endian.go b/vendor/github.com/cilium/ebpf/internal/endian.go
@@ -0,0 +1,24 @@
+package internal
+
+import (
+ "encoding/binary"
+ "unsafe"
+)
+
+// NativeEndian is set to either binary.BigEndian or binary.LittleEndian,
+// depending on the host's endianness.
+var NativeEndian binary.ByteOrder
+
+func init() {
+ if isBigEndian() {
+ NativeEndian = binary.BigEndian
+ } else {
+ NativeEndian = binary.LittleEndian
+ }
+}
+
+func isBigEndian() (ret bool) {
+ i := int(0x1)
+ bs := (*[int(unsafe.Sizeof(i))]byte)(unsafe.Pointer(&i))
+ return bs[0] == 0
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/errors.go b/vendor/github.com/cilium/ebpf/internal/errors.go
@@ -0,0 +1,47 @@
+package internal
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/cilium/ebpf/internal/unix"
+)
+
+// ErrorWithLog returns an error that includes logs from the
+// kernel verifier.
+//
+// logErr should be the error returned by the syscall that generated
+// the log. It is used to check for truncation of the output.
+func ErrorWithLog(err error, log []byte, logErr error) error {
+ logStr := strings.Trim(CString(log), "\t\r\n ")
+ if errors.Is(logErr, unix.ENOSPC) {
+ logStr += " (truncated...)"
+ }
+
+ return &VerifierError{err, logStr}
+}
+
+// VerifierError includes information from the eBPF verifier.
+type VerifierError struct {
+ cause error
+ log string
+}
+
+func (le *VerifierError) Error() string {
+ if le.log == "" {
+ return le.cause.Error()
+ }
+
+ return fmt.Sprintf("%s: %s", le.cause, le.log)
+}
+
+// CString turns a NUL / zero terminated byte buffer into a string.
+func CString(in []byte) string {
+ inLen := bytes.IndexByte(in, 0)
+ if inLen == -1 {
+ return ""
+ }
+ return string(in[:inLen])
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/fd.go b/vendor/github.com/cilium/ebpf/internal/fd.go
@@ -0,0 +1,69 @@
+package internal
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "runtime"
+ "strconv"
+
+ "github.com/cilium/ebpf/internal/unix"
+)
+
+var ErrClosedFd = errors.New("use of closed file descriptor")
+
+type FD struct {
+ raw int64
+}
+
+func NewFD(value uint32) *FD {
+ fd := &FD{int64(value)}
+ runtime.SetFinalizer(fd, (*FD).Close)
+ return fd
+}
+
+func (fd *FD) String() string {
+ return strconv.FormatInt(fd.raw, 10)
+}
+
+func (fd *FD) Value() (uint32, error) {
+ if fd.raw < 0 {
+ return 0, ErrClosedFd
+ }
+
+ return uint32(fd.raw), nil
+}
+
+func (fd *FD) Close() error {
+ if fd.raw < 0 {
+ return nil
+ }
+
+ value := int(fd.raw)
+ fd.raw = -1
+
+ fd.Forget()
+ return unix.Close(value)
+}
+
+func (fd *FD) Forget() {
+ runtime.SetFinalizer(fd, nil)
+}
+
+func (fd *FD) Dup() (*FD, error) {
+ if fd.raw < 0 {
+ return nil, ErrClosedFd
+ }
+
+ dup, err := unix.FcntlInt(uintptr(fd.raw), unix.F_DUPFD_CLOEXEC, 0)
+ if err != nil {
+ return nil, fmt.Errorf("can't dup fd: %v", err)
+ }
+
+ return NewFD(uint32(dup)), nil
+}
+
+func (fd *FD) File(name string) *os.File {
+ fd.Forget()
+ return os.NewFile(uintptr(fd.raw), name)
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/feature.go b/vendor/github.com/cilium/ebpf/internal/feature.go
@@ -0,0 +1,138 @@
+package internal
+
+import (
+ "errors"
+ "fmt"
+ "sync"
+)
+
+// ErrNotSupported indicates that a feature is not supported by the current kernel.
+var ErrNotSupported = errors.New("not supported")
+
+// UnsupportedFeatureError is returned by FeatureTest() functions.
+type UnsupportedFeatureError struct {
+ // The minimum Linux mainline version required for this feature.
+ // Used for the error string, and for sanity checking during testing.
+ MinimumVersion Version
+
+ // The name of the feature that isn't supported.
+ Name string
+}
+
+func (ufe *UnsupportedFeatureError) Error() string {
+ if ufe.MinimumVersion.Unspecified() {
+ return fmt.Sprintf("%s not supported", ufe.Name)
+ }
+ return fmt.Sprintf("%s not supported (requires >= %s)", ufe.Name, ufe.MinimumVersion)
+}
+
+// Is indicates that UnsupportedFeatureError is ErrNotSupported.
+func (ufe *UnsupportedFeatureError) Is(target error) bool {
+ return target == ErrNotSupported
+}
+
+type featureTest struct {
+ sync.RWMutex
+ successful bool
+ result error
+}
+
+// FeatureTestFn is used to determine whether the kernel supports
+// a certain feature.
+//
+// The return values have the following semantics:
+//
+// err == ErrNotSupported: the feature is not available
+// err == nil: the feature is available
+// err != nil: the test couldn't be executed
+type FeatureTestFn func() error
+
+// FeatureTest wraps a function so that it is run at most once.
+//
+// name should identify the tested feature, while version must be in the
+// form Major.Minor[.Patch].
+//
+// Returns an error wrapping ErrNotSupported if the feature is not supported.
+func FeatureTest(name, version string, fn FeatureTestFn) func() error {
+ v, err := NewVersion(version)
+ if err != nil {
+ return func() error { return err }
+ }
+
+ ft := new(featureTest)
+ return func() error {
+ ft.RLock()
+ if ft.successful {
+ defer ft.RUnlock()
+ return ft.result
+ }
+ ft.RUnlock()
+ ft.Lock()
+ defer ft.Unlock()
+ // check one more time on the off
+ // chance that two go routines
+ // were able to call into the write
+ // lock
+ if ft.successful {
+ return ft.result
+ }
+ err := fn()
+ switch {
+ case errors.Is(err, ErrNotSupported):
+ ft.result = &UnsupportedFeatureError{
+ MinimumVersion: v,
+ Name: name,
+ }
+ fallthrough
+
+ case err == nil:
+ ft.successful = true
+
+ default:
+ // We couldn't execute the feature test to a point
+ // where it could make a determination.
+ // Don't cache the result, just return it.
+ return fmt.Errorf("detect support for %s: %w", name, err)
+ }
+
+ return ft.result
+ }
+}
+
+// A Version in the form Major.Minor.Patch.
+type Version [3]uint16
+
+// NewVersion creates a version from a string like "Major.Minor.Patch".
+//
+// Patch is optional.
+func NewVersion(ver string) (Version, error) {
+ var major, minor, patch uint16
+ n, _ := fmt.Sscanf(ver, "%d.%d.%d", &major, &minor, &patch)
+ if n < 2 {
+ return Version{}, fmt.Errorf("invalid version: %s", ver)
+ }
+ return Version{major, minor, patch}, nil
+}
+
+func (v Version) String() string {
+ if v[2] == 0 {
+ return fmt.Sprintf("v%d.%d", v[0], v[1])
+ }
+ return fmt.Sprintf("v%d.%d.%d", v[0], v[1], v[2])
+}
+
+// Less returns true if the version is less than another version.
+func (v Version) Less(other Version) bool {
+ for i, a := range v {
+ if a == other[i] {
+ continue
+ }
+ return a < other[i]
+ }
+ return false
+}
+
+// Unspecified returns true if the version is all zero.
+func (v Version) Unspecified() bool {
+ return v[0] == 0 && v[1] == 0 && v[2] == 0
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/io.go b/vendor/github.com/cilium/ebpf/internal/io.go
@@ -0,0 +1,16 @@
+package internal
+
+import "errors"
+
+// DiscardZeroes makes sure that all written bytes are zero
+// before discarding them.
+type DiscardZeroes struct{}
+
+func (DiscardZeroes) Write(p []byte) (int, error) {
+ for _, b := range p {
+ if b != 0 {
+ return 0, errors.New("encountered non-zero byte")
+ }
+ }
+ return len(p), nil
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/ptr.go b/vendor/github.com/cilium/ebpf/internal/ptr.go
@@ -0,0 +1,30 @@
+package internal
+
+import "unsafe"
+
+// NewPointer creates a 64-bit pointer from an unsafe Pointer.
+func NewPointer(ptr unsafe.Pointer) Pointer {
+ return Pointer{ptr: ptr}
+}
+
+// NewSlicePointer creates a 64-bit pointer from a byte slice.
+func NewSlicePointer(buf []byte) Pointer {
+ if len(buf) == 0 {
+ return Pointer{}
+ }
+
+ return Pointer{ptr: unsafe.Pointer(&buf[0])}
+}
+
+// NewStringPointer creates a 64-bit pointer from a string.
+func NewStringPointer(str string) Pointer {
+ if str == "" {
+ return Pointer{}
+ }
+
+ // The kernel expects strings to be zero terminated
+ buf := make([]byte, len(str)+1)
+ copy(buf, str)
+
+ return Pointer{ptr: unsafe.Pointer(&buf[0])}
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/ptr_32_be.go b/vendor/github.com/cilium/ebpf/internal/ptr_32_be.go
@@ -0,0 +1,14 @@
+// +build armbe mips mips64p32
+
+package internal
+
+import (
+ "unsafe"
+)
+
+// Pointer wraps an unsafe.Pointer to be 64bit to
+// conform to the syscall specification.
+type Pointer struct {
+ pad uint32
+ ptr unsafe.Pointer
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/ptr_32_le.go b/vendor/github.com/cilium/ebpf/internal/ptr_32_le.go
@@ -0,0 +1,14 @@
+// +build 386 amd64p32 arm mipsle mips64p32le
+
+package internal
+
+import (
+ "unsafe"
+)
+
+// Pointer wraps an unsafe.Pointer to be 64bit to
+// conform to the syscall specification.
+type Pointer struct {
+ ptr unsafe.Pointer
+ pad uint32
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/ptr_64.go b/vendor/github.com/cilium/ebpf/internal/ptr_64.go
@@ -0,0 +1,14 @@
+// +build !386,!amd64p32,!arm,!mipsle,!mips64p32le
+// +build !armbe,!mips,!mips64p32
+
+package internal
+
+import (
+ "unsafe"
+)
+
+// Pointer wraps an unsafe.Pointer to be 64bit to
+// conform to the syscall specification.
+type Pointer struct {
+ ptr unsafe.Pointer
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/syscall.go b/vendor/github.com/cilium/ebpf/internal/syscall.go
@@ -0,0 +1,179 @@
+package internal
+
+import (
+ "fmt"
+ "path/filepath"
+ "runtime"
+ "unsafe"
+
+ "github.com/cilium/ebpf/internal/unix"
+)
+
+//go:generate stringer -output syscall_string.go -type=BPFCmd
+
+// BPFCmd identifies a subcommand of the bpf syscall.
+type BPFCmd int
+
+// Well known BPF commands.
+const (
+ BPF_MAP_CREATE BPFCmd = iota
+ BPF_MAP_LOOKUP_ELEM
+ BPF_MAP_UPDATE_ELEM
+ BPF_MAP_DELETE_ELEM
+ BPF_MAP_GET_NEXT_KEY
+ BPF_PROG_LOAD
+ BPF_OBJ_PIN
+ BPF_OBJ_GET
+ BPF_PROG_ATTACH
+ BPF_PROG_DETACH
+ BPF_PROG_TEST_RUN
+ BPF_PROG_GET_NEXT_ID
+ BPF_MAP_GET_NEXT_ID
+ BPF_PROG_GET_FD_BY_ID
+ BPF_MAP_GET_FD_BY_ID
+ BPF_OBJ_GET_INFO_BY_FD
+ BPF_PROG_QUERY
+ BPF_RAW_TRACEPOINT_OPEN
+ BPF_BTF_LOAD
+ BPF_BTF_GET_FD_BY_ID
+ BPF_TASK_FD_QUERY
+ BPF_MAP_LOOKUP_AND_DELETE_ELEM
+ BPF_MAP_FREEZE
+ BPF_BTF_GET_NEXT_ID
+ BPF_MAP_LOOKUP_BATCH
+ BPF_MAP_LOOKUP_AND_DELETE_BATCH
+ BPF_MAP_UPDATE_BATCH
+ BPF_MAP_DELETE_BATCH
+ BPF_LINK_CREATE
+ BPF_LINK_UPDATE
+ BPF_LINK_GET_FD_BY_ID
+ BPF_LINK_GET_NEXT_ID
+ BPF_ENABLE_STATS
+ BPF_ITER_CREATE
+)
+
+// BPF wraps SYS_BPF.
+//
+// Any pointers contained in attr must use the Pointer type from this package.
+func BPF(cmd BPFCmd, attr unsafe.Pointer, size uintptr) (uintptr, error) {
+ r1, _, errNo := unix.Syscall(unix.SYS_BPF, uintptr(cmd), uintptr(attr), size)
+ runtime.KeepAlive(attr)
+
+ var err error
+ if errNo != 0 {
+ err = errNo
+ }
+
+ return r1, err
+}
+
+type BPFProgAttachAttr struct {
+ TargetFd uint32
+ AttachBpfFd uint32
+ AttachType uint32
+ AttachFlags uint32
+ ReplaceBpfFd uint32
+}
+
+func BPFProgAttach(attr *BPFProgAttachAttr) error {
+ _, err := BPF(BPF_PROG_ATTACH, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ return err
+}
+
+type BPFProgDetachAttr struct {
+ TargetFd uint32
+ AttachBpfFd uint32
+ AttachType uint32
+}
+
+func BPFProgDetach(attr *BPFProgDetachAttr) error {
+ _, err := BPF(BPF_PROG_DETACH, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ return err
+}
+
+type BPFEnableStatsAttr struct {
+ StatsType uint32
+}
+
+func BPFEnableStats(attr *BPFEnableStatsAttr) (*FD, error) {
+ ptr, err := BPF(BPF_ENABLE_STATS, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ if err != nil {
+ return nil, fmt.Errorf("enable stats: %w", err)
+ }
+ return NewFD(uint32(ptr)), nil
+
+}
+
+type bpfObjAttr struct {
+ fileName Pointer
+ fd uint32
+ fileFlags uint32
+}
+
+const bpfFSType = 0xcafe4a11
+
+// BPFObjPin wraps BPF_OBJ_PIN.
+func BPFObjPin(fileName string, fd *FD) error {
+ dirName := filepath.Dir(fileName)
+ var statfs unix.Statfs_t
+ if err := unix.Statfs(dirName, &statfs); err != nil {
+ return err
+ }
+ if uint64(statfs.Type) != bpfFSType {
+ return fmt.Errorf("%s is not on a bpf filesystem", fileName)
+ }
+
+ value, err := fd.Value()
+ if err != nil {
+ return err
+ }
+
+ attr := bpfObjAttr{
+ fileName: NewStringPointer(fileName),
+ fd: value,
+ }
+ _, err = BPF(BPF_OBJ_PIN, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ if err != nil {
+ return fmt.Errorf("pin object %s: %w", fileName, err)
+ }
+ return nil
+}
+
+// BPFObjGet wraps BPF_OBJ_GET.
+func BPFObjGet(fileName string) (*FD, error) {
+ attr := bpfObjAttr{
+ fileName: NewStringPointer(fileName),
+ }
+ ptr, err := BPF(BPF_OBJ_GET, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ if err != nil {
+ return nil, fmt.Errorf("get object %s: %w", fileName, err)
+ }
+ return NewFD(uint32(ptr)), nil
+}
+
+type bpfObjGetInfoByFDAttr struct {
+ fd uint32
+ infoLen uint32
+ info Pointer
+}
+
+// BPFObjGetInfoByFD wraps BPF_OBJ_GET_INFO_BY_FD.
+//
+// Available from 4.13.
+func BPFObjGetInfoByFD(fd *FD, info unsafe.Pointer, size uintptr) error {
+ value, err := fd.Value()
+ if err != nil {
+ return err
+ }
+
+ attr := bpfObjGetInfoByFDAttr{
+ fd: value,
+ infoLen: uint32(size),
+ info: NewPointer(info),
+ }
+ _, err = BPF(BPF_OBJ_GET_INFO_BY_FD, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ if err != nil {
+ return fmt.Errorf("fd %v: %w", fd, err)
+ }
+ return nil
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/syscall_string.go b/vendor/github.com/cilium/ebpf/internal/syscall_string.go
@@ -0,0 +1,56 @@
+// Code generated by "stringer -output syscall_string.go -type=BPFCmd"; DO NOT EDIT.
+
+package internal
+
+import "strconv"
+
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[BPF_MAP_CREATE-0]
+ _ = x[BPF_MAP_LOOKUP_ELEM-1]
+ _ = x[BPF_MAP_UPDATE_ELEM-2]
+ _ = x[BPF_MAP_DELETE_ELEM-3]
+ _ = x[BPF_MAP_GET_NEXT_KEY-4]
+ _ = x[BPF_PROG_LOAD-5]
+ _ = x[BPF_OBJ_PIN-6]
+ _ = x[BPF_OBJ_GET-7]
+ _ = x[BPF_PROG_ATTACH-8]
+ _ = x[BPF_PROG_DETACH-9]
+ _ = x[BPF_PROG_TEST_RUN-10]
+ _ = x[BPF_PROG_GET_NEXT_ID-11]
+ _ = x[BPF_MAP_GET_NEXT_ID-12]
+ _ = x[BPF_PROG_GET_FD_BY_ID-13]
+ _ = x[BPF_MAP_GET_FD_BY_ID-14]
+ _ = x[BPF_OBJ_GET_INFO_BY_FD-15]
+ _ = x[BPF_PROG_QUERY-16]
+ _ = x[BPF_RAW_TRACEPOINT_OPEN-17]
+ _ = x[BPF_BTF_LOAD-18]
+ _ = x[BPF_BTF_GET_FD_BY_ID-19]
+ _ = x[BPF_TASK_FD_QUERY-20]
+ _ = x[BPF_MAP_LOOKUP_AND_DELETE_ELEM-21]
+ _ = x[BPF_MAP_FREEZE-22]
+ _ = x[BPF_BTF_GET_NEXT_ID-23]
+ _ = x[BPF_MAP_LOOKUP_BATCH-24]
+ _ = x[BPF_MAP_LOOKUP_AND_DELETE_BATCH-25]
+ _ = x[BPF_MAP_UPDATE_BATCH-26]
+ _ = x[BPF_MAP_DELETE_BATCH-27]
+ _ = x[BPF_LINK_CREATE-28]
+ _ = x[BPF_LINK_UPDATE-29]
+ _ = x[BPF_LINK_GET_FD_BY_ID-30]
+ _ = x[BPF_LINK_GET_NEXT_ID-31]
+ _ = x[BPF_ENABLE_STATS-32]
+ _ = x[BPF_ITER_CREATE-33]
+}
+
+const _BPFCmd_name = "BPF_MAP_CREATEBPF_MAP_LOOKUP_ELEMBPF_MAP_UPDATE_ELEMBPF_MAP_DELETE_ELEMBPF_MAP_GET_NEXT_KEYBPF_PROG_LOADBPF_OBJ_PINBPF_OBJ_GETBPF_PROG_ATTACHBPF_PROG_DETACHBPF_PROG_TEST_RUNBPF_PROG_GET_NEXT_IDBPF_MAP_GET_NEXT_IDBPF_PROG_GET_FD_BY_IDBPF_MAP_GET_FD_BY_IDBPF_OBJ_GET_INFO_BY_FDBPF_PROG_QUERYBPF_RAW_TRACEPOINT_OPENBPF_BTF_LOADBPF_BTF_GET_FD_BY_IDBPF_TASK_FD_QUERYBPF_MAP_LOOKUP_AND_DELETE_ELEMBPF_MAP_FREEZEBPF_BTF_GET_NEXT_IDBPF_MAP_LOOKUP_BATCHBPF_MAP_LOOKUP_AND_DELETE_BATCHBPF_MAP_UPDATE_BATCHBPF_MAP_DELETE_BATCHBPF_LINK_CREATEBPF_LINK_UPDATEBPF_LINK_GET_FD_BY_IDBPF_LINK_GET_NEXT_IDBPF_ENABLE_STATSBPF_ITER_CREATE"
+
+var _BPFCmd_index = [...]uint16{0, 14, 33, 52, 71, 91, 104, 115, 126, 141, 156, 173, 193, 212, 233, 253, 275, 289, 312, 324, 344, 361, 391, 405, 424, 444, 475, 495, 515, 530, 545, 566, 586, 602, 617}
+
+func (i BPFCmd) String() string {
+ if i < 0 || i >= BPFCmd(len(_BPFCmd_index)-1) {
+ return "BPFCmd(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _BPFCmd_name[_BPFCmd_index[i]:_BPFCmd_index[i+1]]
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/unix/types_linux.go b/vendor/github.com/cilium/ebpf/internal/unix/types_linux.go
@@ -0,0 +1,170 @@
+// +build linux
+
+package unix
+
+import (
+ "bytes"
+ "syscall"
+
+ linux "golang.org/x/sys/unix"
+)
+
+const (
+ ENOENT = linux.ENOENT
+ EEXIST = linux.EEXIST
+ EAGAIN = linux.EAGAIN
+ ENOSPC = linux.ENOSPC
+ EINVAL = linux.EINVAL
+ EPOLLIN = linux.EPOLLIN
+ EINTR = linux.EINTR
+ EPERM = linux.EPERM
+ ESRCH = linux.ESRCH
+ ENODEV = linux.ENODEV
+ // ENOTSUPP is not the same as ENOTSUP or EOPNOTSUP
+ ENOTSUPP = syscall.Errno(0x20c)
+
+ EBADF = linux.EBADF
+ BPF_F_NO_PREALLOC = linux.BPF_F_NO_PREALLOC
+ BPF_F_NUMA_NODE = linux.BPF_F_NUMA_NODE
+ BPF_F_RDONLY_PROG = linux.BPF_F_RDONLY_PROG
+ BPF_F_WRONLY_PROG = linux.BPF_F_WRONLY_PROG
+ BPF_OBJ_NAME_LEN = linux.BPF_OBJ_NAME_LEN
+ BPF_TAG_SIZE = linux.BPF_TAG_SIZE
+ SYS_BPF = linux.SYS_BPF
+ F_DUPFD_CLOEXEC = linux.F_DUPFD_CLOEXEC
+ EPOLL_CTL_ADD = linux.EPOLL_CTL_ADD
+ EPOLL_CLOEXEC = linux.EPOLL_CLOEXEC
+ O_CLOEXEC = linux.O_CLOEXEC
+ O_NONBLOCK = linux.O_NONBLOCK
+ PROT_READ = linux.PROT_READ
+ PROT_WRITE = linux.PROT_WRITE
+ MAP_SHARED = linux.MAP_SHARED
+ PERF_TYPE_SOFTWARE = linux.PERF_TYPE_SOFTWARE
+ PERF_COUNT_SW_BPF_OUTPUT = linux.PERF_COUNT_SW_BPF_OUTPUT
+ PerfBitWatermark = linux.PerfBitWatermark
+ PERF_SAMPLE_RAW = linux.PERF_SAMPLE_RAW
+ PERF_FLAG_FD_CLOEXEC = linux.PERF_FLAG_FD_CLOEXEC
+ RLIM_INFINITY = linux.RLIM_INFINITY
+ RLIMIT_MEMLOCK = linux.RLIMIT_MEMLOCK
+ BPF_STATS_RUN_TIME = linux.BPF_STATS_RUN_TIME
+)
+
+// Statfs_t is a wrapper
+type Statfs_t = linux.Statfs_t
+
+// Rlimit is a wrapper
+type Rlimit = linux.Rlimit
+
+// Setrlimit is a wrapper
+func Setrlimit(resource int, rlim *Rlimit) (err error) {
+ return linux.Setrlimit(resource, rlim)
+}
+
+// Syscall is a wrapper
+func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) {
+ return linux.Syscall(trap, a1, a2, a3)
+}
+
+// FcntlInt is a wrapper
+func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
+ return linux.FcntlInt(fd, cmd, arg)
+}
+
+// Statfs is a wrapper
+func Statfs(path string, buf *Statfs_t) (err error) {
+ return linux.Statfs(path, buf)
+}
+
+// Close is a wrapper
+func Close(fd int) (err error) {
+ return linux.Close(fd)
+}
+
+// EpollEvent is a wrapper
+type EpollEvent = linux.EpollEvent
+
+// EpollWait is a wrapper
+func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) {
+ return linux.EpollWait(epfd, events, msec)
+}
+
+// EpollCtl is a wrapper
+func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) {
+ return linux.EpollCtl(epfd, op, fd, event)
+}
+
+// Eventfd is a wrapper
+func Eventfd(initval uint, flags int) (fd int, err error) {
+ return linux.Eventfd(initval, flags)
+}
+
+// Write is a wrapper
+func Write(fd int, p []byte) (n int, err error) {
+ return linux.Write(fd, p)
+}
+
+// EpollCreate1 is a wrapper
+func EpollCreate1(flag int) (fd int, err error) {
+ return linux.EpollCreate1(flag)
+}
+
+// PerfEventMmapPage is a wrapper
+type PerfEventMmapPage linux.PerfEventMmapPage
+
+// SetNonblock is a wrapper
+func SetNonblock(fd int, nonblocking bool) (err error) {
+ return linux.SetNonblock(fd, nonblocking)
+}
+
+// Mmap is a wrapper
+func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
+ return linux.Mmap(fd, offset, length, prot, flags)
+}
+
+// Munmap is a wrapper
+func Munmap(b []byte) (err error) {
+ return linux.Munmap(b)
+}
+
+// PerfEventAttr is a wrapper
+type PerfEventAttr = linux.PerfEventAttr
+
+// PerfEventOpen is a wrapper
+func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) {
+ return linux.PerfEventOpen(attr, pid, cpu, groupFd, flags)
+}
+
+// Utsname is a wrapper
+type Utsname = linux.Utsname
+
+// Uname is a wrapper
+func Uname(buf *Utsname) (err error) {
+ return linux.Uname(buf)
+}
+
+// Getpid is a wrapper
+func Getpid() int {
+ return linux.Getpid()
+}
+
+// Gettid is a wrapper
+func Gettid() int {
+ return linux.Gettid()
+}
+
+// Tgkill is a wrapper
+func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) {
+ return linux.Tgkill(tgid, tid, sig)
+}
+
+func KernelRelease() (string, error) {
+ var uname Utsname
+ err := Uname(&uname)
+ if err != nil {
+ return "", err
+ }
+
+ end := bytes.IndexByte(uname.Release[:], 0)
+ release := string(uname.Release[:end])
+ return release, nil
+}
diff --git a/vendor/github.com/cilium/ebpf/internal/unix/types_other.go b/vendor/github.com/cilium/ebpf/internal/unix/types_other.go
@@ -0,0 +1,228 @@
+// +build !linux
+
+package unix
+
+import (
+ "fmt"
+ "runtime"
+ "syscall"
+)
+
+var errNonLinux = fmt.Errorf("unsupported platform %s/%s", runtime.GOOS, runtime.GOARCH)
+
+const (
+ ENOENT = syscall.ENOENT
+ EEXIST = syscall.EEXIST
+ EAGAIN = syscall.EAGAIN
+ ENOSPC = syscall.ENOSPC
+ EINVAL = syscall.EINVAL
+ EINTR = syscall.EINTR
+ EPERM = syscall.EPERM
+ ESRCH = syscall.ESRCH
+ ENODEV = syscall.ENODEV
+ EBADF = syscall.Errno(0)
+ // ENOTSUPP is not the same as ENOTSUP or EOPNOTSUP
+ ENOTSUPP = syscall.Errno(0x20c)
+
+ BPF_F_NO_PREALLOC = 0
+ BPF_F_NUMA_NODE = 0
+ BPF_F_RDONLY_PROG = 0
+ BPF_F_WRONLY_PROG = 0
+ BPF_OBJ_NAME_LEN = 0x10
+ BPF_TAG_SIZE = 0x8
+ SYS_BPF = 321
+ F_DUPFD_CLOEXEC = 0x406
+ EPOLLIN = 0x1
+ EPOLL_CTL_ADD = 0x1
+ EPOLL_CLOEXEC = 0x80000
+ O_CLOEXEC = 0x80000
+ O_NONBLOCK = 0x800
+ PROT_READ = 0x1
+ PROT_WRITE = 0x2
+ MAP_SHARED = 0x1
+ PERF_TYPE_SOFTWARE = 0x1
+ PERF_COUNT_SW_BPF_OUTPUT = 0xa
+ PerfBitWatermark = 0x4000
+ PERF_SAMPLE_RAW = 0x400
+ PERF_FLAG_FD_CLOEXEC = 0x8
+ RLIM_INFINITY = 0x7fffffffffffffff
+ RLIMIT_MEMLOCK = 8
+ BPF_STATS_RUN_TIME = 0
+)
+
+// Statfs_t is a wrapper
+type Statfs_t struct {
+ Type int64
+ Bsize int64
+ Blocks uint64
+ Bfree uint64
+ Bavail uint64
+ Files uint64
+ Ffree uint64
+ Fsid [2]int32
+ Namelen int64
+ Frsize int64
+ Flags int64
+ Spare [4]int64
+}
+
+// Rlimit is a wrapper
+type Rlimit struct {
+ Cur uint64
+ Max uint64
+}
+
+// Setrlimit is a wrapper
+func Setrlimit(resource int, rlim *Rlimit) (err error) {
+ return errNonLinux
+}
+
+// Syscall is a wrapper
+func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) {
+ return 0, 0, syscall.Errno(1)
+}
+
+// FcntlInt is a wrapper
+func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
+ return -1, errNonLinux
+}
+
+// Statfs is a wrapper
+func Statfs(path string, buf *Statfs_t) error {
+ return errNonLinux
+}
+
+// Close is a wrapper
+func Close(fd int) (err error) {
+ return errNonLinux
+}
+
+// EpollEvent is a wrapper
+type EpollEvent struct {
+ Events uint32
+ Fd int32
+ Pad int32
+}
+
+// EpollWait is a wrapper
+func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) {
+ return 0, errNonLinux
+}
+
+// EpollCtl is a wrapper
+func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) {
+ return errNonLinux
+}
+
+// Eventfd is a wrapper
+func Eventfd(initval uint, flags int) (fd int, err error) {
+ return 0, errNonLinux
+}
+
+// Write is a wrapper
+func Write(fd int, p []byte) (n int, err error) {
+ return 0, errNonLinux
+}
+
+// EpollCreate1 is a wrapper
+func EpollCreate1(flag int) (fd int, err error) {
+ return 0, errNonLinux
+}
+
+// PerfEventMmapPage is a wrapper
+type PerfEventMmapPage struct {
+ Version uint32
+ Compat_version uint32
+ Lock uint32
+ Index uint32
+ Offset int64
+ Time_enabled uint64
+ Time_running uint64
+ Capabilities uint64
+ Pmc_width uint16
+ Time_shift uint16
+ Time_mult uint32
+ Time_offset uint64
+ Time_zero uint64
+ Size uint32
+
+ Data_head uint64
+ Data_tail uint64
+ Data_offset uint64
+ Data_size uint64
+ Aux_head uint64
+ Aux_tail uint64
+ Aux_offset uint64
+ Aux_size uint64
+}
+
+// SetNonblock is a wrapper
+func SetNonblock(fd int, nonblocking bool) (err error) {
+ return errNonLinux
+}
+
+// Mmap is a wrapper
+func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
+ return []byte{}, errNonLinux
+}
+
+// Munmap is a wrapper
+func Munmap(b []byte) (err error) {
+ return errNonLinux
+}
+
+// PerfEventAttr is a wrapper
+type PerfEventAttr struct {
+ Type uint32
+ Size uint32
+ Config uint64
+ Sample uint64
+ Sample_type uint64
+ Read_format uint64
+ Bits uint64
+ Wakeup uint32
+ Bp_type uint32
+ Ext1 uint64
+ Ext2 uint64
+ Branch_sample_type uint64
+ Sample_regs_user uint64
+ Sample_stack_user uint32
+ Clockid int32
+ Sample_regs_intr uint64
+ Aux_watermark uint32
+ Sample_max_stack uint16
+}
+
+// PerfEventOpen is a wrapper
+func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) {
+ return 0, errNonLinux
+}
+
+// Utsname is a wrapper
+type Utsname struct {
+ Release [65]byte
+}
+
+// Uname is a wrapper
+func Uname(buf *Utsname) (err error) {
+ return errNonLinux
+}
+
+// Getpid is a wrapper
+func Getpid() int {
+ return -1
+}
+
+// Gettid is a wrapper
+func Gettid() int {
+ return -1
+}
+
+// Tgkill is a wrapper
+func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) {
+ return errNonLinux
+}
+
+func KernelRelease() (string, error) {
+ return "", errNonLinux
+}
diff --git a/vendor/github.com/cilium/ebpf/link/cgroup.go b/vendor/github.com/cilium/ebpf/link/cgroup.go
@@ -0,0 +1,169 @@
+package link
+
+import (
+ "errors"
+ "fmt"
+ "os"
+
+ "github.com/cilium/ebpf"
+)
+
+type cgroupAttachFlags uint32
+
+// cgroup attach flags
+const (
+ flagAllowOverride cgroupAttachFlags = 1 << iota
+ flagAllowMulti
+ flagReplace
+)
+
+type CgroupOptions struct {
+ // Path to a cgroupv2 folder.
+ Path string
+ // One of the AttachCgroup* constants
+ Attach ebpf.AttachType
+ // Program must be of type CGroup*, and the attach type must match Attach.
+ Program *ebpf.Program
+}
+
+// AttachCgroup links a BPF program to a cgroup.
+func AttachCgroup(opts CgroupOptions) (Link, error) {
+ cgroup, err := os.Open(opts.Path)
+ if err != nil {
+ return nil, fmt.Errorf("can't open cgroup: %s", err)
+ }
+
+ clone, err := opts.Program.Clone()
+ if err != nil {
+ cgroup.Close()
+ return nil, err
+ }
+
+ var cg Link
+ cg, err = newLinkCgroup(cgroup, opts.Attach, clone)
+ if errors.Is(err, ErrNotSupported) {
+ cg, err = newProgAttachCgroup(cgroup, opts.Attach, clone, flagAllowMulti)
+ }
+ if errors.Is(err, ErrNotSupported) {
+ cg, err = newProgAttachCgroup(cgroup, opts.Attach, clone, flagAllowOverride)
+ }
+ if err != nil {
+ cgroup.Close()
+ clone.Close()
+ return nil, err
+ }
+
+ return cg, nil
+}
+
+// LoadPinnedCgroup loads a pinned cgroup from a bpffs.
+func LoadPinnedCgroup(fileName string) (Link, error) {
+ link, err := LoadPinnedRawLink(fileName)
+ if err != nil {
+ return nil, err
+ }
+
+ return &linkCgroup{link}, nil
+}
+
+type progAttachCgroup struct {
+ cgroup *os.File
+ current *ebpf.Program
+ attachType ebpf.AttachType
+ flags cgroupAttachFlags
+}
+
+var _ Link = (*progAttachCgroup)(nil)
+
+func (cg *progAttachCgroup) isLink() {}
+
+func newProgAttachCgroup(cgroup *os.File, attach ebpf.AttachType, prog *ebpf.Program, flags cgroupAttachFlags) (*progAttachCgroup, error) {
+ if flags&flagAllowMulti > 0 {
+ if err := haveProgAttachReplace(); err != nil {
+ return nil, fmt.Errorf("can't support multiple programs: %w", err)
+ }
+ }
+
+ err := RawAttachProgram(RawAttachProgramOptions{
+ Target: int(cgroup.Fd()),
+ Program: prog,
+ Flags: uint32(flags),
+ Attach: attach,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("cgroup: %w", err)
+ }
+
+ return &progAttachCgroup{cgroup, prog, attach, flags}, nil
+}
+
+func (cg *progAttachCgroup) Close() error {
+ defer cg.cgroup.Close()
+ defer cg.current.Close()
+
+ err := RawDetachProgram(RawDetachProgramOptions{
+ Target: int(cg.cgroup.Fd()),
+ Program: cg.current,
+ Attach: cg.attachType,
+ })
+ if err != nil {
+ return fmt.Errorf("close cgroup: %s", err)
+ }
+ return nil
+}
+
+func (cg *progAttachCgroup) Update(prog *ebpf.Program) error {
+ new, err := prog.Clone()
+ if err != nil {
+ return err
+ }
+
+ args := RawAttachProgramOptions{
+ Target: int(cg.cgroup.Fd()),
+ Program: prog,
+ Attach: cg.attachType,
+ Flags: uint32(cg.flags),
+ }
+
+ if cg.flags&flagAllowMulti > 0 {
+ // Atomically replacing multiple programs requires at least
+ // 5.5 (commit 7dd68b3279f17921 "bpf: Support replacing cgroup-bpf
+ // program in MULTI mode")
+ args.Flags |= uint32(flagReplace)
+ args.Replace = cg.current
+ }
+
+ if err := RawAttachProgram(args); err != nil {
+ new.Close()
+ return fmt.Errorf("can't update cgroup: %s", err)
+ }
+
+ cg.current.Close()
+ cg.current = new
+ return nil
+}
+
+func (cg *progAttachCgroup) Pin(string) error {
+ return fmt.Errorf("can't pin cgroup: %w", ErrNotSupported)
+}
+
+type linkCgroup struct {
+ *RawLink
+}
+
+var _ Link = (*linkCgroup)(nil)
+
+func (cg *linkCgroup) isLink() {}
+
+func newLinkCgroup(cgroup *os.File, attach ebpf.AttachType, prog *ebpf.Program) (*linkCgroup, error) {
+ link, err := AttachRawLink(RawLinkOptions{
+ Target: int(cgroup.Fd()),
+ Program: prog,
+ Attach: attach,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return &linkCgroup{link}, err
+}
diff --git a/vendor/github.com/cilium/ebpf/link/doc.go b/vendor/github.com/cilium/ebpf/link/doc.go
@@ -0,0 +1,2 @@
+// Package link allows attaching eBPF programs to various kernel hooks.
+package link
diff --git a/vendor/github.com/cilium/ebpf/link/iter.go b/vendor/github.com/cilium/ebpf/link/iter.go
@@ -0,0 +1,91 @@
+package link
+
+import (
+ "fmt"
+ "io"
+
+ "github.com/cilium/ebpf"
+)
+
+type IterOptions struct {
+ // Program must be of type Tracing with attach type
+ // AttachTraceIter. The kind of iterator to attach to is
+ // determined at load time via the AttachTo field.
+ //
+ // AttachTo requires the kernel to include BTF of itself,
+ // and it to be compiled with a recent pahole (>= 1.16).
+ Program *ebpf.Program
+}
+
+// AttachIter attaches a BPF seq_file iterator.
+func AttachIter(opts IterOptions) (*Iter, error) {
+ link, err := AttachRawLink(RawLinkOptions{
+ Program: opts.Program,
+ Attach: ebpf.AttachTraceIter,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("can't link iterator: %w", err)
+ }
+
+ return &Iter{link}, err
+}
+
+// LoadPinnedIter loads a pinned iterator from a bpffs.
+func LoadPinnedIter(fileName string) (*Iter, error) {
+ link, err := LoadPinnedRawLink(fileName)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Iter{link}, err
+}
+
+// Iter represents an attached bpf_iter.
+type Iter struct {
+ link *RawLink
+}
+
+var _ Link = (*Iter)(nil)
+
+func (it *Iter) isLink() {}
+
+// FD returns the underlying file descriptor.
+func (it *Iter) FD() int {
+ return it.link.FD()
+}
+
+// Close implements Link.
+func (it *Iter) Close() error {
+ return it.link.Close()
+}
+
+// Pin implements Link.
+func (it *Iter) Pin(fileName string) error {
+ return it.link.Pin(fileName)
+}
+
+// Update implements Link.
+func (it *Iter) Update(new *ebpf.Program) error {
+ return it.link.Update(new)
+}
+
+// Open creates a new instance of the iterator.
+//
+// Reading from the returned reader triggers the BPF program.
+func (it *Iter) Open() (io.ReadCloser, error) {
+ linkFd, err := it.link.fd.Value()
+ if err != nil {
+ return nil, err
+ }
+
+ attr := &bpfIterCreateAttr{
+ linkFd: linkFd,
+ }
+
+ fd, err := bpfIterCreate(attr)
+ if err != nil {
+ return nil, fmt.Errorf("can't create iterator: %w", err)
+ }
+
+ return fd.File("bpf_iter"), nil
+}
diff --git a/vendor/github.com/cilium/ebpf/link/link.go b/vendor/github.com/cilium/ebpf/link/link.go
@@ -0,0 +1,214 @@
+package link
+
+import (
+ "fmt"
+ "unsafe"
+
+ "github.com/cilium/ebpf"
+ "github.com/cilium/ebpf/internal"
+)
+
+var ErrNotSupported = internal.ErrNotSupported
+
+// Link represents a Program attached to a BPF hook.
+type Link interface {
+ // Replace the current program with a new program.
+ //
+ // Passing a nil program is an error. May return an error wrapping ErrNotSupported.
+ Update(*ebpf.Program) error
+
+ // Persist a link by pinning it into a bpffs.
+ //
+ // May return an error wrapping ErrNotSupported.
+ Pin(string) error
+
+ // Close frees resources.
+ //
+ // The link will be broken unless it has been pinned. A link
+ // may continue past the lifetime of the process if Close is
+ // not called.
+ Close() error
+
+ // Prevent external users from implementing this interface.
+ isLink()
+}
+
+// ID uniquely identifies a BPF link.
+type ID uint32
+
+// RawLinkOptions control the creation of a raw link.
+type RawLinkOptions struct {
+ // File descriptor to attach to. This differs for each attach type.
+ Target int
+ // Program to attach.
+ Program *ebpf.Program
+ // Attach must match the attach type of Program.
+ Attach ebpf.AttachType
+}
+
+// RawLinkInfo contains metadata on a link.
+type RawLinkInfo struct {
+ Type Type
+ ID ID
+ Program ebpf.ProgramID
+}
+
+// RawLink is the low-level API to bpf_link.
+//
+// You should consider using the higher level interfaces in this
+// package instead.
+type RawLink struct {
+ fd *internal.FD
+}
+
+// AttachRawLink creates a raw link.
+func AttachRawLink(opts RawLinkOptions) (*RawLink, error) {
+ if err := haveBPFLink(); err != nil {
+ return nil, err
+ }
+
+ if opts.Target < 0 {
+ return nil, fmt.Errorf("invalid target: %s", internal.ErrClosedFd)
+ }
+
+ progFd := opts.Program.FD()
+ if progFd < 0 {
+ return nil, fmt.Errorf("invalid program: %s", internal.ErrClosedFd)
+ }
+
+ attr := bpfLinkCreateAttr{
+ targetFd: uint32(opts.Target),
+ progFd: uint32(progFd),
+ attachType: opts.Attach,
+ }
+ fd, err := bpfLinkCreate(&attr)
+ if err != nil {
+ return nil, fmt.Errorf("can't create link: %s", err)
+ }
+
+ return &RawLink{fd}, nil
+}
+
+// LoadPinnedRawLink loads a persisted link from a bpffs.
+func LoadPinnedRawLink(fileName string) (*RawLink, error) {
+ return loadPinnedRawLink(fileName, UnspecifiedType)
+}
+
+func loadPinnedRawLink(fileName string, typ Type) (*RawLink, error) {
+ fd, err := internal.BPFObjGet(fileName)
+ if err != nil {
+ return nil, fmt.Errorf("load pinned link: %s", err)
+ }
+
+ link := &RawLink{fd}
+ if typ == UnspecifiedType {
+ return link, nil
+ }
+
+ info, err := link.Info()
+ if err != nil {
+ link.Close()
+ return nil, fmt.Errorf("get pinned link info: %s", err)
+ }
+
+ if info.Type != typ {
+ link.Close()
+ return nil, fmt.Errorf("link type %v doesn't match %v", info.Type, typ)
+ }
+
+ return link, nil
+}
+
+func (l *RawLink) isLink() {}
+
+// FD returns the raw file descriptor.
+func (l *RawLink) FD() int {
+ fd, err := l.fd.Value()
+ if err != nil {
+ return -1
+ }
+ return int(fd)
+}
+
+// Close breaks the link.
+//
+// Use Pin if you want to make the link persistent.
+func (l *RawLink) Close() error {
+ return l.fd.Close()
+}
+
+// Pin persists a link past the lifetime of the process.
+//
+// Calling Close on a pinned Link will not break the link
+// until the pin is removed.
+func (l *RawLink) Pin(fileName string) error {
+ if err := internal.BPFObjPin(fileName, l.fd); err != nil {
+ return fmt.Errorf("can't pin link: %s", err)
+ }
+ return nil
+}
+
+// Update implements Link.
+func (l *RawLink) Update(new *ebpf.Program) error {
+ return l.UpdateArgs(RawLinkUpdateOptions{
+ New: new,
+ })
+}
+
+// RawLinkUpdateOptions control the behaviour of RawLink.UpdateArgs.
+type RawLinkUpdateOptions struct {
+ New *ebpf.Program
+ Old *ebpf.Program
+ Flags uint32
+}
+
+// UpdateArgs updates a link based on args.
+func (l *RawLink) UpdateArgs(opts RawLinkUpdateOptions) error {
+ newFd := opts.New.FD()
+ if newFd < 0 {
+ return fmt.Errorf("invalid program: %s", internal.ErrClosedFd)
+ }
+
+ var oldFd int
+ if opts.Old != nil {
+ oldFd = opts.Old.FD()
+ if oldFd < 0 {
+ return fmt.Errorf("invalid replacement program: %s", internal.ErrClosedFd)
+ }
+ }
+
+ linkFd, err := l.fd.Value()
+ if err != nil {
+ return fmt.Errorf("can't update link: %s", err)
+ }
+
+ attr := bpfLinkUpdateAttr{
+ linkFd: linkFd,
+ newProgFd: uint32(newFd),
+ oldProgFd: uint32(oldFd),
+ flags: opts.Flags,
+ }
+ return bpfLinkUpdate(&attr)
+}
+
+// struct bpf_link_info
+type bpfLinkInfo struct {
+ typ uint32
+ id uint32
+ prog_id uint32
+}
+
+// Info returns metadata about the link.
+func (l *RawLink) Info() (*RawLinkInfo, error) {
+ var info bpfLinkInfo
+ err := internal.BPFObjGetInfoByFD(l.fd, unsafe.Pointer(&info), unsafe.Sizeof(info))
+ if err != nil {
+ return nil, fmt.Errorf("link info: %s", err)
+ }
+
+ return &RawLinkInfo{
+ Type(info.typ),
+ ID(info.id),
+ ebpf.ProgramID(info.prog_id),
+ }, nil
+}
diff --git a/vendor/github.com/cilium/ebpf/link/netns.go b/vendor/github.com/cilium/ebpf/link/netns.go
@@ -0,0 +1,60 @@
+package link
+
+import (
+ "fmt"
+
+ "github.com/cilium/ebpf"
+)
+
+// NetNsInfo contains metadata about a network namespace link.
+type NetNsInfo struct {
+ RawLinkInfo
+}
+
+// NetNsLink is a program attached to a network namespace.
+type NetNsLink struct {
+ *RawLink
+}
+
+// AttachNetNs attaches a program to a network namespace.
+func AttachNetNs(ns int, prog *ebpf.Program) (*NetNsLink, error) {
+ var attach ebpf.AttachType
+ switch t := prog.Type(); t {
+ case ebpf.FlowDissector:
+ attach = ebpf.AttachFlowDissector
+ case ebpf.SkLookup:
+ attach = ebpf.AttachSkLookup
+ default:
+ return nil, fmt.Errorf("can't attach %v to network namespace", t)
+ }
+
+ link, err := AttachRawLink(RawLinkOptions{
+ Target: ns,
+ Program: prog,
+ Attach: attach,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return &NetNsLink{link}, nil
+}
+
+// LoadPinnedNetNs loads a network namespace link from bpffs.
+func LoadPinnedNetNs(fileName string) (*NetNsLink, error) {
+ link, err := loadPinnedRawLink(fileName, NetNsType)
+ if err != nil {
+ return nil, err
+ }
+
+ return &NetNsLink{link}, nil
+}
+
+// Info returns information about the link.
+func (nns *NetNsLink) Info() (*NetNsInfo, error) {
+ info, err := nns.RawLink.Info()
+ if err != nil {
+ return nil, err
+ }
+ return &NetNsInfo{*info}, nil
+}
diff --git a/vendor/github.com/cilium/ebpf/link/program.go b/vendor/github.com/cilium/ebpf/link/program.go
@@ -0,0 +1,76 @@
+package link
+
+import (
+ "fmt"
+
+ "github.com/cilium/ebpf"
+ "github.com/cilium/ebpf/internal"
+)
+
+type RawAttachProgramOptions struct {
+ // File descriptor to attach to. This differs for each attach type.
+ Target int
+ // Program to attach.
+ Program *ebpf.Program
+ // Program to replace (cgroups).
+ Replace *ebpf.Program
+ // Attach must match the attach type of Program (and Replace).
+ Attach ebpf.AttachType
+ // Flags control the attach behaviour. This differs for each attach type.
+ Flags uint32
+}
+
+// RawAttachProgram is a low level wrapper around BPF_PROG_ATTACH.
+//
+// You should use one of the higher level abstractions available in this
+// package if possible.
+func RawAttachProgram(opts RawAttachProgramOptions) error {
+ if err := haveProgAttach(); err != nil {
+ return err
+ }
+
+ var replaceFd uint32
+ if opts.Replace != nil {
+ replaceFd = uint32(opts.Replace.FD())
+ }
+
+ attr := internal.BPFProgAttachAttr{
+ TargetFd: uint32(opts.Target),
+ AttachBpfFd: uint32(opts.Program.FD()),
+ ReplaceBpfFd: replaceFd,
+ AttachType: uint32(opts.Attach),
+ AttachFlags: uint32(opts.Flags),
+ }
+
+ if err := internal.BPFProgAttach(&attr); err != nil {
+ return fmt.Errorf("can't attach program: %s", err)
+ }
+ return nil
+}
+
+type RawDetachProgramOptions struct {
+ Target int
+ Program *ebpf.Program
+ Attach ebpf.AttachType
+}
+
+// RawDetachProgram is a low level wrapper around BPF_PROG_DETACH.
+//
+// You should use one of the higher level abstractions available in this
+// package if possible.
+func RawDetachProgram(opts RawDetachProgramOptions) error {
+ if err := haveProgAttach(); err != nil {
+ return err
+ }
+
+ attr := internal.BPFProgDetachAttr{
+ TargetFd: uint32(opts.Target),
+ AttachBpfFd: uint32(opts.Program.FD()),
+ AttachType: uint32(opts.Attach),
+ }
+ if err := internal.BPFProgDetach(&attr); err != nil {
+ return fmt.Errorf("can't detach program: %s", err)
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/cilium/ebpf/link/raw_tracepoint.go b/vendor/github.com/cilium/ebpf/link/raw_tracepoint.go
@@ -0,0 +1,57 @@
+package link
+
+import (
+ "fmt"
+
+ "github.com/cilium/ebpf"
+ "github.com/cilium/ebpf/internal"
+)
+
+type RawTracepointOptions struct {
+ // Tracepoint name.
+ Name string
+ // Program must be of type RawTracepoint*
+ Program *ebpf.Program
+}
+
+// AttachRawTracepoint links a BPF program to a raw_tracepoint.
+//
+// Requires at least Linux 4.17.
+func AttachRawTracepoint(opts RawTracepointOptions) (Link, error) {
+ if t := opts.Program.Type(); t != ebpf.RawTracepoint && t != ebpf.RawTracepointWritable {
+ return nil, fmt.Errorf("invalid program type %s, expected RawTracepoint(Writable)", t)
+ }
+ if opts.Program.FD() < 0 {
+ return nil, fmt.Errorf("invalid program: %w", internal.ErrClosedFd)
+ }
+
+ fd, err := bpfRawTracepointOpen(&bpfRawTracepointOpenAttr{
+ name: internal.NewStringPointer(opts.Name),
+ fd: uint32(opts.Program.FD()),
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return &progAttachRawTracepoint{fd: fd}, nil
+}
+
+type progAttachRawTracepoint struct {
+ fd *internal.FD
+}
+
+var _ Link = (*progAttachRawTracepoint)(nil)
+
+func (rt *progAttachRawTracepoint) isLink() {}
+
+func (rt *progAttachRawTracepoint) Close() error {
+ return rt.fd.Close()
+}
+
+func (rt *progAttachRawTracepoint) Update(_ *ebpf.Program) error {
+ return fmt.Errorf("can't update raw_tracepoint: %w", ErrNotSupported)
+}
+
+func (rt *progAttachRawTracepoint) Pin(_ string) error {
+ return fmt.Errorf("can't pin raw_tracepoint: %w", ErrNotSupported)
+}
diff --git a/vendor/github.com/cilium/ebpf/link/syscalls.go b/vendor/github.com/cilium/ebpf/link/syscalls.go
@@ -0,0 +1,173 @@
+package link
+
+import (
+ "errors"
+ "unsafe"
+
+ "github.com/cilium/ebpf"
+ "github.com/cilium/ebpf/asm"
+ "github.com/cilium/ebpf/internal"
+ "github.com/cilium/ebpf/internal/unix"
+)
+
+// Type is the kind of link.
+type Type uint32
+
+// Valid link types.
+//
+// Equivalent to enum bpf_link_type.
+const (
+ UnspecifiedType Type = iota
+ RawTracepointType
+ TracingType
+ CgroupType
+ IterType
+ NetNsType
+ XDPType
+)
+
+var haveProgAttach = internal.FeatureTest("BPF_PROG_ATTACH", "4.10", func() error {
+ prog, err := ebpf.NewProgram(&ebpf.ProgramSpec{
+ Type: ebpf.CGroupSKB,
+ AttachType: ebpf.AttachCGroupInetIngress,
+ License: "MIT",
+ Instructions: asm.Instructions{
+ asm.Mov.Imm(asm.R0, 0),
+ asm.Return(),
+ },
+ })
+ if err != nil {
+ return internal.ErrNotSupported
+ }
+
+ // BPF_PROG_ATTACH was introduced at the same time as CGgroupSKB,
+ // so being able to load the program is enough to infer that we
+ // have the syscall.
+ prog.Close()
+ return nil
+})
+
+var haveProgAttachReplace = internal.FeatureTest("BPF_PROG_ATTACH atomic replacement", "5.5", func() error {
+ if err := haveProgAttach(); err != nil {
+ return err
+ }
+
+ prog, err := ebpf.NewProgram(&ebpf.ProgramSpec{
+ Type: ebpf.CGroupSKB,
+ AttachType: ebpf.AttachCGroupInetIngress,
+ License: "MIT",
+ Instructions: asm.Instructions{
+ asm.Mov.Imm(asm.R0, 0),
+ asm.Return(),
+ },
+ })
+ if err != nil {
+ return internal.ErrNotSupported
+ }
+ defer prog.Close()
+
+ // We know that we have BPF_PROG_ATTACH since we can load CGroupSKB programs.
+ // If passing BPF_F_REPLACE gives us EINVAL we know that the feature isn't
+ // present.
+ attr := internal.BPFProgAttachAttr{
+ // We rely on this being checked after attachFlags.
+ TargetFd: ^uint32(0),
+ AttachBpfFd: uint32(prog.FD()),
+ AttachType: uint32(ebpf.AttachCGroupInetIngress),
+ AttachFlags: uint32(flagReplace),
+ }
+
+ err = internal.BPFProgAttach(&attr)
+ if errors.Is(err, unix.EINVAL) {
+ return internal.ErrNotSupported
+ }
+ if errors.Is(err, unix.EBADF) {
+ return nil
+ }
+ return err
+})
+
+type bpfLinkCreateAttr struct {
+ progFd uint32
+ targetFd uint32
+ attachType ebpf.AttachType
+ flags uint32
+}
+
+func bpfLinkCreate(attr *bpfLinkCreateAttr) (*internal.FD, error) {
+ ptr, err := internal.BPF(internal.BPF_LINK_CREATE, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ if err != nil {
+ return nil, err
+ }
+ return internal.NewFD(uint32(ptr)), nil
+}
+
+type bpfLinkUpdateAttr struct {
+ linkFd uint32
+ newProgFd uint32
+ flags uint32
+ oldProgFd uint32
+}
+
+func bpfLinkUpdate(attr *bpfLinkUpdateAttr) error {
+ _, err := internal.BPF(internal.BPF_LINK_UPDATE, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ return err
+}
+
+var haveBPFLink = internal.FeatureTest("bpf_link", "5.7", func() error {
+ prog, err := ebpf.NewProgram(&ebpf.ProgramSpec{
+ Type: ebpf.CGroupSKB,
+ AttachType: ebpf.AttachCGroupInetIngress,
+ License: "MIT",
+ Instructions: asm.Instructions{
+ asm.Mov.Imm(asm.R0, 0),
+ asm.Return(),
+ },
+ })
+ if err != nil {
+ return internal.ErrNotSupported
+ }
+ defer prog.Close()
+
+ attr := bpfLinkCreateAttr{
+ // This is a hopefully invalid file descriptor, which triggers EBADF.
+ targetFd: ^uint32(0),
+ progFd: uint32(prog.FD()),
+ attachType: ebpf.AttachCGroupInetIngress,
+ }
+ _, err = bpfLinkCreate(&attr)
+ if errors.Is(err, unix.EINVAL) {
+ return internal.ErrNotSupported
+ }
+ if errors.Is(err, unix.EBADF) {
+ return nil
+ }
+ return err
+})
+
+type bpfIterCreateAttr struct {
+ linkFd uint32
+ flags uint32
+}
+
+func bpfIterCreate(attr *bpfIterCreateAttr) (*internal.FD, error) {
+ ptr, err := internal.BPF(internal.BPF_ITER_CREATE, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ if err == nil {
+ return internal.NewFD(uint32(ptr)), nil
+ }
+ return nil, err
+}
+
+type bpfRawTracepointOpenAttr struct {
+ name internal.Pointer
+ fd uint32
+ _ uint32
+}
+
+func bpfRawTracepointOpen(attr *bpfRawTracepointOpenAttr) (*internal.FD, error) {
+ ptr, err := internal.BPF(internal.BPF_RAW_TRACEPOINT_OPEN, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ if err == nil {
+ return internal.NewFD(uint32(ptr)), nil
+ }
+ return nil, err
+}
diff --git a/vendor/github.com/cilium/ebpf/linker.go b/vendor/github.com/cilium/ebpf/linker.go
@@ -0,0 +1,133 @@
+package ebpf
+
+import (
+ "fmt"
+
+ "github.com/cilium/ebpf/asm"
+ "github.com/cilium/ebpf/internal/btf"
+)
+
+// link resolves bpf-to-bpf calls.
+//
+// Each library may contain multiple functions / labels, and is only linked
+// if prog references one of these functions.
+//
+// Libraries also linked.
+func link(prog *ProgramSpec, libs []*ProgramSpec) error {
+ var (
+ linked = make(map[*ProgramSpec]bool)
+ pending = []asm.Instructions{prog.Instructions}
+ insns asm.Instructions
+ )
+ for len(pending) > 0 {
+ insns, pending = pending[0], pending[1:]
+ for _, lib := range libs {
+ if linked[lib] {
+ continue
+ }
+
+ needed, err := needSection(insns, lib.Instructions)
+ if err != nil {
+ return fmt.Errorf("linking %s: %w", lib.Name, err)
+ }
+
+ if !needed {
+ continue
+ }
+
+ linked[lib] = true
+ prog.Instructions = append(prog.Instructions, lib.Instructions...)
+ pending = append(pending, lib.Instructions)
+
+ if prog.BTF != nil && lib.BTF != nil {
+ if err := btf.ProgramAppend(prog.BTF, lib.BTF); err != nil {
+ return fmt.Errorf("linking BTF of %s: %w", lib.Name, err)
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
+func needSection(insns, section asm.Instructions) (bool, error) {
+ // A map of symbols to the libraries which contain them.
+ symbols, err := section.SymbolOffsets()
+ if err != nil {
+ return false, err
+ }
+
+ for _, ins := range insns {
+ if ins.Reference == "" {
+ continue
+ }
+
+ if ins.OpCode.JumpOp() != asm.Call || ins.Src != asm.PseudoCall {
+ continue
+ }
+
+ if ins.Constant != -1 {
+ // This is already a valid call, no need to link again.
+ continue
+ }
+
+ if _, ok := symbols[ins.Reference]; !ok {
+ // Symbol isn't available in this section
+ continue
+ }
+
+ // At this point we know that at least one function in the
+ // library is called from insns, so we have to link it.
+ return true, nil
+ }
+
+ // None of the functions in the section are called.
+ return false, nil
+}
+
+func fixupJumpsAndCalls(insns asm.Instructions) error {
+ symbolOffsets := make(map[string]asm.RawInstructionOffset)
+ iter := insns.Iterate()
+ for iter.Next() {
+ ins := iter.Ins
+
+ if ins.Symbol == "" {
+ continue
+ }
+
+ if _, ok := symbolOffsets[ins.Symbol]; ok {
+ return fmt.Errorf("duplicate symbol %s", ins.Symbol)
+ }
+
+ symbolOffsets[ins.Symbol] = iter.Offset
+ }
+
+ iter = insns.Iterate()
+ for iter.Next() {
+ i := iter.Index
+ offset := iter.Offset
+ ins := iter.Ins
+
+ switch {
+ case ins.IsFunctionCall() && ins.Constant == -1:
+ // Rewrite bpf to bpf call
+ callOffset, ok := symbolOffsets[ins.Reference]
+ if !ok {
+ return fmt.Errorf("instruction %d: reference to missing symbol %q", i, ins.Reference)
+ }
+
+ ins.Constant = int64(callOffset - offset - 1)
+
+ case ins.OpCode.Class() == asm.JumpClass && ins.Offset == -1:
+ // Rewrite jump to label
+ jumpOffset, ok := symbolOffsets[ins.Reference]
+ if !ok {
+ return fmt.Errorf("instruction %d: reference to missing symbol %q", i, ins.Reference)
+ }
+
+ ins.Offset = int16(jumpOffset - offset - 1)
+ }
+ }
+
+ return nil
+}
diff --git a/vendor/github.com/cilium/ebpf/map.go b/vendor/github.com/cilium/ebpf/map.go
@@ -0,0 +1,1188 @@
+package ebpf
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "path/filepath"
+ "reflect"
+ "strings"
+
+ "github.com/cilium/ebpf/internal"
+ "github.com/cilium/ebpf/internal/btf"
+ "github.com/cilium/ebpf/internal/unix"
+)
+
+// Errors returned by Map and MapIterator methods.
+var (
+ ErrKeyNotExist = errors.New("key does not exist")
+ ErrKeyExist = errors.New("key already exists")
+ ErrIterationAborted = errors.New("iteration aborted")
+)
+
+// MapOptions control loading a map into the kernel.
+type MapOptions struct {
+ // The base path to pin maps in if requested via PinByName.
+ // Existing maps will be re-used if they are compatible, otherwise an
+ // error is returned.
+ PinPath string
+}
+
+// MapID represents the unique ID of an eBPF map
+type MapID uint32
+
+// MapSpec defines a Map.
+type MapSpec struct {
+ // Name is passed to the kernel as a debug aid. Must only contain
+ // alpha numeric and '_' characters.
+ Name string
+ Type MapType
+ KeySize uint32
+ ValueSize uint32
+ MaxEntries uint32
+ Flags uint32
+
+ // Automatically pin and load a map from MapOptions.PinPath.
+ // Generates an error if an existing pinned map is incompatible with the MapSpec.
+ Pinning PinType
+
+ // Specify numa node during map creation
+ // (effective only if unix.BPF_F_NUMA_NODE flag is set,
+ // which can be imported from golang.org/x/sys/unix)
+ NumaNode uint32
+
+ // The initial contents of the map. May be nil.
+ Contents []MapKV
+
+ // Whether to freeze a map after setting its initial contents.
+ Freeze bool
+
+ // InnerMap is used as a template for ArrayOfMaps and HashOfMaps
+ InnerMap *MapSpec
+
+ // The BTF associated with this map.
+ BTF *btf.Map
+}
+
+func (ms *MapSpec) String() string {
+ return fmt.Sprintf("%s(keySize=%d, valueSize=%d, maxEntries=%d, flags=%d)", ms.Type, ms.KeySize, ms.ValueSize, ms.MaxEntries, ms.Flags)
+}
+
+// Copy returns a copy of the spec.
+//
+// MapSpec.Contents is a shallow copy.
+func (ms *MapSpec) Copy() *MapSpec {
+ if ms == nil {
+ return nil
+ }
+
+ cpy := *ms
+ cpy.Contents = make([]MapKV, len(ms.Contents))
+ copy(cpy.Contents, ms.Contents)
+ cpy.InnerMap = ms.InnerMap.Copy()
+ return &cpy
+}
+
+// MapKV is used to initialize the contents of a Map.
+type MapKV struct {
+ Key interface{}
+ Value interface{}
+}
+
+func (ms *MapSpec) checkCompatibility(m *Map) error {
+ switch {
+ case m.typ != ms.Type:
+ return fmt.Errorf("expected type %v, got %v", ms.Type, m.typ)
+
+ case m.keySize != ms.KeySize:
+ return fmt.Errorf("expected key size %v, got %v", ms.KeySize, m.keySize)
+
+ case m.valueSize != ms.ValueSize:
+ return fmt.Errorf("expected value size %v, got %v", ms.ValueSize, m.valueSize)
+
+ case m.maxEntries != ms.MaxEntries:
+ return fmt.Errorf("expected max entries %v, got %v", ms.MaxEntries, m.maxEntries)
+
+ case m.flags != ms.Flags:
+ return fmt.Errorf("expected flags %v, got %v", ms.Flags, m.flags)
+ }
+ return nil
+}
+
+// Map represents a Map file descriptor.
+//
+// It is not safe to close a map which is used by other goroutines.
+//
+// Methods which take interface{} arguments by default encode
+// them using binary.Read/Write in the machine's native endianness.
+//
+// Implement encoding.BinaryMarshaler or encoding.BinaryUnmarshaler
+// if you require custom encoding.
+type Map struct {
+ name string
+ fd *internal.FD
+ typ MapType
+ keySize uint32
+ valueSize uint32
+ maxEntries uint32
+ flags uint32
+ pinnedPath string
+ // Per CPU maps return values larger than the size in the spec
+ fullValueSize int
+}
+
+// NewMapFromFD creates a map from a raw fd.
+//
+// You should not use fd after calling this function.
+func NewMapFromFD(fd int) (*Map, error) {
+ if fd < 0 {
+ return nil, errors.New("invalid fd")
+ }
+
+ return newMapFromFD(internal.NewFD(uint32(fd)))
+}
+
+func newMapFromFD(fd *internal.FD) (*Map, error) {
+ info, err := newMapInfoFromFd(fd)
+ if err != nil {
+ fd.Close()
+ return nil, fmt.Errorf("get map info: %s", err)
+ }
+
+ return newMap(fd, info.Name, info.Type, info.KeySize, info.ValueSize, info.MaxEntries, info.Flags)
+}
+
+// NewMap creates a new Map.
+//
+// It's equivalent to calling NewMapWithOptions with default options.
+func NewMap(spec *MapSpec) (*Map, error) {
+ return NewMapWithOptions(spec, MapOptions{})
+}
+
+// NewMapWithOptions creates a new Map.
+//
+// Creating a map for the first time will perform feature detection
+// by creating small, temporary maps.
+//
+// The caller is responsible for ensuring the process' rlimit is set
+// sufficiently high for locking memory during map creation. This can be done
+// by calling unix.Setrlimit with unix.RLIMIT_MEMLOCK prior to calling NewMapWithOptions.
+func NewMapWithOptions(spec *MapSpec, opts MapOptions) (*Map, error) {
+ btfs := make(btfHandleCache)
+ defer btfs.close()
+
+ return newMapWithOptions(spec, opts, btfs)
+}
+
+func newMapWithOptions(spec *MapSpec, opts MapOptions, btfs btfHandleCache) (*Map, error) {
+ switch spec.Pinning {
+ case PinByName:
+ if spec.Name == "" || opts.PinPath == "" {
+ return nil, fmt.Errorf("pin by name: missing Name or PinPath")
+ }
+
+ m, err := LoadPinnedMap(filepath.Join(opts.PinPath, spec.Name))
+ if errors.Is(err, unix.ENOENT) {
+ break
+ }
+ if err != nil {
+ return nil, fmt.Errorf("load pinned map: %s", err)
+ }
+
+ if err := spec.checkCompatibility(m); err != nil {
+ m.Close()
+ return nil, fmt.Errorf("use pinned map %s: %s", spec.Name, err)
+ }
+
+ return m, nil
+
+ case PinNone:
+ // Nothing to do here
+
+ default:
+ return nil, fmt.Errorf("unsupported pin type %d", int(spec.Pinning))
+ }
+
+ var innerFd *internal.FD
+ if spec.Type == ArrayOfMaps || spec.Type == HashOfMaps {
+ if spec.InnerMap == nil {
+ return nil, fmt.Errorf("%s requires InnerMap", spec.Type)
+ }
+
+ if spec.InnerMap.Pinning != PinNone {
+ return nil, errors.New("inner maps cannot be pinned")
+ }
+
+ template, err := createMap(spec.InnerMap, nil, opts, btfs)
+ if err != nil {
+ return nil, err
+ }
+ defer template.Close()
+
+ innerFd = template.fd
+ }
+
+ m, err := createMap(spec, innerFd, opts, btfs)
+ if err != nil {
+ return nil, err
+ }
+
+ if spec.Pinning == PinByName {
+ if err := m.Pin(filepath.Join(opts.PinPath, spec.Name)); err != nil {
+ m.Close()
+ return nil, fmt.Errorf("pin map: %s", err)
+ }
+ }
+
+ return m, nil
+}
+
+func createMap(spec *MapSpec, inner *internal.FD, opts MapOptions, btfs btfHandleCache) (_ *Map, err error) {
+ closeOnError := func(closer io.Closer) {
+ if err != nil {
+ closer.Close()
+ }
+ }
+
+ spec = spec.Copy()
+
+ switch spec.Type {
+ case ArrayOfMaps:
+ fallthrough
+ case HashOfMaps:
+ if err := haveNestedMaps(); err != nil {
+ return nil, err
+ }
+
+ if spec.ValueSize != 0 && spec.ValueSize != 4 {
+ return nil, errors.New("ValueSize must be zero or four for map of map")
+ }
+ spec.ValueSize = 4
+
+ case PerfEventArray:
+ if spec.KeySize != 0 && spec.KeySize != 4 {
+ return nil, errors.New("KeySize must be zero or four for perf event array")
+ }
+ spec.KeySize = 4
+
+ if spec.ValueSize != 0 && spec.ValueSize != 4 {
+ return nil, errors.New("ValueSize must be zero or four for perf event array")
+ }
+ spec.ValueSize = 4
+
+ if spec.MaxEntries == 0 {
+ n, err := internal.PossibleCPUs()
+ if err != nil {
+ return nil, fmt.Errorf("perf event array: %w", err)
+ }
+ spec.MaxEntries = uint32(n)
+ }
+ }
+
+ if spec.Flags&(unix.BPF_F_RDONLY_PROG|unix.BPF_F_WRONLY_PROG) > 0 || spec.Freeze {
+ if err := haveMapMutabilityModifiers(); err != nil {
+ return nil, fmt.Errorf("map create: %w", err)
+ }
+ }
+
+ attr := bpfMapCreateAttr{
+ mapType: spec.Type,
+ keySize: spec.KeySize,
+ valueSize: spec.ValueSize,
+ maxEntries: spec.MaxEntries,
+ flags: spec.Flags,
+ numaNode: spec.NumaNode,
+ }
+
+ if inner != nil {
+ var err error
+ attr.innerMapFd, err = inner.Value()
+ if err != nil {
+ return nil, fmt.Errorf("map create: %w", err)
+ }
+ }
+
+ if haveObjName() == nil {
+ attr.mapName = newBPFObjName(spec.Name)
+ }
+
+ var btfDisabled bool
+ if spec.BTF != nil {
+ handle, err := btfs.load(btf.MapSpec(spec.BTF))
+ btfDisabled = errors.Is(err, btf.ErrNotSupported)
+ if err != nil && !btfDisabled {
+ return nil, fmt.Errorf("load BTF: %w", err)
+ }
+
+ if handle != nil {
+ attr.btfFd = uint32(handle.FD())
+ attr.btfKeyTypeID = btf.MapKey(spec.BTF).ID()
+ attr.btfValueTypeID = btf.MapValue(spec.BTF).ID()
+ }
+ }
+
+ fd, err := bpfMapCreate(&attr)
+ if err != nil {
+ if errors.Is(err, unix.EPERM) {
+ return nil, fmt.Errorf("map create: RLIMIT_MEMLOCK may be too low: %w", err)
+ }
+ if btfDisabled {
+ return nil, fmt.Errorf("map create without BTF: %w", err)
+ }
+ return nil, fmt.Errorf("map create: %w", err)
+ }
+ defer closeOnError(fd)
+
+ m, err := newMap(fd, spec.Name, spec.Type, spec.KeySize, spec.ValueSize, spec.MaxEntries, spec.Flags)
+ if err != nil {
+ return nil, fmt.Errorf("map create: %w", err)
+ }
+
+ if err := m.populate(spec.Contents); err != nil {
+ return nil, fmt.Errorf("map create: can't set initial contents: %w", err)
+ }
+
+ if spec.Freeze {
+ if err := m.Freeze(); err != nil {
+ return nil, fmt.Errorf("can't freeze map: %w", err)
+ }
+ }
+
+ return m, nil
+}
+
+func newMap(fd *internal.FD, name string, typ MapType, keySize, valueSize, maxEntries, flags uint32) (*Map, error) {
+ m := &Map{
+ name,
+ fd,
+ typ,
+ keySize,
+ valueSize,
+ maxEntries,
+ flags,
+ "",
+ int(valueSize),
+ }
+
+ if !typ.hasPerCPUValue() {
+ return m, nil
+ }
+
+ possibleCPUs, err := internal.PossibleCPUs()
+ if err != nil {
+ return nil, err
+ }
+
+ m.fullValueSize = align(int(valueSize), 8) * possibleCPUs
+ return m, nil
+}
+
+func (m *Map) String() string {
+ if m.name != "" {
+ return fmt.Sprintf("%s(%s)#%v", m.typ, m.name, m.fd)
+ }
+ return fmt.Sprintf("%s#%v", m.typ, m.fd)
+}
+
+// Type returns the underlying type of the map.
+func (m *Map) Type() MapType {
+ return m.typ
+}
+
+// KeySize returns the size of the map key in bytes.
+func (m *Map) KeySize() uint32 {
+ return m.keySize
+}
+
+// ValueSize returns the size of the map value in bytes.
+func (m *Map) ValueSize() uint32 {
+ return m.valueSize
+}
+
+// MaxEntries returns the maximum number of elements the map can hold.
+func (m *Map) MaxEntries() uint32 {
+ return m.maxEntries
+}
+
+// Flags returns the flags of the map.
+func (m *Map) Flags() uint32 {
+ return m.flags
+}
+
+// Info returns metadata about the map.
+func (m *Map) Info() (*MapInfo, error) {
+ return newMapInfoFromFd(m.fd)
+}
+
+// Lookup retrieves a value from a Map.
+//
+// Calls Close() on valueOut if it is of type **Map or **Program,
+// and *valueOut is not nil.
+//
+// Returns an error if the key doesn't exist, see ErrKeyNotExist.
+func (m *Map) Lookup(key, valueOut interface{}) error {
+ valuePtr, valueBytes := makeBuffer(valueOut, m.fullValueSize)
+ if err := m.lookup(key, valuePtr); err != nil {
+ return err
+ }
+
+ return m.unmarshalValue(valueOut, valueBytes)
+}
+
+// LookupAndDelete retrieves and deletes a value from a Map.
+//
+// Returns ErrKeyNotExist if the key doesn't exist.
+func (m *Map) LookupAndDelete(key, valueOut interface{}) error {
+ valuePtr, valueBytes := makeBuffer(valueOut, m.fullValueSize)
+
+ keyPtr, err := m.marshalKey(key)
+ if err != nil {
+ return fmt.Errorf("can't marshal key: %w", err)
+ }
+
+ if err := bpfMapLookupAndDelete(m.fd, keyPtr, valuePtr); err != nil {
+ return fmt.Errorf("lookup and delete failed: %w", err)
+ }
+
+ return m.unmarshalValue(valueOut, valueBytes)
+}
+
+// LookupBytes gets a value from Map.
+//
+// Returns a nil value if a key doesn't exist.
+func (m *Map) LookupBytes(key interface{}) ([]byte, error) {
+ valueBytes := make([]byte, m.fullValueSize)
+ valuePtr := internal.NewSlicePointer(valueBytes)
+
+ err := m.lookup(key, valuePtr)
+ if errors.Is(err, ErrKeyNotExist) {
+ return nil, nil
+ }
+
+ return valueBytes, err
+}
+
+func (m *Map) lookup(key interface{}, valueOut internal.Pointer) error {
+ keyPtr, err := m.marshalKey(key)
+ if err != nil {
+ return fmt.Errorf("can't marshal key: %w", err)
+ }
+
+ if err = bpfMapLookupElem(m.fd, keyPtr, valueOut); err != nil {
+ return fmt.Errorf("lookup failed: %w", err)
+ }
+ return nil
+}
+
+// MapUpdateFlags controls the behaviour of the Map.Update call.
+//
+// The exact semantics depend on the specific MapType.
+type MapUpdateFlags uint64
+
+const (
+ // UpdateAny creates a new element or update an existing one.
+ UpdateAny MapUpdateFlags = iota
+ // UpdateNoExist creates a new element.
+ UpdateNoExist MapUpdateFlags = 1 << (iota - 1)
+ // UpdateExist updates an existing element.
+ UpdateExist
+)
+
+// Put replaces or creates a value in map.
+//
+// It is equivalent to calling Update with UpdateAny.
+func (m *Map) Put(key, value interface{}) error {
+ return m.Update(key, value, UpdateAny)
+}
+
+// Update changes the value of a key.
+func (m *Map) Update(key, value interface{}, flags MapUpdateFlags) error {
+ keyPtr, err := m.marshalKey(key)
+ if err != nil {
+ return fmt.Errorf("can't marshal key: %w", err)
+ }
+
+ valuePtr, err := m.marshalValue(value)
+ if err != nil {
+ return fmt.Errorf("can't marshal value: %w", err)
+ }
+
+ if err = bpfMapUpdateElem(m.fd, keyPtr, valuePtr, uint64(flags)); err != nil {
+ return fmt.Errorf("update failed: %w", err)
+ }
+
+ return nil
+}
+
+// Delete removes a value.
+//
+// Returns ErrKeyNotExist if the key does not exist.
+func (m *Map) Delete(key interface{}) error {
+ keyPtr, err := m.marshalKey(key)
+ if err != nil {
+ return fmt.Errorf("can't marshal key: %w", err)
+ }
+
+ if err = bpfMapDeleteElem(m.fd, keyPtr); err != nil {
+ return fmt.Errorf("delete failed: %w", err)
+ }
+ return nil
+}
+
+// NextKey finds the key following an initial key.
+//
+// See NextKeyBytes for details.
+//
+// Returns ErrKeyNotExist if there is no next key.
+func (m *Map) NextKey(key, nextKeyOut interface{}) error {
+ nextKeyPtr, nextKeyBytes := makeBuffer(nextKeyOut, int(m.keySize))
+
+ if err := m.nextKey(key, nextKeyPtr); err != nil {
+ return err
+ }
+
+ if err := m.unmarshalKey(nextKeyOut, nextKeyBytes); err != nil {
+ return fmt.Errorf("can't unmarshal next key: %w", err)
+ }
+ return nil
+}
+
+// NextKeyBytes returns the key following an initial key as a byte slice.
+//
+// Passing nil will return the first key.
+//
+// Use Iterate if you want to traverse all entries in the map.
+//
+// Returns nil if there are no more keys.
+func (m *Map) NextKeyBytes(key interface{}) ([]byte, error) {
+ nextKey := make([]byte, m.keySize)
+ nextKeyPtr := internal.NewSlicePointer(nextKey)
+
+ err := m.nextKey(key, nextKeyPtr)
+ if errors.Is(err, ErrKeyNotExist) {
+ return nil, nil
+ }
+
+ return nextKey, err
+}
+
+func (m *Map) nextKey(key interface{}, nextKeyOut internal.Pointer) error {
+ var (
+ keyPtr internal.Pointer
+ err error
+ )
+
+ if key != nil {
+ keyPtr, err = m.marshalKey(key)
+ if err != nil {
+ return fmt.Errorf("can't marshal key: %w", err)
+ }
+ }
+
+ if err = bpfMapGetNextKey(m.fd, keyPtr, nextKeyOut); err != nil {
+ return fmt.Errorf("next key failed: %w", err)
+ }
+ return nil
+}
+
+// BatchLookup looks up many elements in a map at once.
+//
+// "keysOut" and "valuesOut" must be of type slice, a pointer
+// to a slice or buffer will not work.
+// "prevKey" is the key to start the batch lookup from, it will
+// *not* be included in the results. Use nil to start at the first key.
+//
+// ErrKeyNotExist is returned when the batch lookup has reached
+// the end of all possible results, even when partial results
+// are returned. It should be used to evaluate when lookup is "done".
+func (m *Map) BatchLookup(prevKey, nextKeyOut, keysOut, valuesOut interface{}, opts *BatchOptions) (int, error) {
+ return m.batchLookup(internal.BPF_MAP_LOOKUP_BATCH, prevKey, nextKeyOut, keysOut, valuesOut, opts)
+}
+
+// BatchLookupAndDelete looks up many elements in a map at once,
+//
+// It then deletes all those elements.
+// "keysOut" and "valuesOut" must be of type slice, a pointer
+// to a slice or buffer will not work.
+// "prevKey" is the key to start the batch lookup from, it will
+// *not* be included in the results. Use nil to start at the first key.
+//
+// ErrKeyNotExist is returned when the batch lookup has reached
+// the end of all possible results, even when partial results
+// are returned. It should be used to evaluate when lookup is "done".
+func (m *Map) BatchLookupAndDelete(prevKey, nextKeyOut, keysOut, valuesOut interface{}, opts *BatchOptions) (int, error) {
+ return m.batchLookup(internal.BPF_MAP_LOOKUP_AND_DELETE_BATCH, prevKey, nextKeyOut, keysOut, valuesOut, opts)
+}
+
+func (m *Map) batchLookup(cmd internal.BPFCmd, startKey, nextKeyOut, keysOut, valuesOut interface{}, opts *BatchOptions) (int, error) {
+ if err := haveBatchAPI(); err != nil {
+ return 0, err
+ }
+ if m.typ.hasPerCPUValue() {
+ return 0, ErrNotSupported
+ }
+ keysValue := reflect.ValueOf(keysOut)
+ if keysValue.Kind() != reflect.Slice {
+ return 0, fmt.Errorf("keys must be a slice")
+ }
+ valuesValue := reflect.ValueOf(valuesOut)
+ if valuesValue.Kind() != reflect.Slice {
+ return 0, fmt.Errorf("valuesOut must be a slice")
+ }
+ count := keysValue.Len()
+ if count != valuesValue.Len() {
+ return 0, fmt.Errorf("keysOut and valuesOut must be the same length")
+ }
+ keyBuf := make([]byte, count*int(m.keySize))
+ keyPtr := internal.NewSlicePointer(keyBuf)
+ valueBuf := make([]byte, count*int(m.fullValueSize))
+ valuePtr := internal.NewSlicePointer(valueBuf)
+
+ var (
+ startPtr internal.Pointer
+ err error
+ retErr error
+ )
+ if startKey != nil {
+ startPtr, err = marshalPtr(startKey, int(m.keySize))
+ if err != nil {
+ return 0, err
+ }
+ }
+ nextPtr, nextBuf := makeBuffer(nextKeyOut, int(m.keySize))
+
+ ct, err := bpfMapBatch(cmd, m.fd, startPtr, nextPtr, keyPtr, valuePtr, uint32(count), opts)
+ if err != nil {
+ if !errors.Is(err, ErrKeyNotExist) {
+ return 0, err
+ }
+ retErr = ErrKeyNotExist
+ }
+
+ err = m.unmarshalKey(nextKeyOut, nextBuf)
+ if err != nil {
+ return 0, err
+ }
+ err = unmarshalBytes(keysOut, keyBuf)
+ if err != nil {
+ return 0, err
+ }
+ err = unmarshalBytes(valuesOut, valueBuf)
+ if err != nil {
+ retErr = err
+ }
+ return int(ct), retErr
+}
+
+// BatchUpdate updates the map with multiple keys and values
+// simultaneously.
+// "keys" and "values" must be of type slice, a pointer
+// to a slice or buffer will not work.
+func (m *Map) BatchUpdate(keys, values interface{}, opts *BatchOptions) (int, error) {
+ if err := haveBatchAPI(); err != nil {
+ return 0, err
+ }
+ if m.typ.hasPerCPUValue() {
+ return 0, ErrNotSupported
+ }
+ keysValue := reflect.ValueOf(keys)
+ if keysValue.Kind() != reflect.Slice {
+ return 0, fmt.Errorf("keys must be a slice")
+ }
+ valuesValue := reflect.ValueOf(values)
+ if valuesValue.Kind() != reflect.Slice {
+ return 0, fmt.Errorf("values must be a slice")
+ }
+ var (
+ count = keysValue.Len()
+ valuePtr internal.Pointer
+ err error
+ )
+ if count != valuesValue.Len() {
+ return 0, fmt.Errorf("keys and values must be the same length")
+ }
+ keyPtr, err := marshalPtr(keys, count*int(m.keySize))
+ if err != nil {
+ return 0, err
+ }
+ valuePtr, err = marshalPtr(values, count*int(m.valueSize))
+ if err != nil {
+ return 0, err
+ }
+ var nilPtr internal.Pointer
+ ct, err := bpfMapBatch(internal.BPF_MAP_UPDATE_BATCH, m.fd, nilPtr, nilPtr, keyPtr, valuePtr, uint32(count), opts)
+ return int(ct), err
+}
+
+// BatchDelete batch deletes entries in the map by keys.
+// "keys" must be of type slice, a pointer to a slice or buffer will not work.
+func (m *Map) BatchDelete(keys interface{}, opts *BatchOptions) (int, error) {
+ if err := haveBatchAPI(); err != nil {
+ return 0, err
+ }
+ if m.typ.hasPerCPUValue() {
+ return 0, ErrNotSupported
+ }
+ keysValue := reflect.ValueOf(keys)
+ if keysValue.Kind() != reflect.Slice {
+ return 0, fmt.Errorf("keys must be a slice")
+ }
+ count := keysValue.Len()
+ keyPtr, err := marshalPtr(keys, count*int(m.keySize))
+ if err != nil {
+ return 0, fmt.Errorf("cannot marshal keys: %v", err)
+ }
+ var nilPtr internal.Pointer
+ ct, err := bpfMapBatch(internal.BPF_MAP_DELETE_BATCH, m.fd, nilPtr, nilPtr, keyPtr, nilPtr, uint32(count), opts)
+ return int(ct), err
+}
+
+// Iterate traverses a map.
+//
+// It's safe to create multiple iterators at the same time.
+//
+// It's not possible to guarantee that all keys in a map will be
+// returned if there are concurrent modifications to the map.
+func (m *Map) Iterate() *MapIterator {
+ return newMapIterator(m)
+}
+
+// Close removes a Map
+func (m *Map) Close() error {
+ if m == nil {
+ // This makes it easier to clean up when iterating maps
+ // of maps / programs.
+ return nil
+ }
+
+ return m.fd.Close()
+}
+
+// FD gets the file descriptor of the Map.
+//
+// Calling this function is invalid after Close has been called.
+func (m *Map) FD() int {
+ fd, err := m.fd.Value()
+ if err != nil {
+ // Best effort: -1 is the number most likely to be an
+ // invalid file descriptor.
+ return -1
+ }
+
+ return int(fd)
+}
+
+// Clone creates a duplicate of the Map.
+//
+// Closing the duplicate does not affect the original, and vice versa.
+// Changes made to the map are reflected by both instances however.
+// If the original map was pinned, the cloned map will not be pinned by default.
+//
+// Cloning a nil Map returns nil.
+func (m *Map) Clone() (*Map, error) {
+ if m == nil {
+ return nil, nil
+ }
+
+ dup, err := m.fd.Dup()
+ if err != nil {
+ return nil, fmt.Errorf("can't clone map: %w", err)
+ }
+
+ return &Map{
+ m.name,
+ dup,
+ m.typ,
+ m.keySize,
+ m.valueSize,
+ m.maxEntries,
+ m.flags,
+ "",
+ m.fullValueSize,
+ }, nil
+}
+
+// Pin persists the map on the BPF virtual file system past the lifetime of
+// the process that created it .
+//
+// Calling Pin on a previously pinned map will override the path.
+// You can Clone a map to pin it to a different path.
+//
+// This requires bpffs to be mounted above fileName. See https://docs.cilium.io/en/k8s-doc/admin/#admin-mount-bpffs
+func (m *Map) Pin(fileName string) error {
+ if err := pin(m.pinnedPath, fileName, m.fd); err != nil {
+ return err
+ }
+ m.pinnedPath = fileName
+ return nil
+}
+
+// Unpin removes the persisted state for the map from the BPF virtual filesystem.
+//
+// Failed calls to Unpin will not alter the state returned by IsPinned.
+//
+// Unpinning an unpinned Map returns nil.
+func (m *Map) Unpin() error {
+ if err := unpin(m.pinnedPath); err != nil {
+ return err
+ }
+ m.pinnedPath = ""
+ return nil
+}
+
+// IsPinned returns true if the map has a non-empty pinned path.
+func (m *Map) IsPinned() bool {
+ if m.pinnedPath == "" {
+ return false
+ }
+ return true
+}
+
+// Freeze prevents a map to be modified from user space.
+//
+// It makes no changes to kernel-side restrictions.
+func (m *Map) Freeze() error {
+ if err := haveMapMutabilityModifiers(); err != nil {
+ return fmt.Errorf("can't freeze map: %w", err)
+ }
+
+ if err := bpfMapFreeze(m.fd); err != nil {
+ return fmt.Errorf("can't freeze map: %w", err)
+ }
+ return nil
+}
+
+func (m *Map) populate(contents []MapKV) error {
+ for _, kv := range contents {
+ if err := m.Put(kv.Key, kv.Value); err != nil {
+ return fmt.Errorf("key %v: %w", kv.Key, err)
+ }
+ }
+ return nil
+}
+
+func (m *Map) marshalKey(data interface{}) (internal.Pointer, error) {
+ if data == nil {
+ if m.keySize == 0 {
+ // Queues have a key length of zero, so passing nil here is valid.
+ return internal.NewPointer(nil), nil
+ }
+ return internal.Pointer{}, errors.New("can't use nil as key of map")
+ }
+
+ return marshalPtr(data, int(m.keySize))
+}
+
+func (m *Map) unmarshalKey(data interface{}, buf []byte) error {
+ if buf == nil {
+ // This is from a makeBuffer call, nothing do do here.
+ return nil
+ }
+
+ return unmarshalBytes(data, buf)
+}
+
+func (m *Map) marshalValue(data interface{}) (internal.Pointer, error) {
+ if m.typ.hasPerCPUValue() {
+ return marshalPerCPUValue(data, int(m.valueSize))
+ }
+
+ var (
+ buf []byte
+ err error
+ )
+
+ switch value := data.(type) {
+ case *Map:
+ if !m.typ.canStoreMap() {
+ return internal.Pointer{}, fmt.Errorf("can't store map in %s", m.typ)
+ }
+ buf, err = marshalMap(value, int(m.valueSize))
+
+ case *Program:
+ if !m.typ.canStoreProgram() {
+ return internal.Pointer{}, fmt.Errorf("can't store program in %s", m.typ)
+ }
+ buf, err = marshalProgram(value, int(m.valueSize))
+
+ default:
+ return marshalPtr(data, int(m.valueSize))
+ }
+
+ if err != nil {
+ return internal.Pointer{}, err
+ }
+
+ return internal.NewSlicePointer(buf), nil
+}
+
+func (m *Map) unmarshalValue(value interface{}, buf []byte) error {
+ if buf == nil {
+ // This is from a makeBuffer call, nothing do do here.
+ return nil
+ }
+
+ if m.typ.hasPerCPUValue() {
+ return unmarshalPerCPUValue(value, int(m.valueSize), buf)
+ }
+
+ switch value := value.(type) {
+ case **Map:
+ if !m.typ.canStoreMap() {
+ return fmt.Errorf("can't read a map from %s", m.typ)
+ }
+
+ other, err := unmarshalMap(buf)
+ if err != nil {
+ return err
+ }
+
+ (*value).Close()
+ *value = other
+ return nil
+
+ case *Map:
+ if !m.typ.canStoreMap() {
+ return fmt.Errorf("can't read a map from %s", m.typ)
+ }
+ return errors.New("require pointer to *Map")
+
+ case **Program:
+ if !m.typ.canStoreProgram() {
+ return fmt.Errorf("can't read a program from %s", m.typ)
+ }
+
+ other, err := unmarshalProgram(buf)
+ if err != nil {
+ return err
+ }
+
+ (*value).Close()
+ *value = other
+ return nil
+
+ case *Program:
+ if !m.typ.canStoreProgram() {
+ return fmt.Errorf("can't read a program from %s", m.typ)
+ }
+ return errors.New("require pointer to *Program")
+ }
+
+ return unmarshalBytes(value, buf)
+}
+
+// LoadPinnedMap load a Map from a BPF file.
+func LoadPinnedMap(fileName string) (*Map, error) {
+ fd, err := internal.BPFObjGet(fileName)
+ if err != nil {
+ return nil, err
+ }
+
+ m, err := newMapFromFD(fd)
+ if err == nil {
+ m.pinnedPath = fileName
+ }
+
+ return m, err
+}
+
+// unmarshalMap creates a map from a map ID encoded in host endianness.
+func unmarshalMap(buf []byte) (*Map, error) {
+ if len(buf) != 4 {
+ return nil, errors.New("map id requires 4 byte value")
+ }
+
+ id := internal.NativeEndian.Uint32(buf)
+ return NewMapFromID(MapID(id))
+}
+
+// marshalMap marshals the fd of a map into a buffer in host endianness.
+func marshalMap(m *Map, length int) ([]byte, error) {
+ if length != 4 {
+ return nil, fmt.Errorf("can't marshal map to %d bytes", length)
+ }
+
+ fd, err := m.fd.Value()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, 4)
+ internal.NativeEndian.PutUint32(buf, fd)
+ return buf, nil
+}
+
+func patchValue(value []byte, typ btf.Type, replacements map[string]interface{}) error {
+ replaced := make(map[string]bool)
+ replace := func(name string, offset, size int, replacement interface{}) error {
+ if offset+size > len(value) {
+ return fmt.Errorf("%s: offset %d(+%d) is out of bounds", name, offset, size)
+ }
+
+ buf, err := marshalBytes(replacement, size)
+ if err != nil {
+ return fmt.Errorf("marshal %s: %w", name, err)
+ }
+
+ copy(value[offset:offset+size], buf)
+ replaced[name] = true
+ return nil
+ }
+
+ switch parent := typ.(type) {
+ case *btf.Datasec:
+ for _, secinfo := range parent.Vars {
+ name := string(secinfo.Type.(*btf.Var).Name)
+ replacement, ok := replacements[name]
+ if !ok {
+ continue
+ }
+
+ err := replace(name, int(secinfo.Offset), int(secinfo.Size), replacement)
+ if err != nil {
+ return err
+ }
+ }
+
+ default:
+ return fmt.Errorf("patching %T is not supported", typ)
+ }
+
+ if len(replaced) == len(replacements) {
+ return nil
+ }
+
+ var missing []string
+ for name := range replacements {
+ if !replaced[name] {
+ missing = append(missing, name)
+ }
+ }
+
+ if len(missing) == 1 {
+ return fmt.Errorf("unknown field: %s", missing[0])
+ }
+
+ return fmt.Errorf("unknown fields: %s", strings.Join(missing, ","))
+}
+
+// MapIterator iterates a Map.
+//
+// See Map.Iterate.
+type MapIterator struct {
+ target *Map
+ prevKey interface{}
+ prevBytes []byte
+ count, maxEntries uint32
+ done bool
+ err error
+}
+
+func newMapIterator(target *Map) *MapIterator {
+ return &MapIterator{
+ target: target,
+ maxEntries: target.maxEntries,
+ prevBytes: make([]byte, target.keySize),
+ }
+}
+
+// Next decodes the next key and value.
+//
+// Iterating a hash map from which keys are being deleted is not
+// safe. You may see the same key multiple times. Iteration may
+// also abort with an error, see IsIterationAborted.
+//
+// Returns false if there are no more entries. You must check
+// the result of Err afterwards.
+//
+// See Map.Get for further caveats around valueOut.
+func (mi *MapIterator) Next(keyOut, valueOut interface{}) bool {
+ if mi.err != nil || mi.done {
+ return false
+ }
+
+ // For array-like maps NextKeyBytes returns nil only on after maxEntries
+ // iterations.
+ for mi.count <= mi.maxEntries {
+ var nextBytes []byte
+ nextBytes, mi.err = mi.target.NextKeyBytes(mi.prevKey)
+ if mi.err != nil {
+ return false
+ }
+
+ if nextBytes == nil {
+ mi.done = true
+ return false
+ }
+
+ // The user can get access to nextBytes since unmarshalBytes
+ // does not copy when unmarshaling into a []byte.
+ // Make a copy to prevent accidental corruption of
+ // iterator state.
+ copy(mi.prevBytes, nextBytes)
+ mi.prevKey = mi.prevBytes
+
+ mi.count++
+ mi.err = mi.target.Lookup(nextBytes, valueOut)
+ if errors.Is(mi.err, ErrKeyNotExist) {
+ // Even though the key should be valid, we couldn't look up
+ // its value. If we're iterating a hash map this is probably
+ // because a concurrent delete removed the value before we
+ // could get it. This means that the next call to NextKeyBytes
+ // is very likely to restart iteration.
+ // If we're iterating one of the fd maps like
+ // ProgramArray it means that a given slot doesn't have
+ // a valid fd associated. It's OK to continue to the next slot.
+ continue
+ }
+ if mi.err != nil {
+ return false
+ }
+
+ mi.err = mi.target.unmarshalKey(keyOut, nextBytes)
+ return mi.err == nil
+ }
+
+ mi.err = fmt.Errorf("%w", ErrIterationAborted)
+ return false
+}
+
+// Err returns any encountered error.
+//
+// The method must be called after Next returns nil.
+//
+// Returns ErrIterationAborted if it wasn't possible to do a full iteration.
+func (mi *MapIterator) Err() error {
+ return mi.err
+}
+
+// MapGetNextID returns the ID of the next eBPF map.
+//
+// Returns ErrNotExist, if there is no next eBPF map.
+func MapGetNextID(startID MapID) (MapID, error) {
+ id, err := objGetNextID(internal.BPF_MAP_GET_NEXT_ID, uint32(startID))
+ return MapID(id), err
+}
+
+// NewMapFromID returns the map for a given id.
+//
+// Returns ErrNotExist, if there is no eBPF map with the given id.
+func NewMapFromID(id MapID) (*Map, error) {
+ fd, err := bpfObjGetFDByID(internal.BPF_MAP_GET_FD_BY_ID, uint32(id))
+ if err != nil {
+ return nil, err
+ }
+
+ return newMapFromFD(fd)
+}
+
+// ID returns the systemwide unique ID of the map.
+//
+// Deprecated: use MapInfo.ID() instead.
+func (m *Map) ID() (MapID, error) {
+ info, err := bpfGetMapInfoByFD(m.fd)
+ if err != nil {
+ return MapID(0), err
+ }
+ return MapID(info.id), nil
+}
diff --git a/vendor/github.com/cilium/ebpf/marshalers.go b/vendor/github.com/cilium/ebpf/marshalers.go
@@ -0,0 +1,216 @@
+package ebpf
+
+import (
+ "bytes"
+ "encoding"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "reflect"
+ "runtime"
+ "unsafe"
+
+ "github.com/cilium/ebpf/internal"
+)
+
+// marshalPtr converts an arbitrary value into a pointer suitable
+// to be passed to the kernel.
+//
+// As an optimization, it returns the original value if it is an
+// unsafe.Pointer.
+func marshalPtr(data interface{}, length int) (internal.Pointer, error) {
+ if ptr, ok := data.(unsafe.Pointer); ok {
+ return internal.NewPointer(ptr), nil
+ }
+
+ buf, err := marshalBytes(data, length)
+ if err != nil {
+ return internal.Pointer{}, err
+ }
+
+ return internal.NewSlicePointer(buf), nil
+}
+
+// marshalBytes converts an arbitrary value into a byte buffer.
+//
+// Prefer using Map.marshalKey and Map.marshalValue if possible, since
+// those have special cases that allow more types to be encoded.
+//
+// Returns an error if the given value isn't representable in exactly
+// length bytes.
+func marshalBytes(data interface{}, length int) (buf []byte, err error) {
+ switch value := data.(type) {
+ case encoding.BinaryMarshaler:
+ buf, err = value.MarshalBinary()
+ case string:
+ buf = []byte(value)
+ case []byte:
+ buf = value
+ case unsafe.Pointer:
+ err = errors.New("can't marshal from unsafe.Pointer")
+ case Map, *Map, Program, *Program:
+ err = fmt.Errorf("can't marshal %T", value)
+ default:
+ var wr bytes.Buffer
+ err = binary.Write(&wr, internal.NativeEndian, value)
+ if err != nil {
+ err = fmt.Errorf("encoding %T: %v", value, err)
+ }
+ buf = wr.Bytes()
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ if len(buf) != length {
+ return nil, fmt.Errorf("%T doesn't marshal to %d bytes", data, length)
+ }
+ return buf, nil
+}
+
+func makeBuffer(dst interface{}, length int) (internal.Pointer, []byte) {
+ if ptr, ok := dst.(unsafe.Pointer); ok {
+ return internal.NewPointer(ptr), nil
+ }
+
+ buf := make([]byte, length)
+ return internal.NewSlicePointer(buf), buf
+}
+
+// unmarshalBytes converts a byte buffer into an arbitrary value.
+//
+// Prefer using Map.unmarshalKey and Map.unmarshalValue if possible, since
+// those have special cases that allow more types to be encoded.
+func unmarshalBytes(data interface{}, buf []byte) error {
+ switch value := data.(type) {
+ case unsafe.Pointer:
+ sh := &reflect.SliceHeader{
+ Data: uintptr(value),
+ Len: len(buf),
+ Cap: len(buf),
+ }
+
+ dst := *(*[]byte)(unsafe.Pointer(sh))
+ copy(dst, buf)
+ runtime.KeepAlive(value)
+ return nil
+ case Map, *Map, Program, *Program:
+ return fmt.Errorf("can't unmarshal into %T", value)
+ case encoding.BinaryUnmarshaler:
+ return value.UnmarshalBinary(buf)
+ case *string:
+ *value = string(buf)
+ return nil
+ case *[]byte:
+ *value = buf
+ return nil
+ case string:
+ return errors.New("require pointer to string")
+ case []byte:
+ return errors.New("require pointer to []byte")
+ default:
+ rd := bytes.NewReader(buf)
+ if err := binary.Read(rd, internal.NativeEndian, value); err != nil {
+ return fmt.Errorf("decoding %T: %v", value, err)
+ }
+ return nil
+ }
+}
+
+// marshalPerCPUValue encodes a slice containing one value per
+// possible CPU into a buffer of bytes.
+//
+// Values are initialized to zero if the slice has less elements than CPUs.
+//
+// slice must have a type like []elementType.
+func marshalPerCPUValue(slice interface{}, elemLength int) (internal.Pointer, error) {
+ sliceType := reflect.TypeOf(slice)
+ if sliceType.Kind() != reflect.Slice {
+ return internal.Pointer{}, errors.New("per-CPU value requires slice")
+ }
+
+ possibleCPUs, err := internal.PossibleCPUs()
+ if err != nil {
+ return internal.Pointer{}, err
+ }
+
+ sliceValue := reflect.ValueOf(slice)
+ sliceLen := sliceValue.Len()
+ if sliceLen > possibleCPUs {
+ return internal.Pointer{}, fmt.Errorf("per-CPU value exceeds number of CPUs")
+ }
+
+ alignedElemLength := align(elemLength, 8)
+ buf := make([]byte, alignedElemLength*possibleCPUs)
+
+ for i := 0; i < sliceLen; i++ {
+ elem := sliceValue.Index(i).Interface()
+ elemBytes, err := marshalBytes(elem, elemLength)
+ if err != nil {
+ return internal.Pointer{}, err
+ }
+
+ offset := i * alignedElemLength
+ copy(buf[offset:offset+elemLength], elemBytes)
+ }
+
+ return internal.NewSlicePointer(buf), nil
+}
+
+// unmarshalPerCPUValue decodes a buffer into a slice containing one value per
+// possible CPU.
+//
+// valueOut must have a type like *[]elementType
+func unmarshalPerCPUValue(slicePtr interface{}, elemLength int, buf []byte) error {
+ slicePtrType := reflect.TypeOf(slicePtr)
+ if slicePtrType.Kind() != reflect.Ptr || slicePtrType.Elem().Kind() != reflect.Slice {
+ return fmt.Errorf("per-cpu value requires pointer to slice")
+ }
+
+ possibleCPUs, err := internal.PossibleCPUs()
+ if err != nil {
+ return err
+ }
+
+ sliceType := slicePtrType.Elem()
+ slice := reflect.MakeSlice(sliceType, possibleCPUs, possibleCPUs)
+
+ sliceElemType := sliceType.Elem()
+ sliceElemIsPointer := sliceElemType.Kind() == reflect.Ptr
+ if sliceElemIsPointer {
+ sliceElemType = sliceElemType.Elem()
+ }
+
+ step := len(buf) / possibleCPUs
+ if step < elemLength {
+ return fmt.Errorf("per-cpu element length is larger than available data")
+ }
+ for i := 0; i < possibleCPUs; i++ {
+ var elem interface{}
+ if sliceElemIsPointer {
+ newElem := reflect.New(sliceElemType)
+ slice.Index(i).Set(newElem)
+ elem = newElem.Interface()
+ } else {
+ elem = slice.Index(i).Addr().Interface()
+ }
+
+ // Make a copy, since unmarshal can hold on to itemBytes
+ elemBytes := make([]byte, elemLength)
+ copy(elemBytes, buf[:elemLength])
+
+ err := unmarshalBytes(elem, elemBytes)
+ if err != nil {
+ return fmt.Errorf("cpu %d: %w", i, err)
+ }
+
+ buf = buf[step:]
+ }
+
+ reflect.ValueOf(slicePtr).Elem().Set(slice)
+ return nil
+}
+
+func align(n, alignment int) int {
+ return (int(n) + alignment - 1) / alignment * alignment
+}
diff --git a/vendor/github.com/cilium/ebpf/pinning.go b/vendor/github.com/cilium/ebpf/pinning.go
@@ -0,0 +1,42 @@
+package ebpf
+
+import (
+ "errors"
+ "fmt"
+ "os"
+
+ "github.com/cilium/ebpf/internal"
+)
+
+func pin(currentPath, newPath string, fd *internal.FD) error {
+ if newPath == "" {
+ return errors.New("given pinning path cannot be empty")
+ }
+ if currentPath == "" {
+ return internal.BPFObjPin(newPath, fd)
+ }
+ if currentPath == newPath {
+ return nil
+ }
+ var err error
+ // Object is now moved to the new pinning path.
+ if err = os.Rename(currentPath, newPath); err == nil {
+ return nil
+ }
+ if !os.IsNotExist(err) {
+ return fmt.Errorf("unable to move pinned object to new path %v: %w", newPath, err)
+ }
+ // Internal state not in sync with the file system so let's fix it.
+ return internal.BPFObjPin(newPath, fd)
+}
+
+func unpin(pinnedPath string) error {
+ if pinnedPath == "" {
+ return nil
+ }
+ err := os.Remove(pinnedPath)
+ if err == nil || os.IsNotExist(err) {
+ return nil
+ }
+ return err
+}
diff --git a/vendor/github.com/cilium/ebpf/prog.go b/vendor/github.com/cilium/ebpf/prog.go
@@ -0,0 +1,698 @@
+package ebpf
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "math"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/cilium/ebpf/asm"
+ "github.com/cilium/ebpf/internal"
+ "github.com/cilium/ebpf/internal/btf"
+ "github.com/cilium/ebpf/internal/unix"
+)
+
+// ErrNotSupported is returned whenever the kernel doesn't support a feature.
+var ErrNotSupported = internal.ErrNotSupported
+
+// ProgramID represents the unique ID of an eBPF program.
+type ProgramID uint32
+
+const (
+ // Number of bytes to pad the output buffer for BPF_PROG_TEST_RUN.
+ // This is currently the maximum of spare space allocated for SKB
+ // and XDP programs, and equal to XDP_PACKET_HEADROOM + NET_IP_ALIGN.
+ outputPad = 256 + 2
+)
+
+// DefaultVerifierLogSize is the default number of bytes allocated for the
+// verifier log.
+const DefaultVerifierLogSize = 64 * 1024
+
+// ProgramOptions control loading a program into the kernel.
+type ProgramOptions struct {
+ // Controls the detail emitted by the kernel verifier. Set to non-zero
+ // to enable logging.
+ LogLevel uint32
+ // Controls the output buffer size for the verifier. Defaults to
+ // DefaultVerifierLogSize.
+ LogSize int
+}
+
+// ProgramSpec defines a Program.
+type ProgramSpec struct {
+ // Name is passed to the kernel as a debug aid. Must only contain
+ // alpha numeric and '_' characters.
+ Name string
+ // Type determines at which hook in the kernel a program will run.
+ Type ProgramType
+ AttachType AttachType
+ // Name of a kernel data structure to attach to. It's interpretation
+ // depends on Type and AttachType.
+ AttachTo string
+ Instructions asm.Instructions
+
+ // License of the program. Some helpers are only available if
+ // the license is deemed compatible with the GPL.
+ //
+ // See https://www.kernel.org/doc/html/latest/process/license-rules.html#id1
+ License string
+
+ // Version used by tracing programs.
+ //
+ // Deprecated: superseded by BTF.
+ KernelVersion uint32
+
+ // The BTF associated with this program. Changing Instructions
+ // will most likely invalidate the contained data, and may
+ // result in errors when attempting to load it into the kernel.
+ BTF *btf.Program
+
+ // The byte order this program was compiled for, may be nil.
+ ByteOrder binary.ByteOrder
+}
+
+// Copy returns a copy of the spec.
+func (ps *ProgramSpec) Copy() *ProgramSpec {
+ if ps == nil {
+ return nil
+ }
+
+ cpy := *ps
+ cpy.Instructions = make(asm.Instructions, len(ps.Instructions))
+ copy(cpy.Instructions, ps.Instructions)
+ return &cpy
+}
+
+// Tag calculates the kernel tag for a series of instructions.
+//
+// Use asm.Instructions.Tag if you need to calculate for non-native endianness.
+func (ps *ProgramSpec) Tag() (string, error) {
+ return ps.Instructions.Tag(internal.NativeEndian)
+}
+
+// Program represents BPF program loaded into the kernel.
+//
+// It is not safe to close a Program which is used by other goroutines.
+type Program struct {
+ // Contains the output of the kernel verifier if enabled,
+ // otherwise it is empty.
+ VerifierLog string
+
+ fd *internal.FD
+ name string
+ pinnedPath string
+ typ ProgramType
+}
+
+// NewProgram creates a new Program.
+//
+// Loading a program for the first time will perform
+// feature detection by loading small, temporary programs.
+func NewProgram(spec *ProgramSpec) (*Program, error) {
+ return NewProgramWithOptions(spec, ProgramOptions{})
+}
+
+// NewProgramWithOptions creates a new Program.
+//
+// Loading a program for the first time will perform
+// feature detection by loading small, temporary programs.
+func NewProgramWithOptions(spec *ProgramSpec, opts ProgramOptions) (*Program, error) {
+ btfs := make(btfHandleCache)
+ defer btfs.close()
+
+ return newProgramWithOptions(spec, opts, btfs)
+}
+
+func newProgramWithOptions(spec *ProgramSpec, opts ProgramOptions, btfs btfHandleCache) (*Program, error) {
+ if len(spec.Instructions) == 0 {
+ return nil, errors.New("Instructions cannot be empty")
+ }
+
+ if len(spec.License) == 0 {
+ return nil, errors.New("License cannot be empty")
+ }
+
+ if spec.ByteOrder != nil && spec.ByteOrder != internal.NativeEndian {
+ return nil, fmt.Errorf("can't load %s program on %s", spec.ByteOrder, internal.NativeEndian)
+ }
+
+ insns := make(asm.Instructions, len(spec.Instructions))
+ copy(insns, spec.Instructions)
+
+ if err := fixupJumpsAndCalls(insns); err != nil {
+ return nil, err
+ }
+
+ buf := bytes.NewBuffer(make([]byte, 0, len(spec.Instructions)*asm.InstructionSize))
+ err := insns.Marshal(buf, internal.NativeEndian)
+ if err != nil {
+ return nil, err
+ }
+
+ bytecode := buf.Bytes()
+ insCount := uint32(len(bytecode) / asm.InstructionSize)
+ attr := &bpfProgLoadAttr{
+ progType: spec.Type,
+ expectedAttachType: spec.AttachType,
+ insCount: insCount,
+ instructions: internal.NewSlicePointer(bytecode),
+ license: internal.NewStringPointer(spec.License),
+ kernelVersion: spec.KernelVersion,
+ }
+
+ if haveObjName() == nil {
+ attr.progName = newBPFObjName(spec.Name)
+ }
+
+ var btfDisabled bool
+ if spec.BTF != nil {
+ if relos, err := btf.ProgramRelocations(spec.BTF, nil); err != nil {
+ return nil, fmt.Errorf("CO-RE relocations: %s", err)
+ } else if len(relos) > 0 {
+ return nil, fmt.Errorf("applying CO-RE relocations: %w", ErrNotSupported)
+ }
+
+ handle, err := btfs.load(btf.ProgramSpec(spec.BTF))
+ btfDisabled = errors.Is(err, btf.ErrNotSupported)
+ if err != nil && !btfDisabled {
+ return nil, fmt.Errorf("load BTF: %w", err)
+ }
+
+ if handle != nil {
+ attr.progBTFFd = uint32(handle.FD())
+
+ recSize, bytes, err := btf.ProgramLineInfos(spec.BTF)
+ if err != nil {
+ return nil, fmt.Errorf("get BTF line infos: %w", err)
+ }
+ attr.lineInfoRecSize = recSize
+ attr.lineInfoCnt = uint32(uint64(len(bytes)) / uint64(recSize))
+ attr.lineInfo = internal.NewSlicePointer(bytes)
+
+ recSize, bytes, err = btf.ProgramFuncInfos(spec.BTF)
+ if err != nil {
+ return nil, fmt.Errorf("get BTF function infos: %w", err)
+ }
+ attr.funcInfoRecSize = recSize
+ attr.funcInfoCnt = uint32(uint64(len(bytes)) / uint64(recSize))
+ attr.funcInfo = internal.NewSlicePointer(bytes)
+ }
+ }
+
+ if spec.AttachTo != "" {
+ target, err := resolveBTFType(spec.AttachTo, spec.Type, spec.AttachType)
+ if err != nil {
+ return nil, err
+ }
+ if target != nil {
+ attr.attachBTFID = target.ID()
+ }
+ }
+
+ logSize := DefaultVerifierLogSize
+ if opts.LogSize > 0 {
+ logSize = opts.LogSize
+ }
+
+ var logBuf []byte
+ if opts.LogLevel > 0 {
+ logBuf = make([]byte, logSize)
+ attr.logLevel = opts.LogLevel
+ attr.logSize = uint32(len(logBuf))
+ attr.logBuf = internal.NewSlicePointer(logBuf)
+ }
+
+ fd, err := bpfProgLoad(attr)
+ if err == nil {
+ return &Program{internal.CString(logBuf), fd, spec.Name, "", spec.Type}, nil
+ }
+
+ logErr := err
+ if opts.LogLevel == 0 {
+ // Re-run with the verifier enabled to get better error messages.
+ logBuf = make([]byte, logSize)
+ attr.logLevel = 1
+ attr.logSize = uint32(len(logBuf))
+ attr.logBuf = internal.NewSlicePointer(logBuf)
+
+ _, logErr = bpfProgLoad(attr)
+ }
+
+ if errors.Is(logErr, unix.EPERM) && logBuf[0] == 0 {
+ // EPERM due to RLIMIT_MEMLOCK happens before the verifier, so we can
+ // check that the log is empty to reduce false positives.
+ return nil, fmt.Errorf("load program: RLIMIT_MEMLOCK may be too low: %w", logErr)
+ }
+
+ err = internal.ErrorWithLog(err, logBuf, logErr)
+ if btfDisabled {
+ return nil, fmt.Errorf("load program without BTF: %w", err)
+ }
+ return nil, fmt.Errorf("load program: %w", err)
+}
+
+// NewProgramFromFD creates a program from a raw fd.
+//
+// You should not use fd after calling this function.
+//
+// Requires at least Linux 4.10.
+func NewProgramFromFD(fd int) (*Program, error) {
+ if fd < 0 {
+ return nil, errors.New("invalid fd")
+ }
+
+ return newProgramFromFD(internal.NewFD(uint32(fd)))
+}
+
+// NewProgramFromID returns the program for a given id.
+//
+// Returns ErrNotExist, if there is no eBPF program with the given id.
+func NewProgramFromID(id ProgramID) (*Program, error) {
+ fd, err := bpfObjGetFDByID(internal.BPF_PROG_GET_FD_BY_ID, uint32(id))
+ if err != nil {
+ return nil, fmt.Errorf("get program by id: %w", err)
+ }
+
+ return newProgramFromFD(fd)
+}
+
+func newProgramFromFD(fd *internal.FD) (*Program, error) {
+ info, err := newProgramInfoFromFd(fd)
+ if err != nil {
+ fd.Close()
+ return nil, fmt.Errorf("discover program type: %w", err)
+ }
+
+ return &Program{"", fd, "", "", info.Type}, nil
+}
+
+func (p *Program) String() string {
+ if p.name != "" {
+ return fmt.Sprintf("%s(%s)#%v", p.typ, p.name, p.fd)
+ }
+ return fmt.Sprintf("%s(%v)", p.typ, p.fd)
+}
+
+// Type returns the underlying type of the program.
+func (p *Program) Type() ProgramType {
+ return p.typ
+}
+
+// Info returns metadata about the program.
+//
+// Requires at least 4.10.
+func (p *Program) Info() (*ProgramInfo, error) {
+ return newProgramInfoFromFd(p.fd)
+}
+
+// FD gets the file descriptor of the Program.
+//
+// It is invalid to call this function after Close has been called.
+func (p *Program) FD() int {
+ fd, err := p.fd.Value()
+ if err != nil {
+ // Best effort: -1 is the number most likely to be an
+ // invalid file descriptor.
+ return -1
+ }
+
+ return int(fd)
+}
+
+// Clone creates a duplicate of the Program.
+//
+// Closing the duplicate does not affect the original, and vice versa.
+//
+// Cloning a nil Program returns nil.
+func (p *Program) Clone() (*Program, error) {
+ if p == nil {
+ return nil, nil
+ }
+
+ dup, err := p.fd.Dup()
+ if err != nil {
+ return nil, fmt.Errorf("can't clone program: %w", err)
+ }
+
+ return &Program{p.VerifierLog, dup, p.name, "", p.typ}, nil
+}
+
+// Pin persists the Program on the BPF virtual file system past the lifetime of
+// the process that created it
+//
+// This requires bpffs to be mounted above fileName. See https://docs.cilium.io/en/k8s-doc/admin/#admin-mount-bpffs
+func (p *Program) Pin(fileName string) error {
+ if err := pin(p.pinnedPath, fileName, p.fd); err != nil {
+ return err
+ }
+ p.pinnedPath = fileName
+ return nil
+}
+
+// Unpin removes the persisted state for the Program from the BPF virtual filesystem.
+//
+// Failed calls to Unpin will not alter the state returned by IsPinned.
+//
+// Unpinning an unpinned Program returns nil.
+func (p *Program) Unpin() error {
+ if err := unpin(p.pinnedPath); err != nil {
+ return err
+ }
+ p.pinnedPath = ""
+ return nil
+}
+
+// IsPinned returns true if the Program has a non-empty pinned path.
+func (p *Program) IsPinned() bool {
+ if p.pinnedPath == "" {
+ return false
+ }
+ return true
+}
+
+// Close unloads the program from the kernel.
+func (p *Program) Close() error {
+ if p == nil {
+ return nil
+ }
+
+ return p.fd.Close()
+}
+
+// Test runs the Program in the kernel with the given input and returns the
+// value returned by the eBPF program. outLen may be zero.
+//
+// Note: the kernel expects at least 14 bytes input for an ethernet header for
+// XDP and SKB programs.
+//
+// This function requires at least Linux 4.12.
+func (p *Program) Test(in []byte) (uint32, []byte, error) {
+ ret, out, _, err := p.testRun(in, 1, nil)
+ if err != nil {
+ return ret, nil, fmt.Errorf("can't test program: %w", err)
+ }
+ return ret, out, nil
+}
+
+// Benchmark runs the Program with the given input for a number of times
+// and returns the time taken per iteration.
+//
+// Returns the result of the last execution of the program and the time per
+// run or an error. reset is called whenever the benchmark syscall is
+// interrupted, and should be set to testing.B.ResetTimer or similar.
+//
+// Note: profiling a call to this function will skew it's results, see
+// https://github.com/cilium/ebpf/issues/24
+//
+// This function requires at least Linux 4.12.
+func (p *Program) Benchmark(in []byte, repeat int, reset func()) (uint32, time.Duration, error) {
+ ret, _, total, err := p.testRun(in, repeat, reset)
+ if err != nil {
+ return ret, total, fmt.Errorf("can't benchmark program: %w", err)
+ }
+ return ret, total, nil
+}
+
+var haveProgTestRun = internal.FeatureTest("BPF_PROG_TEST_RUN", "4.12", func() error {
+ prog, err := NewProgram(&ProgramSpec{
+ Type: SocketFilter,
+ Instructions: asm.Instructions{
+ asm.LoadImm(asm.R0, 0, asm.DWord),
+ asm.Return(),
+ },
+ License: "MIT",
+ })
+ if err != nil {
+ // This may be because we lack sufficient permissions, etc.
+ return err
+ }
+ defer prog.Close()
+
+ // Programs require at least 14 bytes input
+ in := make([]byte, 14)
+ attr := bpfProgTestRunAttr{
+ fd: uint32(prog.FD()),
+ dataSizeIn: uint32(len(in)),
+ dataIn: internal.NewSlicePointer(in),
+ }
+
+ err = bpfProgTestRun(&attr)
+ if errors.Is(err, unix.EINVAL) {
+ // Check for EINVAL specifically, rather than err != nil since we
+ // otherwise misdetect due to insufficient permissions.
+ return internal.ErrNotSupported
+ }
+ if errors.Is(err, unix.EINTR) {
+ // We know that PROG_TEST_RUN is supported if we get EINTR.
+ return nil
+ }
+ return err
+})
+
+func (p *Program) testRun(in []byte, repeat int, reset func()) (uint32, []byte, time.Duration, error) {
+ if uint(repeat) > math.MaxUint32 {
+ return 0, nil, 0, fmt.Errorf("repeat is too high")
+ }
+
+ if len(in) == 0 {
+ return 0, nil, 0, fmt.Errorf("missing input")
+ }
+
+ if uint(len(in)) > math.MaxUint32 {
+ return 0, nil, 0, fmt.Errorf("input is too long")
+ }
+
+ if err := haveProgTestRun(); err != nil {
+ return 0, nil, 0, err
+ }
+
+ // Older kernels ignore the dataSizeOut argument when copying to user space.
+ // Combined with things like bpf_xdp_adjust_head() we don't really know what the final
+ // size will be. Hence we allocate an output buffer which we hope will always be large
+ // enough, and panic if the kernel wrote past the end of the allocation.
+ // See https://patchwork.ozlabs.org/cover/1006822/
+ out := make([]byte, len(in)+outputPad)
+
+ fd, err := p.fd.Value()
+ if err != nil {
+ return 0, nil, 0, err
+ }
+
+ attr := bpfProgTestRunAttr{
+ fd: fd,
+ dataSizeIn: uint32(len(in)),
+ dataSizeOut: uint32(len(out)),
+ dataIn: internal.NewSlicePointer(in),
+ dataOut: internal.NewSlicePointer(out),
+ repeat: uint32(repeat),
+ }
+
+ for {
+ err = bpfProgTestRun(&attr)
+ if err == nil {
+ break
+ }
+
+ if errors.Is(err, unix.EINTR) {
+ if reset != nil {
+ reset()
+ }
+ continue
+ }
+
+ return 0, nil, 0, fmt.Errorf("can't run test: %w", err)
+ }
+
+ if int(attr.dataSizeOut) > cap(out) {
+ // Houston, we have a problem. The program created more data than we allocated,
+ // and the kernel wrote past the end of our buffer.
+ panic("kernel wrote past end of output buffer")
+ }
+ out = out[:int(attr.dataSizeOut)]
+
+ total := time.Duration(attr.duration) * time.Nanosecond
+ return attr.retval, out, total, nil
+}
+
+func unmarshalProgram(buf []byte) (*Program, error) {
+ if len(buf) != 4 {
+ return nil, errors.New("program id requires 4 byte value")
+ }
+
+ // Looking up an entry in a nested map or prog array returns an id,
+ // not an fd.
+ id := internal.NativeEndian.Uint32(buf)
+ return NewProgramFromID(ProgramID(id))
+}
+
+func marshalProgram(p *Program, length int) ([]byte, error) {
+ if length != 4 {
+ return nil, fmt.Errorf("can't marshal program to %d bytes", length)
+ }
+
+ value, err := p.fd.Value()
+ if err != nil {
+ return nil, err
+ }
+
+ buf := make([]byte, 4)
+ internal.NativeEndian.PutUint32(buf, value)
+ return buf, nil
+}
+
+// Attach a Program.
+//
+// Deprecated: use link.RawAttachProgram instead.
+func (p *Program) Attach(fd int, typ AttachType, flags AttachFlags) error {
+ if fd < 0 {
+ return errors.New("invalid fd")
+ }
+
+ pfd, err := p.fd.Value()
+ if err != nil {
+ return err
+ }
+
+ attr := internal.BPFProgAttachAttr{
+ TargetFd: uint32(fd),
+ AttachBpfFd: pfd,
+ AttachType: uint32(typ),
+ AttachFlags: uint32(flags),
+ }
+
+ return internal.BPFProgAttach(&attr)
+}
+
+// Detach a Program.
+//
+// Deprecated: use link.RawDetachProgram instead.
+func (p *Program) Detach(fd int, typ AttachType, flags AttachFlags) error {
+ if fd < 0 {
+ return errors.New("invalid fd")
+ }
+
+ if flags != 0 {
+ return errors.New("flags must be zero")
+ }
+
+ pfd, err := p.fd.Value()
+ if err != nil {
+ return err
+ }
+
+ attr := internal.BPFProgDetachAttr{
+ TargetFd: uint32(fd),
+ AttachBpfFd: pfd,
+ AttachType: uint32(typ),
+ }
+
+ return internal.BPFProgDetach(&attr)
+}
+
+// LoadPinnedProgram loads a Program from a BPF file.
+//
+// Requires at least Linux 4.11.
+func LoadPinnedProgram(fileName string) (*Program, error) {
+ fd, err := internal.BPFObjGet(fileName)
+ if err != nil {
+ return nil, err
+ }
+
+ info, err := newProgramInfoFromFd(fd)
+ if err != nil {
+ _ = fd.Close()
+ return nil, fmt.Errorf("info for %s: %w", fileName, err)
+ }
+
+ return &Program{"", fd, filepath.Base(fileName), "", info.Type}, nil
+}
+
+// SanitizeName replaces all invalid characters in name with replacement.
+// Passing a negative value for replacement will delete characters instead
+// of replacing them. Use this to automatically generate valid names for maps
+// and programs at runtime.
+//
+// The set of allowed characters depends on the running kernel version.
+// Dots are only allowed as of kernel 5.2.
+func SanitizeName(name string, replacement rune) string {
+ return strings.Map(func(char rune) rune {
+ if invalidBPFObjNameChar(char) {
+ return replacement
+ }
+ return char
+ }, name)
+}
+
+// ProgramGetNextID returns the ID of the next eBPF program.
+//
+// Returns ErrNotExist, if there is no next eBPF program.
+func ProgramGetNextID(startID ProgramID) (ProgramID, error) {
+ id, err := objGetNextID(internal.BPF_PROG_GET_NEXT_ID, uint32(startID))
+ return ProgramID(id), err
+}
+
+// ID returns the systemwide unique ID of the program.
+//
+// Deprecated: use ProgramInfo.ID() instead.
+func (p *Program) ID() (ProgramID, error) {
+ info, err := bpfGetProgInfoByFD(p.fd)
+ if err != nil {
+ return ProgramID(0), err
+ }
+ return ProgramID(info.id), nil
+}
+
+func findKernelType(name string, typ btf.Type) error {
+ kernel, err := btf.LoadKernelSpec()
+ if err != nil {
+ return fmt.Errorf("can't load kernel spec: %w", err)
+ }
+
+ return kernel.FindType(name, typ)
+}
+
+func resolveBTFType(name string, progType ProgramType, attachType AttachType) (btf.Type, error) {
+ type match struct {
+ p ProgramType
+ a AttachType
+ }
+
+ target := match{progType, attachType}
+ switch target {
+ case match{LSM, AttachLSMMac}:
+ var target btf.Func
+ err := findKernelType("bpf_lsm_"+name, &target)
+ if errors.Is(err, btf.ErrNotFound) {
+ return nil, &internal.UnsupportedFeatureError{
+ Name: name + " LSM hook",
+ }
+ }
+ if err != nil {
+ return nil, fmt.Errorf("resolve BTF for LSM hook %s: %w", name, err)
+ }
+
+ return &target, nil
+
+ case match{Tracing, AttachTraceIter}:
+ var target btf.Func
+ err := findKernelType("bpf_iter_"+name, &target)
+ if errors.Is(err, btf.ErrNotFound) {
+ return nil, &internal.UnsupportedFeatureError{
+ Name: name + " iterator",
+ }
+ }
+ if err != nil {
+ return nil, fmt.Errorf("resolve BTF for iterator %s: %w", name, err)
+ }
+
+ return &target, nil
+
+ default:
+ return nil, nil
+ }
+}
diff --git a/vendor/github.com/cilium/ebpf/run-tests.sh b/vendor/github.com/cilium/ebpf/run-tests.sh
@@ -0,0 +1,91 @@
+#!/bin/bash
+# Test the current package under a different kernel.
+# Requires virtme and qemu to be installed.
+
+set -eu
+set -o pipefail
+
+if [[ "${1:-}" = "--in-vm" ]]; then
+ shift
+
+ mount -t bpf bpf /sys/fs/bpf
+ export CGO_ENABLED=0
+ export GOFLAGS=-mod=readonly
+ export GOPATH=/run/go-path
+ export GOPROXY=file:///run/go-path/pkg/mod/cache/download
+ export GOSUMDB=off
+ export GOCACHE=/run/go-cache
+
+ if [[ -d "/run/input/bpf" ]]; then
+ export KERNEL_SELFTESTS="/run/input/bpf"
+ fi
+
+ readonly output="${1}"
+ shift
+
+ echo Running tests...
+ go test -v -coverpkg=./... -coverprofile="$output/coverage.txt" -count 1 ./...
+ touch "$output/success"
+ exit 0
+fi
+
+# Pull all dependencies, so that we can run tests without the
+# vm having network access.
+go mod download
+
+# Use sudo if /dev/kvm isn't accessible by the current user.
+sudo=""
+if [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then
+ sudo="sudo"
+fi
+readonly sudo
+
+readonly kernel_version="${1:-}"
+if [[ -z "${kernel_version}" ]]; then
+ echo "Expecting kernel version as first argument"
+ exit 1
+fi
+
+readonly kernel="linux-${kernel_version}.bz"
+readonly selftests="linux-${kernel_version}-selftests-bpf.bz"
+readonly input="$(mktemp -d)"
+readonly output="$(mktemp -d)"
+readonly tmp_dir="${TMPDIR:-/tmp}"
+readonly branch="${BRANCH:-master}"
+
+fetch() {
+ echo Fetching "${1}"
+ wget -nv -N -P "${tmp_dir}" "https://github.com/cilium/ci-kernels/raw/${branch}/${1}"
+}
+
+fetch "${kernel}"
+
+if fetch "${selftests}"; then
+ mkdir "${input}/bpf"
+ tar --strip-components=4 -xjf "${tmp_dir}/${selftests}" -C "${input}/bpf"
+else
+ echo "No selftests found, disabling"
+fi
+
+echo Testing on "${kernel_version}"
+$sudo virtme-run --kimg "${tmp_dir}/${kernel}" --memory 512M --pwd \
+ --rw \
+ --rwdir=/run/input="${input}" \
+ --rwdir=/run/output="${output}" \
+ --rodir=/run/go-path="$(go env GOPATH)" \
+ --rwdir=/run/go-cache="$(go env GOCACHE)" \
+ --script-sh "PATH=\"$PATH\" $(realpath "$0") --in-vm /run/output" \
+ --qemu-opts -smp 2 # need at least two CPUs for some tests
+
+if [[ ! -e "${output}/success" ]]; then
+ echo "Test failed on ${kernel_version}"
+ exit 1
+else
+ echo "Test successful on ${kernel_version}"
+ if [[ -v COVERALLS_TOKEN ]]; then
+ goveralls -coverprofile="${output}/coverage.txt" -service=semaphore -repotoken "$COVERALLS_TOKEN"
+ fi
+fi
+
+$sudo rm -r "${input}"
+$sudo rm -r "${output}"
diff --git a/vendor/github.com/cilium/ebpf/syscalls.go b/vendor/github.com/cilium/ebpf/syscalls.go
@@ -0,0 +1,491 @@
+package ebpf
+
+import (
+ "errors"
+ "fmt"
+ "unsafe"
+
+ "github.com/cilium/ebpf/internal"
+ "github.com/cilium/ebpf/internal/btf"
+ "github.com/cilium/ebpf/internal/unix"
+)
+
+// Generic errors returned by BPF syscalls.
+var ErrNotExist = errors.New("requested object does not exist")
+
+// bpfObjName is a null-terminated string made up of
+// 'A-Za-z0-9_' characters.
+type bpfObjName [unix.BPF_OBJ_NAME_LEN]byte
+
+// newBPFObjName truncates the result if it is too long.
+func newBPFObjName(name string) bpfObjName {
+ var result bpfObjName
+ copy(result[:unix.BPF_OBJ_NAME_LEN-1], name)
+ return result
+}
+
+// invalidBPFObjNameChar returns true if char may not appear in
+// a BPF object name.
+func invalidBPFObjNameChar(char rune) bool {
+ dotAllowed := objNameAllowsDot() == nil
+
+ switch {
+ case char >= 'A' && char <= 'Z':
+ return false
+ case char >= 'a' && char <= 'z':
+ return false
+ case char >= '0' && char <= '9':
+ return false
+ case dotAllowed && char == '.':
+ return false
+ case char == '_':
+ return false
+ default:
+ return true
+ }
+}
+
+type bpfMapCreateAttr struct {
+ mapType MapType
+ keySize uint32
+ valueSize uint32
+ maxEntries uint32
+ flags uint32
+ innerMapFd uint32 // since 4.12 56f668dfe00d
+ numaNode uint32 // since 4.14 96eabe7a40aa
+ mapName bpfObjName // since 4.15 ad5b177bd73f
+ mapIfIndex uint32
+ btfFd uint32
+ btfKeyTypeID btf.TypeID
+ btfValueTypeID btf.TypeID
+}
+
+type bpfMapOpAttr struct {
+ mapFd uint32
+ padding uint32
+ key internal.Pointer
+ value internal.Pointer
+ flags uint64
+}
+
+type bpfBatchMapOpAttr struct {
+ inBatch internal.Pointer
+ outBatch internal.Pointer
+ keys internal.Pointer
+ values internal.Pointer
+ count uint32
+ mapFd uint32
+ elemFlags uint64
+ flags uint64
+}
+
+type bpfMapInfo struct {
+ map_type uint32 // since 4.12 1e2709769086
+ id uint32
+ key_size uint32
+ value_size uint32
+ max_entries uint32
+ map_flags uint32
+ name bpfObjName // since 4.15 ad5b177bd73f
+ ifindex uint32 // since 4.16 52775b33bb50
+ btf_vmlinux_value_type_id uint32 // since 5.6 85d33df357b6
+ netns_dev uint64 // since 4.16 52775b33bb50
+ netns_ino uint64
+ btf_id uint32 // since 4.18 78958fca7ead
+ btf_key_type_id uint32 // since 4.18 9b2cf328b2ec
+ btf_value_type_id uint32
+}
+
+type bpfProgLoadAttr struct {
+ progType ProgramType
+ insCount uint32
+ instructions internal.Pointer
+ license internal.Pointer
+ logLevel uint32
+ logSize uint32
+ logBuf internal.Pointer
+ kernelVersion uint32 // since 4.1 2541517c32be
+ progFlags uint32 // since 4.11 e07b98d9bffe
+ progName bpfObjName // since 4.15 067cae47771c
+ progIfIndex uint32 // since 4.15 1f6f4cb7ba21
+ expectedAttachType AttachType // since 4.17 5e43f899b03a
+ progBTFFd uint32
+ funcInfoRecSize uint32
+ funcInfo internal.Pointer
+ funcInfoCnt uint32
+ lineInfoRecSize uint32
+ lineInfo internal.Pointer
+ lineInfoCnt uint32
+ attachBTFID btf.TypeID
+ attachProgFd uint32
+}
+
+type bpfProgInfo struct {
+ prog_type uint32
+ id uint32
+ tag [unix.BPF_TAG_SIZE]byte
+ jited_prog_len uint32
+ xlated_prog_len uint32
+ jited_prog_insns internal.Pointer
+ xlated_prog_insns internal.Pointer
+ load_time uint64 // since 4.15 cb4d2b3f03d8
+ created_by_uid uint32
+ nr_map_ids uint32
+ map_ids internal.Pointer
+ name bpfObjName // since 4.15 067cae47771c
+ ifindex uint32
+ gpl_compatible uint32
+ netns_dev uint64
+ netns_ino uint64
+ nr_jited_ksyms uint32
+ nr_jited_func_lens uint32
+ jited_ksyms internal.Pointer
+ jited_func_lens internal.Pointer
+ btf_id uint32
+ func_info_rec_size uint32
+ func_info internal.Pointer
+ nr_func_info uint32
+ nr_line_info uint32
+ line_info internal.Pointer
+ jited_line_info internal.Pointer
+ nr_jited_line_info uint32
+ line_info_rec_size uint32
+ jited_line_info_rec_size uint32
+ nr_prog_tags uint32
+ prog_tags internal.Pointer
+ run_time_ns uint64
+ run_cnt uint64
+}
+
+type bpfProgTestRunAttr struct {
+ fd uint32
+ retval uint32
+ dataSizeIn uint32
+ dataSizeOut uint32
+ dataIn internal.Pointer
+ dataOut internal.Pointer
+ repeat uint32
+ duration uint32
+}
+
+type bpfGetFDByIDAttr struct {
+ id uint32
+ next uint32
+}
+
+type bpfMapFreezeAttr struct {
+ mapFd uint32
+}
+
+type bpfObjGetNextIDAttr struct {
+ startID uint32
+ nextID uint32
+ openFlags uint32
+}
+
+func bpfProgLoad(attr *bpfProgLoadAttr) (*internal.FD, error) {
+ for {
+ fd, err := internal.BPF(internal.BPF_PROG_LOAD, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ // As of ~4.20 the verifier can be interrupted by a signal,
+ // and returns EAGAIN in that case.
+ if err == unix.EAGAIN {
+ continue
+ }
+
+ if err != nil {
+ return nil, err
+ }
+
+ return internal.NewFD(uint32(fd)), nil
+ }
+}
+
+func bpfProgTestRun(attr *bpfProgTestRunAttr) error {
+ _, err := internal.BPF(internal.BPF_PROG_TEST_RUN, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ return err
+}
+
+func bpfMapCreate(attr *bpfMapCreateAttr) (*internal.FD, error) {
+ fd, err := internal.BPF(internal.BPF_MAP_CREATE, unsafe.Pointer(attr), unsafe.Sizeof(*attr))
+ if err != nil {
+ return nil, err
+ }
+
+ return internal.NewFD(uint32(fd)), nil
+}
+
+var haveNestedMaps = internal.FeatureTest("nested maps", "4.12", func() error {
+ _, err := bpfMapCreate(&bpfMapCreateAttr{
+ mapType: ArrayOfMaps,
+ keySize: 4,
+ valueSize: 4,
+ maxEntries: 1,
+ // Invalid file descriptor.
+ innerMapFd: ^uint32(0),
+ })
+ if errors.Is(err, unix.EINVAL) {
+ return internal.ErrNotSupported
+ }
+ if errors.Is(err, unix.EBADF) {
+ return nil
+ }
+ return err
+})
+
+var haveMapMutabilityModifiers = internal.FeatureTest("read- and write-only maps", "5.2", func() error {
+ // This checks BPF_F_RDONLY_PROG and BPF_F_WRONLY_PROG. Since
+ // BPF_MAP_FREEZE appeared in 5.2 as well we don't do a separate check.
+ m, err := bpfMapCreate(&bpfMapCreateAttr{
+ mapType: Array,
+ keySize: 4,
+ valueSize: 4,
+ maxEntries: 1,
+ flags: unix.BPF_F_RDONLY_PROG,
+ })
+ if err != nil {
+ return internal.ErrNotSupported
+ }
+ _ = m.Close()
+ return nil
+})
+
+func bpfMapLookupElem(m *internal.FD, key, valueOut internal.Pointer) error {
+ fd, err := m.Value()
+ if err != nil {
+ return err
+ }
+
+ attr := bpfMapOpAttr{
+ mapFd: fd,
+ key: key,
+ value: valueOut,
+ }
+ _, err = internal.BPF(internal.BPF_MAP_LOOKUP_ELEM, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ return wrapMapError(err)
+}
+
+func bpfMapLookupAndDelete(m *internal.FD, key, valueOut internal.Pointer) error {
+ fd, err := m.Value()
+ if err != nil {
+ return err
+ }
+
+ attr := bpfMapOpAttr{
+ mapFd: fd,
+ key: key,
+ value: valueOut,
+ }
+ _, err = internal.BPF(internal.BPF_MAP_LOOKUP_AND_DELETE_ELEM, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ return wrapMapError(err)
+}
+
+func bpfMapUpdateElem(m *internal.FD, key, valueOut internal.Pointer, flags uint64) error {
+ fd, err := m.Value()
+ if err != nil {
+ return err
+ }
+
+ attr := bpfMapOpAttr{
+ mapFd: fd,
+ key: key,
+ value: valueOut,
+ flags: flags,
+ }
+ _, err = internal.BPF(internal.BPF_MAP_UPDATE_ELEM, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ return wrapMapError(err)
+}
+
+func bpfMapDeleteElem(m *internal.FD, key internal.Pointer) error {
+ fd, err := m.Value()
+ if err != nil {
+ return err
+ }
+
+ attr := bpfMapOpAttr{
+ mapFd: fd,
+ key: key,
+ }
+ _, err = internal.BPF(internal.BPF_MAP_DELETE_ELEM, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ return wrapMapError(err)
+}
+
+func bpfMapGetNextKey(m *internal.FD, key, nextKeyOut internal.Pointer) error {
+ fd, err := m.Value()
+ if err != nil {
+ return err
+ }
+
+ attr := bpfMapOpAttr{
+ mapFd: fd,
+ key: key,
+ value: nextKeyOut,
+ }
+ _, err = internal.BPF(internal.BPF_MAP_GET_NEXT_KEY, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ return wrapMapError(err)
+}
+
+func objGetNextID(cmd internal.BPFCmd, start uint32) (uint32, error) {
+ attr := bpfObjGetNextIDAttr{
+ startID: start,
+ }
+ _, err := internal.BPF(cmd, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ return attr.nextID, wrapObjError(err)
+}
+
+func bpfMapBatch(cmd internal.BPFCmd, m *internal.FD, inBatch, outBatch, keys, values internal.Pointer, count uint32, opts *BatchOptions) (uint32, error) {
+ fd, err := m.Value()
+ if err != nil {
+ return 0, err
+ }
+
+ attr := bpfBatchMapOpAttr{
+ inBatch: inBatch,
+ outBatch: outBatch,
+ keys: keys,
+ values: values,
+ count: count,
+ mapFd: fd,
+ }
+ if opts != nil {
+ attr.elemFlags = opts.ElemFlags
+ attr.flags = opts.Flags
+ }
+ _, err = internal.BPF(cmd, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ // always return count even on an error, as things like update might partially be fulfilled.
+ return attr.count, wrapMapError(err)
+}
+
+func wrapObjError(err error) error {
+ if err == nil {
+ return nil
+ }
+ if errors.Is(err, unix.ENOENT) {
+ return fmt.Errorf("%w", ErrNotExist)
+ }
+
+ return errors.New(err.Error())
+}
+
+func wrapMapError(err error) error {
+ if err == nil {
+ return nil
+ }
+
+ if errors.Is(err, unix.ENOENT) {
+ return ErrKeyNotExist
+ }
+
+ if errors.Is(err, unix.EEXIST) {
+ return ErrKeyExist
+ }
+
+ if errors.Is(err, unix.ENOTSUPP) {
+ return ErrNotSupported
+ }
+
+ return errors.New(err.Error())
+}
+
+func bpfMapFreeze(m *internal.FD) error {
+ fd, err := m.Value()
+ if err != nil {
+ return err
+ }
+
+ attr := bpfMapFreezeAttr{
+ mapFd: fd,
+ }
+ _, err = internal.BPF(internal.BPF_MAP_FREEZE, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ return err
+}
+
+func bpfGetProgInfoByFD(fd *internal.FD) (*bpfProgInfo, error) {
+ var info bpfProgInfo
+ if err := internal.BPFObjGetInfoByFD(fd, unsafe.Pointer(&info), unsafe.Sizeof(info)); err != nil {
+ return nil, fmt.Errorf("can't get program info: %w", err)
+ }
+ return &info, nil
+}
+
+func bpfGetMapInfoByFD(fd *internal.FD) (*bpfMapInfo, error) {
+ var info bpfMapInfo
+ err := internal.BPFObjGetInfoByFD(fd, unsafe.Pointer(&info), unsafe.Sizeof(info))
+ if err != nil {
+ return nil, fmt.Errorf("can't get map info: %w", err)
+ }
+ return &info, nil
+}
+
+var haveObjName = internal.FeatureTest("object names", "4.15", func() error {
+ attr := bpfMapCreateAttr{
+ mapType: Array,
+ keySize: 4,
+ valueSize: 4,
+ maxEntries: 1,
+ mapName: newBPFObjName("feature_test"),
+ }
+
+ fd, err := bpfMapCreate(&attr)
+ if err != nil {
+ return internal.ErrNotSupported
+ }
+
+ _ = fd.Close()
+ return nil
+})
+
+var objNameAllowsDot = internal.FeatureTest("dot in object names", "5.2", func() error {
+ if err := haveObjName(); err != nil {
+ return err
+ }
+
+ attr := bpfMapCreateAttr{
+ mapType: Array,
+ keySize: 4,
+ valueSize: 4,
+ maxEntries: 1,
+ mapName: newBPFObjName(".test"),
+ }
+
+ fd, err := bpfMapCreate(&attr)
+ if err != nil {
+ return internal.ErrNotSupported
+ }
+
+ _ = fd.Close()
+ return nil
+})
+
+var haveBatchAPI = internal.FeatureTest("map batch api", "5.6", func() error {
+ var maxEntries uint32 = 2
+ attr := bpfMapCreateAttr{
+ mapType: Hash,
+ keySize: 4,
+ valueSize: 4,
+ maxEntries: maxEntries,
+ }
+
+ fd, err := bpfMapCreate(&attr)
+ if err != nil {
+ return internal.ErrNotSupported
+ }
+ defer fd.Close()
+ keys := []uint32{1, 2}
+ values := []uint32{3, 4}
+ kp, _ := marshalPtr(keys, 8)
+ vp, _ := marshalPtr(values, 8)
+ nilPtr := internal.NewPointer(nil)
+ _, err = bpfMapBatch(internal.BPF_MAP_UPDATE_BATCH, fd, nilPtr, nilPtr, kp, vp, maxEntries, nil)
+ if err != nil {
+ return internal.ErrNotSupported
+ }
+ return nil
+})
+
+func bpfObjGetFDByID(cmd internal.BPFCmd, id uint32) (*internal.FD, error) {
+ attr := bpfGetFDByIDAttr{
+ id: id,
+ }
+ ptr, err := internal.BPF(cmd, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
+ return internal.NewFD(uint32(ptr)), wrapObjError(err)
+}
diff --git a/vendor/github.com/cilium/ebpf/types.go b/vendor/github.com/cilium/ebpf/types.go
@@ -0,0 +1,213 @@
+package ebpf
+
+//go:generate stringer -output types_string.go -type=MapType,ProgramType,AttachType,PinType
+
+// MapType indicates the type map structure
+// that will be initialized in the kernel.
+type MapType uint32
+
+// All the various map types that can be created
+const (
+ UnspecifiedMap MapType = iota
+ // Hash is a hash map
+ Hash
+ // Array is an array map
+ Array
+ // ProgramArray - A program array map is a special kind of array map whose map
+ // values contain only file descriptors referring to other eBPF
+ // programs. Thus, both the key_size and value_size must be
+ // exactly four bytes. This map is used in conjunction with the
+ // TailCall helper.
+ ProgramArray
+ // PerfEventArray - A perf event array is used in conjunction with PerfEventRead
+ // and PerfEventOutput calls, to read the raw bpf_perf_data from the registers.
+ PerfEventArray
+ // PerCPUHash - This data structure is useful for people who have high performance
+ // network needs and can reconcile adds at the end of some cycle, so that
+ // hashes can be lock free without the use of XAdd, which can be costly.
+ PerCPUHash
+ // PerCPUArray - This data structure is useful for people who have high performance
+ // network needs and can reconcile adds at the end of some cycle, so that
+ // hashes can be lock free without the use of XAdd, which can be costly.
+ // Each CPU gets a copy of this hash, the contents of all of which can be reconciled
+ // later.
+ PerCPUArray
+ // StackTrace - This holds whole user and kernel stack traces, it can be retrieved with
+ // GetStackID
+ StackTrace
+ // CGroupArray - This is a very niche structure used to help SKBInCGroup determine
+ // if an skb is from a socket belonging to a specific cgroup
+ CGroupArray
+ // LRUHash - This allows you to create a small hash structure that will purge the
+ // least recently used items rather than thow an error when you run out of memory
+ LRUHash
+ // LRUCPUHash - This is NOT like PerCPUHash, this structure is shared among the CPUs,
+ // it has more to do with including the CPU id with the LRU calculation so that if a
+ // particular CPU is using a value over-and-over again, then it will be saved, but if
+ // a value is being retrieved a lot but sparsely across CPUs it is not as important, basically
+ // giving weight to CPU locality over overall usage.
+ LRUCPUHash
+ // LPMTrie - This is an implementation of Longest-Prefix-Match Trie structure. It is useful,
+ // for storing things like IP addresses which can be bit masked allowing for keys of differing
+ // values to refer to the same reference based on their masks. See wikipedia for more details.
+ LPMTrie
+ // ArrayOfMaps - Each item in the array is another map. The inner map mustn't be a map of maps
+ // itself.
+ ArrayOfMaps
+ // HashOfMaps - Each item in the hash map is another map. The inner map mustn't be a map of maps
+ // itself.
+ HashOfMaps
+ // DevMap - Specialized map to store references to network devices.
+ DevMap
+ // SockMap - Specialized map to store references to sockets.
+ SockMap
+ // CPUMap - Specialized map to store references to CPUs.
+ CPUMap
+ // XSKMap - Specialized map for XDP programs to store references to open sockets.
+ XSKMap
+ // SockHash - Specialized hash to store references to sockets.
+ SockHash
+ // CGroupStorage - Special map for CGroups.
+ CGroupStorage
+ // ReusePortSockArray - Specialized map to store references to sockets that can be reused.
+ ReusePortSockArray
+ // PerCPUCGroupStorage - Special per CPU map for CGroups.
+ PerCPUCGroupStorage
+ // Queue - FIFO storage for BPF programs.
+ Queue
+ // Stack - LIFO storage for BPF programs.
+ Stack
+ // SkStorage - Specialized map for local storage at SK for BPF programs.
+ SkStorage
+ // DevMapHash - Hash-based indexing scheme for references to network devices.
+ DevMapHash
+)
+
+// hasPerCPUValue returns true if the Map stores a value per CPU.
+func (mt MapType) hasPerCPUValue() bool {
+ return mt == PerCPUHash || mt == PerCPUArray || mt == LRUCPUHash
+}
+
+// canStoreMap returns true if the map type accepts a map fd
+// for update and returns a map id for lookup.
+func (mt MapType) canStoreMap() bool {
+ return mt == ArrayOfMaps || mt == HashOfMaps
+}
+
+// canStoreProgram returns true if the map type accepts a program fd
+// for update and returns a program id for lookup.
+func (mt MapType) canStoreProgram() bool {
+ return mt == ProgramArray
+}
+
+// ProgramType of the eBPF program
+type ProgramType uint32
+
+// eBPF program types
+const (
+ UnspecifiedProgram ProgramType = iota
+ SocketFilter
+ Kprobe
+ SchedCLS
+ SchedACT
+ TracePoint
+ XDP
+ PerfEvent
+ CGroupSKB
+ CGroupSock
+ LWTIn
+ LWTOut
+ LWTXmit
+ SockOps
+ SkSKB
+ CGroupDevice
+ SkMsg
+ RawTracepoint
+ CGroupSockAddr
+ LWTSeg6Local
+ LircMode2
+ SkReuseport
+ FlowDissector
+ CGroupSysctl
+ RawTracepointWritable
+ CGroupSockopt
+ Tracing
+ StructOps
+ Extension
+ LSM
+ SkLookup
+)
+
+// AttachType of the eBPF program, needed to differentiate allowed context accesses in
+// some newer program types like CGroupSockAddr. Should be set to AttachNone if not required.
+// Will cause invalid argument (EINVAL) at program load time if set incorrectly.
+type AttachType uint32
+
+// AttachNone is an alias for AttachCGroupInetIngress for readability reasons.
+const AttachNone AttachType = 0
+
+const (
+ AttachCGroupInetIngress AttachType = iota
+ AttachCGroupInetEgress
+ AttachCGroupInetSockCreate
+ AttachCGroupSockOps
+ AttachSkSKBStreamParser
+ AttachSkSKBStreamVerdict
+ AttachCGroupDevice
+ AttachSkMsgVerdict
+ AttachCGroupInet4Bind
+ AttachCGroupInet6Bind
+ AttachCGroupInet4Connect
+ AttachCGroupInet6Connect
+ AttachCGroupInet4PostBind
+ AttachCGroupInet6PostBind
+ AttachCGroupUDP4Sendmsg
+ AttachCGroupUDP6Sendmsg
+ AttachLircMode2
+ AttachFlowDissector
+ AttachCGroupSysctl
+ AttachCGroupUDP4Recvmsg
+ AttachCGroupUDP6Recvmsg
+ AttachCGroupGetsockopt
+ AttachCGroupSetsockopt
+ AttachTraceRawTp
+ AttachTraceFEntry
+ AttachTraceFExit
+ AttachModifyReturn
+ AttachLSMMac
+ AttachTraceIter
+ AttachCgroupInet4GetPeername
+ AttachCgroupInet6GetPeername
+ AttachCgroupInet4GetSockname
+ AttachCgroupInet6GetSockname
+ AttachXDPDevMap
+ AttachCgroupInetSockRelease
+ AttachXDPCPUMap
+ AttachSkLookup
+ AttachXDP
+)
+
+// AttachFlags of the eBPF program used in BPF_PROG_ATTACH command
+type AttachFlags uint32
+
+// PinType determines whether a map is pinned into a BPFFS.
+type PinType int
+
+// Valid pin types.
+//
+// Mirrors enum libbpf_pin_type.
+const (
+ PinNone PinType = iota
+ // Pin an object by using its name as the filename.
+ PinByName
+)
+
+// BatchOptions batch map operations options
+//
+// Mirrors libbpf struct bpf_map_batch_opts
+// Currently BPF_F_FLAG is the only supported
+// flag (for ElemFlags).
+type BatchOptions struct {
+ ElemFlags uint64
+ Flags uint64
+}
diff --git a/vendor/github.com/cilium/ebpf/types_string.go b/vendor/github.com/cilium/ebpf/types_string.go
@@ -0,0 +1,168 @@
+// Code generated by "stringer -output types_string.go -type=MapType,ProgramType,AttachType,PinType"; DO NOT EDIT.
+
+package ebpf
+
+import "strconv"
+
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[UnspecifiedMap-0]
+ _ = x[Hash-1]
+ _ = x[Array-2]
+ _ = x[ProgramArray-3]
+ _ = x[PerfEventArray-4]
+ _ = x[PerCPUHash-5]
+ _ = x[PerCPUArray-6]
+ _ = x[StackTrace-7]
+ _ = x[CGroupArray-8]
+ _ = x[LRUHash-9]
+ _ = x[LRUCPUHash-10]
+ _ = x[LPMTrie-11]
+ _ = x[ArrayOfMaps-12]
+ _ = x[HashOfMaps-13]
+ _ = x[DevMap-14]
+ _ = x[SockMap-15]
+ _ = x[CPUMap-16]
+ _ = x[XSKMap-17]
+ _ = x[SockHash-18]
+ _ = x[CGroupStorage-19]
+ _ = x[ReusePortSockArray-20]
+ _ = x[PerCPUCGroupStorage-21]
+ _ = x[Queue-22]
+ _ = x[Stack-23]
+ _ = x[SkStorage-24]
+ _ = x[DevMapHash-25]
+}
+
+const _MapType_name = "UnspecifiedMapHashArrayProgramArrayPerfEventArrayPerCPUHashPerCPUArrayStackTraceCGroupArrayLRUHashLRUCPUHashLPMTrieArrayOfMapsHashOfMapsDevMapSockMapCPUMapXSKMapSockHashCGroupStorageReusePortSockArrayPerCPUCGroupStorageQueueStackSkStorageDevMapHash"
+
+var _MapType_index = [...]uint8{0, 14, 18, 23, 35, 49, 59, 70, 80, 91, 98, 108, 115, 126, 136, 142, 149, 155, 161, 169, 182, 200, 219, 224, 229, 238, 248}
+
+func (i MapType) String() string {
+ if i >= MapType(len(_MapType_index)-1) {
+ return "MapType(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _MapType_name[_MapType_index[i]:_MapType_index[i+1]]
+}
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[UnspecifiedProgram-0]
+ _ = x[SocketFilter-1]
+ _ = x[Kprobe-2]
+ _ = x[SchedCLS-3]
+ _ = x[SchedACT-4]
+ _ = x[TracePoint-5]
+ _ = x[XDP-6]
+ _ = x[PerfEvent-7]
+ _ = x[CGroupSKB-8]
+ _ = x[CGroupSock-9]
+ _ = x[LWTIn-10]
+ _ = x[LWTOut-11]
+ _ = x[LWTXmit-12]
+ _ = x[SockOps-13]
+ _ = x[SkSKB-14]
+ _ = x[CGroupDevice-15]
+ _ = x[SkMsg-16]
+ _ = x[RawTracepoint-17]
+ _ = x[CGroupSockAddr-18]
+ _ = x[LWTSeg6Local-19]
+ _ = x[LircMode2-20]
+ _ = x[SkReuseport-21]
+ _ = x[FlowDissector-22]
+ _ = x[CGroupSysctl-23]
+ _ = x[RawTracepointWritable-24]
+ _ = x[CGroupSockopt-25]
+ _ = x[Tracing-26]
+ _ = x[StructOps-27]
+ _ = x[Extension-28]
+ _ = x[LSM-29]
+ _ = x[SkLookup-30]
+}
+
+const _ProgramType_name = "UnspecifiedProgramSocketFilterKprobeSchedCLSSchedACTTracePointXDPPerfEventCGroupSKBCGroupSockLWTInLWTOutLWTXmitSockOpsSkSKBCGroupDeviceSkMsgRawTracepointCGroupSockAddrLWTSeg6LocalLircMode2SkReuseportFlowDissectorCGroupSysctlRawTracepointWritableCGroupSockoptTracingStructOpsExtensionLSMSkLookup"
+
+var _ProgramType_index = [...]uint16{0, 18, 30, 36, 44, 52, 62, 65, 74, 83, 93, 98, 104, 111, 118, 123, 135, 140, 153, 167, 179, 188, 199, 212, 224, 245, 258, 265, 274, 283, 286, 294}
+
+func (i ProgramType) String() string {
+ if i >= ProgramType(len(_ProgramType_index)-1) {
+ return "ProgramType(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _ProgramType_name[_ProgramType_index[i]:_ProgramType_index[i+1]]
+}
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[AttachNone-0]
+ _ = x[AttachCGroupInetIngress-0]
+ _ = x[AttachCGroupInetEgress-1]
+ _ = x[AttachCGroupInetSockCreate-2]
+ _ = x[AttachCGroupSockOps-3]
+ _ = x[AttachSkSKBStreamParser-4]
+ _ = x[AttachSkSKBStreamVerdict-5]
+ _ = x[AttachCGroupDevice-6]
+ _ = x[AttachSkMsgVerdict-7]
+ _ = x[AttachCGroupInet4Bind-8]
+ _ = x[AttachCGroupInet6Bind-9]
+ _ = x[AttachCGroupInet4Connect-10]
+ _ = x[AttachCGroupInet6Connect-11]
+ _ = x[AttachCGroupInet4PostBind-12]
+ _ = x[AttachCGroupInet6PostBind-13]
+ _ = x[AttachCGroupUDP4Sendmsg-14]
+ _ = x[AttachCGroupUDP6Sendmsg-15]
+ _ = x[AttachLircMode2-16]
+ _ = x[AttachFlowDissector-17]
+ _ = x[AttachCGroupSysctl-18]
+ _ = x[AttachCGroupUDP4Recvmsg-19]
+ _ = x[AttachCGroupUDP6Recvmsg-20]
+ _ = x[AttachCGroupGetsockopt-21]
+ _ = x[AttachCGroupSetsockopt-22]
+ _ = x[AttachTraceRawTp-23]
+ _ = x[AttachTraceFEntry-24]
+ _ = x[AttachTraceFExit-25]
+ _ = x[AttachModifyReturn-26]
+ _ = x[AttachLSMMac-27]
+ _ = x[AttachTraceIter-28]
+ _ = x[AttachCgroupInet4GetPeername-29]
+ _ = x[AttachCgroupInet6GetPeername-30]
+ _ = x[AttachCgroupInet4GetSockname-31]
+ _ = x[AttachCgroupInet6GetSockname-32]
+ _ = x[AttachXDPDevMap-33]
+ _ = x[AttachCgroupInetSockRelease-34]
+ _ = x[AttachXDPCPUMap-35]
+ _ = x[AttachSkLookup-36]
+ _ = x[AttachXDP-37]
+}
+
+const _AttachType_name = "AttachNoneAttachCGroupInetEgressAttachCGroupInetSockCreateAttachCGroupSockOpsAttachSkSKBStreamParserAttachSkSKBStreamVerdictAttachCGroupDeviceAttachSkMsgVerdictAttachCGroupInet4BindAttachCGroupInet6BindAttachCGroupInet4ConnectAttachCGroupInet6ConnectAttachCGroupInet4PostBindAttachCGroupInet6PostBindAttachCGroupUDP4SendmsgAttachCGroupUDP6SendmsgAttachLircMode2AttachFlowDissectorAttachCGroupSysctlAttachCGroupUDP4RecvmsgAttachCGroupUDP6RecvmsgAttachCGroupGetsockoptAttachCGroupSetsockoptAttachTraceRawTpAttachTraceFEntryAttachTraceFExitAttachModifyReturnAttachLSMMacAttachTraceIterAttachCgroupInet4GetPeernameAttachCgroupInet6GetPeernameAttachCgroupInet4GetSocknameAttachCgroupInet6GetSocknameAttachXDPDevMapAttachCgroupInetSockReleaseAttachXDPCPUMapAttachSkLookupAttachXDP"
+
+var _AttachType_index = [...]uint16{0, 10, 32, 58, 77, 100, 124, 142, 160, 181, 202, 226, 250, 275, 300, 323, 346, 361, 380, 398, 421, 444, 466, 488, 504, 521, 537, 555, 567, 582, 610, 638, 666, 694, 709, 736, 751, 765, 774}
+
+func (i AttachType) String() string {
+ if i >= AttachType(len(_AttachType_index)-1) {
+ return "AttachType(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _AttachType_name[_AttachType_index[i]:_AttachType_index[i+1]]
+}
+func _() {
+ // An "invalid array index" compiler error signifies that the constant values have changed.
+ // Re-run the stringer command to generate them again.
+ var x [1]struct{}
+ _ = x[PinNone-0]
+ _ = x[PinByName-1]
+}
+
+const _PinType_name = "PinNonePinByName"
+
+var _PinType_index = [...]uint8{0, 7, 16}
+
+func (i PinType) String() string {
+ if i < 0 || i >= PinType(len(_PinType_index)-1) {
+ return "PinType(" + strconv.FormatInt(int64(i), 10) + ")"
+ }
+ return _PinType_name[_PinType_index[i]:_PinType_index[i+1]]
+}
diff --git a/vendor/github.com/containerd/cgroups/.gitignore b/vendor/github.com/containerd/cgroups/.gitignore
@@ -0,0 +1,2 @@
+example/example
+cmd/cgctl/cgctl
diff --git a/vendor/github.com/containerd/cgroups/LICENSE b/vendor/github.com/containerd/cgroups/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/containerd/cgroups/Makefile b/vendor/github.com/containerd/cgroups/Makefile
@@ -0,0 +1,24 @@
+# Copyright The containerd 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.
+
+PACKAGES=$(shell go list ./... | grep -v /vendor/)
+
+all: cgutil
+ go build -v
+
+cgutil:
+ cd cmd/cgctl && go build -v
+
+proto:
+ protobuild --quiet ${PACKAGES}
diff --git a/vendor/github.com/containerd/cgroups/Protobuild.toml b/vendor/github.com/containerd/cgroups/Protobuild.toml
@@ -0,0 +1,46 @@
+version = "unstable"
+generator = "gogoctrd"
+plugins = ["grpc"]
+
+# Control protoc include paths. Below are usually some good defaults, but feel
+# free to try it without them if it works for your project.
+[includes]
+ # Include paths that will be added before all others. Typically, you want to
+ # treat the root of the project as an include, but this may not be necessary.
+ # before = ["."]
+
+ # Paths that should be treated as include roots in relation to the vendor
+ # directory. These will be calculated with the vendor directory nearest the
+ # target package.
+ # vendored = ["github.com/gogo/protobuf"]
+ packages = ["github.com/gogo/protobuf"]
+
+ # Paths that will be added untouched to the end of the includes. We use
+ # `/usr/local/include` to pickup the common install location of protobuf.
+ # This is the default.
+ after = ["/usr/local/include", "/usr/include"]
+
+# This section maps protobuf imports to Go packages. These will become
+# `-M` directives in the call to the go protobuf generator.
+[packages]
+ "gogoproto/gogo.proto" = "github.com/gogo/protobuf/gogoproto"
+ "google/protobuf/any.proto" = "github.com/gogo/protobuf/types"
+ "google/protobuf/descriptor.proto" = "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
+ "google/protobuf/field_mask.proto" = "github.com/gogo/protobuf/types"
+ "google/protobuf/timestamp.proto" = "github.com/gogo/protobuf/types"
+
+# Aggregrate the API descriptors to lock down API changes.
+[[descriptors]]
+prefix = "github.com/containerd/cgroups/stats/v1"
+target = "stats/v1/metrics.pb.txt"
+ignore_files = [
+ "google/protobuf/descriptor.proto",
+ "gogoproto/gogo.proto"
+]
+[[descriptors]]
+prefix = "github.com/containerd/cgroups/v2/stats"
+target = "v2/stats/metrics.pb.txt"
+ignore_files = [
+ "google/protobuf/descriptor.proto",
+ "gogoproto/gogo.proto"
+]
diff --git a/vendor/github.com/containerd/cgroups/README.md b/vendor/github.com/containerd/cgroups/README.md
@@ -0,0 +1,149 @@
+# cgroups
+
+[![Build Status](https://github.com/containerd/cgroups/workflows/CI/badge.svg)](https://github.com/containerd/cgroups/actions?query=workflow%3ACI)
+[![codecov](https://codecov.io/gh/containerd/cgroups/branch/main/graph/badge.svg)](https://codecov.io/gh/containerd/cgroups)
+[![GoDoc](https://godoc.org/github.com/containerd/cgroups?status.svg)](https://godoc.org/github.com/containerd/cgroups)
+[![Go Report Card](https://goreportcard.com/badge/github.com/containerd/cgroups)](https://goreportcard.com/report/github.com/containerd/cgroups)
+
+Go package for creating, managing, inspecting, and destroying cgroups.
+The resources format for settings on the cgroup uses the OCI runtime-spec found
+[here](https://github.com/opencontainers/runtime-spec).
+
+## Examples
+
+### Create a new cgroup
+
+This creates a new cgroup using a static path for all subsystems under `/test`.
+
+* /sys/fs/cgroup/cpu/test
+* /sys/fs/cgroup/memory/test
+* etc....
+
+It uses a single hierarchy and specifies cpu shares as a resource constraint and
+uses the v1 implementation of cgroups.
+
+
+```go
+shares := uint64(100)
+control, err := cgroups.New(cgroups.V1, cgroups.StaticPath("/test"), &specs.LinuxResources{
+ CPU: &specs.LinuxCPU{
+ Shares: &shares,
+ },
+})
+defer control.Delete()
+```
+
+### Create with systemd slice support
+
+
+```go
+control, err := cgroups.New(cgroups.Systemd, cgroups.Slice("system.slice", "runc-test"), &specs.LinuxResources{
+ CPU: &specs.CPU{
+ Shares: &shares,
+ },
+})
+
+```
+
+### Load an existing cgroup
+
+```go
+control, err = cgroups.Load(cgroups.V1, cgroups.StaticPath("/test"))
+```
+
+### Add a process to the cgroup
+
+```go
+if err := control.Add(cgroups.Process{Pid:1234}); err != nil {
+}
+```
+
+### Update the cgroup
+
+To update the resources applied in the cgroup
+
+```go
+shares = uint64(200)
+if err := control.Update(&specs.LinuxResources{
+ CPU: &specs.LinuxCPU{
+ Shares: &shares,
+ },
+}); err != nil {
+}
+```
+
+### Freeze and Thaw the cgroup
+
+```go
+if err := control.Freeze(); err != nil {
+}
+if err := control.Thaw(); err != nil {
+}
+```
+
+### List all processes in the cgroup or recursively
+
+```go
+processes, err := control.Processes(cgroups.Devices, recursive)
+```
+
+### Get Stats on the cgroup
+
+```go
+stats, err := control.Stat()
+```
+
+By adding `cgroups.IgnoreNotExist` all non-existent files will be ignored, e.g. swap memory stats without swap enabled
+```go
+stats, err := control.Stat(cgroups.IgnoreNotExist)
+```
+
+### Move process across cgroups
+
+This allows you to take processes from one cgroup and move them to another.
+
+```go
+err := control.MoveTo(destination)
+```
+
+### Create subcgroup
+
+```go
+subCgroup, err := control.New("child", resources)
+```
+
+### Registering for memory events
+
+This allows you to get notified by an eventfd for v1 memory cgroups events.
+
+```go
+event := cgroups.MemoryThresholdEvent(50 * 1024 * 1024, false)
+efd, err := control.RegisterMemoryEvent(event)
+```
+
+```go
+event := cgroups.MemoryPressureEvent(cgroups.MediumPressure, cgroups.DefaultMode)
+efd, err := control.RegisterMemoryEvent(event)
+```
+
+```go
+efd, err := control.OOMEventFD()
+// or by using RegisterMemoryEvent
+event := cgroups.OOMEvent()
+efd, err := control.RegisterMemoryEvent(event)
+```
+
+### Attention
+
+All static path should not include `/sys/fs/cgroup/` prefix, it should start with your own cgroups name
+
+## Project details
+
+Cgroups is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE).
+As a containerd sub-project, you will find the:
+
+ * [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md),
+ * [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS),
+ * and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md)
+
+information in our [`containerd/project`](https://github.com/containerd/project) repository.
diff --git a/vendor/github.com/containerd/cgroups/Vagrantfile b/vendor/github.com/containerd/cgroups/Vagrantfile
@@ -0,0 +1,46 @@
+# -*- mode: ruby -*-
+# vi: set ft=ruby :
+
+Vagrant.configure("2") do |config|
+# Fedora box is used for testing cgroup v2 support
+ config.vm.box = "fedora/35-cloud-base"
+ config.vm.provider :virtualbox do |v|
+ v.memory = 4096
+ v.cpus = 2
+ end
+ config.vm.provider :libvirt do |v|
+ v.memory = 4096
+ v.cpus = 2
+ end
+ config.vm.provision "shell", inline: <<-SHELL
+ set -eux -o pipefail
+ # configuration
+ GO_VERSION="1.17.7"
+
+ # install gcc and Golang
+ dnf -y install gcc
+ curl -fsSL "https://dl.google.com/go/go${GO_VERSION}.linux-amd64.tar.gz" | tar Cxz /usr/local
+
+ # setup env vars
+ cat >> /etc/profile.d/sh.local <<EOF
+PATH=/usr/local/go/bin:$PATH
+GO111MODULE=on
+export PATH GO111MODULE
+EOF
+ source /etc/profile.d/sh.local
+
+ # enter /root/go/src/github.com/containerd/cgroups
+ mkdir -p /root/go/src/github.com/containerd
+ ln -s /vagrant /root/go/src/github.com/containerd/cgroups
+ cd /root/go/src/github.com/containerd/cgroups
+
+ # create /test.sh
+ cat > /test.sh <<EOF
+#!/bin/bash
+set -eux -o pipefail
+cd /root/go/src/github.com/containerd/cgroups
+go test -v ./...
+EOF
+ chmod +x /test.sh
+ SHELL
+end
diff --git a/vendor/github.com/containerd/cgroups/blkio.go b/vendor/github.com/containerd/cgroups/blkio.go
@@ -0,0 +1,361 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ v1 "github.com/containerd/cgroups/stats/v1"
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+// NewBlkio returns a Blkio controller given the root folder of cgroups.
+// It may optionally accept other configuration options, such as ProcRoot(path)
+func NewBlkio(root string, options ...func(controller *blkioController)) *blkioController {
+ ctrl := &blkioController{
+ root: filepath.Join(root, string(Blkio)),
+ procRoot: "/proc",
+ }
+ for _, opt := range options {
+ opt(ctrl)
+ }
+ return ctrl
+}
+
+// ProcRoot overrides the default location of the "/proc" filesystem
+func ProcRoot(path string) func(controller *blkioController) {
+ return func(c *blkioController) {
+ c.procRoot = path
+ }
+}
+
+type blkioController struct {
+ root string
+ procRoot string
+}
+
+func (b *blkioController) Name() Name {
+ return Blkio
+}
+
+func (b *blkioController) Path(path string) string {
+ return filepath.Join(b.root, path)
+}
+
+func (b *blkioController) Create(path string, resources *specs.LinuxResources) error {
+ if err := os.MkdirAll(b.Path(path), defaultDirPerm); err != nil {
+ return err
+ }
+ if resources.BlockIO == nil {
+ return nil
+ }
+ for _, t := range createBlkioSettings(resources.BlockIO) {
+ if t.value != nil {
+ if err := retryingWriteFile(
+ filepath.Join(b.Path(path), "blkio."+t.name),
+ t.format(t.value),
+ defaultFilePerm,
+ ); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func (b *blkioController) Update(path string, resources *specs.LinuxResources) error {
+ return b.Create(path, resources)
+}
+
+func (b *blkioController) Stat(path string, stats *v1.Metrics) error {
+ stats.Blkio = &v1.BlkIOStat{}
+
+ var settings []blkioStatSettings
+
+ // Try to read CFQ stats available on all CFQ enabled kernels first
+ if _, err := os.Lstat(filepath.Join(b.Path(path), "blkio.io_serviced_recursive")); err == nil {
+ settings = []blkioStatSettings{
+ {
+ name: "sectors_recursive",
+ entry: &stats.Blkio.SectorsRecursive,
+ },
+ {
+ name: "io_service_bytes_recursive",
+ entry: &stats.Blkio.IoServiceBytesRecursive,
+ },
+ {
+ name: "io_serviced_recursive",
+ entry: &stats.Blkio.IoServicedRecursive,
+ },
+ {
+ name: "io_queued_recursive",
+ entry: &stats.Blkio.IoQueuedRecursive,
+ },
+ {
+ name: "io_service_time_recursive",
+ entry: &stats.Blkio.IoServiceTimeRecursive,
+ },
+ {
+ name: "io_wait_time_recursive",
+ entry: &stats.Blkio.IoWaitTimeRecursive,
+ },
+ {
+ name: "io_merged_recursive",
+ entry: &stats.Blkio.IoMergedRecursive,
+ },
+ {
+ name: "time_recursive",
+ entry: &stats.Blkio.IoTimeRecursive,
+ },
+ }
+ }
+
+ f, err := os.Open(filepath.Join(b.procRoot, "partitions"))
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+
+ devices, err := getDevices(f)
+ if err != nil {
+ return err
+ }
+
+ var size int
+ for _, t := range settings {
+ if err := b.readEntry(devices, path, t.name, t.entry); err != nil {
+ return err
+ }
+ size += len(*t.entry)
+ }
+ if size > 0 {
+ return nil
+ }
+
+ // Even the kernel is compiled with the CFQ scheduler, the cgroup may not use
+ // block devices with the CFQ scheduler. If so, we should fallback to throttle.* files.
+ settings = []blkioStatSettings{
+ {
+ name: "throttle.io_serviced",
+ entry: &stats.Blkio.IoServicedRecursive,
+ },
+ {
+ name: "throttle.io_service_bytes",
+ entry: &stats.Blkio.IoServiceBytesRecursive,
+ },
+ }
+ for _, t := range settings {
+ if err := b.readEntry(devices, path, t.name, t.entry); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (b *blkioController) readEntry(devices map[deviceKey]string, path, name string, entry *[]*v1.BlkIOEntry) error {
+ f, err := os.Open(filepath.Join(b.Path(path), "blkio."+name))
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ sc := bufio.NewScanner(f)
+ for sc.Scan() {
+ // format: dev type amount
+ fields := strings.FieldsFunc(sc.Text(), splitBlkIOStatLine)
+ if len(fields) < 3 {
+ if len(fields) == 2 && fields[0] == "Total" {
+ // skip total line
+ continue
+ } else {
+ return fmt.Errorf("invalid line found while parsing %s: %s", path, sc.Text())
+ }
+ }
+ major, err := strconv.ParseUint(fields[0], 10, 64)
+ if err != nil {
+ return err
+ }
+ minor, err := strconv.ParseUint(fields[1], 10, 64)
+ if err != nil {
+ return err
+ }
+ op := ""
+ valueField := 2
+ if len(fields) == 4 {
+ op = fields[2]
+ valueField = 3
+ }
+ v, err := strconv.ParseUint(fields[valueField], 10, 64)
+ if err != nil {
+ return err
+ }
+ *entry = append(*entry, &v1.BlkIOEntry{
+ Device: devices[deviceKey{major, minor}],
+ Major: major,
+ Minor: minor,
+ Op: op,
+ Value: v,
+ })
+ }
+ return sc.Err()
+}
+
+func createBlkioSettings(blkio *specs.LinuxBlockIO) []blkioSettings {
+ settings := []blkioSettings{}
+
+ if blkio.Weight != nil {
+ settings = append(settings,
+ blkioSettings{
+ name: "weight",
+ value: blkio.Weight,
+ format: uintf,
+ })
+ }
+ if blkio.LeafWeight != nil {
+ settings = append(settings,
+ blkioSettings{
+ name: "leaf_weight",
+ value: blkio.LeafWeight,
+ format: uintf,
+ })
+ }
+ for _, wd := range blkio.WeightDevice {
+ if wd.Weight != nil {
+ settings = append(settings,
+ blkioSettings{
+ name: "weight_device",
+ value: wd,
+ format: weightdev,
+ })
+ }
+ if wd.LeafWeight != nil {
+ settings = append(settings,
+ blkioSettings{
+ name: "leaf_weight_device",
+ value: wd,
+ format: weightleafdev,
+ })
+ }
+ }
+ for _, t := range []struct {
+ name string
+ list []specs.LinuxThrottleDevice
+ }{
+ {
+ name: "throttle.read_bps_device",
+ list: blkio.ThrottleReadBpsDevice,
+ },
+ {
+ name: "throttle.read_iops_device",
+ list: blkio.ThrottleReadIOPSDevice,
+ },
+ {
+ name: "throttle.write_bps_device",
+ list: blkio.ThrottleWriteBpsDevice,
+ },
+ {
+ name: "throttle.write_iops_device",
+ list: blkio.ThrottleWriteIOPSDevice,
+ },
+ } {
+ for _, td := range t.list {
+ settings = append(settings, blkioSettings{
+ name: t.name,
+ value: td,
+ format: throttleddev,
+ })
+ }
+ }
+ return settings
+}
+
+type blkioSettings struct {
+ name string
+ value interface{}
+ format func(v interface{}) []byte
+}
+
+type blkioStatSettings struct {
+ name string
+ entry *[]*v1.BlkIOEntry
+}
+
+func uintf(v interface{}) []byte {
+ return []byte(strconv.FormatUint(uint64(*v.(*uint16)), 10))
+}
+
+func weightdev(v interface{}) []byte {
+ wd := v.(specs.LinuxWeightDevice)
+ return []byte(fmt.Sprintf("%d:%d %d", wd.Major, wd.Minor, *wd.Weight))
+}
+
+func weightleafdev(v interface{}) []byte {
+ wd := v.(specs.LinuxWeightDevice)
+ return []byte(fmt.Sprintf("%d:%d %d", wd.Major, wd.Minor, *wd.LeafWeight))
+}
+
+func throttleddev(v interface{}) []byte {
+ td := v.(specs.LinuxThrottleDevice)
+ return []byte(fmt.Sprintf("%d:%d %d", td.Major, td.Minor, td.Rate))
+}
+
+func splitBlkIOStatLine(r rune) bool {
+ return r == ' ' || r == ':'
+}
+
+type deviceKey struct {
+ major, minor uint64
+}
+
+// getDevices makes a best effort attempt to read all the devices into a map
+// keyed by major and minor number. Since devices may be mapped multiple times,
+// we err on taking the first occurrence.
+func getDevices(r io.Reader) (map[deviceKey]string, error) {
+
+ var (
+ s = bufio.NewScanner(r)
+ devices = make(map[deviceKey]string)
+ )
+ for i := 0; s.Scan(); i++ {
+ if i < 2 {
+ continue
+ }
+ fields := strings.Fields(s.Text())
+ major, err := strconv.Atoi(fields[0])
+ if err != nil {
+ return nil, err
+ }
+ minor, err := strconv.Atoi(fields[1])
+ if err != nil {
+ return nil, err
+ }
+ key := deviceKey{
+ major: uint64(major),
+ minor: uint64(minor),
+ }
+ if _, ok := devices[key]; ok {
+ continue
+ }
+ devices[key] = filepath.Join("/dev", fields[3])
+ }
+ return devices, s.Err()
+}
diff --git a/vendor/github.com/containerd/cgroups/cgroup.go b/vendor/github.com/containerd/cgroups/cgroup.go
@@ -0,0 +1,533 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+
+ v1 "github.com/containerd/cgroups/stats/v1"
+
+ "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+// New returns a new control via the cgroup cgroups interface
+func New(hierarchy Hierarchy, path Path, resources *specs.LinuxResources, opts ...InitOpts) (Cgroup, error) {
+ config := newInitConfig()
+ for _, o := range opts {
+ if err := o(config); err != nil {
+ return nil, err
+ }
+ }
+ subsystems, err := hierarchy()
+ if err != nil {
+ return nil, err
+ }
+ var active []Subsystem
+ for _, s := range subsystems {
+ // check if subsystem exists
+ if err := initializeSubsystem(s, path, resources); err != nil {
+ if err == ErrControllerNotActive {
+ if config.InitCheck != nil {
+ if skerr := config.InitCheck(s, path, err); skerr != nil {
+ if skerr != ErrIgnoreSubsystem {
+ return nil, skerr
+ }
+ }
+ }
+ continue
+ }
+ return nil, err
+ }
+ active = append(active, s)
+ }
+ return &cgroup{
+ path: path,
+ subsystems: active,
+ }, nil
+}
+
+// Load will load an existing cgroup and allow it to be controlled
+// All static path should not include `/sys/fs/cgroup/` prefix, it should start with your own cgroups name
+func Load(hierarchy Hierarchy, path Path, opts ...InitOpts) (Cgroup, error) {
+ config := newInitConfig()
+ for _, o := range opts {
+ if err := o(config); err != nil {
+ return nil, err
+ }
+ }
+ var activeSubsystems []Subsystem
+ subsystems, err := hierarchy()
+ if err != nil {
+ return nil, err
+ }
+ // check that the subsystems still exist, and keep only those that actually exist
+ for _, s := range pathers(subsystems) {
+ p, err := path(s.Name())
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, ErrCgroupDeleted
+ }
+ if err == ErrControllerNotActive {
+ if config.InitCheck != nil {
+ if skerr := config.InitCheck(s, path, err); skerr != nil {
+ if skerr != ErrIgnoreSubsystem {
+ return nil, skerr
+ }
+ }
+ }
+ continue
+ }
+ return nil, err
+ }
+ if _, err := os.Lstat(s.Path(p)); err != nil {
+ if os.IsNotExist(err) {
+ continue
+ }
+ return nil, err
+ }
+ activeSubsystems = append(activeSubsystems, s)
+ }
+ // if we do not have any active systems then the cgroup is deleted
+ if len(activeSubsystems) == 0 {
+ return nil, ErrCgroupDeleted
+ }
+ return &cgroup{
+ path: path,
+ subsystems: activeSubsystems,
+ }, nil
+}
+
+type cgroup struct {
+ path Path
+
+ subsystems []Subsystem
+ mu sync.Mutex
+ err error
+}
+
+// New returns a new sub cgroup
+func (c *cgroup) New(name string, resources *specs.LinuxResources) (Cgroup, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return nil, c.err
+ }
+ path := subPath(c.path, name)
+ for _, s := range c.subsystems {
+ if err := initializeSubsystem(s, path, resources); err != nil {
+ return nil, err
+ }
+ }
+ return &cgroup{
+ path: path,
+ subsystems: c.subsystems,
+ }, nil
+}
+
+// Subsystems returns all the subsystems that are currently being
+// consumed by the group
+func (c *cgroup) Subsystems() []Subsystem {
+ return c.subsystems
+}
+
+func (c *cgroup) subsystemsFilter(subsystems ...Name) []Subsystem {
+ if len(subsystems) == 0 {
+ return c.subsystems
+ }
+
+ var filteredSubsystems = []Subsystem{}
+ for _, s := range c.subsystems {
+ for _, f := range subsystems {
+ if s.Name() == f {
+ filteredSubsystems = append(filteredSubsystems, s)
+ break
+ }
+ }
+ }
+
+ return filteredSubsystems
+}
+
+// Add moves the provided process into the new cgroup.
+// Without additional arguments, the process is added to all the cgroup subsystems.
+// When giving Add a list of subsystem names, the process is only added to those
+// subsystems, provided that they are active in the targeted cgroup.
+func (c *cgroup) Add(process Process, subsystems ...Name) error {
+ return c.add(process, cgroupProcs, subsystems...)
+}
+
+// AddProc moves the provided process id into the new cgroup.
+// Without additional arguments, the process with the given id is added to all
+// the cgroup subsystems. When giving AddProc a list of subsystem names, the process
+// id is only added to those subsystems, provided that they are active in the targeted
+// cgroup.
+func (c *cgroup) AddProc(pid uint64, subsystems ...Name) error {
+ return c.add(Process{Pid: int(pid)}, cgroupProcs, subsystems...)
+}
+
+// AddTask moves the provided tasks (threads) into the new cgroup.
+// Without additional arguments, the task is added to all the cgroup subsystems.
+// When giving AddTask a list of subsystem names, the task is only added to those
+// subsystems, provided that they are active in the targeted cgroup.
+func (c *cgroup) AddTask(process Process, subsystems ...Name) error {
+ return c.add(process, cgroupTasks, subsystems...)
+}
+
+func (c *cgroup) add(process Process, pType procType, subsystems ...Name) error {
+ if process.Pid <= 0 {
+ return ErrInvalidPid
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return c.err
+ }
+ for _, s := range pathers(c.subsystemsFilter(subsystems...)) {
+ p, err := c.path(s.Name())
+ if err != nil {
+ return err
+ }
+ err = retryingWriteFile(
+ filepath.Join(s.Path(p), pType),
+ []byte(strconv.Itoa(process.Pid)),
+ defaultFilePerm,
+ )
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Delete will remove the control group from each of the subsystems registered
+func (c *cgroup) Delete() error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return c.err
+ }
+ var errs []string
+ for _, s := range c.subsystems {
+ if d, ok := s.(deleter); ok {
+ sp, err := c.path(s.Name())
+ if err != nil {
+ return err
+ }
+ if err := d.Delete(sp); err != nil {
+ errs = append(errs, string(s.Name()))
+ }
+ continue
+ }
+ if p, ok := s.(pather); ok {
+ sp, err := c.path(s.Name())
+ if err != nil {
+ return err
+ }
+ path := p.Path(sp)
+ if err := remove(path); err != nil {
+ errs = append(errs, path)
+ }
+ }
+ }
+ if len(errs) > 0 {
+ return fmt.Errorf("cgroups: unable to remove paths %s", strings.Join(errs, ", "))
+ }
+ c.err = ErrCgroupDeleted
+ return nil
+}
+
+// Stat returns the current metrics for the cgroup
+func (c *cgroup) Stat(handlers ...ErrorHandler) (*v1.Metrics, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return nil, c.err
+ }
+ if len(handlers) == 0 {
+ handlers = append(handlers, errPassthrough)
+ }
+ var (
+ stats = &v1.Metrics{
+ CPU: &v1.CPUStat{
+ Throttling: &v1.Throttle{},
+ Usage: &v1.CPUUsage{},
+ },
+ }
+ wg = &sync.WaitGroup{}
+ errs = make(chan error, len(c.subsystems))
+ )
+ for _, s := range c.subsystems {
+ if ss, ok := s.(stater); ok {
+ sp, err := c.path(s.Name())
+ if err != nil {
+ return nil, err
+ }
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if err := ss.Stat(sp, stats); err != nil {
+ for _, eh := range handlers {
+ if herr := eh(err); herr != nil {
+ errs <- herr
+ }
+ }
+ }
+ }()
+ }
+ }
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ return nil, err
+ }
+ return stats, nil
+}
+
+// Update updates the cgroup with the new resource values provided
+//
+// Be prepared to handle EBUSY when trying to update a cgroup with
+// live processes and other operations like Stats being performed at the
+// same time
+func (c *cgroup) Update(resources *specs.LinuxResources) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return c.err
+ }
+ for _, s := range c.subsystems {
+ if u, ok := s.(updater); ok {
+ sp, err := c.path(s.Name())
+ if err != nil {
+ return err
+ }
+ if err := u.Update(sp, resources); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// Processes returns the processes running inside the cgroup along
+// with the subsystem used, pid, and path
+func (c *cgroup) Processes(subsystem Name, recursive bool) ([]Process, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return nil, c.err
+ }
+ return c.processes(subsystem, recursive, cgroupProcs)
+}
+
+// Tasks returns the tasks running inside the cgroup along
+// with the subsystem used, pid, and path
+func (c *cgroup) Tasks(subsystem Name, recursive bool) ([]Task, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return nil, c.err
+ }
+ return c.processes(subsystem, recursive, cgroupTasks)
+}
+
+func (c *cgroup) processes(subsystem Name, recursive bool, pType procType) ([]Process, error) {
+ s := c.getSubsystem(subsystem)
+ sp, err := c.path(subsystem)
+ if err != nil {
+ return nil, err
+ }
+ if s == nil {
+ return nil, fmt.Errorf("cgroups: %s doesn't exist in %s subsystem", sp, subsystem)
+ }
+ path := s.(pather).Path(sp)
+ var processes []Process
+ err = filepath.Walk(path, func(p string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ if !recursive && info.IsDir() {
+ if p == path {
+ return nil
+ }
+ return filepath.SkipDir
+ }
+ dir, name := filepath.Split(p)
+ if name != pType {
+ return nil
+ }
+ procs, err := readPids(dir, subsystem, pType)
+ if err != nil {
+ return err
+ }
+ processes = append(processes, procs...)
+ return nil
+ })
+ return processes, err
+}
+
+// Freeze freezes the entire cgroup and all the processes inside it
+func (c *cgroup) Freeze() error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return c.err
+ }
+ s := c.getSubsystem(Freezer)
+ if s == nil {
+ return ErrFreezerNotSupported
+ }
+ sp, err := c.path(Freezer)
+ if err != nil {
+ return err
+ }
+ return s.(*freezerController).Freeze(sp)
+}
+
+// Thaw thaws out the cgroup and all the processes inside it
+func (c *cgroup) Thaw() error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return c.err
+ }
+ s := c.getSubsystem(Freezer)
+ if s == nil {
+ return ErrFreezerNotSupported
+ }
+ sp, err := c.path(Freezer)
+ if err != nil {
+ return err
+ }
+ return s.(*freezerController).Thaw(sp)
+}
+
+// OOMEventFD returns the memory cgroup's out of memory event fd that triggers
+// when processes inside the cgroup receive an oom event. Returns
+// ErrMemoryNotSupported if memory cgroups is not supported.
+func (c *cgroup) OOMEventFD() (uintptr, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return 0, c.err
+ }
+ s := c.getSubsystem(Memory)
+ if s == nil {
+ return 0, ErrMemoryNotSupported
+ }
+ sp, err := c.path(Memory)
+ if err != nil {
+ return 0, err
+ }
+ return s.(*memoryController).memoryEvent(sp, OOMEvent())
+}
+
+// RegisterMemoryEvent allows the ability to register for all v1 memory cgroups
+// notifications.
+func (c *cgroup) RegisterMemoryEvent(event MemoryEvent) (uintptr, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return 0, c.err
+ }
+ s := c.getSubsystem(Memory)
+ if s == nil {
+ return 0, ErrMemoryNotSupported
+ }
+ sp, err := c.path(Memory)
+ if err != nil {
+ return 0, err
+ }
+ return s.(*memoryController).memoryEvent(sp, event)
+}
+
+// State returns the state of the cgroup and its processes
+func (c *cgroup) State() State {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.checkExists()
+ if c.err != nil && c.err == ErrCgroupDeleted {
+ return Deleted
+ }
+ s := c.getSubsystem(Freezer)
+ if s == nil {
+ return Thawed
+ }
+ sp, err := c.path(Freezer)
+ if err != nil {
+ return Unknown
+ }
+ state, err := s.(*freezerController).state(sp)
+ if err != nil {
+ return Unknown
+ }
+ return state
+}
+
+// MoveTo does a recursive move subsystem by subsystem of all the processes
+// inside the group
+func (c *cgroup) MoveTo(destination Cgroup) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.err != nil {
+ return c.err
+ }
+ for _, s := range c.subsystems {
+ processes, err := c.processes(s.Name(), true, cgroupProcs)
+ if err != nil {
+ return err
+ }
+ for _, p := range processes {
+ if err := destination.Add(p); err != nil {
+ if strings.Contains(err.Error(), "no such process") {
+ continue
+ }
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func (c *cgroup) getSubsystem(n Name) Subsystem {
+ for _, s := range c.subsystems {
+ if s.Name() == n {
+ return s
+ }
+ }
+ return nil
+}
+
+func (c *cgroup) checkExists() {
+ for _, s := range pathers(c.subsystems) {
+ p, err := c.path(s.Name())
+ if err != nil {
+ return
+ }
+ if _, err := os.Lstat(s.Path(p)); err != nil {
+ if os.IsNotExist(err) {
+ c.err = ErrCgroupDeleted
+ return
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/containerd/cgroups/control.go b/vendor/github.com/containerd/cgroups/control.go
@@ -0,0 +1,99 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "os"
+
+ v1 "github.com/containerd/cgroups/stats/v1"
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+type procType = string
+
+const (
+ cgroupProcs procType = "cgroup.procs"
+ cgroupTasks procType = "tasks"
+ defaultDirPerm = 0755
+)
+
+// defaultFilePerm is a var so that the test framework can change the filemode
+// of all files created when the tests are running. The difference between the
+// tests and real world use is that files like "cgroup.procs" will exist when writing
+// to a read cgroup filesystem and do not exist prior when running in the tests.
+// this is set to a non 0 value in the test code
+var defaultFilePerm = os.FileMode(0)
+
+type Process struct {
+ // Subsystem is the name of the subsystem that the process / task is in.
+ Subsystem Name
+ // Pid is the process id of the process / task.
+ Pid int
+ // Path is the full path of the subsystem and location that the process / task is in.
+ Path string
+}
+
+type Task = Process
+
+// Cgroup handles interactions with the individual groups to perform
+// actions on them as them main interface to this cgroup package
+type Cgroup interface {
+ // New creates a new cgroup under the calling cgroup
+ New(string, *specs.LinuxResources) (Cgroup, error)
+ // Add adds a process to the cgroup (cgroup.procs). Without additional arguments,
+ // the process is added to all the cgroup subsystems. When giving Add a list of
+ // subsystem names, the process is only added to those subsystems, provided that
+ // they are active in the targeted cgroup.
+ Add(Process, ...Name) error
+ // AddProc adds the process with the given id to the cgroup (cgroup.procs).
+ // Without additional arguments, the process with the given id is added to all
+ // the cgroup subsystems. When giving AddProc a list of subsystem names, the process
+ // id is only added to those subsystems, provided that they are active in the targeted
+ // cgroup.
+ AddProc(uint64, ...Name) error
+ // AddTask adds a process to the cgroup (tasks). Without additional arguments, the
+ // task is added to all the cgroup subsystems. When giving AddTask a list of subsystem
+ // names, the task is only added to those subsystems, provided that they are active in
+ // the targeted cgroup.
+ AddTask(Process, ...Name) error
+ // Delete removes the cgroup as a whole
+ Delete() error
+ // MoveTo moves all the processes under the calling cgroup to the provided one
+ // subsystems are moved one at a time
+ MoveTo(Cgroup) error
+ // Stat returns the stats for all subsystems in the cgroup
+ Stat(...ErrorHandler) (*v1.Metrics, error)
+ // Update updates all the subsystems with the provided resource changes
+ Update(resources *specs.LinuxResources) error
+ // Processes returns all the processes in a select subsystem for the cgroup
+ Processes(Name, bool) ([]Process, error)
+ // Tasks returns all the tasks in a select subsystem for the cgroup
+ Tasks(Name, bool) ([]Task, error)
+ // Freeze freezes or pauses all processes inside the cgroup
+ Freeze() error
+ // Thaw thaw or resumes all processes inside the cgroup
+ Thaw() error
+ // OOMEventFD returns the memory subsystem's event fd for OOM events
+ OOMEventFD() (uintptr, error)
+ // RegisterMemoryEvent returns the memory subsystems event fd for whatever memory event was
+ // registered for. Can alternatively register for the oom event with this method.
+ RegisterMemoryEvent(MemoryEvent) (uintptr, error)
+ // State returns the cgroups current state
+ State() State
+ // Subsystems returns all the subsystems in the cgroup
+ Subsystems() []Subsystem
+}
diff --git a/vendor/github.com/containerd/cgroups/cpu.go b/vendor/github.com/containerd/cgroups/cpu.go
@@ -0,0 +1,125 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "bufio"
+ "os"
+ "path/filepath"
+ "strconv"
+
+ v1 "github.com/containerd/cgroups/stats/v1"
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+func NewCpu(root string) *cpuController {
+ return &cpuController{
+ root: filepath.Join(root, string(Cpu)),
+ }
+}
+
+type cpuController struct {
+ root string
+}
+
+func (c *cpuController) Name() Name {
+ return Cpu
+}
+
+func (c *cpuController) Path(path string) string {
+ return filepath.Join(c.root, path)
+}
+
+func (c *cpuController) Create(path string, resources *specs.LinuxResources) error {
+ if err := os.MkdirAll(c.Path(path), defaultDirPerm); err != nil {
+ return err
+ }
+ if cpu := resources.CPU; cpu != nil {
+ for _, t := range []struct {
+ name string
+ ivalue *int64
+ uvalue *uint64
+ }{
+ {
+ name: "rt_period_us",
+ uvalue: cpu.RealtimePeriod,
+ },
+ {
+ name: "rt_runtime_us",
+ ivalue: cpu.RealtimeRuntime,
+ },
+ {
+ name: "shares",
+ uvalue: cpu.Shares,
+ },
+ {
+ name: "cfs_period_us",
+ uvalue: cpu.Period,
+ },
+ {
+ name: "cfs_quota_us",
+ ivalue: cpu.Quota,
+ },
+ } {
+ var value []byte
+ if t.uvalue != nil {
+ value = []byte(strconv.FormatUint(*t.uvalue, 10))
+ } else if t.ivalue != nil {
+ value = []byte(strconv.FormatInt(*t.ivalue, 10))
+ }
+ if value != nil {
+ if err := retryingWriteFile(
+ filepath.Join(c.Path(path), "cpu."+t.name),
+ value,
+ defaultFilePerm,
+ ); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (c *cpuController) Update(path string, resources *specs.LinuxResources) error {
+ return c.Create(path, resources)
+}
+
+func (c *cpuController) Stat(path string, stats *v1.Metrics) error {
+ f, err := os.Open(filepath.Join(c.Path(path), "cpu.stat"))
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ // get or create the cpu field because cpuacct can also set values on this struct
+ sc := bufio.NewScanner(f)
+ for sc.Scan() {
+ key, v, err := parseKV(sc.Text())
+ if err != nil {
+ return err
+ }
+ switch key {
+ case "nr_periods":
+ stats.CPU.Throttling.Periods = v
+ case "nr_throttled":
+ stats.CPU.Throttling.ThrottledPeriods = v
+ case "throttled_time":
+ stats.CPU.Throttling.ThrottledTime = v
+ }
+ }
+ return sc.Err()
+}
diff --git a/vendor/github.com/containerd/cgroups/cpuacct.go b/vendor/github.com/containerd/cgroups/cpuacct.go
@@ -0,0 +1,123 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "fmt"
+ "io/ioutil"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ v1 "github.com/containerd/cgroups/stats/v1"
+)
+
+const nanosecondsInSecond = 1000000000
+
+var clockTicks = getClockTicks()
+
+func NewCpuacct(root string) *cpuacctController {
+ return &cpuacctController{
+ root: filepath.Join(root, string(Cpuacct)),
+ }
+}
+
+type cpuacctController struct {
+ root string
+}
+
+func (c *cpuacctController) Name() Name {
+ return Cpuacct
+}
+
+func (c *cpuacctController) Path(path string) string {
+ return filepath.Join(c.root, path)
+}
+
+func (c *cpuacctController) Stat(path string, stats *v1.Metrics) error {
+ user, kernel, err := c.getUsage(path)
+ if err != nil {
+ return err
+ }
+ total, err := readUint(filepath.Join(c.Path(path), "cpuacct.usage"))
+ if err != nil {
+ return err
+ }
+ percpu, err := c.percpuUsage(path)
+ if err != nil {
+ return err
+ }
+ stats.CPU.Usage.Total = total
+ stats.CPU.Usage.User = user
+ stats.CPU.Usage.Kernel = kernel
+ stats.CPU.Usage.PerCPU = percpu
+ return nil
+}
+
+func (c *cpuacctController) percpuUsage(path string) ([]uint64, error) {
+ var usage []uint64
+ data, err := ioutil.ReadFile(filepath.Join(c.Path(path), "cpuacct.usage_percpu"))
+ if err != nil {
+ return nil, err
+ }
+ for _, v := range strings.Fields(string(data)) {
+ u, err := strconv.ParseUint(v, 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ usage = append(usage, u)
+ }
+ return usage, nil
+}
+
+func (c *cpuacctController) getUsage(path string) (user uint64, kernel uint64, err error) {
+ statPath := filepath.Join(c.Path(path), "cpuacct.stat")
+ data, err := ioutil.ReadFile(statPath)
+ if err != nil {
+ return 0, 0, err
+ }
+ fields := strings.Fields(string(data))
+ if len(fields) != 4 {
+ return 0, 0, fmt.Errorf("%q is expected to have 4 fields", statPath)
+ }
+ for _, t := range []struct {
+ index int
+ name string
+ value *uint64
+ }{
+ {
+ index: 0,
+ name: "user",
+ value: &user,
+ },
+ {
+ index: 2,
+ name: "system",
+ value: &kernel,
+ },
+ } {
+ if fields[t.index] != t.name {
+ return 0, 0, fmt.Errorf("expected field %q but found %q in %q", t.name, fields[t.index], statPath)
+ }
+ v, err := strconv.ParseUint(fields[t.index+1], 10, 64)
+ if err != nil {
+ return 0, 0, err
+ }
+ *t.value = v
+ }
+ return (user * nanosecondsInSecond) / clockTicks, (kernel * nanosecondsInSecond) / clockTicks, nil
+}
diff --git a/vendor/github.com/containerd/cgroups/cpuset.go b/vendor/github.com/containerd/cgroups/cpuset.go
@@ -0,0 +1,159 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "bytes"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+func NewCpuset(root string) *cpusetController {
+ return &cpusetController{
+ root: filepath.Join(root, string(Cpuset)),
+ }
+}
+
+type cpusetController struct {
+ root string
+}
+
+func (c *cpusetController) Name() Name {
+ return Cpuset
+}
+
+func (c *cpusetController) Path(path string) string {
+ return filepath.Join(c.root, path)
+}
+
+func (c *cpusetController) Create(path string, resources *specs.LinuxResources) error {
+ if err := c.ensureParent(c.Path(path), c.root); err != nil {
+ return err
+ }
+ if err := os.MkdirAll(c.Path(path), defaultDirPerm); err != nil {
+ return err
+ }
+ if err := c.copyIfNeeded(c.Path(path), filepath.Dir(c.Path(path))); err != nil {
+ return err
+ }
+ if resources.CPU != nil {
+ for _, t := range []struct {
+ name string
+ value string
+ }{
+ {
+ name: "cpus",
+ value: resources.CPU.Cpus,
+ },
+ {
+ name: "mems",
+ value: resources.CPU.Mems,
+ },
+ } {
+ if t.value != "" {
+ if err := retryingWriteFile(
+ filepath.Join(c.Path(path), "cpuset."+t.name),
+ []byte(t.value),
+ defaultFilePerm,
+ ); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (c *cpusetController) Update(path string, resources *specs.LinuxResources) error {
+ return c.Create(path, resources)
+}
+
+func (c *cpusetController) getValues(path string) (cpus []byte, mems []byte, err error) {
+ if cpus, err = ioutil.ReadFile(filepath.Join(path, "cpuset.cpus")); err != nil && !os.IsNotExist(err) {
+ return
+ }
+ if mems, err = ioutil.ReadFile(filepath.Join(path, "cpuset.mems")); err != nil && !os.IsNotExist(err) {
+ return
+ }
+ return cpus, mems, nil
+}
+
+// ensureParent makes sure that the parent directory of current is created
+// and populated with the proper cpus and mems files copied from
+// it's parent.
+func (c *cpusetController) ensureParent(current, root string) error {
+ parent := filepath.Dir(current)
+ if _, err := filepath.Rel(root, parent); err != nil {
+ return nil
+ }
+ // Avoid infinite recursion.
+ if parent == current {
+ return fmt.Errorf("cpuset: cgroup parent path outside cgroup root")
+ }
+ if cleanPath(parent) != root {
+ if err := c.ensureParent(parent, root); err != nil {
+ return err
+ }
+ }
+ if err := os.MkdirAll(current, defaultDirPerm); err != nil {
+ return err
+ }
+ return c.copyIfNeeded(current, parent)
+}
+
+// copyIfNeeded copies the cpuset.cpus and cpuset.mems from the parent
+// directory to the current directory if the file's contents are 0
+func (c *cpusetController) copyIfNeeded(current, parent string) error {
+ var (
+ err error
+ currentCpus, currentMems []byte
+ parentCpus, parentMems []byte
+ )
+ if currentCpus, currentMems, err = c.getValues(current); err != nil {
+ return err
+ }
+ if parentCpus, parentMems, err = c.getValues(parent); err != nil {
+ return err
+ }
+ if isEmpty(currentCpus) {
+ if err := retryingWriteFile(
+ filepath.Join(current, "cpuset.cpus"),
+ parentCpus,
+ defaultFilePerm,
+ ); err != nil {
+ return err
+ }
+ }
+ if isEmpty(currentMems) {
+ if err := retryingWriteFile(
+ filepath.Join(current, "cpuset.mems"),
+ parentMems,
+ defaultFilePerm,
+ ); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func isEmpty(b []byte) bool {
+ return len(bytes.Trim(b, "\n")) == 0
+}
diff --git a/vendor/github.com/containerd/cgroups/devices.go b/vendor/github.com/containerd/cgroups/devices.go
@@ -0,0 +1,92 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+const (
+ allowDeviceFile = "devices.allow"
+ denyDeviceFile = "devices.deny"
+ wildcard = -1
+)
+
+func NewDevices(root string) *devicesController {
+ return &devicesController{
+ root: filepath.Join(root, string(Devices)),
+ }
+}
+
+type devicesController struct {
+ root string
+}
+
+func (d *devicesController) Name() Name {
+ return Devices
+}
+
+func (d *devicesController) Path(path string) string {
+ return filepath.Join(d.root, path)
+}
+
+func (d *devicesController) Create(path string, resources *specs.LinuxResources) error {
+ if err := os.MkdirAll(d.Path(path), defaultDirPerm); err != nil {
+ return err
+ }
+ for _, device := range resources.Devices {
+ file := denyDeviceFile
+ if device.Allow {
+ file = allowDeviceFile
+ }
+ if device.Type == "" {
+ device.Type = "a"
+ }
+ if err := retryingWriteFile(
+ filepath.Join(d.Path(path), file),
+ []byte(deviceString(device)),
+ defaultFilePerm,
+ ); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (d *devicesController) Update(path string, resources *specs.LinuxResources) error {
+ return d.Create(path, resources)
+}
+
+func deviceString(device specs.LinuxDeviceCgroup) string {
+ return fmt.Sprintf("%s %s:%s %s",
+ device.Type,
+ deviceNumber(device.Major),
+ deviceNumber(device.Minor),
+ device.Access,
+ )
+}
+
+func deviceNumber(number *int64) string {
+ if number == nil || *number == wildcard {
+ return "*"
+ }
+ return fmt.Sprint(*number)
+}
diff --git a/vendor/github.com/containerd/cgroups/errors.go b/vendor/github.com/containerd/cgroups/errors.go
@@ -0,0 +1,47 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "errors"
+ "os"
+)
+
+var (
+ ErrInvalidPid = errors.New("cgroups: pid must be greater than 0")
+ ErrMountPointNotExist = errors.New("cgroups: cgroup mountpoint does not exist")
+ ErrInvalidFormat = errors.New("cgroups: parsing file with invalid format failed")
+ ErrFreezerNotSupported = errors.New("cgroups: freezer cgroup not supported on this system")
+ ErrMemoryNotSupported = errors.New("cgroups: memory cgroup not supported on this system")
+ ErrCgroupDeleted = errors.New("cgroups: cgroup deleted")
+ ErrNoCgroupMountDestination = errors.New("cgroups: cannot find cgroup mount destination")
+)
+
+// ErrorHandler is a function that handles and acts on errors
+type ErrorHandler func(err error) error
+
+// IgnoreNotExist ignores any errors that are for not existing files
+func IgnoreNotExist(err error) error {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+}
+
+func errPassthrough(err error) error {
+ return err
+}
diff --git a/vendor/github.com/containerd/cgroups/freezer.go b/vendor/github.com/containerd/cgroups/freezer.go
@@ -0,0 +1,82 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "io/ioutil"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+func NewFreezer(root string) *freezerController {
+ return &freezerController{
+ root: filepath.Join(root, string(Freezer)),
+ }
+}
+
+type freezerController struct {
+ root string
+}
+
+func (f *freezerController) Name() Name {
+ return Freezer
+}
+
+func (f *freezerController) Path(path string) string {
+ return filepath.Join(f.root, path)
+}
+
+func (f *freezerController) Freeze(path string) error {
+ return f.waitState(path, Frozen)
+}
+
+func (f *freezerController) Thaw(path string) error {
+ return f.waitState(path, Thawed)
+}
+
+func (f *freezerController) changeState(path string, state State) error {
+ return retryingWriteFile(
+ filepath.Join(f.root, path, "freezer.state"),
+ []byte(strings.ToUpper(string(state))),
+ defaultFilePerm,
+ )
+}
+
+func (f *freezerController) state(path string) (State, error) {
+ current, err := ioutil.ReadFile(filepath.Join(f.root, path, "freezer.state"))
+ if err != nil {
+ return "", err
+ }
+ return State(strings.ToLower(strings.TrimSpace(string(current)))), nil
+}
+
+func (f *freezerController) waitState(path string, state State) error {
+ for {
+ if err := f.changeState(path, state); err != nil {
+ return err
+ }
+ current, err := f.state(path)
+ if err != nil {
+ return err
+ }
+ if current == state {
+ return nil
+ }
+ time.Sleep(1 * time.Millisecond)
+ }
+}
diff --git a/vendor/github.com/containerd/cgroups/hierarchy.go b/vendor/github.com/containerd/cgroups/hierarchy.go
@@ -0,0 +1,20 @@
+/*
+ Copyright The containerd 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 cgroups
+
+// Hierarchy enables both unified and split hierarchy for cgroups
+type Hierarchy func() ([]Subsystem, error)
diff --git a/vendor/github.com/containerd/cgroups/hugetlb.go b/vendor/github.com/containerd/cgroups/hugetlb.go
@@ -0,0 +1,109 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ v1 "github.com/containerd/cgroups/stats/v1"
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+func NewHugetlb(root string) (*hugetlbController, error) {
+ sizes, err := hugePageSizes()
+ if err != nil {
+ return nil, err
+ }
+
+ return &hugetlbController{
+ root: filepath.Join(root, string(Hugetlb)),
+ sizes: sizes,
+ }, nil
+}
+
+type hugetlbController struct {
+ root string
+ sizes []string
+}
+
+func (h *hugetlbController) Name() Name {
+ return Hugetlb
+}
+
+func (h *hugetlbController) Path(path string) string {
+ return filepath.Join(h.root, path)
+}
+
+func (h *hugetlbController) Create(path string, resources *specs.LinuxResources) error {
+ if err := os.MkdirAll(h.Path(path), defaultDirPerm); err != nil {
+ return err
+ }
+ for _, limit := range resources.HugepageLimits {
+ if err := retryingWriteFile(
+ filepath.Join(h.Path(path), strings.Join([]string{"hugetlb", limit.Pagesize, "limit_in_bytes"}, ".")),
+ []byte(strconv.FormatUint(limit.Limit, 10)),
+ defaultFilePerm,
+ ); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (h *hugetlbController) Stat(path string, stats *v1.Metrics) error {
+ for _, size := range h.sizes {
+ s, err := h.readSizeStat(path, size)
+ if err != nil {
+ return err
+ }
+ stats.Hugetlb = append(stats.Hugetlb, s)
+ }
+ return nil
+}
+
+func (h *hugetlbController) readSizeStat(path, size string) (*v1.HugetlbStat, error) {
+ s := v1.HugetlbStat{
+ Pagesize: size,
+ }
+ for _, t := range []struct {
+ name string
+ value *uint64
+ }{
+ {
+ name: "usage_in_bytes",
+ value: &s.Usage,
+ },
+ {
+ name: "max_usage_in_bytes",
+ value: &s.Max,
+ },
+ {
+ name: "failcnt",
+ value: &s.Failcnt,
+ },
+ } {
+ v, err := readUint(filepath.Join(h.Path(path), strings.Join([]string{"hugetlb", size, t.name}, ".")))
+ if err != nil {
+ return nil, err
+ }
+ *t.value = v
+ }
+ return &s, nil
+}
diff --git a/vendor/github.com/containerd/cgroups/memory.go b/vendor/github.com/containerd/cgroups/memory.go
@@ -0,0 +1,480 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ v1 "github.com/containerd/cgroups/stats/v1"
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+ "golang.org/x/sys/unix"
+)
+
+// MemoryEvent is an interface that V1 memory Cgroup notifications implement. Arg returns the
+// file name whose fd should be written to "cgroups.event_control". EventFile returns the name of
+// the file that supports the notification api e.g. "memory.usage_in_bytes".
+type MemoryEvent interface {
+ Arg() string
+ EventFile() string
+}
+
+type memoryThresholdEvent struct {
+ threshold uint64
+ swap bool
+}
+
+// MemoryThresholdEvent returns a new memory threshold event to be used with RegisterMemoryEvent.
+// If swap is true, the event will be registered using memory.memsw.usage_in_bytes
+func MemoryThresholdEvent(threshold uint64, swap bool) MemoryEvent {
+ return &memoryThresholdEvent{
+ threshold,
+ swap,
+ }
+}
+
+func (m *memoryThresholdEvent) Arg() string {
+ return strconv.FormatUint(m.threshold, 10)
+}
+
+func (m *memoryThresholdEvent) EventFile() string {
+ if m.swap {
+ return "memory.memsw.usage_in_bytes"
+ }
+ return "memory.usage_in_bytes"
+}
+
+type oomEvent struct{}
+
+// OOMEvent returns a new oom event to be used with RegisterMemoryEvent.
+func OOMEvent() MemoryEvent {
+ return &oomEvent{}
+}
+
+func (oom *oomEvent) Arg() string {
+ return ""
+}
+
+func (oom *oomEvent) EventFile() string {
+ return "memory.oom_control"
+}
+
+type memoryPressureEvent struct {
+ pressureLevel MemoryPressureLevel
+ hierarchy EventNotificationMode
+}
+
+// MemoryPressureEvent returns a new memory pressure event to be used with RegisterMemoryEvent.
+func MemoryPressureEvent(pressureLevel MemoryPressureLevel, hierarchy EventNotificationMode) MemoryEvent {
+ return &memoryPressureEvent{
+ pressureLevel,
+ hierarchy,
+ }
+}
+
+func (m *memoryPressureEvent) Arg() string {
+ return string(m.pressureLevel) + "," + string(m.hierarchy)
+}
+
+func (m *memoryPressureEvent) EventFile() string {
+ return "memory.pressure_level"
+}
+
+// MemoryPressureLevel corresponds to the memory pressure levels defined
+// for memory cgroups.
+type MemoryPressureLevel string
+
+// The three memory pressure levels are as follows.
+// - The "low" level means that the system is reclaiming memory for new
+// allocations. Monitoring this reclaiming activity might be useful for
+// maintaining cache level. Upon notification, the program (typically
+// "Activity Manager") might analyze vmstat and act in advance (i.e.
+// prematurely shutdown unimportant services).
+// - The "medium" level means that the system is experiencing medium memory
+// pressure, the system might be making swap, paging out active file caches,
+// etc. Upon this event applications may decide to further analyze
+// vmstat/zoneinfo/memcg or internal memory usage statistics and free any
+// resources that can be easily reconstructed or re-read from a disk.
+// - The "critical" level means that the system is actively thrashing, it is
+// about to out of memory (OOM) or even the in-kernel OOM killer is on its
+// way to trigger. Applications should do whatever they can to help the
+// system. It might be too late to consult with vmstat or any other
+// statistics, so it is advisable to take an immediate action.
+// "https://www.kernel.org/doc/Documentation/cgroup-v1/memory.txt" Section 11
+const (
+ LowPressure MemoryPressureLevel = "low"
+ MediumPressure MemoryPressureLevel = "medium"
+ CriticalPressure MemoryPressureLevel = "critical"
+)
+
+// EventNotificationMode corresponds to the notification modes
+// for the memory cgroups pressure level notifications.
+type EventNotificationMode string
+
+// There are three optional modes that specify different propagation behavior:
+// - "default": this is the default behavior specified above. This mode is the
+// same as omitting the optional mode parameter, preserved by backwards
+// compatibility.
+// - "hierarchy": events always propagate up to the root, similar to the default
+// behavior, except that propagation continues regardless of whether there are
+// event listeners at each level, with the "hierarchy" mode. In the above
+// example, groups A, B, and C will receive notification of memory pressure.
+// - "local": events are pass-through, i.e. they only receive notifications when
+// memory pressure is experienced in the memcg for which the notification is
+// registered. In the above example, group C will receive notification if
+// registered for "local" notification and the group experiences memory
+// pressure. However, group B will never receive notification, regardless if
+// there is an event listener for group C or not, if group B is registered for
+// local notification.
+// "https://www.kernel.org/doc/Documentation/cgroup-v1/memory.txt" Section 11
+const (
+ DefaultMode EventNotificationMode = "default"
+ LocalMode EventNotificationMode = "local"
+ HierarchyMode EventNotificationMode = "hierarchy"
+)
+
+// NewMemory returns a Memory controller given the root folder of cgroups.
+// It may optionally accept other configuration options, such as IgnoreModules(...)
+func NewMemory(root string, options ...func(*memoryController)) *memoryController {
+ mc := &memoryController{
+ root: filepath.Join(root, string(Memory)),
+ ignored: map[string]struct{}{},
+ }
+ for _, opt := range options {
+ opt(mc)
+ }
+ return mc
+}
+
+// IgnoreModules configure the memory controller to not read memory metrics for some
+// module names (e.g. passing "memsw" would avoid all the memory.memsw.* entries)
+func IgnoreModules(names ...string) func(*memoryController) {
+ return func(mc *memoryController) {
+ for _, name := range names {
+ mc.ignored[name] = struct{}{}
+ }
+ }
+}
+
+// OptionalSwap allows the memory controller to not fail if cgroups is not accounting
+// Swap memory (there are no memory.memsw.* entries)
+func OptionalSwap() func(*memoryController) {
+ return func(mc *memoryController) {
+ _, err := os.Stat(filepath.Join(mc.root, "memory.memsw.usage_in_bytes"))
+ if os.IsNotExist(err) {
+ mc.ignored["memsw"] = struct{}{}
+ }
+ }
+}
+
+type memoryController struct {
+ root string
+ ignored map[string]struct{}
+}
+
+func (m *memoryController) Name() Name {
+ return Memory
+}
+
+func (m *memoryController) Path(path string) string {
+ return filepath.Join(m.root, path)
+}
+
+func (m *memoryController) Create(path string, resources *specs.LinuxResources) error {
+ if err := os.MkdirAll(m.Path(path), defaultDirPerm); err != nil {
+ return err
+ }
+ if resources.Memory == nil {
+ return nil
+ }
+ return m.set(path, getMemorySettings(resources))
+}
+
+func (m *memoryController) Update(path string, resources *specs.LinuxResources) error {
+ if resources.Memory == nil {
+ return nil
+ }
+ g := func(v *int64) bool {
+ return v != nil && *v > 0
+ }
+ settings := getMemorySettings(resources)
+ if g(resources.Memory.Limit) && g(resources.Memory.Swap) {
+ // if the updated swap value is larger than the current memory limit set the swap changes first
+ // then set the memory limit as swap must always be larger than the current limit
+ current, err := readUint(filepath.Join(m.Path(path), "memory.limit_in_bytes"))
+ if err != nil {
+ return err
+ }
+ if current < uint64(*resources.Memory.Swap) {
+ settings[0], settings[1] = settings[1], settings[0]
+ }
+ }
+ return m.set(path, settings)
+}
+
+func (m *memoryController) Stat(path string, stats *v1.Metrics) error {
+ fMemStat, err := os.Open(filepath.Join(m.Path(path), "memory.stat"))
+ if err != nil {
+ return err
+ }
+ defer fMemStat.Close()
+ stats.Memory = &v1.MemoryStat{
+ Usage: &v1.MemoryEntry{},
+ Swap: &v1.MemoryEntry{},
+ Kernel: &v1.MemoryEntry{},
+ KernelTCP: &v1.MemoryEntry{},
+ }
+ if err := m.parseStats(fMemStat, stats.Memory); err != nil {
+ return err
+ }
+
+ fMemOomControl, err := os.Open(filepath.Join(m.Path(path), "memory.oom_control"))
+ if err != nil {
+ return err
+ }
+ defer fMemOomControl.Close()
+ stats.MemoryOomControl = &v1.MemoryOomControl{}
+ if err := m.parseOomControlStats(fMemOomControl, stats.MemoryOomControl); err != nil {
+ return err
+ }
+ for _, t := range []struct {
+ module string
+ entry *v1.MemoryEntry
+ }{
+ {
+ module: "",
+ entry: stats.Memory.Usage,
+ },
+ {
+ module: "memsw",
+ entry: stats.Memory.Swap,
+ },
+ {
+ module: "kmem",
+ entry: stats.Memory.Kernel,
+ },
+ {
+ module: "kmem.tcp",
+ entry: stats.Memory.KernelTCP,
+ },
+ } {
+ if _, ok := m.ignored[t.module]; ok {
+ continue
+ }
+ for _, tt := range []struct {
+ name string
+ value *uint64
+ }{
+ {
+ name: "usage_in_bytes",
+ value: &t.entry.Usage,
+ },
+ {
+ name: "max_usage_in_bytes",
+ value: &t.entry.Max,
+ },
+ {
+ name: "failcnt",
+ value: &t.entry.Failcnt,
+ },
+ {
+ name: "limit_in_bytes",
+ value: &t.entry.Limit,
+ },
+ } {
+ parts := []string{"memory"}
+ if t.module != "" {
+ parts = append(parts, t.module)
+ }
+ parts = append(parts, tt.name)
+ v, err := readUint(filepath.Join(m.Path(path), strings.Join(parts, ".")))
+ if err != nil {
+ return err
+ }
+ *tt.value = v
+ }
+ }
+ return nil
+}
+
+func (m *memoryController) parseStats(r io.Reader, stat *v1.MemoryStat) error {
+ var (
+ raw = make(map[string]uint64)
+ sc = bufio.NewScanner(r)
+ line int
+ )
+ for sc.Scan() {
+ key, v, err := parseKV(sc.Text())
+ if err != nil {
+ return fmt.Errorf("%d: %v", line, err)
+ }
+ raw[key] = v
+ line++
+ }
+ if err := sc.Err(); err != nil {
+ return err
+ }
+ stat.Cache = raw["cache"]
+ stat.RSS = raw["rss"]
+ stat.RSSHuge = raw["rss_huge"]
+ stat.MappedFile = raw["mapped_file"]
+ stat.Dirty = raw["dirty"]
+ stat.Writeback = raw["writeback"]
+ stat.PgPgIn = raw["pgpgin"]
+ stat.PgPgOut = raw["pgpgout"]
+ stat.PgFault = raw["pgfault"]
+ stat.PgMajFault = raw["pgmajfault"]
+ stat.InactiveAnon = raw["inactive_anon"]
+ stat.ActiveAnon = raw["active_anon"]
+ stat.InactiveFile = raw["inactive_file"]
+ stat.ActiveFile = raw["active_file"]
+ stat.Unevictable = raw["unevictable"]
+ stat.HierarchicalMemoryLimit = raw["hierarchical_memory_limit"]
+ stat.HierarchicalSwapLimit = raw["hierarchical_memsw_limit"]
+ stat.TotalCache = raw["total_cache"]
+ stat.TotalRSS = raw["total_rss"]
+ stat.TotalRSSHuge = raw["total_rss_huge"]
+ stat.TotalMappedFile = raw["total_mapped_file"]
+ stat.TotalDirty = raw["total_dirty"]
+ stat.TotalWriteback = raw["total_writeback"]
+ stat.TotalPgPgIn = raw["total_pgpgin"]
+ stat.TotalPgPgOut = raw["total_pgpgout"]
+ stat.TotalPgFault = raw["total_pgfault"]
+ stat.TotalPgMajFault = raw["total_pgmajfault"]
+ stat.TotalInactiveAnon = raw["total_inactive_anon"]
+ stat.TotalActiveAnon = raw["total_active_anon"]
+ stat.TotalInactiveFile = raw["total_inactive_file"]
+ stat.TotalActiveFile = raw["total_active_file"]
+ stat.TotalUnevictable = raw["total_unevictable"]
+ return nil
+}
+
+func (m *memoryController) parseOomControlStats(r io.Reader, stat *v1.MemoryOomControl) error {
+ var (
+ raw = make(map[string]uint64)
+ sc = bufio.NewScanner(r)
+ line int
+ )
+ for sc.Scan() {
+ key, v, err := parseKV(sc.Text())
+ if err != nil {
+ return fmt.Errorf("%d: %v", line, err)
+ }
+ raw[key] = v
+ line++
+ }
+ if err := sc.Err(); err != nil {
+ return err
+ }
+ stat.OomKillDisable = raw["oom_kill_disable"]
+ stat.UnderOom = raw["under_oom"]
+ stat.OomKill = raw["oom_kill"]
+ return nil
+}
+
+func (m *memoryController) set(path string, settings []memorySettings) error {
+ for _, t := range settings {
+ if t.value != nil {
+ if err := retryingWriteFile(
+ filepath.Join(m.Path(path), "memory."+t.name),
+ []byte(strconv.FormatInt(*t.value, 10)),
+ defaultFilePerm,
+ ); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+type memorySettings struct {
+ name string
+ value *int64
+}
+
+func getMemorySettings(resources *specs.LinuxResources) []memorySettings {
+ mem := resources.Memory
+ var swappiness *int64
+ if mem.Swappiness != nil {
+ v := int64(*mem.Swappiness)
+ swappiness = &v
+ }
+ return []memorySettings{
+ {
+ name: "limit_in_bytes",
+ value: mem.Limit,
+ },
+ {
+ name: "soft_limit_in_bytes",
+ value: mem.Reservation,
+ },
+ {
+ name: "memsw.limit_in_bytes",
+ value: mem.Swap,
+ },
+ {
+ name: "kmem.limit_in_bytes",
+ value: mem.Kernel,
+ },
+ {
+ name: "kmem.tcp.limit_in_bytes",
+ value: mem.KernelTCP,
+ },
+ {
+ name: "oom_control",
+ value: getOomControlValue(mem),
+ },
+ {
+ name: "swappiness",
+ value: swappiness,
+ },
+ }
+}
+
+func getOomControlValue(mem *specs.LinuxMemory) *int64 {
+ if mem.DisableOOMKiller != nil && *mem.DisableOOMKiller {
+ i := int64(1)
+ return &i
+ }
+ return nil
+}
+
+func (m *memoryController) memoryEvent(path string, event MemoryEvent) (uintptr, error) {
+ root := m.Path(path)
+ efd, err := unix.Eventfd(0, unix.EFD_CLOEXEC)
+ if err != nil {
+ return 0, err
+ }
+ evtFile, err := os.Open(filepath.Join(root, event.EventFile()))
+ if err != nil {
+ unix.Close(efd)
+ return 0, err
+ }
+ defer evtFile.Close()
+ data := fmt.Sprintf("%d %d %s", efd, evtFile.Fd(), event.Arg())
+ evctlPath := filepath.Join(root, "cgroup.event_control")
+ if err := retryingWriteFile(evctlPath, []byte(data), 0700); err != nil {
+ unix.Close(efd)
+ return 0, err
+ }
+ return uintptr(efd), nil
+}
diff --git a/vendor/github.com/containerd/cgroups/named.go b/vendor/github.com/containerd/cgroups/named.go
@@ -0,0 +1,39 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import "path/filepath"
+
+func NewNamed(root string, name Name) *namedController {
+ return &namedController{
+ root: root,
+ name: name,
+ }
+}
+
+type namedController struct {
+ root string
+ name Name
+}
+
+func (n *namedController) Name() Name {
+ return n.name
+}
+
+func (n *namedController) Path(path string) string {
+ return filepath.Join(n.root, string(n.name), path)
+}
diff --git a/vendor/github.com/containerd/cgroups/net_cls.go b/vendor/github.com/containerd/cgroups/net_cls.go
@@ -0,0 +1,61 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "os"
+ "path/filepath"
+ "strconv"
+
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+func NewNetCls(root string) *netclsController {
+ return &netclsController{
+ root: filepath.Join(root, string(NetCLS)),
+ }
+}
+
+type netclsController struct {
+ root string
+}
+
+func (n *netclsController) Name() Name {
+ return NetCLS
+}
+
+func (n *netclsController) Path(path string) string {
+ return filepath.Join(n.root, path)
+}
+
+func (n *netclsController) Create(path string, resources *specs.LinuxResources) error {
+ if err := os.MkdirAll(n.Path(path), defaultDirPerm); err != nil {
+ return err
+ }
+ if resources.Network != nil && resources.Network.ClassID != nil && *resources.Network.ClassID > 0 {
+ return retryingWriteFile(
+ filepath.Join(n.Path(path), "net_cls.classid"),
+ []byte(strconv.FormatUint(uint64(*resources.Network.ClassID), 10)),
+ defaultFilePerm,
+ )
+ }
+ return nil
+}
+
+func (n *netclsController) Update(path string, resources *specs.LinuxResources) error {
+ return n.Create(path, resources)
+}
diff --git a/vendor/github.com/containerd/cgroups/net_prio.go b/vendor/github.com/containerd/cgroups/net_prio.go
@@ -0,0 +1,65 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+func NewNetPrio(root string) *netprioController {
+ return &netprioController{
+ root: filepath.Join(root, string(NetPrio)),
+ }
+}
+
+type netprioController struct {
+ root string
+}
+
+func (n *netprioController) Name() Name {
+ return NetPrio
+}
+
+func (n *netprioController) Path(path string) string {
+ return filepath.Join(n.root, path)
+}
+
+func (n *netprioController) Create(path string, resources *specs.LinuxResources) error {
+ if err := os.MkdirAll(n.Path(path), defaultDirPerm); err != nil {
+ return err
+ }
+ if resources.Network != nil {
+ for _, prio := range resources.Network.Priorities {
+ if err := retryingWriteFile(
+ filepath.Join(n.Path(path), "net_prio.ifpriomap"),
+ formatPrio(prio.Name, prio.Priority),
+ defaultFilePerm,
+ ); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func formatPrio(name string, prio uint32) []byte {
+ return []byte(fmt.Sprintf("%s %d", name, prio))
+}
diff --git a/vendor/github.com/containerd/cgroups/opts.go b/vendor/github.com/containerd/cgroups/opts.go
@@ -0,0 +1,61 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "errors"
+)
+
+var (
+ // ErrIgnoreSubsystem allows the specific subsystem to be skipped
+ ErrIgnoreSubsystem = errors.New("skip subsystem")
+ // ErrDevicesRequired is returned when the devices subsystem is required but
+ // does not exist or is not active
+ ErrDevicesRequired = errors.New("devices subsystem is required")
+)
+
+// InitOpts allows configuration for the creation or loading of a cgroup
+type InitOpts func(*InitConfig) error
+
+// InitConfig provides configuration options for the creation
+// or loading of a cgroup and its subsystems
+type InitConfig struct {
+ // InitCheck can be used to check initialization errors from the subsystem
+ InitCheck InitCheck
+}
+
+func newInitConfig() *InitConfig {
+ return &InitConfig{
+ InitCheck: RequireDevices,
+ }
+}
+
+// InitCheck allows subsystems errors to be checked when initialized or loaded
+type InitCheck func(Subsystem, Path, error) error
+
+// AllowAny allows any subsystem errors to be skipped
+func AllowAny(_ Subsystem, _ Path, _ error) error {
+ return ErrIgnoreSubsystem
+}
+
+// RequireDevices requires the device subsystem but no others
+func RequireDevices(s Subsystem, _ Path, _ error) error {
+ if s.Name() == Devices {
+ return ErrDevicesRequired
+ }
+ return ErrIgnoreSubsystem
+}
diff --git a/vendor/github.com/containerd/cgroups/paths.go b/vendor/github.com/containerd/cgroups/paths.go
@@ -0,0 +1,106 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "errors"
+ "fmt"
+ "path/filepath"
+)
+
+type Path func(subsystem Name) (string, error)
+
+func RootPath(subsystem Name) (string, error) {
+ return "/", nil
+}
+
+// StaticPath returns a static path to use for all cgroups
+func StaticPath(path string) Path {
+ return func(_ Name) (string, error) {
+ return path, nil
+ }
+}
+
+// NestedPath will nest the cgroups based on the calling processes cgroup
+// placing its child processes inside its own path
+func NestedPath(suffix string) Path {
+ paths, err := ParseCgroupFile("/proc/self/cgroup")
+ if err != nil {
+ return errorPath(err)
+ }
+ return existingPath(paths, suffix)
+}
+
+// PidPath will return the correct cgroup paths for an existing process running inside a cgroup
+// This is commonly used for the Load function to restore an existing container
+func PidPath(pid int) Path {
+ p := fmt.Sprintf("/proc/%d/cgroup", pid)
+ paths, err := ParseCgroupFile(p)
+ if err != nil {
+ return errorPath(fmt.Errorf("parse cgroup file %s: %w", p, err))
+ }
+ return existingPath(paths, "")
+}
+
+// ErrControllerNotActive is returned when a controller is not supported or enabled
+var ErrControllerNotActive = errors.New("controller is not supported")
+
+func existingPath(paths map[string]string, suffix string) Path {
+ // localize the paths based on the root mount dest for nested cgroups
+ for n, p := range paths {
+ dest, err := getCgroupDestination(n)
+ if err != nil {
+ return errorPath(err)
+ }
+ rel, err := filepath.Rel(dest, p)
+ if err != nil {
+ return errorPath(err)
+ }
+ if rel == "." {
+ rel = dest
+ }
+ paths[n] = filepath.Join("/", rel)
+ }
+ return func(name Name) (string, error) {
+ root, ok := paths[string(name)]
+ if !ok {
+ if root, ok = paths["name="+string(name)]; !ok {
+ return "", ErrControllerNotActive
+ }
+ }
+ if suffix != "" {
+ return filepath.Join(root, suffix), nil
+ }
+ return root, nil
+ }
+}
+
+func subPath(path Path, subName string) Path {
+ return func(name Name) (string, error) {
+ p, err := path(name)
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(p, subName), nil
+ }
+}
+
+func errorPath(err error) Path {
+ return func(_ Name) (string, error) {
+ return "", err
+ }
+}
diff --git a/vendor/github.com/containerd/cgroups/perf_event.go b/vendor/github.com/containerd/cgroups/perf_event.go
@@ -0,0 +1,37 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import "path/filepath"
+
+func NewPerfEvent(root string) *PerfEventController {
+ return &PerfEventController{
+ root: filepath.Join(root, string(PerfEvent)),
+ }
+}
+
+type PerfEventController struct {
+ root string
+}
+
+func (p *PerfEventController) Name() Name {
+ return PerfEvent
+}
+
+func (p *PerfEventController) Path(path string) string {
+ return filepath.Join(p.root, path)
+}
diff --git a/vendor/github.com/containerd/cgroups/pids.go b/vendor/github.com/containerd/cgroups/pids.go
@@ -0,0 +1,86 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ v1 "github.com/containerd/cgroups/stats/v1"
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+func NewPids(root string) *pidsController {
+ return &pidsController{
+ root: filepath.Join(root, string(Pids)),
+ }
+}
+
+type pidsController struct {
+ root string
+}
+
+func (p *pidsController) Name() Name {
+ return Pids
+}
+
+func (p *pidsController) Path(path string) string {
+ return filepath.Join(p.root, path)
+}
+
+func (p *pidsController) Create(path string, resources *specs.LinuxResources) error {
+ if err := os.MkdirAll(p.Path(path), defaultDirPerm); err != nil {
+ return err
+ }
+ if resources.Pids != nil && resources.Pids.Limit > 0 {
+ return retryingWriteFile(
+ filepath.Join(p.Path(path), "pids.max"),
+ []byte(strconv.FormatInt(resources.Pids.Limit, 10)),
+ defaultFilePerm,
+ )
+ }
+ return nil
+}
+
+func (p *pidsController) Update(path string, resources *specs.LinuxResources) error {
+ return p.Create(path, resources)
+}
+
+func (p *pidsController) Stat(path string, stats *v1.Metrics) error {
+ current, err := readUint(filepath.Join(p.Path(path), "pids.current"))
+ if err != nil {
+ return err
+ }
+ var max uint64
+ maxData, err := ioutil.ReadFile(filepath.Join(p.Path(path), "pids.max"))
+ if err != nil {
+ return err
+ }
+ if maxS := strings.TrimSpace(string(maxData)); maxS != "max" {
+ if max, err = parseUint(maxS, 10, 64); err != nil {
+ return err
+ }
+ }
+ stats.Pids = &v1.PidsStat{
+ Current: current,
+ Limit: max,
+ }
+ return nil
+}
diff --git a/vendor/github.com/containerd/cgroups/rdma.go b/vendor/github.com/containerd/cgroups/rdma.go
@@ -0,0 +1,155 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "io/ioutil"
+ "math"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ v1 "github.com/containerd/cgroups/stats/v1"
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+type rdmaController struct {
+ root string
+}
+
+func (p *rdmaController) Name() Name {
+ return Rdma
+}
+
+func (p *rdmaController) Path(path string) string {
+ return filepath.Join(p.root, path)
+}
+
+func NewRdma(root string) *rdmaController {
+ return &rdmaController{
+ root: filepath.Join(root, string(Rdma)),
+ }
+}
+
+func createCmdString(device string, limits *specs.LinuxRdma) string {
+ var cmdString string
+
+ cmdString = device
+ if limits.HcaHandles != nil {
+ cmdString = cmdString + " " + "hca_handle=" + strconv.FormatUint(uint64(*limits.HcaHandles), 10)
+ }
+
+ if limits.HcaObjects != nil {
+ cmdString = cmdString + " " + "hca_object=" + strconv.FormatUint(uint64(*limits.HcaObjects), 10)
+ }
+ return cmdString
+}
+
+func (p *rdmaController) Create(path string, resources *specs.LinuxResources) error {
+ if err := os.MkdirAll(p.Path(path), defaultDirPerm); err != nil {
+ return err
+ }
+
+ for device, limit := range resources.Rdma {
+ if device != "" && (limit.HcaHandles != nil || limit.HcaObjects != nil) {
+ limit := limit
+ return retryingWriteFile(
+ filepath.Join(p.Path(path), "rdma.max"),
+ []byte(createCmdString(device, &limit)),
+ defaultFilePerm,
+ )
+ }
+ }
+ return nil
+}
+
+func (p *rdmaController) Update(path string, resources *specs.LinuxResources) error {
+ return p.Create(path, resources)
+}
+
+func parseRdmaKV(raw string, entry *v1.RdmaEntry) {
+ var value uint64
+ var err error
+
+ parts := strings.Split(raw, "=")
+ switch len(parts) {
+ case 2:
+ if parts[1] == "max" {
+ value = math.MaxUint32
+ } else {
+ value, err = parseUint(parts[1], 10, 32)
+ if err != nil {
+ return
+ }
+ }
+ if parts[0] == "hca_handle" {
+ entry.HcaHandles = uint32(value)
+ } else if parts[0] == "hca_object" {
+ entry.HcaObjects = uint32(value)
+ }
+ }
+}
+
+func toRdmaEntry(strEntries []string) []*v1.RdmaEntry {
+ var rdmaEntries []*v1.RdmaEntry
+ for i := range strEntries {
+ parts := strings.Fields(strEntries[i])
+ switch len(parts) {
+ case 3:
+ entry := new(v1.RdmaEntry)
+ entry.Device = parts[0]
+ parseRdmaKV(parts[1], entry)
+ parseRdmaKV(parts[2], entry)
+
+ rdmaEntries = append(rdmaEntries, entry)
+ default:
+ continue
+ }
+ }
+ return rdmaEntries
+}
+
+func (p *rdmaController) Stat(path string, stats *v1.Metrics) error {
+
+ currentData, err := ioutil.ReadFile(filepath.Join(p.Path(path), "rdma.current"))
+ if err != nil {
+ return err
+ }
+ currentPerDevices := strings.Split(string(currentData), "\n")
+
+ maxData, err := ioutil.ReadFile(filepath.Join(p.Path(path), "rdma.max"))
+ if err != nil {
+ return err
+ }
+ maxPerDevices := strings.Split(string(maxData), "\n")
+
+ // If device got removed between reading two files, ignore returning
+ // stats.
+ if len(currentPerDevices) != len(maxPerDevices) {
+ return nil
+ }
+
+ currentEntries := toRdmaEntry(currentPerDevices)
+ maxEntries := toRdmaEntry(maxPerDevices)
+
+ stats.Rdma = &v1.RdmaStat{
+ Current: currentEntries,
+ Limit: maxEntries,
+ }
+ return nil
+}
diff --git a/vendor/github.com/containerd/cgroups/state.go b/vendor/github.com/containerd/cgroups/state.go
@@ -0,0 +1,28 @@
+/*
+ Copyright The containerd 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 cgroups
+
+// State is a type that represents the state of the current cgroup
+type State string
+
+const (
+ Unknown State = ""
+ Thawed State = "thawed"
+ Frozen State = "frozen"
+ Freezing State = "freezing"
+ Deleted State = "deleted"
+)
diff --git a/vendor/github.com/containerd/cgroups/stats/v1/doc.go b/vendor/github.com/containerd/cgroups/stats/v1/doc.go
@@ -0,0 +1,17 @@
+/*
+ Copyright The containerd 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
diff --git a/vendor/github.com/containerd/cgroups/stats/v1/metrics.pb.go b/vendor/github.com/containerd/cgroups/stats/v1/metrics.pb.go
@@ -0,0 +1,6125 @@
+// Code generated by protoc-gen-gogo. DO NOT EDIT.
+// source: github.com/containerd/cgroups/stats/v1/metrics.proto
+
+package v1
+
+import (
+ fmt "fmt"
+ _ "github.com/gogo/protobuf/gogoproto"
+ proto "github.com/gogo/protobuf/proto"
+ io "io"
+ math "math"
+ math_bits "math/bits"
+ reflect "reflect"
+ strings "strings"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
+
+type Metrics struct {
+ Hugetlb []*HugetlbStat `protobuf:"bytes,1,rep,name=hugetlb,proto3" json:"hugetlb,omitempty"`
+ Pids *PidsStat `protobuf:"bytes,2,opt,name=pids,proto3" json:"pids,omitempty"`
+ CPU *CPUStat `protobuf:"bytes,3,opt,name=cpu,proto3" json:"cpu,omitempty"`
+ Memory *MemoryStat `protobuf:"bytes,4,opt,name=memory,proto3" json:"memory,omitempty"`
+ Blkio *BlkIOStat `protobuf:"bytes,5,opt,name=blkio,proto3" json:"blkio,omitempty"`
+ Rdma *RdmaStat `protobuf:"bytes,6,opt,name=rdma,proto3" json:"rdma,omitempty"`
+ Network []*NetworkStat `protobuf:"bytes,7,rep,name=network,proto3" json:"network,omitempty"`
+ CgroupStats *CgroupStats `protobuf:"bytes,8,opt,name=cgroup_stats,json=cgroupStats,proto3" json:"cgroup_stats,omitempty"`
+ MemoryOomControl *MemoryOomControl `protobuf:"bytes,9,opt,name=memory_oom_control,json=memoryOomControl,proto3" json:"memory_oom_control,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Metrics) Reset() { *m = Metrics{} }
+func (*Metrics) ProtoMessage() {}
+func (*Metrics) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{0}
+}
+func (m *Metrics) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *Metrics) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_Metrics.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *Metrics) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Metrics.Merge(m, src)
+}
+func (m *Metrics) XXX_Size() int {
+ return m.Size()
+}
+func (m *Metrics) XXX_DiscardUnknown() {
+ xxx_messageInfo_Metrics.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Metrics proto.InternalMessageInfo
+
+type HugetlbStat struct {
+ Usage uint64 `protobuf:"varint,1,opt,name=usage,proto3" json:"usage,omitempty"`
+ Max uint64 `protobuf:"varint,2,opt,name=max,proto3" json:"max,omitempty"`
+ Failcnt uint64 `protobuf:"varint,3,opt,name=failcnt,proto3" json:"failcnt,omitempty"`
+ Pagesize string `protobuf:"bytes,4,opt,name=pagesize,proto3" json:"pagesize,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *HugetlbStat) Reset() { *m = HugetlbStat{} }
+func (*HugetlbStat) ProtoMessage() {}
+func (*HugetlbStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{1}
+}
+func (m *HugetlbStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *HugetlbStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_HugetlbStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *HugetlbStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_HugetlbStat.Merge(m, src)
+}
+func (m *HugetlbStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *HugetlbStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_HugetlbStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_HugetlbStat proto.InternalMessageInfo
+
+type PidsStat struct {
+ Current uint64 `protobuf:"varint,1,opt,name=current,proto3" json:"current,omitempty"`
+ Limit uint64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *PidsStat) Reset() { *m = PidsStat{} }
+func (*PidsStat) ProtoMessage() {}
+func (*PidsStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{2}
+}
+func (m *PidsStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *PidsStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_PidsStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *PidsStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_PidsStat.Merge(m, src)
+}
+func (m *PidsStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *PidsStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_PidsStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_PidsStat proto.InternalMessageInfo
+
+type CPUStat struct {
+ Usage *CPUUsage `protobuf:"bytes,1,opt,name=usage,proto3" json:"usage,omitempty"`
+ Throttling *Throttle `protobuf:"bytes,2,opt,name=throttling,proto3" json:"throttling,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *CPUStat) Reset() { *m = CPUStat{} }
+func (*CPUStat) ProtoMessage() {}
+func (*CPUStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{3}
+}
+func (m *CPUStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *CPUStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_CPUStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *CPUStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_CPUStat.Merge(m, src)
+}
+func (m *CPUStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *CPUStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_CPUStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CPUStat proto.InternalMessageInfo
+
+type CPUUsage struct {
+ // values in nanoseconds
+ Total uint64 `protobuf:"varint,1,opt,name=total,proto3" json:"total,omitempty"`
+ Kernel uint64 `protobuf:"varint,2,opt,name=kernel,proto3" json:"kernel,omitempty"`
+ User uint64 `protobuf:"varint,3,opt,name=user,proto3" json:"user,omitempty"`
+ PerCPU []uint64 `protobuf:"varint,4,rep,packed,name=per_cpu,json=perCpu,proto3" json:"per_cpu,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *CPUUsage) Reset() { *m = CPUUsage{} }
+func (*CPUUsage) ProtoMessage() {}
+func (*CPUUsage) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{4}
+}
+func (m *CPUUsage) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *CPUUsage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_CPUUsage.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *CPUUsage) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_CPUUsage.Merge(m, src)
+}
+func (m *CPUUsage) XXX_Size() int {
+ return m.Size()
+}
+func (m *CPUUsage) XXX_DiscardUnknown() {
+ xxx_messageInfo_CPUUsage.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CPUUsage proto.InternalMessageInfo
+
+type Throttle struct {
+ Periods uint64 `protobuf:"varint,1,opt,name=periods,proto3" json:"periods,omitempty"`
+ ThrottledPeriods uint64 `protobuf:"varint,2,opt,name=throttled_periods,json=throttledPeriods,proto3" json:"throttled_periods,omitempty"`
+ ThrottledTime uint64 `protobuf:"varint,3,opt,name=throttled_time,json=throttledTime,proto3" json:"throttled_time,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Throttle) Reset() { *m = Throttle{} }
+func (*Throttle) ProtoMessage() {}
+func (*Throttle) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{5}
+}
+func (m *Throttle) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *Throttle) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_Throttle.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *Throttle) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Throttle.Merge(m, src)
+}
+func (m *Throttle) XXX_Size() int {
+ return m.Size()
+}
+func (m *Throttle) XXX_DiscardUnknown() {
+ xxx_messageInfo_Throttle.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Throttle proto.InternalMessageInfo
+
+type MemoryStat struct {
+ Cache uint64 `protobuf:"varint,1,opt,name=cache,proto3" json:"cache,omitempty"`
+ RSS uint64 `protobuf:"varint,2,opt,name=rss,proto3" json:"rss,omitempty"`
+ RSSHuge uint64 `protobuf:"varint,3,opt,name=rss_huge,json=rssHuge,proto3" json:"rss_huge,omitempty"`
+ MappedFile uint64 `protobuf:"varint,4,opt,name=mapped_file,json=mappedFile,proto3" json:"mapped_file,omitempty"`
+ Dirty uint64 `protobuf:"varint,5,opt,name=dirty,proto3" json:"dirty,omitempty"`
+ Writeback uint64 `protobuf:"varint,6,opt,name=writeback,proto3" json:"writeback,omitempty"`
+ PgPgIn uint64 `protobuf:"varint,7,opt,name=pg_pg_in,json=pgPgIn,proto3" json:"pg_pg_in,omitempty"`
+ PgPgOut uint64 `protobuf:"varint,8,opt,name=pg_pg_out,json=pgPgOut,proto3" json:"pg_pg_out,omitempty"`
+ PgFault uint64 `protobuf:"varint,9,opt,name=pg_fault,json=pgFault,proto3" json:"pg_fault,omitempty"`
+ PgMajFault uint64 `protobuf:"varint,10,opt,name=pg_maj_fault,json=pgMajFault,proto3" json:"pg_maj_fault,omitempty"`
+ InactiveAnon uint64 `protobuf:"varint,11,opt,name=inactive_anon,json=inactiveAnon,proto3" json:"inactive_anon,omitempty"`
+ ActiveAnon uint64 `protobuf:"varint,12,opt,name=active_anon,json=activeAnon,proto3" json:"active_anon,omitempty"`
+ InactiveFile uint64 `protobuf:"varint,13,opt,name=inactive_file,json=inactiveFile,proto3" json:"inactive_file,omitempty"`
+ ActiveFile uint64 `protobuf:"varint,14,opt,name=active_file,json=activeFile,proto3" json:"active_file,omitempty"`
+ Unevictable uint64 `protobuf:"varint,15,opt,name=unevictable,proto3" json:"unevictable,omitempty"`
+ HierarchicalMemoryLimit uint64 `protobuf:"varint,16,opt,name=hierarchical_memory_limit,json=hierarchicalMemoryLimit,proto3" json:"hierarchical_memory_limit,omitempty"`
+ HierarchicalSwapLimit uint64 `protobuf:"varint,17,opt,name=hierarchical_swap_limit,json=hierarchicalSwapLimit,proto3" json:"hierarchical_swap_limit,omitempty"`
+ TotalCache uint64 `protobuf:"varint,18,opt,name=total_cache,json=totalCache,proto3" json:"total_cache,omitempty"`
+ TotalRSS uint64 `protobuf:"varint,19,opt,name=total_rss,json=totalRss,proto3" json:"total_rss,omitempty"`
+ TotalRSSHuge uint64 `protobuf:"varint,20,opt,name=total_rss_huge,json=totalRssHuge,proto3" json:"total_rss_huge,omitempty"`
+ TotalMappedFile uint64 `protobuf:"varint,21,opt,name=total_mapped_file,json=totalMappedFile,proto3" json:"total_mapped_file,omitempty"`
+ TotalDirty uint64 `protobuf:"varint,22,opt,name=total_dirty,json=totalDirty,proto3" json:"total_dirty,omitempty"`
+ TotalWriteback uint64 `protobuf:"varint,23,opt,name=total_writeback,json=totalWriteback,proto3" json:"total_writeback,omitempty"`
+ TotalPgPgIn uint64 `protobuf:"varint,24,opt,name=total_pg_pg_in,json=totalPgPgIn,proto3" json:"total_pg_pg_in,omitempty"`
+ TotalPgPgOut uint64 `protobuf:"varint,25,opt,name=total_pg_pg_out,json=totalPgPgOut,proto3" json:"total_pg_pg_out,omitempty"`
+ TotalPgFault uint64 `protobuf:"varint,26,opt,name=total_pg_fault,json=totalPgFault,proto3" json:"total_pg_fault,omitempty"`
+ TotalPgMajFault uint64 `protobuf:"varint,27,opt,name=total_pg_maj_fault,json=totalPgMajFault,proto3" json:"total_pg_maj_fault,omitempty"`
+ TotalInactiveAnon uint64 `protobuf:"varint,28,opt,name=total_inactive_anon,json=totalInactiveAnon,proto3" json:"total_inactive_anon,omitempty"`
+ TotalActiveAnon uint64 `protobuf:"varint,29,opt,name=total_active_anon,json=totalActiveAnon,proto3" json:"total_active_anon,omitempty"`
+ TotalInactiveFile uint64 `protobuf:"varint,30,opt,name=total_inactive_file,json=totalInactiveFile,proto3" json:"total_inactive_file,omitempty"`
+ TotalActiveFile uint64 `protobuf:"varint,31,opt,name=total_active_file,json=totalActiveFile,proto3" json:"total_active_file,omitempty"`
+ TotalUnevictable uint64 `protobuf:"varint,32,opt,name=total_unevictable,json=totalUnevictable,proto3" json:"total_unevictable,omitempty"`
+ Usage *MemoryEntry `protobuf:"bytes,33,opt,name=usage,proto3" json:"usage,omitempty"`
+ Swap *MemoryEntry `protobuf:"bytes,34,opt,name=swap,proto3" json:"swap,omitempty"`
+ Kernel *MemoryEntry `protobuf:"bytes,35,opt,name=kernel,proto3" json:"kernel,omitempty"`
+ KernelTCP *MemoryEntry `protobuf:"bytes,36,opt,name=kernel_tcp,json=kernelTcp,proto3" json:"kernel_tcp,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *MemoryStat) Reset() { *m = MemoryStat{} }
+func (*MemoryStat) ProtoMessage() {}
+func (*MemoryStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{6}
+}
+func (m *MemoryStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *MemoryStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_MemoryStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *MemoryStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MemoryStat.Merge(m, src)
+}
+func (m *MemoryStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *MemoryStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_MemoryStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_MemoryStat proto.InternalMessageInfo
+
+type MemoryEntry struct {
+ Limit uint64 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"`
+ Usage uint64 `protobuf:"varint,2,opt,name=usage,proto3" json:"usage,omitempty"`
+ Max uint64 `protobuf:"varint,3,opt,name=max,proto3" json:"max,omitempty"`
+ Failcnt uint64 `protobuf:"varint,4,opt,name=failcnt,proto3" json:"failcnt,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *MemoryEntry) Reset() { *m = MemoryEntry{} }
+func (*MemoryEntry) ProtoMessage() {}
+func (*MemoryEntry) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{7}
+}
+func (m *MemoryEntry) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *MemoryEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_MemoryEntry.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *MemoryEntry) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MemoryEntry.Merge(m, src)
+}
+func (m *MemoryEntry) XXX_Size() int {
+ return m.Size()
+}
+func (m *MemoryEntry) XXX_DiscardUnknown() {
+ xxx_messageInfo_MemoryEntry.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_MemoryEntry proto.InternalMessageInfo
+
+type MemoryOomControl struct {
+ OomKillDisable uint64 `protobuf:"varint,1,opt,name=oom_kill_disable,json=oomKillDisable,proto3" json:"oom_kill_disable,omitempty"`
+ UnderOom uint64 `protobuf:"varint,2,opt,name=under_oom,json=underOom,proto3" json:"under_oom,omitempty"`
+ OomKill uint64 `protobuf:"varint,3,opt,name=oom_kill,json=oomKill,proto3" json:"oom_kill,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *MemoryOomControl) Reset() { *m = MemoryOomControl{} }
+func (*MemoryOomControl) ProtoMessage() {}
+func (*MemoryOomControl) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{8}
+}
+func (m *MemoryOomControl) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *MemoryOomControl) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_MemoryOomControl.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *MemoryOomControl) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MemoryOomControl.Merge(m, src)
+}
+func (m *MemoryOomControl) XXX_Size() int {
+ return m.Size()
+}
+func (m *MemoryOomControl) XXX_DiscardUnknown() {
+ xxx_messageInfo_MemoryOomControl.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_MemoryOomControl proto.InternalMessageInfo
+
+type BlkIOStat struct {
+ IoServiceBytesRecursive []*BlkIOEntry `protobuf:"bytes,1,rep,name=io_service_bytes_recursive,json=ioServiceBytesRecursive,proto3" json:"io_service_bytes_recursive,omitempty"`
+ IoServicedRecursive []*BlkIOEntry `protobuf:"bytes,2,rep,name=io_serviced_recursive,json=ioServicedRecursive,proto3" json:"io_serviced_recursive,omitempty"`
+ IoQueuedRecursive []*BlkIOEntry `protobuf:"bytes,3,rep,name=io_queued_recursive,json=ioQueuedRecursive,proto3" json:"io_queued_recursive,omitempty"`
+ IoServiceTimeRecursive []*BlkIOEntry `protobuf:"bytes,4,rep,name=io_service_time_recursive,json=ioServiceTimeRecursive,proto3" json:"io_service_time_recursive,omitempty"`
+ IoWaitTimeRecursive []*BlkIOEntry `protobuf:"bytes,5,rep,name=io_wait_time_recursive,json=ioWaitTimeRecursive,proto3" json:"io_wait_time_recursive,omitempty"`
+ IoMergedRecursive []*BlkIOEntry `protobuf:"bytes,6,rep,name=io_merged_recursive,json=ioMergedRecursive,proto3" json:"io_merged_recursive,omitempty"`
+ IoTimeRecursive []*BlkIOEntry `protobuf:"bytes,7,rep,name=io_time_recursive,json=ioTimeRecursive,proto3" json:"io_time_recursive,omitempty"`
+ SectorsRecursive []*BlkIOEntry `protobuf:"bytes,8,rep,name=sectors_recursive,json=sectorsRecursive,proto3" json:"sectors_recursive,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *BlkIOStat) Reset() { *m = BlkIOStat{} }
+func (*BlkIOStat) ProtoMessage() {}
+func (*BlkIOStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{9}
+}
+func (m *BlkIOStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *BlkIOStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_BlkIOStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *BlkIOStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_BlkIOStat.Merge(m, src)
+}
+func (m *BlkIOStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *BlkIOStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_BlkIOStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_BlkIOStat proto.InternalMessageInfo
+
+type BlkIOEntry struct {
+ Op string `protobuf:"bytes,1,opt,name=op,proto3" json:"op,omitempty"`
+ Device string `protobuf:"bytes,2,opt,name=device,proto3" json:"device,omitempty"`
+ Major uint64 `protobuf:"varint,3,opt,name=major,proto3" json:"major,omitempty"`
+ Minor uint64 `protobuf:"varint,4,opt,name=minor,proto3" json:"minor,omitempty"`
+ Value uint64 `protobuf:"varint,5,opt,name=value,proto3" json:"value,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *BlkIOEntry) Reset() { *m = BlkIOEntry{} }
+func (*BlkIOEntry) ProtoMessage() {}
+func (*BlkIOEntry) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{10}
+}
+func (m *BlkIOEntry) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *BlkIOEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_BlkIOEntry.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *BlkIOEntry) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_BlkIOEntry.Merge(m, src)
+}
+func (m *BlkIOEntry) XXX_Size() int {
+ return m.Size()
+}
+func (m *BlkIOEntry) XXX_DiscardUnknown() {
+ xxx_messageInfo_BlkIOEntry.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_BlkIOEntry proto.InternalMessageInfo
+
+type RdmaStat struct {
+ Current []*RdmaEntry `protobuf:"bytes,1,rep,name=current,proto3" json:"current,omitempty"`
+ Limit []*RdmaEntry `protobuf:"bytes,2,rep,name=limit,proto3" json:"limit,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *RdmaStat) Reset() { *m = RdmaStat{} }
+func (*RdmaStat) ProtoMessage() {}
+func (*RdmaStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{11}
+}
+func (m *RdmaStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *RdmaStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_RdmaStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *RdmaStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_RdmaStat.Merge(m, src)
+}
+func (m *RdmaStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *RdmaStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_RdmaStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_RdmaStat proto.InternalMessageInfo
+
+type RdmaEntry struct {
+ Device string `protobuf:"bytes,1,opt,name=device,proto3" json:"device,omitempty"`
+ HcaHandles uint32 `protobuf:"varint,2,opt,name=hca_handles,json=hcaHandles,proto3" json:"hca_handles,omitempty"`
+ HcaObjects uint32 `protobuf:"varint,3,opt,name=hca_objects,json=hcaObjects,proto3" json:"hca_objects,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *RdmaEntry) Reset() { *m = RdmaEntry{} }
+func (*RdmaEntry) ProtoMessage() {}
+func (*RdmaEntry) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{12}
+}
+func (m *RdmaEntry) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *RdmaEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_RdmaEntry.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *RdmaEntry) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_RdmaEntry.Merge(m, src)
+}
+func (m *RdmaEntry) XXX_Size() int {
+ return m.Size()
+}
+func (m *RdmaEntry) XXX_DiscardUnknown() {
+ xxx_messageInfo_RdmaEntry.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_RdmaEntry proto.InternalMessageInfo
+
+type NetworkStat struct {
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ RxBytes uint64 `protobuf:"varint,2,opt,name=rx_bytes,json=rxBytes,proto3" json:"rx_bytes,omitempty"`
+ RxPackets uint64 `protobuf:"varint,3,opt,name=rx_packets,json=rxPackets,proto3" json:"rx_packets,omitempty"`
+ RxErrors uint64 `protobuf:"varint,4,opt,name=rx_errors,json=rxErrors,proto3" json:"rx_errors,omitempty"`
+ RxDropped uint64 `protobuf:"varint,5,opt,name=rx_dropped,json=rxDropped,proto3" json:"rx_dropped,omitempty"`
+ TxBytes uint64 `protobuf:"varint,6,opt,name=tx_bytes,json=txBytes,proto3" json:"tx_bytes,omitempty"`
+ TxPackets uint64 `protobuf:"varint,7,opt,name=tx_packets,json=txPackets,proto3" json:"tx_packets,omitempty"`
+ TxErrors uint64 `protobuf:"varint,8,opt,name=tx_errors,json=txErrors,proto3" json:"tx_errors,omitempty"`
+ TxDropped uint64 `protobuf:"varint,9,opt,name=tx_dropped,json=txDropped,proto3" json:"tx_dropped,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *NetworkStat) Reset() { *m = NetworkStat{} }
+func (*NetworkStat) ProtoMessage() {}
+func (*NetworkStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{13}
+}
+func (m *NetworkStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *NetworkStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_NetworkStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *NetworkStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_NetworkStat.Merge(m, src)
+}
+func (m *NetworkStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *NetworkStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_NetworkStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_NetworkStat proto.InternalMessageInfo
+
+// CgroupStats exports per-cgroup statistics.
+type CgroupStats struct {
+ // number of tasks sleeping
+ NrSleeping uint64 `protobuf:"varint,1,opt,name=nr_sleeping,json=nrSleeping,proto3" json:"nr_sleeping,omitempty"`
+ // number of tasks running
+ NrRunning uint64 `protobuf:"varint,2,opt,name=nr_running,json=nrRunning,proto3" json:"nr_running,omitempty"`
+ // number of tasks in stopped state
+ NrStopped uint64 `protobuf:"varint,3,opt,name=nr_stopped,json=nrStopped,proto3" json:"nr_stopped,omitempty"`
+ // number of tasks in uninterruptible state
+ NrUninterruptible uint64 `protobuf:"varint,4,opt,name=nr_uninterruptible,json=nrUninterruptible,proto3" json:"nr_uninterruptible,omitempty"`
+ // number of tasks waiting on IO
+ NrIoWait uint64 `protobuf:"varint,5,opt,name=nr_io_wait,json=nrIoWait,proto3" json:"nr_io_wait,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *CgroupStats) Reset() { *m = CgroupStats{} }
+func (*CgroupStats) ProtoMessage() {}
+func (*CgroupStats) Descriptor() ([]byte, []int) {
+ return fileDescriptor_a17b2d87c332bfaa, []int{14}
+}
+func (m *CgroupStats) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *CgroupStats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_CgroupStats.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *CgroupStats) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_CgroupStats.Merge(m, src)
+}
+func (m *CgroupStats) XXX_Size() int {
+ return m.Size()
+}
+func (m *CgroupStats) XXX_DiscardUnknown() {
+ xxx_messageInfo_CgroupStats.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CgroupStats proto.InternalMessageInfo
+
+func init() {
+ proto.RegisterType((*Metrics)(nil), "io.containerd.cgroups.v1.Metrics")
+ proto.RegisterType((*HugetlbStat)(nil), "io.containerd.cgroups.v1.HugetlbStat")
+ proto.RegisterType((*PidsStat)(nil), "io.containerd.cgroups.v1.PidsStat")
+ proto.RegisterType((*CPUStat)(nil), "io.containerd.cgroups.v1.CPUStat")
+ proto.RegisterType((*CPUUsage)(nil), "io.containerd.cgroups.v1.CPUUsage")
+ proto.RegisterType((*Throttle)(nil), "io.containerd.cgroups.v1.Throttle")
+ proto.RegisterType((*MemoryStat)(nil), "io.containerd.cgroups.v1.MemoryStat")
+ proto.RegisterType((*MemoryEntry)(nil), "io.containerd.cgroups.v1.MemoryEntry")
+ proto.RegisterType((*MemoryOomControl)(nil), "io.containerd.cgroups.v1.MemoryOomControl")
+ proto.RegisterType((*BlkIOStat)(nil), "io.containerd.cgroups.v1.BlkIOStat")
+ proto.RegisterType((*BlkIOEntry)(nil), "io.containerd.cgroups.v1.BlkIOEntry")
+ proto.RegisterType((*RdmaStat)(nil), "io.containerd.cgroups.v1.RdmaStat")
+ proto.RegisterType((*RdmaEntry)(nil), "io.containerd.cgroups.v1.RdmaEntry")
+ proto.RegisterType((*NetworkStat)(nil), "io.containerd.cgroups.v1.NetworkStat")
+ proto.RegisterType((*CgroupStats)(nil), "io.containerd.cgroups.v1.CgroupStats")
+}
+
+func init() {
+ proto.RegisterFile("github.com/containerd/cgroups/stats/v1/metrics.proto", fileDescriptor_a17b2d87c332bfaa)
+}
+
+var fileDescriptor_a17b2d87c332bfaa = []byte{
+ // 1749 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x58, 0xcd, 0x72, 0xe3, 0xc6,
+ 0x11, 0x36, 0x45, 0x48, 0x24, 0x9a, 0x92, 0x56, 0x9a, 0xfd, 0x83, 0xe4, 0xb5, 0x28, 0x53, 0xbb,
+ 0x89, 0xe2, 0xad, 0x48, 0x65, 0x27, 0xb5, 0x95, 0x75, 0xec, 0x4a, 0x59, 0x5a, 0xbb, 0x76, 0xcb,
+ 0x51, 0x44, 0x83, 0x52, 0xd9, 0x39, 0xa1, 0x40, 0x70, 0x16, 0x9c, 0x15, 0x80, 0x81, 0x07, 0x03,
+ 0x89, 0xca, 0x29, 0x87, 0x54, 0xe5, 0x94, 0x07, 0xca, 0x1b, 0xf8, 0x98, 0x4b, 0x52, 0xc9, 0x45,
+ 0x15, 0xf3, 0x49, 0x52, 0x33, 0x3d, 0xf8, 0xa1, 0xbc, 0x5a, 0x85, 0x37, 0x76, 0xcf, 0xd7, 0x5f,
+ 0xf7, 0x34, 0xbe, 0x19, 0x34, 0x08, 0xbf, 0x0e, 0x99, 0x1c, 0xe7, 0xc3, 0xbd, 0x80, 0xc7, 0xfb,
+ 0x01, 0x4f, 0xa4, 0xcf, 0x12, 0x2a, 0x46, 0xfb, 0x41, 0x28, 0x78, 0x9e, 0x66, 0xfb, 0x99, 0xf4,
+ 0x65, 0xb6, 0x7f, 0xfe, 0xf1, 0x7e, 0x4c, 0xa5, 0x60, 0x41, 0xb6, 0x97, 0x0a, 0x2e, 0x39, 0x71,
+ 0x18, 0xdf, 0xab, 0xd0, 0x7b, 0x06, 0xbd, 0x77, 0xfe, 0xf1, 0xe6, 0xbd, 0x90, 0x87, 0x5c, 0x83,
+ 0xf6, 0xd5, 0x2f, 0xc4, 0xf7, 0xfe, 0x65, 0x41, 0xeb, 0x08, 0x19, 0xc8, 0xef, 0xa0, 0x35, 0xce,
+ 0x43, 0x2a, 0xa3, 0xa1, 0xd3, 0xd8, 0x6e, 0xee, 0x76, 0x3e, 0x79, 0xb2, 0x77, 0x13, 0xdb, 0xde,
+ 0x4b, 0x04, 0x0e, 0xa4, 0x2f, 0xdd, 0x22, 0x8a, 0x3c, 0x03, 0x2b, 0x65, 0xa3, 0xcc, 0x59, 0xd8,
+ 0x6e, 0xec, 0x76, 0x3e, 0xe9, 0xdd, 0x1c, 0xdd, 0x67, 0xa3, 0x4c, 0x87, 0x6a, 0x3c, 0xf9, 0x0c,
+ 0x9a, 0x41, 0x9a, 0x3b, 0x4d, 0x1d, 0xf6, 0xe1, 0xcd, 0x61, 0x87, 0xfd, 0x53, 0x15, 0x75, 0xd0,
+ 0x9a, 0x5e, 0x75, 0x9b, 0x87, 0xfd, 0x53, 0x57, 0x85, 0x91, 0xcf, 0x60, 0x29, 0xa6, 0x31, 0x17,
+ 0x97, 0x8e, 0xa5, 0x09, 0x1e, 0xdf, 0x4c, 0x70, 0xa4, 0x71, 0x3a, 0xb3, 0x89, 0x21, 0xcf, 0x61,
+ 0x71, 0x18, 0x9d, 0x31, 0xee, 0x2c, 0xea, 0xe0, 0x9d, 0x9b, 0x83, 0x0f, 0xa2, 0xb3, 0x57, 0xc7,
+ 0x3a, 0x16, 0x23, 0xd4, 0x76, 0xc5, 0x28, 0xf6, 0x9d, 0xa5, 0xdb, 0xb6, 0xeb, 0x8e, 0x62, 0x1f,
+ 0xb7, 0xab, 0xf0, 0xaa, 0xcf, 0x09, 0x95, 0x17, 0x5c, 0x9c, 0x39, 0xad, 0xdb, 0xfa, 0xfc, 0x07,
+ 0x04, 0x62, 0x9f, 0x4d, 0x14, 0x79, 0x09, 0xcb, 0x08, 0xf1, 0xb4, 0x0a, 0x9c, 0xb6, 0x2e, 0xe0,
+ 0x1d, 0x2c, 0x87, 0xfa, 0xa7, 0x22, 0xc9, 0xdc, 0x4e, 0x50, 0x19, 0xe4, 0x3b, 0x20, 0xd8, 0x07,
+ 0x8f, 0xf3, 0xd8, 0x53, 0xc1, 0x82, 0x47, 0x8e, 0xad, 0xf9, 0x3e, 0xba, 0xad, 0x8f, 0xc7, 0x3c,
+ 0x3e, 0xc4, 0x08, 0x77, 0x2d, 0xbe, 0xe6, 0xe9, 0x9d, 0x41, 0xa7, 0xa6, 0x11, 0x72, 0x0f, 0x16,
+ 0xf3, 0xcc, 0x0f, 0xa9, 0xd3, 0xd8, 0x6e, 0xec, 0x5a, 0x2e, 0x1a, 0x64, 0x0d, 0x9a, 0xb1, 0x3f,
+ 0xd1, 0x7a, 0xb1, 0x5c, 0xf5, 0x93, 0x38, 0xd0, 0x7a, 0xed, 0xb3, 0x28, 0x48, 0xa4, 0x96, 0x83,
+ 0xe5, 0x16, 0x26, 0xd9, 0x84, 0x76, 0xea, 0x87, 0x34, 0x63, 0x7f, 0xa2, 0xfa, 0x41, 0xdb, 0x6e,
+ 0x69, 0xf7, 0x3e, 0x85, 0x76, 0x21, 0x29, 0xc5, 0x10, 0xe4, 0x42, 0xd0, 0x44, 0x9a, 0x5c, 0x85,
+ 0xa9, 0x6a, 0x88, 0x58, 0xcc, 0xa4, 0xc9, 0x87, 0x46, 0xef, 0xaf, 0x0d, 0x68, 0x19, 0x61, 0x91,
+ 0xdf, 0xd4, 0xab, 0x7c, 0xe7, 0x23, 0x3d, 0xec, 0x9f, 0x9e, 0x2a, 0x64, 0xb1, 0x93, 0x03, 0x00,
+ 0x39, 0x16, 0x5c, 0xca, 0x88, 0x25, 0xe1, 0xed, 0x07, 0xe0, 0x04, 0xb1, 0xd4, 0xad, 0x45, 0xf5,
+ 0xbe, 0x87, 0x76, 0x41, 0xab, 0x6a, 0x95, 0x5c, 0xfa, 0x51, 0xd1, 0x2f, 0x6d, 0x90, 0x07, 0xb0,
+ 0x74, 0x46, 0x45, 0x42, 0x23, 0xb3, 0x05, 0x63, 0x11, 0x02, 0x56, 0x9e, 0x51, 0x61, 0x5a, 0xa6,
+ 0x7f, 0x93, 0x1d, 0x68, 0xa5, 0x54, 0x78, 0xea, 0x60, 0x59, 0xdb, 0xcd, 0x5d, 0xeb, 0x00, 0xa6,
+ 0x57, 0xdd, 0xa5, 0x3e, 0x15, 0xea, 0xe0, 0x2c, 0xa5, 0x54, 0x1c, 0xa6, 0x79, 0x6f, 0x02, 0xed,
+ 0xa2, 0x14, 0xd5, 0xb8, 0x94, 0x0a, 0xc6, 0x47, 0x59, 0xd1, 0x38, 0x63, 0x92, 0xa7, 0xb0, 0x6e,
+ 0xca, 0xa4, 0x23, 0xaf, 0xc0, 0x60, 0x05, 0x6b, 0xe5, 0x42, 0xdf, 0x80, 0x9f, 0xc0, 0x6a, 0x05,
+ 0x96, 0x2c, 0xa6, 0xa6, 0xaa, 0x95, 0xd2, 0x7b, 0xc2, 0x62, 0xda, 0xfb, 0x4f, 0x07, 0xa0, 0x3a,
+ 0x8e, 0x6a, 0xbf, 0x81, 0x1f, 0x8c, 0x4b, 0x7d, 0x68, 0x83, 0x6c, 0x40, 0x53, 0x64, 0x26, 0x15,
+ 0x9e, 0x7a, 0x77, 0x30, 0x70, 0x95, 0x8f, 0xfc, 0x0c, 0xda, 0x22, 0xcb, 0x3c, 0x75, 0xf5, 0x60,
+ 0x82, 0x83, 0xce, 0xf4, 0xaa, 0xdb, 0x72, 0x07, 0x03, 0x25, 0x3b, 0xb7, 0x25, 0xb2, 0x4c, 0xfd,
+ 0x20, 0x5d, 0xe8, 0xc4, 0x7e, 0x9a, 0xd2, 0x91, 0xf7, 0x9a, 0x45, 0xa8, 0x1c, 0xcb, 0x05, 0x74,
+ 0x7d, 0xc5, 0x22, 0xdd, 0xe9, 0x11, 0x13, 0xf2, 0x52, 0x5f, 0x00, 0x96, 0x8b, 0x06, 0x79, 0x04,
+ 0xf6, 0x85, 0x60, 0x92, 0x0e, 0xfd, 0xe0, 0x4c, 0x1f, 0x70, 0xcb, 0xad, 0x1c, 0xc4, 0x81, 0x76,
+ 0x1a, 0x7a, 0x69, 0xe8, 0xb1, 0xc4, 0x69, 0xe1, 0x93, 0x48, 0xc3, 0x7e, 0xf8, 0x2a, 0x21, 0x9b,
+ 0x60, 0xe3, 0x0a, 0xcf, 0xa5, 0x3e, 0x97, 0xaa, 0x8d, 0x61, 0x3f, 0x3c, 0xce, 0x25, 0xd9, 0xd0,
+ 0x51, 0xaf, 0xfd, 0x3c, 0x92, 0xfa, 0x88, 0xe9, 0xa5, 0xaf, 0x94, 0x49, 0xb6, 0x61, 0x39, 0x0d,
+ 0xbd, 0xd8, 0x7f, 0x63, 0x96, 0x01, 0xcb, 0x4c, 0xc3, 0x23, 0xff, 0x0d, 0x22, 0x76, 0x60, 0x85,
+ 0x25, 0x7e, 0x20, 0xd9, 0x39, 0xf5, 0xfc, 0x84, 0x27, 0x4e, 0x47, 0x43, 0x96, 0x0b, 0xe7, 0x17,
+ 0x09, 0x4f, 0xd4, 0x66, 0xeb, 0x90, 0x65, 0x64, 0xa9, 0x01, 0xea, 0x2c, 0xba, 0x1f, 0x2b, 0xb3,
+ 0x2c, 0xba, 0x23, 0x15, 0x8b, 0x86, 0xac, 0xd6, 0x59, 0x34, 0x60, 0x1b, 0x3a, 0x79, 0x42, 0xcf,
+ 0x59, 0x20, 0xfd, 0x61, 0x44, 0x9d, 0x3b, 0x1a, 0x50, 0x77, 0x91, 0x4f, 0x61, 0x63, 0xcc, 0xa8,
+ 0xf0, 0x45, 0x30, 0x66, 0x81, 0x1f, 0x79, 0xe6, 0x92, 0xc1, 0xe3, 0xb7, 0xa6, 0xf1, 0x0f, 0xeb,
+ 0x00, 0x54, 0xc2, 0xef, 0xd5, 0x32, 0x79, 0x06, 0x33, 0x4b, 0x5e, 0x76, 0xe1, 0xa7, 0x26, 0x72,
+ 0x5d, 0x47, 0xde, 0xaf, 0x2f, 0x0f, 0x2e, 0xfc, 0x14, 0xe3, 0xba, 0xd0, 0xd1, 0xa7, 0xc4, 0x43,
+ 0x21, 0x11, 0x2c, 0x5b, 0xbb, 0x0e, 0xb5, 0x9a, 0x7e, 0x01, 0x36, 0x02, 0x94, 0xa6, 0xee, 0x6a,
+ 0xcd, 0x2c, 0x4f, 0xaf, 0xba, 0xed, 0x13, 0xe5, 0x54, 0xc2, 0x6a, 0xeb, 0x65, 0x37, 0xcb, 0xc8,
+ 0x33, 0x58, 0x2d, 0xa1, 0xa8, 0xb1, 0x7b, 0x1a, 0xbf, 0x36, 0xbd, 0xea, 0x2e, 0x17, 0x78, 0x2d,
+ 0xb4, 0xe5, 0x22, 0x46, 0xab, 0xed, 0x23, 0x58, 0xc7, 0xb8, 0xba, 0xe6, 0xee, 0xeb, 0x4a, 0xee,
+ 0xe8, 0x85, 0xa3, 0x4a, 0x78, 0x65, 0xbd, 0x28, 0xbf, 0x07, 0xb5, 0x7a, 0x5f, 0x68, 0x0d, 0xfe,
+ 0x1c, 0x30, 0xc6, 0xab, 0x94, 0xf8, 0x50, 0x83, 0xb0, 0xb6, 0x6f, 0x4b, 0x39, 0xee, 0x14, 0xd5,
+ 0x96, 0xa2, 0x74, 0xf0, 0x91, 0x68, 0x6f, 0x1f, 0x95, 0xf9, 0xa4, 0x60, 0xab, 0xf4, 0xb9, 0x81,
+ 0x0f, 0xbf, 0x44, 0x29, 0x91, 0x3e, 0xae, 0x71, 0xa1, 0x16, 0x37, 0x67, 0x50, 0xa8, 0xc6, 0xa7,
+ 0x40, 0x4a, 0x54, 0xa5, 0xda, 0xf7, 0x6b, 0x1b, 0xed, 0x57, 0xd2, 0xdd, 0x83, 0xbb, 0x08, 0x9e,
+ 0x15, 0xf0, 0x23, 0x8d, 0xc6, 0x7e, 0xbd, 0xaa, 0xab, 0xb8, 0x6c, 0x62, 0x1d, 0xfd, 0x41, 0x8d,
+ 0xfb, 0x8b, 0x0a, 0xfb, 0x53, 0x6e, 0xdd, 0xf2, 0xad, 0xb7, 0x70, 0xeb, 0xa6, 0x5f, 0xe7, 0xd6,
+ 0xe8, 0xee, 0x4f, 0xb8, 0x35, 0xf6, 0x69, 0x81, 0xad, 0x8b, 0x7d, 0xdb, 0x5c, 0x7b, 0x6a, 0xe1,
+ 0xb4, 0xa6, 0xf8, 0xdf, 0x16, 0xaf, 0x8e, 0x0f, 0x6f, 0x7b, 0x19, 0xa3, 0xd6, 0xbf, 0x4c, 0xa4,
+ 0xb8, 0x2c, 0xde, 0x1e, 0xcf, 0xc1, 0x52, 0x2a, 0x77, 0x7a, 0xf3, 0xc4, 0xea, 0x10, 0xf2, 0x79,
+ 0xf9, 0x4a, 0xd8, 0x99, 0x27, 0xb8, 0x78, 0x73, 0x0c, 0x00, 0xf0, 0x97, 0x27, 0x83, 0xd4, 0x79,
+ 0x3c, 0x07, 0xc5, 0xc1, 0xca, 0xf4, 0xaa, 0x6b, 0x7f, 0xad, 0x83, 0x4f, 0x0e, 0xfb, 0xae, 0x8d,
+ 0x3c, 0x27, 0x41, 0xda, 0xa3, 0xd0, 0xa9, 0x01, 0xab, 0xf7, 0x6e, 0xa3, 0xf6, 0xde, 0xad, 0x26,
+ 0x82, 0x85, 0xb7, 0x4c, 0x04, 0xcd, 0xb7, 0x4e, 0x04, 0xd6, 0xcc, 0x44, 0xd0, 0x93, 0xb0, 0x76,
+ 0x7d, 0x10, 0x21, 0xbb, 0xb0, 0xa6, 0x26, 0x99, 0x33, 0x16, 0xa9, 0x73, 0x95, 0xe9, 0x47, 0x86,
+ 0x69, 0x57, 0x39, 0x8f, 0xbf, 0x66, 0x51, 0xf4, 0x02, 0xbd, 0xe4, 0x7d, 0xb0, 0xf3, 0x64, 0x44,
+ 0x85, 0x9a, 0x7c, 0x4c, 0x0d, 0x6d, 0xed, 0x38, 0xe6, 0xb1, 0xba, 0xaa, 0x0b, 0x9a, 0x62, 0x0e,
+ 0x31, 0xe1, 0xbd, 0x7f, 0x2e, 0x82, 0x5d, 0x8e, 0x82, 0xc4, 0x87, 0x4d, 0xc6, 0xbd, 0x8c, 0x8a,
+ 0x73, 0x16, 0x50, 0x6f, 0x78, 0x29, 0x69, 0xe6, 0x09, 0x1a, 0xe4, 0x22, 0x63, 0xe7, 0xd4, 0x8c,
+ 0xd1, 0x8f, 0x6f, 0x99, 0x29, 0xf1, 0x89, 0x3c, 0x64, 0x7c, 0x80, 0x34, 0x07, 0x8a, 0xc5, 0x2d,
+ 0x48, 0xc8, 0x77, 0x70, 0xbf, 0x4a, 0x31, 0xaa, 0xb1, 0x2f, 0xcc, 0xc1, 0x7e, 0xb7, 0x64, 0x1f,
+ 0x55, 0xcc, 0x27, 0x70, 0x97, 0x71, 0xef, 0xfb, 0x9c, 0xe6, 0x33, 0xbc, 0xcd, 0x39, 0x78, 0xd7,
+ 0x19, 0xff, 0x46, 0xc7, 0x57, 0xac, 0x1e, 0x6c, 0xd4, 0x5a, 0xa2, 0x26, 0x80, 0x1a, 0xb7, 0x35,
+ 0x07, 0xf7, 0x83, 0xb2, 0x66, 0x35, 0x31, 0x54, 0x09, 0xfe, 0x08, 0x0f, 0x18, 0xf7, 0x2e, 0x7c,
+ 0x26, 0xaf, 0xb3, 0x2f, 0xce, 0xd7, 0x91, 0x6f, 0x7d, 0x26, 0x67, 0xa9, 0xb1, 0x23, 0x31, 0x15,
+ 0xe1, 0x4c, 0x47, 0x96, 0xe6, 0xeb, 0xc8, 0x91, 0x8e, 0xaf, 0x58, 0xfb, 0xb0, 0xce, 0xf8, 0xf5,
+ 0x5a, 0x5b, 0x73, 0x70, 0xde, 0x61, 0x7c, 0xb6, 0xce, 0x6f, 0x60, 0x3d, 0xa3, 0x81, 0xe4, 0xa2,
+ 0xae, 0xb6, 0xf6, 0x1c, 0x8c, 0x6b, 0x26, 0xbc, 0xa4, 0xec, 0x9d, 0x03, 0x54, 0xeb, 0x64, 0x15,
+ 0x16, 0x78, 0xaa, 0x4f, 0x8e, 0xed, 0x2e, 0xf0, 0x54, 0x4d, 0x9e, 0x23, 0x75, 0xd9, 0xe1, 0x71,
+ 0xb5, 0x5d, 0x63, 0xa9, 0x53, 0x1c, 0xfb, 0x6f, 0x78, 0x31, 0x7a, 0xa2, 0xa1, 0xbd, 0x2c, 0xe1,
+ 0xc2, 0x9c, 0x58, 0x34, 0x94, 0xf7, 0xdc, 0x8f, 0x72, 0x5a, 0x4c, 0x5a, 0xda, 0xe8, 0xfd, 0xa5,
+ 0x01, 0xed, 0xe2, 0x03, 0x89, 0x7c, 0x5e, 0x1f, 0xde, 0x9b, 0xef, 0xfe, 0x1e, 0x53, 0x41, 0xb8,
+ 0x99, 0x72, 0xc2, 0x7f, 0x5e, 0x4d, 0xf8, 0xff, 0x77, 0xb0, 0xf9, 0x0c, 0xa0, 0x60, 0x97, 0xbe,
+ 0xda, 0x6e, 0x1b, 0x33, 0xbb, 0xed, 0x42, 0x67, 0x1c, 0xf8, 0xde, 0xd8, 0x4f, 0x46, 0x11, 0xc5,
+ 0xb9, 0x74, 0xc5, 0x85, 0x71, 0xe0, 0xbf, 0x44, 0x4f, 0x01, 0xe0, 0xc3, 0x37, 0x34, 0x90, 0x99,
+ 0x6e, 0x0a, 0x02, 0x8e, 0xd1, 0xd3, 0xfb, 0xdb, 0x02, 0x74, 0x6a, 0xdf, 0x74, 0x6a, 0x72, 0x4f,
+ 0xfc, 0xb8, 0xc8, 0xa3, 0x7f, 0xab, 0xcb, 0x47, 0x4c, 0xf0, 0x2e, 0x31, 0x17, 0x53, 0x4b, 0x4c,
+ 0xf4, 0xa5, 0x40, 0x3e, 0x00, 0x10, 0x13, 0x2f, 0xf5, 0x83, 0x33, 0x6a, 0xe8, 0x2d, 0xd7, 0x16,
+ 0x93, 0x3e, 0x3a, 0xd4, 0x9d, 0x26, 0x26, 0x1e, 0x15, 0x82, 0x8b, 0xcc, 0xf4, 0xbe, 0x2d, 0x26,
+ 0x5f, 0x6a, 0xdb, 0xc4, 0x8e, 0x04, 0x57, 0x13, 0x88, 0x79, 0x06, 0xb6, 0x98, 0xbc, 0x40, 0x87,
+ 0xca, 0x2a, 0x8b, 0xac, 0x38, 0xf0, 0xb6, 0x64, 0x95, 0x55, 0x56, 0x59, 0x71, 0xe0, 0xb5, 0x65,
+ 0x3d, 0xab, 0x2c, 0xb3, 0xe2, 0xcc, 0xdb, 0x96, 0xb5, 0xac, 0xb2, 0xca, 0x6a, 0x17, 0xb1, 0x26,
+ 0x6b, 0xef, 0xef, 0x0d, 0xe8, 0xd4, 0xbe, 0x4e, 0x55, 0x03, 0x13, 0xe1, 0x65, 0x11, 0xa5, 0xa9,
+ 0xfa, 0x90, 0xc2, 0xab, 0x1b, 0x12, 0x31, 0x30, 0x1e, 0xc5, 0x97, 0x08, 0x4f, 0xe4, 0x49, 0x52,
+ 0x7c, 0x68, 0x59, 0xae, 0x9d, 0x08, 0x17, 0x1d, 0x66, 0x39, 0x93, 0x98, 0xae, 0x59, 0x2c, 0x0f,
+ 0xd0, 0x41, 0x7e, 0x09, 0x24, 0x11, 0x5e, 0x9e, 0xb0, 0x44, 0x52, 0x21, 0xf2, 0x54, 0xb2, 0x61,
+ 0xf9, 0x51, 0xb0, 0x9e, 0x88, 0xd3, 0xd9, 0x05, 0xf2, 0x48, 0xb3, 0x99, 0xcb, 0xc6, 0xb4, 0xac,
+ 0x9d, 0x88, 0x57, 0xfa, 0xe6, 0x38, 0x70, 0x7e, 0xf8, 0x71, 0xeb, 0xbd, 0x7f, 0xff, 0xb8, 0xf5,
+ 0xde, 0x9f, 0xa7, 0x5b, 0x8d, 0x1f, 0xa6, 0x5b, 0x8d, 0x7f, 0x4c, 0xb7, 0x1a, 0xff, 0x9d, 0x6e,
+ 0x35, 0x86, 0x4b, 0xfa, 0xcf, 0x95, 0x5f, 0xfd, 0x2f, 0x00, 0x00, 0xff, 0xff, 0xc4, 0x4e, 0x24,
+ 0x22, 0xc4, 0x11, 0x00, 0x00,
+}
+
+func (m *Metrics) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Metrics) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *Metrics) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.MemoryOomControl != nil {
+ {
+ size, err := m.MemoryOomControl.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x4a
+ }
+ if m.CgroupStats != nil {
+ {
+ size, err := m.CgroupStats.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x42
+ }
+ if len(m.Network) > 0 {
+ for iNdEx := len(m.Network) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.Network[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x3a
+ }
+ }
+ if m.Rdma != nil {
+ {
+ size, err := m.Rdma.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x32
+ }
+ if m.Blkio != nil {
+ {
+ size, err := m.Blkio.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x2a
+ }
+ if m.Memory != nil {
+ {
+ size, err := m.Memory.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x22
+ }
+ if m.CPU != nil {
+ {
+ size, err := m.CPU.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x1a
+ }
+ if m.Pids != nil {
+ {
+ size, err := m.Pids.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x12
+ }
+ if len(m.Hugetlb) > 0 {
+ for iNdEx := len(m.Hugetlb) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.Hugetlb[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0xa
+ }
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *HugetlbStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *HugetlbStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *HugetlbStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if len(m.Pagesize) > 0 {
+ i -= len(m.Pagesize)
+ copy(dAtA[i:], m.Pagesize)
+ i = encodeVarintMetrics(dAtA, i, uint64(len(m.Pagesize)))
+ i--
+ dAtA[i] = 0x22
+ }
+ if m.Failcnt != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Failcnt))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.Max != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Max))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Usage != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Usage))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *PidsStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *PidsStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *PidsStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.Limit != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Limit))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Current != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Current))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *CPUStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CPUStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CPUStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.Throttling != nil {
+ {
+ size, err := m.Throttling.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x12
+ }
+ if m.Usage != nil {
+ {
+ size, err := m.Usage.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0xa
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *CPUUsage) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CPUUsage) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CPUUsage) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if len(m.PerCPU) > 0 {
+ dAtA11 := make([]byte, len(m.PerCPU)*10)
+ var j10 int
+ for _, num := range m.PerCPU {
+ for num >= 1<<7 {
+ dAtA11[j10] = uint8(uint64(num)&0x7f | 0x80)
+ num >>= 7
+ j10++
+ }
+ dAtA11[j10] = uint8(num)
+ j10++
+ }
+ i -= j10
+ copy(dAtA[i:], dAtA11[:j10])
+ i = encodeVarintMetrics(dAtA, i, uint64(j10))
+ i--
+ dAtA[i] = 0x22
+ }
+ if m.User != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.User))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.Kernel != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Kernel))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Total != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Total))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *Throttle) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Throttle) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *Throttle) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.ThrottledTime != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.ThrottledTime))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.ThrottledPeriods != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.ThrottledPeriods))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Periods != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Periods))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *MemoryStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *MemoryStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *MemoryStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.KernelTCP != nil {
+ {
+ size, err := m.KernelTCP.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x2
+ i--
+ dAtA[i] = 0xa2
+ }
+ if m.Kernel != nil {
+ {
+ size, err := m.Kernel.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x2
+ i--
+ dAtA[i] = 0x9a
+ }
+ if m.Swap != nil {
+ {
+ size, err := m.Swap.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x2
+ i--
+ dAtA[i] = 0x92
+ }
+ if m.Usage != nil {
+ {
+ size, err := m.Usage.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x2
+ i--
+ dAtA[i] = 0x8a
+ }
+ if m.TotalUnevictable != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalUnevictable))
+ i--
+ dAtA[i] = 0x2
+ i--
+ dAtA[i] = 0x80
+ }
+ if m.TotalActiveFile != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalActiveFile))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xf8
+ }
+ if m.TotalInactiveFile != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalInactiveFile))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xf0
+ }
+ if m.TotalActiveAnon != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalActiveAnon))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xe8
+ }
+ if m.TotalInactiveAnon != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalInactiveAnon))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xe0
+ }
+ if m.TotalPgMajFault != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalPgMajFault))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xd8
+ }
+ if m.TotalPgFault != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalPgFault))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xd0
+ }
+ if m.TotalPgPgOut != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalPgPgOut))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xc8
+ }
+ if m.TotalPgPgIn != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalPgPgIn))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xc0
+ }
+ if m.TotalWriteback != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalWriteback))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xb8
+ }
+ if m.TotalDirty != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalDirty))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xb0
+ }
+ if m.TotalMappedFile != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalMappedFile))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xa8
+ }
+ if m.TotalRSSHuge != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalRSSHuge))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xa0
+ }
+ if m.TotalRSS != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalRSS))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0x98
+ }
+ if m.TotalCache != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TotalCache))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0x90
+ }
+ if m.HierarchicalSwapLimit != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.HierarchicalSwapLimit))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0x88
+ }
+ if m.HierarchicalMemoryLimit != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.HierarchicalMemoryLimit))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0x80
+ }
+ if m.Unevictable != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Unevictable))
+ i--
+ dAtA[i] = 0x78
+ }
+ if m.ActiveFile != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.ActiveFile))
+ i--
+ dAtA[i] = 0x70
+ }
+ if m.InactiveFile != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.InactiveFile))
+ i--
+ dAtA[i] = 0x68
+ }
+ if m.ActiveAnon != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.ActiveAnon))
+ i--
+ dAtA[i] = 0x60
+ }
+ if m.InactiveAnon != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.InactiveAnon))
+ i--
+ dAtA[i] = 0x58
+ }
+ if m.PgMajFault != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.PgMajFault))
+ i--
+ dAtA[i] = 0x50
+ }
+ if m.PgFault != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.PgFault))
+ i--
+ dAtA[i] = 0x48
+ }
+ if m.PgPgOut != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.PgPgOut))
+ i--
+ dAtA[i] = 0x40
+ }
+ if m.PgPgIn != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.PgPgIn))
+ i--
+ dAtA[i] = 0x38
+ }
+ if m.Writeback != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Writeback))
+ i--
+ dAtA[i] = 0x30
+ }
+ if m.Dirty != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Dirty))
+ i--
+ dAtA[i] = 0x28
+ }
+ if m.MappedFile != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.MappedFile))
+ i--
+ dAtA[i] = 0x20
+ }
+ if m.RSSHuge != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.RSSHuge))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.RSS != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.RSS))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Cache != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Cache))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *MemoryEntry) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *MemoryEntry) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *MemoryEntry) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.Failcnt != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Failcnt))
+ i--
+ dAtA[i] = 0x20
+ }
+ if m.Max != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Max))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.Usage != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Usage))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Limit != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Limit))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *MemoryOomControl) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *MemoryOomControl) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *MemoryOomControl) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.OomKill != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.OomKill))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.UnderOom != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.UnderOom))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.OomKillDisable != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.OomKillDisable))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *BlkIOStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *BlkIOStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *BlkIOStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if len(m.SectorsRecursive) > 0 {
+ for iNdEx := len(m.SectorsRecursive) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.SectorsRecursive[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x42
+ }
+ }
+ if len(m.IoTimeRecursive) > 0 {
+ for iNdEx := len(m.IoTimeRecursive) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.IoTimeRecursive[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x3a
+ }
+ }
+ if len(m.IoMergedRecursive) > 0 {
+ for iNdEx := len(m.IoMergedRecursive) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.IoMergedRecursive[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x32
+ }
+ }
+ if len(m.IoWaitTimeRecursive) > 0 {
+ for iNdEx := len(m.IoWaitTimeRecursive) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.IoWaitTimeRecursive[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x2a
+ }
+ }
+ if len(m.IoServiceTimeRecursive) > 0 {
+ for iNdEx := len(m.IoServiceTimeRecursive) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.IoServiceTimeRecursive[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x22
+ }
+ }
+ if len(m.IoQueuedRecursive) > 0 {
+ for iNdEx := len(m.IoQueuedRecursive) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.IoQueuedRecursive[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x1a
+ }
+ }
+ if len(m.IoServicedRecursive) > 0 {
+ for iNdEx := len(m.IoServicedRecursive) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.IoServicedRecursive[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x12
+ }
+ }
+ if len(m.IoServiceBytesRecursive) > 0 {
+ for iNdEx := len(m.IoServiceBytesRecursive) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.IoServiceBytesRecursive[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0xa
+ }
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *BlkIOEntry) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *BlkIOEntry) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *BlkIOEntry) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.Value != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Value))
+ i--
+ dAtA[i] = 0x28
+ }
+ if m.Minor != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Minor))
+ i--
+ dAtA[i] = 0x20
+ }
+ if m.Major != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Major))
+ i--
+ dAtA[i] = 0x18
+ }
+ if len(m.Device) > 0 {
+ i -= len(m.Device)
+ copy(dAtA[i:], m.Device)
+ i = encodeVarintMetrics(dAtA, i, uint64(len(m.Device)))
+ i--
+ dAtA[i] = 0x12
+ }
+ if len(m.Op) > 0 {
+ i -= len(m.Op)
+ copy(dAtA[i:], m.Op)
+ i = encodeVarintMetrics(dAtA, i, uint64(len(m.Op)))
+ i--
+ dAtA[i] = 0xa
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *RdmaStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RdmaStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *RdmaStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if len(m.Limit) > 0 {
+ for iNdEx := len(m.Limit) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.Limit[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x12
+ }
+ }
+ if len(m.Current) > 0 {
+ for iNdEx := len(m.Current) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.Current[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0xa
+ }
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *RdmaEntry) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RdmaEntry) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *RdmaEntry) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.HcaObjects != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.HcaObjects))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.HcaHandles != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.HcaHandles))
+ i--
+ dAtA[i] = 0x10
+ }
+ if len(m.Device) > 0 {
+ i -= len(m.Device)
+ copy(dAtA[i:], m.Device)
+ i = encodeVarintMetrics(dAtA, i, uint64(len(m.Device)))
+ i--
+ dAtA[i] = 0xa
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *NetworkStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *NetworkStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *NetworkStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.TxDropped != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TxDropped))
+ i--
+ dAtA[i] = 0x48
+ }
+ if m.TxErrors != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TxErrors))
+ i--
+ dAtA[i] = 0x40
+ }
+ if m.TxPackets != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TxPackets))
+ i--
+ dAtA[i] = 0x38
+ }
+ if m.TxBytes != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.TxBytes))
+ i--
+ dAtA[i] = 0x30
+ }
+ if m.RxDropped != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.RxDropped))
+ i--
+ dAtA[i] = 0x28
+ }
+ if m.RxErrors != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.RxErrors))
+ i--
+ dAtA[i] = 0x20
+ }
+ if m.RxPackets != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.RxPackets))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.RxBytes != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.RxBytes))
+ i--
+ dAtA[i] = 0x10
+ }
+ if len(m.Name) > 0 {
+ i -= len(m.Name)
+ copy(dAtA[i:], m.Name)
+ i = encodeVarintMetrics(dAtA, i, uint64(len(m.Name)))
+ i--
+ dAtA[i] = 0xa
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *CgroupStats) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CgroupStats) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CgroupStats) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.NrIoWait != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.NrIoWait))
+ i--
+ dAtA[i] = 0x28
+ }
+ if m.NrUninterruptible != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.NrUninterruptible))
+ i--
+ dAtA[i] = 0x20
+ }
+ if m.NrStopped != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.NrStopped))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.NrRunning != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.NrRunning))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.NrSleeping != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.NrSleeping))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func encodeVarintMetrics(dAtA []byte, offset int, v uint64) int {
+ offset -= sovMetrics(v)
+ base := offset
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return base
+}
+func (m *Metrics) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if len(m.Hugetlb) > 0 {
+ for _, e := range m.Hugetlb {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if m.Pids != nil {
+ l = m.Pids.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.CPU != nil {
+ l = m.CPU.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.Memory != nil {
+ l = m.Memory.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.Blkio != nil {
+ l = m.Blkio.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.Rdma != nil {
+ l = m.Rdma.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if len(m.Network) > 0 {
+ for _, e := range m.Network {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if m.CgroupStats != nil {
+ l = m.CgroupStats.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.MemoryOomControl != nil {
+ l = m.MemoryOomControl.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *HugetlbStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Usage != 0 {
+ n += 1 + sovMetrics(uint64(m.Usage))
+ }
+ if m.Max != 0 {
+ n += 1 + sovMetrics(uint64(m.Max))
+ }
+ if m.Failcnt != 0 {
+ n += 1 + sovMetrics(uint64(m.Failcnt))
+ }
+ l = len(m.Pagesize)
+ if l > 0 {
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *PidsStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Current != 0 {
+ n += 1 + sovMetrics(uint64(m.Current))
+ }
+ if m.Limit != 0 {
+ n += 1 + sovMetrics(uint64(m.Limit))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *CPUStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Usage != nil {
+ l = m.Usage.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.Throttling != nil {
+ l = m.Throttling.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *CPUUsage) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Total != 0 {
+ n += 1 + sovMetrics(uint64(m.Total))
+ }
+ if m.Kernel != 0 {
+ n += 1 + sovMetrics(uint64(m.Kernel))
+ }
+ if m.User != 0 {
+ n += 1 + sovMetrics(uint64(m.User))
+ }
+ if len(m.PerCPU) > 0 {
+ l = 0
+ for _, e := range m.PerCPU {
+ l += sovMetrics(uint64(e))
+ }
+ n += 1 + sovMetrics(uint64(l)) + l
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *Throttle) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Periods != 0 {
+ n += 1 + sovMetrics(uint64(m.Periods))
+ }
+ if m.ThrottledPeriods != 0 {
+ n += 1 + sovMetrics(uint64(m.ThrottledPeriods))
+ }
+ if m.ThrottledTime != 0 {
+ n += 1 + sovMetrics(uint64(m.ThrottledTime))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *MemoryStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Cache != 0 {
+ n += 1 + sovMetrics(uint64(m.Cache))
+ }
+ if m.RSS != 0 {
+ n += 1 + sovMetrics(uint64(m.RSS))
+ }
+ if m.RSSHuge != 0 {
+ n += 1 + sovMetrics(uint64(m.RSSHuge))
+ }
+ if m.MappedFile != 0 {
+ n += 1 + sovMetrics(uint64(m.MappedFile))
+ }
+ if m.Dirty != 0 {
+ n += 1 + sovMetrics(uint64(m.Dirty))
+ }
+ if m.Writeback != 0 {
+ n += 1 + sovMetrics(uint64(m.Writeback))
+ }
+ if m.PgPgIn != 0 {
+ n += 1 + sovMetrics(uint64(m.PgPgIn))
+ }
+ if m.PgPgOut != 0 {
+ n += 1 + sovMetrics(uint64(m.PgPgOut))
+ }
+ if m.PgFault != 0 {
+ n += 1 + sovMetrics(uint64(m.PgFault))
+ }
+ if m.PgMajFault != 0 {
+ n += 1 + sovMetrics(uint64(m.PgMajFault))
+ }
+ if m.InactiveAnon != 0 {
+ n += 1 + sovMetrics(uint64(m.InactiveAnon))
+ }
+ if m.ActiveAnon != 0 {
+ n += 1 + sovMetrics(uint64(m.ActiveAnon))
+ }
+ if m.InactiveFile != 0 {
+ n += 1 + sovMetrics(uint64(m.InactiveFile))
+ }
+ if m.ActiveFile != 0 {
+ n += 1 + sovMetrics(uint64(m.ActiveFile))
+ }
+ if m.Unevictable != 0 {
+ n += 1 + sovMetrics(uint64(m.Unevictable))
+ }
+ if m.HierarchicalMemoryLimit != 0 {
+ n += 2 + sovMetrics(uint64(m.HierarchicalMemoryLimit))
+ }
+ if m.HierarchicalSwapLimit != 0 {
+ n += 2 + sovMetrics(uint64(m.HierarchicalSwapLimit))
+ }
+ if m.TotalCache != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalCache))
+ }
+ if m.TotalRSS != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalRSS))
+ }
+ if m.TotalRSSHuge != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalRSSHuge))
+ }
+ if m.TotalMappedFile != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalMappedFile))
+ }
+ if m.TotalDirty != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalDirty))
+ }
+ if m.TotalWriteback != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalWriteback))
+ }
+ if m.TotalPgPgIn != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalPgPgIn))
+ }
+ if m.TotalPgPgOut != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalPgPgOut))
+ }
+ if m.TotalPgFault != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalPgFault))
+ }
+ if m.TotalPgMajFault != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalPgMajFault))
+ }
+ if m.TotalInactiveAnon != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalInactiveAnon))
+ }
+ if m.TotalActiveAnon != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalActiveAnon))
+ }
+ if m.TotalInactiveFile != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalInactiveFile))
+ }
+ if m.TotalActiveFile != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalActiveFile))
+ }
+ if m.TotalUnevictable != 0 {
+ n += 2 + sovMetrics(uint64(m.TotalUnevictable))
+ }
+ if m.Usage != nil {
+ l = m.Usage.Size()
+ n += 2 + l + sovMetrics(uint64(l))
+ }
+ if m.Swap != nil {
+ l = m.Swap.Size()
+ n += 2 + l + sovMetrics(uint64(l))
+ }
+ if m.Kernel != nil {
+ l = m.Kernel.Size()
+ n += 2 + l + sovMetrics(uint64(l))
+ }
+ if m.KernelTCP != nil {
+ l = m.KernelTCP.Size()
+ n += 2 + l + sovMetrics(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *MemoryEntry) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Limit != 0 {
+ n += 1 + sovMetrics(uint64(m.Limit))
+ }
+ if m.Usage != 0 {
+ n += 1 + sovMetrics(uint64(m.Usage))
+ }
+ if m.Max != 0 {
+ n += 1 + sovMetrics(uint64(m.Max))
+ }
+ if m.Failcnt != 0 {
+ n += 1 + sovMetrics(uint64(m.Failcnt))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *MemoryOomControl) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.OomKillDisable != 0 {
+ n += 1 + sovMetrics(uint64(m.OomKillDisable))
+ }
+ if m.UnderOom != 0 {
+ n += 1 + sovMetrics(uint64(m.UnderOom))
+ }
+ if m.OomKill != 0 {
+ n += 1 + sovMetrics(uint64(m.OomKill))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *BlkIOStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if len(m.IoServiceBytesRecursive) > 0 {
+ for _, e := range m.IoServiceBytesRecursive {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if len(m.IoServicedRecursive) > 0 {
+ for _, e := range m.IoServicedRecursive {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if len(m.IoQueuedRecursive) > 0 {
+ for _, e := range m.IoQueuedRecursive {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if len(m.IoServiceTimeRecursive) > 0 {
+ for _, e := range m.IoServiceTimeRecursive {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if len(m.IoWaitTimeRecursive) > 0 {
+ for _, e := range m.IoWaitTimeRecursive {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if len(m.IoMergedRecursive) > 0 {
+ for _, e := range m.IoMergedRecursive {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if len(m.IoTimeRecursive) > 0 {
+ for _, e := range m.IoTimeRecursive {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if len(m.SectorsRecursive) > 0 {
+ for _, e := range m.SectorsRecursive {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *BlkIOEntry) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ l = len(m.Op)
+ if l > 0 {
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ l = len(m.Device)
+ if l > 0 {
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.Major != 0 {
+ n += 1 + sovMetrics(uint64(m.Major))
+ }
+ if m.Minor != 0 {
+ n += 1 + sovMetrics(uint64(m.Minor))
+ }
+ if m.Value != 0 {
+ n += 1 + sovMetrics(uint64(m.Value))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *RdmaStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if len(m.Current) > 0 {
+ for _, e := range m.Current {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if len(m.Limit) > 0 {
+ for _, e := range m.Limit {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *RdmaEntry) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ l = len(m.Device)
+ if l > 0 {
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.HcaHandles != 0 {
+ n += 1 + sovMetrics(uint64(m.HcaHandles))
+ }
+ if m.HcaObjects != 0 {
+ n += 1 + sovMetrics(uint64(m.HcaObjects))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *NetworkStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ l = len(m.Name)
+ if l > 0 {
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.RxBytes != 0 {
+ n += 1 + sovMetrics(uint64(m.RxBytes))
+ }
+ if m.RxPackets != 0 {
+ n += 1 + sovMetrics(uint64(m.RxPackets))
+ }
+ if m.RxErrors != 0 {
+ n += 1 + sovMetrics(uint64(m.RxErrors))
+ }
+ if m.RxDropped != 0 {
+ n += 1 + sovMetrics(uint64(m.RxDropped))
+ }
+ if m.TxBytes != 0 {
+ n += 1 + sovMetrics(uint64(m.TxBytes))
+ }
+ if m.TxPackets != 0 {
+ n += 1 + sovMetrics(uint64(m.TxPackets))
+ }
+ if m.TxErrors != 0 {
+ n += 1 + sovMetrics(uint64(m.TxErrors))
+ }
+ if m.TxDropped != 0 {
+ n += 1 + sovMetrics(uint64(m.TxDropped))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *CgroupStats) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.NrSleeping != 0 {
+ n += 1 + sovMetrics(uint64(m.NrSleeping))
+ }
+ if m.NrRunning != 0 {
+ n += 1 + sovMetrics(uint64(m.NrRunning))
+ }
+ if m.NrStopped != 0 {
+ n += 1 + sovMetrics(uint64(m.NrStopped))
+ }
+ if m.NrUninterruptible != 0 {
+ n += 1 + sovMetrics(uint64(m.NrUninterruptible))
+ }
+ if m.NrIoWait != 0 {
+ n += 1 + sovMetrics(uint64(m.NrIoWait))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func sovMetrics(x uint64) (n int) {
+ return (math_bits.Len64(x|1) + 6) / 7
+}
+func sozMetrics(x uint64) (n int) {
+ return sovMetrics(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *Metrics) String() string {
+ if this == nil {
+ return "nil"
+ }
+ repeatedStringForHugetlb := "[]*HugetlbStat{"
+ for _, f := range this.Hugetlb {
+ repeatedStringForHugetlb += strings.Replace(f.String(), "HugetlbStat", "HugetlbStat", 1) + ","
+ }
+ repeatedStringForHugetlb += "}"
+ repeatedStringForNetwork := "[]*NetworkStat{"
+ for _, f := range this.Network {
+ repeatedStringForNetwork += strings.Replace(f.String(), "NetworkStat", "NetworkStat", 1) + ","
+ }
+ repeatedStringForNetwork += "}"
+ s := strings.Join([]string{`&Metrics{`,
+ `Hugetlb:` + repeatedStringForHugetlb + `,`,
+ `Pids:` + strings.Replace(this.Pids.String(), "PidsStat", "PidsStat", 1) + `,`,
+ `CPU:` + strings.Replace(this.CPU.String(), "CPUStat", "CPUStat", 1) + `,`,
+ `Memory:` + strings.Replace(this.Memory.String(), "MemoryStat", "MemoryStat", 1) + `,`,
+ `Blkio:` + strings.Replace(this.Blkio.String(), "BlkIOStat", "BlkIOStat", 1) + `,`,
+ `Rdma:` + strings.Replace(this.Rdma.String(), "RdmaStat", "RdmaStat", 1) + `,`,
+ `Network:` + repeatedStringForNetwork + `,`,
+ `CgroupStats:` + strings.Replace(this.CgroupStats.String(), "CgroupStats", "CgroupStats", 1) + `,`,
+ `MemoryOomControl:` + strings.Replace(this.MemoryOomControl.String(), "MemoryOomControl", "MemoryOomControl", 1) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *HugetlbStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&HugetlbStat{`,
+ `Usage:` + fmt.Sprintf("%v", this.Usage) + `,`,
+ `Max:` + fmt.Sprintf("%v", this.Max) + `,`,
+ `Failcnt:` + fmt.Sprintf("%v", this.Failcnt) + `,`,
+ `Pagesize:` + fmt.Sprintf("%v", this.Pagesize) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *PidsStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PidsStat{`,
+ `Current:` + fmt.Sprintf("%v", this.Current) + `,`,
+ `Limit:` + fmt.Sprintf("%v", this.Limit) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CPUStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CPUStat{`,
+ `Usage:` + strings.Replace(this.Usage.String(), "CPUUsage", "CPUUsage", 1) + `,`,
+ `Throttling:` + strings.Replace(this.Throttling.String(), "Throttle", "Throttle", 1) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CPUUsage) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CPUUsage{`,
+ `Total:` + fmt.Sprintf("%v", this.Total) + `,`,
+ `Kernel:` + fmt.Sprintf("%v", this.Kernel) + `,`,
+ `User:` + fmt.Sprintf("%v", this.User) + `,`,
+ `PerCPU:` + fmt.Sprintf("%v", this.PerCPU) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *Throttle) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&Throttle{`,
+ `Periods:` + fmt.Sprintf("%v", this.Periods) + `,`,
+ `ThrottledPeriods:` + fmt.Sprintf("%v", this.ThrottledPeriods) + `,`,
+ `ThrottledTime:` + fmt.Sprintf("%v", this.ThrottledTime) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *MemoryStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&MemoryStat{`,
+ `Cache:` + fmt.Sprintf("%v", this.Cache) + `,`,
+ `RSS:` + fmt.Sprintf("%v", this.RSS) + `,`,
+ `RSSHuge:` + fmt.Sprintf("%v", this.RSSHuge) + `,`,
+ `MappedFile:` + fmt.Sprintf("%v", this.MappedFile) + `,`,
+ `Dirty:` + fmt.Sprintf("%v", this.Dirty) + `,`,
+ `Writeback:` + fmt.Sprintf("%v", this.Writeback) + `,`,
+ `PgPgIn:` + fmt.Sprintf("%v", this.PgPgIn) + `,`,
+ `PgPgOut:` + fmt.Sprintf("%v", this.PgPgOut) + `,`,
+ `PgFault:` + fmt.Sprintf("%v", this.PgFault) + `,`,
+ `PgMajFault:` + fmt.Sprintf("%v", this.PgMajFault) + `,`,
+ `InactiveAnon:` + fmt.Sprintf("%v", this.InactiveAnon) + `,`,
+ `ActiveAnon:` + fmt.Sprintf("%v", this.ActiveAnon) + `,`,
+ `InactiveFile:` + fmt.Sprintf("%v", this.InactiveFile) + `,`,
+ `ActiveFile:` + fmt.Sprintf("%v", this.ActiveFile) + `,`,
+ `Unevictable:` + fmt.Sprintf("%v", this.Unevictable) + `,`,
+ `HierarchicalMemoryLimit:` + fmt.Sprintf("%v", this.HierarchicalMemoryLimit) + `,`,
+ `HierarchicalSwapLimit:` + fmt.Sprintf("%v", this.HierarchicalSwapLimit) + `,`,
+ `TotalCache:` + fmt.Sprintf("%v", this.TotalCache) + `,`,
+ `TotalRSS:` + fmt.Sprintf("%v", this.TotalRSS) + `,`,
+ `TotalRSSHuge:` + fmt.Sprintf("%v", this.TotalRSSHuge) + `,`,
+ `TotalMappedFile:` + fmt.Sprintf("%v", this.TotalMappedFile) + `,`,
+ `TotalDirty:` + fmt.Sprintf("%v", this.TotalDirty) + `,`,
+ `TotalWriteback:` + fmt.Sprintf("%v", this.TotalWriteback) + `,`,
+ `TotalPgPgIn:` + fmt.Sprintf("%v", this.TotalPgPgIn) + `,`,
+ `TotalPgPgOut:` + fmt.Sprintf("%v", this.TotalPgPgOut) + `,`,
+ `TotalPgFault:` + fmt.Sprintf("%v", this.TotalPgFault) + `,`,
+ `TotalPgMajFault:` + fmt.Sprintf("%v", this.TotalPgMajFault) + `,`,
+ `TotalInactiveAnon:` + fmt.Sprintf("%v", this.TotalInactiveAnon) + `,`,
+ `TotalActiveAnon:` + fmt.Sprintf("%v", this.TotalActiveAnon) + `,`,
+ `TotalInactiveFile:` + fmt.Sprintf("%v", this.TotalInactiveFile) + `,`,
+ `TotalActiveFile:` + fmt.Sprintf("%v", this.TotalActiveFile) + `,`,
+ `TotalUnevictable:` + fmt.Sprintf("%v", this.TotalUnevictable) + `,`,
+ `Usage:` + strings.Replace(this.Usage.String(), "MemoryEntry", "MemoryEntry", 1) + `,`,
+ `Swap:` + strings.Replace(this.Swap.String(), "MemoryEntry", "MemoryEntry", 1) + `,`,
+ `Kernel:` + strings.Replace(this.Kernel.String(), "MemoryEntry", "MemoryEntry", 1) + `,`,
+ `KernelTCP:` + strings.Replace(this.KernelTCP.String(), "MemoryEntry", "MemoryEntry", 1) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *MemoryEntry) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&MemoryEntry{`,
+ `Limit:` + fmt.Sprintf("%v", this.Limit) + `,`,
+ `Usage:` + fmt.Sprintf("%v", this.Usage) + `,`,
+ `Max:` + fmt.Sprintf("%v", this.Max) + `,`,
+ `Failcnt:` + fmt.Sprintf("%v", this.Failcnt) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *MemoryOomControl) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&MemoryOomControl{`,
+ `OomKillDisable:` + fmt.Sprintf("%v", this.OomKillDisable) + `,`,
+ `UnderOom:` + fmt.Sprintf("%v", this.UnderOom) + `,`,
+ `OomKill:` + fmt.Sprintf("%v", this.OomKill) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *BlkIOStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ repeatedStringForIoServiceBytesRecursive := "[]*BlkIOEntry{"
+ for _, f := range this.IoServiceBytesRecursive {
+ repeatedStringForIoServiceBytesRecursive += strings.Replace(f.String(), "BlkIOEntry", "BlkIOEntry", 1) + ","
+ }
+ repeatedStringForIoServiceBytesRecursive += "}"
+ repeatedStringForIoServicedRecursive := "[]*BlkIOEntry{"
+ for _, f := range this.IoServicedRecursive {
+ repeatedStringForIoServicedRecursive += strings.Replace(f.String(), "BlkIOEntry", "BlkIOEntry", 1) + ","
+ }
+ repeatedStringForIoServicedRecursive += "}"
+ repeatedStringForIoQueuedRecursive := "[]*BlkIOEntry{"
+ for _, f := range this.IoQueuedRecursive {
+ repeatedStringForIoQueuedRecursive += strings.Replace(f.String(), "BlkIOEntry", "BlkIOEntry", 1) + ","
+ }
+ repeatedStringForIoQueuedRecursive += "}"
+ repeatedStringForIoServiceTimeRecursive := "[]*BlkIOEntry{"
+ for _, f := range this.IoServiceTimeRecursive {
+ repeatedStringForIoServiceTimeRecursive += strings.Replace(f.String(), "BlkIOEntry", "BlkIOEntry", 1) + ","
+ }
+ repeatedStringForIoServiceTimeRecursive += "}"
+ repeatedStringForIoWaitTimeRecursive := "[]*BlkIOEntry{"
+ for _, f := range this.IoWaitTimeRecursive {
+ repeatedStringForIoWaitTimeRecursive += strings.Replace(f.String(), "BlkIOEntry", "BlkIOEntry", 1) + ","
+ }
+ repeatedStringForIoWaitTimeRecursive += "}"
+ repeatedStringForIoMergedRecursive := "[]*BlkIOEntry{"
+ for _, f := range this.IoMergedRecursive {
+ repeatedStringForIoMergedRecursive += strings.Replace(f.String(), "BlkIOEntry", "BlkIOEntry", 1) + ","
+ }
+ repeatedStringForIoMergedRecursive += "}"
+ repeatedStringForIoTimeRecursive := "[]*BlkIOEntry{"
+ for _, f := range this.IoTimeRecursive {
+ repeatedStringForIoTimeRecursive += strings.Replace(f.String(), "BlkIOEntry", "BlkIOEntry", 1) + ","
+ }
+ repeatedStringForIoTimeRecursive += "}"
+ repeatedStringForSectorsRecursive := "[]*BlkIOEntry{"
+ for _, f := range this.SectorsRecursive {
+ repeatedStringForSectorsRecursive += strings.Replace(f.String(), "BlkIOEntry", "BlkIOEntry", 1) + ","
+ }
+ repeatedStringForSectorsRecursive += "}"
+ s := strings.Join([]string{`&BlkIOStat{`,
+ `IoServiceBytesRecursive:` + repeatedStringForIoServiceBytesRecursive + `,`,
+ `IoServicedRecursive:` + repeatedStringForIoServicedRecursive + `,`,
+ `IoQueuedRecursive:` + repeatedStringForIoQueuedRecursive + `,`,
+ `IoServiceTimeRecursive:` + repeatedStringForIoServiceTimeRecursive + `,`,
+ `IoWaitTimeRecursive:` + repeatedStringForIoWaitTimeRecursive + `,`,
+ `IoMergedRecursive:` + repeatedStringForIoMergedRecursive + `,`,
+ `IoTimeRecursive:` + repeatedStringForIoTimeRecursive + `,`,
+ `SectorsRecursive:` + repeatedStringForSectorsRecursive + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *BlkIOEntry) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&BlkIOEntry{`,
+ `Op:` + fmt.Sprintf("%v", this.Op) + `,`,
+ `Device:` + fmt.Sprintf("%v", this.Device) + `,`,
+ `Major:` + fmt.Sprintf("%v", this.Major) + `,`,
+ `Minor:` + fmt.Sprintf("%v", this.Minor) + `,`,
+ `Value:` + fmt.Sprintf("%v", this.Value) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RdmaStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ repeatedStringForCurrent := "[]*RdmaEntry{"
+ for _, f := range this.Current {
+ repeatedStringForCurrent += strings.Replace(f.String(), "RdmaEntry", "RdmaEntry", 1) + ","
+ }
+ repeatedStringForCurrent += "}"
+ repeatedStringForLimit := "[]*RdmaEntry{"
+ for _, f := range this.Limit {
+ repeatedStringForLimit += strings.Replace(f.String(), "RdmaEntry", "RdmaEntry", 1) + ","
+ }
+ repeatedStringForLimit += "}"
+ s := strings.Join([]string{`&RdmaStat{`,
+ `Current:` + repeatedStringForCurrent + `,`,
+ `Limit:` + repeatedStringForLimit + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RdmaEntry) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RdmaEntry{`,
+ `Device:` + fmt.Sprintf("%v", this.Device) + `,`,
+ `HcaHandles:` + fmt.Sprintf("%v", this.HcaHandles) + `,`,
+ `HcaObjects:` + fmt.Sprintf("%v", this.HcaObjects) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *NetworkStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&NetworkStat{`,
+ `Name:` + fmt.Sprintf("%v", this.Name) + `,`,
+ `RxBytes:` + fmt.Sprintf("%v", this.RxBytes) + `,`,
+ `RxPackets:` + fmt.Sprintf("%v", this.RxPackets) + `,`,
+ `RxErrors:` + fmt.Sprintf("%v", this.RxErrors) + `,`,
+ `RxDropped:` + fmt.Sprintf("%v", this.RxDropped) + `,`,
+ `TxBytes:` + fmt.Sprintf("%v", this.TxBytes) + `,`,
+ `TxPackets:` + fmt.Sprintf("%v", this.TxPackets) + `,`,
+ `TxErrors:` + fmt.Sprintf("%v", this.TxErrors) + `,`,
+ `TxDropped:` + fmt.Sprintf("%v", this.TxDropped) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CgroupStats) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CgroupStats{`,
+ `NrSleeping:` + fmt.Sprintf("%v", this.NrSleeping) + `,`,
+ `NrRunning:` + fmt.Sprintf("%v", this.NrRunning) + `,`,
+ `NrStopped:` + fmt.Sprintf("%v", this.NrStopped) + `,`,
+ `NrUninterruptible:` + fmt.Sprintf("%v", this.NrUninterruptible) + `,`,
+ `NrIoWait:` + fmt.Sprintf("%v", this.NrIoWait) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringMetrics(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *Metrics) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Metrics: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Metrics: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Hugetlb", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Hugetlb = append(m.Hugetlb, &HugetlbStat{})
+ if err := m.Hugetlb[len(m.Hugetlb)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pids", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Pids == nil {
+ m.Pids = &PidsStat{}
+ }
+ if err := m.Pids.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CPU", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.CPU == nil {
+ m.CPU = &CPUStat{}
+ }
+ if err := m.CPU.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Memory", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Memory == nil {
+ m.Memory = &MemoryStat{}
+ }
+ if err := m.Memory.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Blkio", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Blkio == nil {
+ m.Blkio = &BlkIOStat{}
+ }
+ if err := m.Blkio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Rdma", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Rdma == nil {
+ m.Rdma = &RdmaStat{}
+ }
+ if err := m.Rdma.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Network", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Network = append(m.Network, &NetworkStat{})
+ if err := m.Network[len(m.Network)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CgroupStats", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.CgroupStats == nil {
+ m.CgroupStats = &CgroupStats{}
+ }
+ if err := m.CgroupStats.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 9:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field MemoryOomControl", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.MemoryOomControl == nil {
+ m.MemoryOomControl = &MemoryOomControl{}
+ }
+ if err := m.MemoryOomControl.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *HugetlbStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: HugetlbStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: HugetlbStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Usage", wireType)
+ }
+ m.Usage = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Usage |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Max", wireType)
+ }
+ m.Max = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Max |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Failcnt", wireType)
+ }
+ m.Failcnt = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Failcnt |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pagesize", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Pagesize = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *PidsStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PidsStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PidsStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Current", wireType)
+ }
+ m.Current = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Current |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType)
+ }
+ m.Limit = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Limit |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CPUStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CPUStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CPUStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Usage", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Usage == nil {
+ m.Usage = &CPUUsage{}
+ }
+ if err := m.Usage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Throttling", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Throttling == nil {
+ m.Throttling = &Throttle{}
+ }
+ if err := m.Throttling.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CPUUsage) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CPUUsage: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CPUUsage: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType)
+ }
+ m.Total = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Total |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Kernel", wireType)
+ }
+ m.Kernel = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Kernel |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field User", wireType)
+ }
+ m.User = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.User |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType == 0 {
+ var v uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.PerCPU = append(m.PerCPU, v)
+ } else if wireType == 2 {
+ var packedLen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ packedLen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if packedLen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + packedLen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ var elementCount int
+ var count int
+ for _, integer := range dAtA[iNdEx:postIndex] {
+ if integer < 128 {
+ count++
+ }
+ }
+ elementCount = count
+ if elementCount != 0 && len(m.PerCPU) == 0 {
+ m.PerCPU = make([]uint64, 0, elementCount)
+ }
+ for iNdEx < postIndex {
+ var v uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ v |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ m.PerCPU = append(m.PerCPU, v)
+ }
+ } else {
+ return fmt.Errorf("proto: wrong wireType = %d for field PerCPU", wireType)
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *Throttle) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Throttle: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Throttle: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Periods", wireType)
+ }
+ m.Periods = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Periods |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ThrottledPeriods", wireType)
+ }
+ m.ThrottledPeriods = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ThrottledPeriods |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ThrottledTime", wireType)
+ }
+ m.ThrottledTime = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ThrottledTime |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *MemoryStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: MemoryStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: MemoryStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Cache", wireType)
+ }
+ m.Cache = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Cache |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RSS", wireType)
+ }
+ m.RSS = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RSS |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RSSHuge", wireType)
+ }
+ m.RSSHuge = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RSSHuge |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field MappedFile", wireType)
+ }
+ m.MappedFile = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.MappedFile |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Dirty", wireType)
+ }
+ m.Dirty = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Dirty |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Writeback", wireType)
+ }
+ m.Writeback = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Writeback |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 7:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PgPgIn", wireType)
+ }
+ m.PgPgIn = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.PgPgIn |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 8:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PgPgOut", wireType)
+ }
+ m.PgPgOut = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.PgPgOut |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 9:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PgFault", wireType)
+ }
+ m.PgFault = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.PgFault |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 10:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field PgMajFault", wireType)
+ }
+ m.PgMajFault = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.PgMajFault |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 11:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field InactiveAnon", wireType)
+ }
+ m.InactiveAnon = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.InactiveAnon |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 12:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ActiveAnon", wireType)
+ }
+ m.ActiveAnon = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ActiveAnon |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 13:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field InactiveFile", wireType)
+ }
+ m.InactiveFile = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.InactiveFile |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 14:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ActiveFile", wireType)
+ }
+ m.ActiveFile = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ActiveFile |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 15:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Unevictable", wireType)
+ }
+ m.Unevictable = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Unevictable |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 16:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field HierarchicalMemoryLimit", wireType)
+ }
+ m.HierarchicalMemoryLimit = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.HierarchicalMemoryLimit |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 17:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field HierarchicalSwapLimit", wireType)
+ }
+ m.HierarchicalSwapLimit = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.HierarchicalSwapLimit |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 18:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalCache", wireType)
+ }
+ m.TotalCache = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalCache |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 19:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalRSS", wireType)
+ }
+ m.TotalRSS = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalRSS |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 20:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalRSSHuge", wireType)
+ }
+ m.TotalRSSHuge = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalRSSHuge |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 21:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalMappedFile", wireType)
+ }
+ m.TotalMappedFile = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalMappedFile |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 22:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalDirty", wireType)
+ }
+ m.TotalDirty = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalDirty |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 23:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalWriteback", wireType)
+ }
+ m.TotalWriteback = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalWriteback |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 24:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalPgPgIn", wireType)
+ }
+ m.TotalPgPgIn = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalPgPgIn |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 25:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalPgPgOut", wireType)
+ }
+ m.TotalPgPgOut = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalPgPgOut |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 26:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalPgFault", wireType)
+ }
+ m.TotalPgFault = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalPgFault |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 27:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalPgMajFault", wireType)
+ }
+ m.TotalPgMajFault = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalPgMajFault |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 28:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalInactiveAnon", wireType)
+ }
+ m.TotalInactiveAnon = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalInactiveAnon |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 29:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalActiveAnon", wireType)
+ }
+ m.TotalActiveAnon = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalActiveAnon |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 30:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalInactiveFile", wireType)
+ }
+ m.TotalInactiveFile = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalInactiveFile |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 31:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalActiveFile", wireType)
+ }
+ m.TotalActiveFile = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalActiveFile |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 32:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TotalUnevictable", wireType)
+ }
+ m.TotalUnevictable = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TotalUnevictable |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 33:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Usage", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Usage == nil {
+ m.Usage = &MemoryEntry{}
+ }
+ if err := m.Usage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 34:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Swap", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Swap == nil {
+ m.Swap = &MemoryEntry{}
+ }
+ if err := m.Swap.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 35:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Kernel", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Kernel == nil {
+ m.Kernel = &MemoryEntry{}
+ }
+ if err := m.Kernel.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 36:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field KernelTCP", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.KernelTCP == nil {
+ m.KernelTCP = &MemoryEntry{}
+ }
+ if err := m.KernelTCP.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *MemoryEntry) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: MemoryEntry: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: MemoryEntry: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType)
+ }
+ m.Limit = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Limit |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Usage", wireType)
+ }
+ m.Usage = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Usage |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Max", wireType)
+ }
+ m.Max = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Max |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Failcnt", wireType)
+ }
+ m.Failcnt = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Failcnt |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *MemoryOomControl) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: MemoryOomControl: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: MemoryOomControl: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field OomKillDisable", wireType)
+ }
+ m.OomKillDisable = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.OomKillDisable |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field UnderOom", wireType)
+ }
+ m.UnderOom = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.UnderOom |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field OomKill", wireType)
+ }
+ m.OomKill = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.OomKill |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *BlkIOStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: BlkIOStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: BlkIOStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IoServiceBytesRecursive", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IoServiceBytesRecursive = append(m.IoServiceBytesRecursive, &BlkIOEntry{})
+ if err := m.IoServiceBytesRecursive[len(m.IoServiceBytesRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IoServicedRecursive", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IoServicedRecursive = append(m.IoServicedRecursive, &BlkIOEntry{})
+ if err := m.IoServicedRecursive[len(m.IoServicedRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IoQueuedRecursive", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IoQueuedRecursive = append(m.IoQueuedRecursive, &BlkIOEntry{})
+ if err := m.IoQueuedRecursive[len(m.IoQueuedRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IoServiceTimeRecursive", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IoServiceTimeRecursive = append(m.IoServiceTimeRecursive, &BlkIOEntry{})
+ if err := m.IoServiceTimeRecursive[len(m.IoServiceTimeRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IoWaitTimeRecursive", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IoWaitTimeRecursive = append(m.IoWaitTimeRecursive, &BlkIOEntry{})
+ if err := m.IoWaitTimeRecursive[len(m.IoWaitTimeRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IoMergedRecursive", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IoMergedRecursive = append(m.IoMergedRecursive, &BlkIOEntry{})
+ if err := m.IoMergedRecursive[len(m.IoMergedRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field IoTimeRecursive", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.IoTimeRecursive = append(m.IoTimeRecursive, &BlkIOEntry{})
+ if err := m.IoTimeRecursive[len(m.IoTimeRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SectorsRecursive", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.SectorsRecursive = append(m.SectorsRecursive, &BlkIOEntry{})
+ if err := m.SectorsRecursive[len(m.SectorsRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *BlkIOEntry) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: BlkIOEntry: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: BlkIOEntry: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Op", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Op = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Device", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Device = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Major", wireType)
+ }
+ m.Major = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Major |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Minor", wireType)
+ }
+ m.Minor = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Minor |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
+ }
+ m.Value = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Value |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RdmaStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RdmaStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RdmaStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Current", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Current = append(m.Current, &RdmaEntry{})
+ if err := m.Current[len(m.Current)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Limit = append(m.Limit, &RdmaEntry{})
+ if err := m.Limit[len(m.Limit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RdmaEntry) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RdmaEntry: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RdmaEntry: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Device", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Device = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field HcaHandles", wireType)
+ }
+ m.HcaHandles = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.HcaHandles |= uint32(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field HcaObjects", wireType)
+ }
+ m.HcaObjects = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.HcaObjects |= uint32(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *NetworkStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: NetworkStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: NetworkStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Name = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RxBytes", wireType)
+ }
+ m.RxBytes = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RxBytes |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RxPackets", wireType)
+ }
+ m.RxPackets = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RxPackets |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RxErrors", wireType)
+ }
+ m.RxErrors = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RxErrors |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field RxDropped", wireType)
+ }
+ m.RxDropped = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.RxDropped |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TxBytes", wireType)
+ }
+ m.TxBytes = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TxBytes |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 7:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TxPackets", wireType)
+ }
+ m.TxPackets = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TxPackets |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 8:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TxErrors", wireType)
+ }
+ m.TxErrors = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TxErrors |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 9:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field TxDropped", wireType)
+ }
+ m.TxDropped = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.TxDropped |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CgroupStats) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CgroupStats: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CgroupStats: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NrSleeping", wireType)
+ }
+ m.NrSleeping = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.NrSleeping |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NrRunning", wireType)
+ }
+ m.NrRunning = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.NrRunning |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NrStopped", wireType)
+ }
+ m.NrStopped = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.NrStopped |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NrUninterruptible", wireType)
+ }
+ m.NrUninterruptible = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.NrUninterruptible |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NrIoWait", wireType)
+ }
+ m.NrIoWait = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.NrIoWait |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipMetrics(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ depth := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ case 1:
+ iNdEx += 8
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if length < 0 {
+ return 0, ErrInvalidLengthMetrics
+ }
+ iNdEx += length
+ case 3:
+ depth++
+ case 4:
+ if depth == 0 {
+ return 0, ErrUnexpectedEndOfGroupMetrics
+ }
+ depth--
+ case 5:
+ iNdEx += 4
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ if iNdEx < 0 {
+ return 0, ErrInvalidLengthMetrics
+ }
+ if depth == 0 {
+ return iNdEx, nil
+ }
+ }
+ return 0, io.ErrUnexpectedEOF
+}
+
+var (
+ ErrInvalidLengthMetrics = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowMetrics = fmt.Errorf("proto: integer overflow")
+ ErrUnexpectedEndOfGroupMetrics = fmt.Errorf("proto: unexpected end of group")
+)
diff --git a/vendor/github.com/containerd/cgroups/stats/v1/metrics.pb.txt b/vendor/github.com/containerd/cgroups/stats/v1/metrics.pb.txt
@@ -0,0 +1,790 @@
+file {
+ name: "github.com/containerd/cgroups/stats/v1/metrics.proto"
+ package: "io.containerd.cgroups.v1"
+ dependency: "gogoproto/gogo.proto"
+ message_type {
+ name: "Metrics"
+ field {
+ name: "hugetlb"
+ number: 1
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.HugetlbStat"
+ json_name: "hugetlb"
+ }
+ field {
+ name: "pids"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.PidsStat"
+ json_name: "pids"
+ }
+ field {
+ name: "cpu"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.CPUStat"
+ options {
+ 65004: "CPU"
+ }
+ json_name: "cpu"
+ }
+ field {
+ name: "memory"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.MemoryStat"
+ json_name: "memory"
+ }
+ field {
+ name: "blkio"
+ number: 5
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.BlkIOStat"
+ json_name: "blkio"
+ }
+ field {
+ name: "rdma"
+ number: 6
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.RdmaStat"
+ json_name: "rdma"
+ }
+ field {
+ name: "network"
+ number: 7
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.NetworkStat"
+ json_name: "network"
+ }
+ field {
+ name: "cgroup_stats"
+ number: 8
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.CgroupStats"
+ json_name: "cgroupStats"
+ }
+ field {
+ name: "memory_oom_control"
+ number: 9
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.MemoryOomControl"
+ json_name: "memoryOomControl"
+ }
+ }
+ message_type {
+ name: "HugetlbStat"
+ field {
+ name: "usage"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "usage"
+ }
+ field {
+ name: "max"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "max"
+ }
+ field {
+ name: "failcnt"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "failcnt"
+ }
+ field {
+ name: "pagesize"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_STRING
+ json_name: "pagesize"
+ }
+ }
+ message_type {
+ name: "PidsStat"
+ field {
+ name: "current"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "current"
+ }
+ field {
+ name: "limit"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "limit"
+ }
+ }
+ message_type {
+ name: "CPUStat"
+ field {
+ name: "usage"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.CPUUsage"
+ json_name: "usage"
+ }
+ field {
+ name: "throttling"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.Throttle"
+ json_name: "throttling"
+ }
+ }
+ message_type {
+ name: "CPUUsage"
+ field {
+ name: "total"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "total"
+ }
+ field {
+ name: "kernel"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "kernel"
+ }
+ field {
+ name: "user"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "user"
+ }
+ field {
+ name: "per_cpu"
+ number: 4
+ label: LABEL_REPEATED
+ type: TYPE_UINT64
+ options {
+ 65004: "PerCPU"
+ }
+ json_name: "perCpu"
+ }
+ }
+ message_type {
+ name: "Throttle"
+ field {
+ name: "periods"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "periods"
+ }
+ field {
+ name: "throttled_periods"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "throttledPeriods"
+ }
+ field {
+ name: "throttled_time"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "throttledTime"
+ }
+ }
+ message_type {
+ name: "MemoryStat"
+ field {
+ name: "cache"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "cache"
+ }
+ field {
+ name: "rss"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ options {
+ 65004: "RSS"
+ }
+ json_name: "rss"
+ }
+ field {
+ name: "rss_huge"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ options {
+ 65004: "RSSHuge"
+ }
+ json_name: "rssHuge"
+ }
+ field {
+ name: "mapped_file"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "mappedFile"
+ }
+ field {
+ name: "dirty"
+ number: 5
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "dirty"
+ }
+ field {
+ name: "writeback"
+ number: 6
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "writeback"
+ }
+ field {
+ name: "pg_pg_in"
+ number: 7
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgPgIn"
+ }
+ field {
+ name: "pg_pg_out"
+ number: 8
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgPgOut"
+ }
+ field {
+ name: "pg_fault"
+ number: 9
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgFault"
+ }
+ field {
+ name: "pg_maj_fault"
+ number: 10
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgMajFault"
+ }
+ field {
+ name: "inactive_anon"
+ number: 11
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "inactiveAnon"
+ }
+ field {
+ name: "active_anon"
+ number: 12
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "activeAnon"
+ }
+ field {
+ name: "inactive_file"
+ number: 13
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "inactiveFile"
+ }
+ field {
+ name: "active_file"
+ number: 14
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "activeFile"
+ }
+ field {
+ name: "unevictable"
+ number: 15
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "unevictable"
+ }
+ field {
+ name: "hierarchical_memory_limit"
+ number: 16
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "hierarchicalMemoryLimit"
+ }
+ field {
+ name: "hierarchical_swap_limit"
+ number: 17
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "hierarchicalSwapLimit"
+ }
+ field {
+ name: "total_cache"
+ number: 18
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalCache"
+ }
+ field {
+ name: "total_rss"
+ number: 19
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ options {
+ 65004: "TotalRSS"
+ }
+ json_name: "totalRss"
+ }
+ field {
+ name: "total_rss_huge"
+ number: 20
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ options {
+ 65004: "TotalRSSHuge"
+ }
+ json_name: "totalRssHuge"
+ }
+ field {
+ name: "total_mapped_file"
+ number: 21
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalMappedFile"
+ }
+ field {
+ name: "total_dirty"
+ number: 22
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalDirty"
+ }
+ field {
+ name: "total_writeback"
+ number: 23
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalWriteback"
+ }
+ field {
+ name: "total_pg_pg_in"
+ number: 24
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalPgPgIn"
+ }
+ field {
+ name: "total_pg_pg_out"
+ number: 25
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalPgPgOut"
+ }
+ field {
+ name: "total_pg_fault"
+ number: 26
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalPgFault"
+ }
+ field {
+ name: "total_pg_maj_fault"
+ number: 27
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalPgMajFault"
+ }
+ field {
+ name: "total_inactive_anon"
+ number: 28
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalInactiveAnon"
+ }
+ field {
+ name: "total_active_anon"
+ number: 29
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalActiveAnon"
+ }
+ field {
+ name: "total_inactive_file"
+ number: 30
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalInactiveFile"
+ }
+ field {
+ name: "total_active_file"
+ number: 31
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalActiveFile"
+ }
+ field {
+ name: "total_unevictable"
+ number: 32
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "totalUnevictable"
+ }
+ field {
+ name: "usage"
+ number: 33
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.MemoryEntry"
+ json_name: "usage"
+ }
+ field {
+ name: "swap"
+ number: 34
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.MemoryEntry"
+ json_name: "swap"
+ }
+ field {
+ name: "kernel"
+ number: 35
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.MemoryEntry"
+ json_name: "kernel"
+ }
+ field {
+ name: "kernel_tcp"
+ number: 36
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.MemoryEntry"
+ options {
+ 65004: "KernelTCP"
+ }
+ json_name: "kernelTcp"
+ }
+ }
+ message_type {
+ name: "MemoryEntry"
+ field {
+ name: "limit"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "limit"
+ }
+ field {
+ name: "usage"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "usage"
+ }
+ field {
+ name: "max"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "max"
+ }
+ field {
+ name: "failcnt"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "failcnt"
+ }
+ }
+ message_type {
+ name: "MemoryOomControl"
+ field {
+ name: "oom_kill_disable"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "oomKillDisable"
+ }
+ field {
+ name: "under_oom"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "underOom"
+ }
+ field {
+ name: "oom_kill"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "oomKill"
+ }
+ }
+ message_type {
+ name: "BlkIOStat"
+ field {
+ name: "io_service_bytes_recursive"
+ number: 1
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.BlkIOEntry"
+ json_name: "ioServiceBytesRecursive"
+ }
+ field {
+ name: "io_serviced_recursive"
+ number: 2
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.BlkIOEntry"
+ json_name: "ioServicedRecursive"
+ }
+ field {
+ name: "io_queued_recursive"
+ number: 3
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.BlkIOEntry"
+ json_name: "ioQueuedRecursive"
+ }
+ field {
+ name: "io_service_time_recursive"
+ number: 4
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.BlkIOEntry"
+ json_name: "ioServiceTimeRecursive"
+ }
+ field {
+ name: "io_wait_time_recursive"
+ number: 5
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.BlkIOEntry"
+ json_name: "ioWaitTimeRecursive"
+ }
+ field {
+ name: "io_merged_recursive"
+ number: 6
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.BlkIOEntry"
+ json_name: "ioMergedRecursive"
+ }
+ field {
+ name: "io_time_recursive"
+ number: 7
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.BlkIOEntry"
+ json_name: "ioTimeRecursive"
+ }
+ field {
+ name: "sectors_recursive"
+ number: 8
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.BlkIOEntry"
+ json_name: "sectorsRecursive"
+ }
+ }
+ message_type {
+ name: "BlkIOEntry"
+ field {
+ name: "op"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_STRING
+ json_name: "op"
+ }
+ field {
+ name: "device"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_STRING
+ json_name: "device"
+ }
+ field {
+ name: "major"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "major"
+ }
+ field {
+ name: "minor"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "minor"
+ }
+ field {
+ name: "value"
+ number: 5
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "value"
+ }
+ }
+ message_type {
+ name: "RdmaStat"
+ field {
+ name: "current"
+ number: 1
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.RdmaEntry"
+ json_name: "current"
+ }
+ field {
+ name: "limit"
+ number: 2
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v1.RdmaEntry"
+ json_name: "limit"
+ }
+ }
+ message_type {
+ name: "RdmaEntry"
+ field {
+ name: "device"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_STRING
+ json_name: "device"
+ }
+ field {
+ name: "hca_handles"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT32
+ json_name: "hcaHandles"
+ }
+ field {
+ name: "hca_objects"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT32
+ json_name: "hcaObjects"
+ }
+ }
+ message_type {
+ name: "NetworkStat"
+ field {
+ name: "name"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_STRING
+ json_name: "name"
+ }
+ field {
+ name: "rx_bytes"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "rxBytes"
+ }
+ field {
+ name: "rx_packets"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "rxPackets"
+ }
+ field {
+ name: "rx_errors"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "rxErrors"
+ }
+ field {
+ name: "rx_dropped"
+ number: 5
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "rxDropped"
+ }
+ field {
+ name: "tx_bytes"
+ number: 6
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "txBytes"
+ }
+ field {
+ name: "tx_packets"
+ number: 7
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "txPackets"
+ }
+ field {
+ name: "tx_errors"
+ number: 8
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "txErrors"
+ }
+ field {
+ name: "tx_dropped"
+ number: 9
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "txDropped"
+ }
+ }
+ message_type {
+ name: "CgroupStats"
+ field {
+ name: "nr_sleeping"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "nrSleeping"
+ }
+ field {
+ name: "nr_running"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "nrRunning"
+ }
+ field {
+ name: "nr_stopped"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "nrStopped"
+ }
+ field {
+ name: "nr_uninterruptible"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "nrUninterruptible"
+ }
+ field {
+ name: "nr_io_wait"
+ number: 5
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "nrIoWait"
+ }
+ }
+ syntax: "proto3"
+}
diff --git a/vendor/github.com/containerd/cgroups/stats/v1/metrics.proto b/vendor/github.com/containerd/cgroups/stats/v1/metrics.proto
@@ -0,0 +1,158 @@
+syntax = "proto3";
+
+package io.containerd.cgroups.v1;
+
+import "gogoproto/gogo.proto";
+
+message Metrics {
+ repeated HugetlbStat hugetlb = 1;
+ PidsStat pids = 2;
+ CPUStat cpu = 3 [(gogoproto.customname) = "CPU"];
+ MemoryStat memory = 4;
+ BlkIOStat blkio = 5;
+ RdmaStat rdma = 6;
+ repeated NetworkStat network = 7;
+ CgroupStats cgroup_stats = 8;
+ MemoryOomControl memory_oom_control = 9;
+}
+
+message HugetlbStat {
+ uint64 usage = 1;
+ uint64 max = 2;
+ uint64 failcnt = 3;
+ string pagesize = 4;
+}
+
+message PidsStat {
+ uint64 current = 1;
+ uint64 limit = 2;
+}
+
+message CPUStat {
+ CPUUsage usage = 1;
+ Throttle throttling = 2;
+}
+
+message CPUUsage {
+ // values in nanoseconds
+ uint64 total = 1;
+ uint64 kernel = 2;
+ uint64 user = 3;
+ repeated uint64 per_cpu = 4 [(gogoproto.customname) = "PerCPU"];
+
+}
+
+message Throttle {
+ uint64 periods = 1;
+ uint64 throttled_periods = 2;
+ uint64 throttled_time = 3;
+}
+
+message MemoryStat {
+ uint64 cache = 1;
+ uint64 rss = 2 [(gogoproto.customname) = "RSS"];
+ uint64 rss_huge = 3 [(gogoproto.customname) = "RSSHuge"];
+ uint64 mapped_file = 4;
+ uint64 dirty = 5;
+ uint64 writeback = 6;
+ uint64 pg_pg_in = 7;
+ uint64 pg_pg_out = 8;
+ uint64 pg_fault = 9;
+ uint64 pg_maj_fault = 10;
+ uint64 inactive_anon = 11;
+ uint64 active_anon = 12;
+ uint64 inactive_file = 13;
+ uint64 active_file = 14;
+ uint64 unevictable = 15;
+ uint64 hierarchical_memory_limit = 16;
+ uint64 hierarchical_swap_limit = 17;
+ uint64 total_cache = 18;
+ uint64 total_rss = 19 [(gogoproto.customname) = "TotalRSS"];
+ uint64 total_rss_huge = 20 [(gogoproto.customname) = "TotalRSSHuge"];
+ uint64 total_mapped_file = 21;
+ uint64 total_dirty = 22;
+ uint64 total_writeback = 23;
+ uint64 total_pg_pg_in = 24;
+ uint64 total_pg_pg_out = 25;
+ uint64 total_pg_fault = 26;
+ uint64 total_pg_maj_fault = 27;
+ uint64 total_inactive_anon = 28;
+ uint64 total_active_anon = 29;
+ uint64 total_inactive_file = 30;
+ uint64 total_active_file = 31;
+ uint64 total_unevictable = 32;
+ MemoryEntry usage = 33;
+ MemoryEntry swap = 34;
+ MemoryEntry kernel = 35;
+ MemoryEntry kernel_tcp = 36 [(gogoproto.customname) = "KernelTCP"];
+
+}
+
+message MemoryEntry {
+ uint64 limit = 1;
+ uint64 usage = 2;
+ uint64 max = 3;
+ uint64 failcnt = 4;
+}
+
+message MemoryOomControl {
+ uint64 oom_kill_disable = 1;
+ uint64 under_oom = 2;
+ uint64 oom_kill = 3;
+}
+
+message BlkIOStat {
+ repeated BlkIOEntry io_service_bytes_recursive = 1;
+ repeated BlkIOEntry io_serviced_recursive = 2;
+ repeated BlkIOEntry io_queued_recursive = 3;
+ repeated BlkIOEntry io_service_time_recursive = 4;
+ repeated BlkIOEntry io_wait_time_recursive = 5;
+ repeated BlkIOEntry io_merged_recursive = 6;
+ repeated BlkIOEntry io_time_recursive = 7;
+ repeated BlkIOEntry sectors_recursive = 8;
+}
+
+message BlkIOEntry {
+ string op = 1;
+ string device = 2;
+ uint64 major = 3;
+ uint64 minor = 4;
+ uint64 value = 5;
+}
+
+message RdmaStat {
+ repeated RdmaEntry current = 1;
+ repeated RdmaEntry limit = 2;
+}
+
+message RdmaEntry {
+ string device = 1;
+ uint32 hca_handles = 2;
+ uint32 hca_objects = 3;
+}
+
+message NetworkStat {
+ string name = 1;
+ uint64 rx_bytes = 2;
+ uint64 rx_packets = 3;
+ uint64 rx_errors = 4;
+ uint64 rx_dropped = 5;
+ uint64 tx_bytes = 6;
+ uint64 tx_packets = 7;
+ uint64 tx_errors = 8;
+ uint64 tx_dropped = 9;
+}
+
+// CgroupStats exports per-cgroup statistics.
+message CgroupStats {
+ // number of tasks sleeping
+ uint64 nr_sleeping = 1;
+ // number of tasks running
+ uint64 nr_running = 2;
+ // number of tasks in stopped state
+ uint64 nr_stopped = 3;
+ // number of tasks in uninterruptible state
+ uint64 nr_uninterruptible = 4;
+ // number of tasks waiting on IO
+ uint64 nr_io_wait = 5;
+}
diff --git a/vendor/github.com/containerd/cgroups/subsystem.go b/vendor/github.com/containerd/cgroups/subsystem.go
@@ -0,0 +1,116 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "fmt"
+ "os"
+
+ v1 "github.com/containerd/cgroups/stats/v1"
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+// Name is a typed name for a cgroup subsystem
+type Name string
+
+const (
+ Devices Name = "devices"
+ Hugetlb Name = "hugetlb"
+ Freezer Name = "freezer"
+ Pids Name = "pids"
+ NetCLS Name = "net_cls"
+ NetPrio Name = "net_prio"
+ PerfEvent Name = "perf_event"
+ Cpuset Name = "cpuset"
+ Cpu Name = "cpu"
+ Cpuacct Name = "cpuacct"
+ Memory Name = "memory"
+ Blkio Name = "blkio"
+ Rdma Name = "rdma"
+)
+
+// Subsystems returns a complete list of the default cgroups
+// available on most linux systems
+func Subsystems() []Name {
+ n := []Name{
+ Freezer,
+ Pids,
+ NetCLS,
+ NetPrio,
+ PerfEvent,
+ Cpuset,
+ Cpu,
+ Cpuacct,
+ Memory,
+ Blkio,
+ Rdma,
+ }
+ if !RunningInUserNS() {
+ n = append(n, Devices)
+ }
+ if _, err := os.Stat("/sys/kernel/mm/hugepages"); err == nil {
+ n = append(n, Hugetlb)
+ }
+ return n
+}
+
+type Subsystem interface {
+ Name() Name
+}
+
+type pather interface {
+ Subsystem
+ Path(path string) string
+}
+
+type creator interface {
+ Subsystem
+ Create(path string, resources *specs.LinuxResources) error
+}
+
+type deleter interface {
+ Subsystem
+ Delete(path string) error
+}
+
+type stater interface {
+ Subsystem
+ Stat(path string, stats *v1.Metrics) error
+}
+
+type updater interface {
+ Subsystem
+ Update(path string, resources *specs.LinuxResources) error
+}
+
+// SingleSubsystem returns a single cgroup subsystem within the base Hierarchy
+func SingleSubsystem(baseHierarchy Hierarchy, subsystem Name) Hierarchy {
+ return func() ([]Subsystem, error) {
+ subsystems, err := baseHierarchy()
+ if err != nil {
+ return nil, err
+ }
+ for _, s := range subsystems {
+ if s.Name() == subsystem {
+ return []Subsystem{
+ s,
+ }, nil
+ }
+ }
+ return nil, fmt.Errorf("unable to find subsystem %s", subsystem)
+ }
+}
diff --git a/vendor/github.com/containerd/cgroups/systemd.go b/vendor/github.com/containerd/cgroups/systemd.go
@@ -0,0 +1,158 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "context"
+ "path/filepath"
+ "strings"
+ "sync"
+
+ systemdDbus "github.com/coreos/go-systemd/v22/dbus"
+ "github.com/godbus/dbus/v5"
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+)
+
+const (
+ SystemdDbus Name = "systemd"
+ defaultSlice = "system.slice"
+)
+
+var (
+ canDelegate bool
+ once sync.Once
+)
+
+func Systemd() ([]Subsystem, error) {
+ root, err := v1MountPoint()
+ if err != nil {
+ return nil, err
+ }
+ defaultSubsystems, err := defaults(root)
+ if err != nil {
+ return nil, err
+ }
+ s, err := NewSystemd(root)
+ if err != nil {
+ return nil, err
+ }
+ // make sure the systemd controller is added first
+ return append([]Subsystem{s}, defaultSubsystems...), nil
+}
+
+func Slice(slice, name string) Path {
+ if slice == "" {
+ slice = defaultSlice
+ }
+ return func(subsystem Name) (string, error) {
+ return filepath.Join(slice, name), nil
+ }
+}
+
+func NewSystemd(root string) (*SystemdController, error) {
+ return &SystemdController{
+ root: root,
+ }, nil
+}
+
+type SystemdController struct {
+ mu sync.Mutex
+ root string
+}
+
+func (s *SystemdController) Name() Name {
+ return SystemdDbus
+}
+
+func (s *SystemdController) Create(path string, _ *specs.LinuxResources) error {
+ ctx := context.TODO()
+ conn, err := systemdDbus.NewWithContext(ctx)
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+ slice, name := splitName(path)
+ // We need to see if systemd can handle the delegate property
+ // Systemd will return an error if it cannot handle delegate regardless
+ // of its bool setting.
+ checkDelegate := func() {
+ canDelegate = true
+ dlSlice := newProperty("Delegate", true)
+ if _, err := conn.StartTransientUnitContext(ctx, slice, "testdelegate", []systemdDbus.Property{dlSlice}, nil); err != nil {
+ if dbusError, ok := err.(dbus.Error); ok {
+ // Starting with systemd v237, Delegate is not even a property of slices anymore,
+ // so the D-Bus call fails with "InvalidArgs" error.
+ if strings.Contains(dbusError.Name, "org.freedesktop.DBus.Error.PropertyReadOnly") || strings.Contains(dbusError.Name, "org.freedesktop.DBus.Error.InvalidArgs") {
+ canDelegate = false
+ }
+ }
+ }
+
+ _, _ = conn.StopUnitContext(ctx, slice, "testDelegate", nil)
+ }
+ once.Do(checkDelegate)
+ properties := []systemdDbus.Property{
+ systemdDbus.PropDescription("cgroup " + name),
+ systemdDbus.PropWants(slice),
+ newProperty("DefaultDependencies", false),
+ newProperty("MemoryAccounting", true),
+ newProperty("CPUAccounting", true),
+ newProperty("BlockIOAccounting", true),
+ }
+
+ // If we can delegate, we add the property back in
+ if canDelegate {
+ properties = append(properties, newProperty("Delegate", true))
+ }
+
+ ch := make(chan string)
+ _, err = conn.StartTransientUnitContext(ctx, name, "replace", properties, ch)
+ if err != nil {
+ return err
+ }
+ <-ch
+ return nil
+}
+
+func (s *SystemdController) Delete(path string) error {
+ ctx := context.TODO()
+ conn, err := systemdDbus.NewWithContext(ctx)
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+ _, name := splitName(path)
+ ch := make(chan string)
+ _, err = conn.StopUnitContext(ctx, name, "replace", ch)
+ if err != nil {
+ return err
+ }
+ <-ch
+ return nil
+}
+
+func newProperty(name string, units interface{}) systemdDbus.Property {
+ return systemdDbus.Property{
+ Name: name,
+ Value: dbus.MakeVariant(units),
+ }
+}
+
+func splitName(path string) (slice string, unit string) {
+ slice, unit = filepath.Split(path)
+ return strings.TrimSuffix(slice, "/"), unit
+}
diff --git a/vendor/github.com/containerd/cgroups/ticks.go b/vendor/github.com/containerd/cgroups/ticks.go
@@ -0,0 +1,26 @@
+/*
+ Copyright The containerd 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 cgroups
+
+func getClockTicks() uint64 {
+ // The value comes from `C.sysconf(C._SC_CLK_TCK)`, and
+ // on Linux it's a constant which is safe to be hard coded,
+ // so we can avoid using cgo here.
+ // See https://github.com/containerd/cgroups/pull/12 for
+ // more details.
+ return 100
+}
diff --git a/vendor/github.com/containerd/cgroups/utils.go b/vendor/github.com/containerd/cgroups/utils.go
@@ -0,0 +1,392 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ units "github.com/docker/go-units"
+ specs "github.com/opencontainers/runtime-spec/specs-go"
+ "golang.org/x/sys/unix"
+)
+
+var (
+ nsOnce sync.Once
+ inUserNS bool
+ checkMode sync.Once
+ cgMode CGMode
+)
+
+const unifiedMountpoint = "/sys/fs/cgroup"
+
+// CGMode is the cgroups mode of the host system
+type CGMode int
+
+const (
+ // Unavailable cgroup mountpoint
+ Unavailable CGMode = iota
+ // Legacy cgroups v1
+ Legacy
+ // Hybrid with cgroups v1 and v2 controllers mounted
+ Hybrid
+ // Unified with only cgroups v2 mounted
+ Unified
+)
+
+// Mode returns the cgroups mode running on the host
+func Mode() CGMode {
+ checkMode.Do(func() {
+ var st unix.Statfs_t
+ if err := unix.Statfs(unifiedMountpoint, &st); err != nil {
+ cgMode = Unavailable
+ return
+ }
+ switch st.Type {
+ case unix.CGROUP2_SUPER_MAGIC:
+ cgMode = Unified
+ default:
+ cgMode = Legacy
+ if err := unix.Statfs(filepath.Join(unifiedMountpoint, "unified"), &st); err != nil {
+ return
+ }
+ if st.Type == unix.CGROUP2_SUPER_MAGIC {
+ cgMode = Hybrid
+ }
+ }
+ })
+ return cgMode
+}
+
+// RunningInUserNS detects whether we are currently running in a user namespace.
+// Copied from github.com/lxc/lxd/shared/util.go
+func RunningInUserNS() bool {
+ nsOnce.Do(func() {
+ file, err := os.Open("/proc/self/uid_map")
+ if err != nil {
+ // This kernel-provided file only exists if user namespaces are supported
+ return
+ }
+ defer file.Close()
+
+ buf := bufio.NewReader(file)
+ l, _, err := buf.ReadLine()
+ if err != nil {
+ return
+ }
+
+ line := string(l)
+ var a, b, c int64
+ fmt.Sscanf(line, "%d %d %d", &a, &b, &c)
+
+ /*
+ * We assume we are in the initial user namespace if we have a full
+ * range - 4294967295 uids starting at uid 0.
+ */
+ if a == 0 && b == 0 && c == 4294967295 {
+ return
+ }
+ inUserNS = true
+ })
+ return inUserNS
+}
+
+// defaults returns all known groups
+func defaults(root string) ([]Subsystem, error) {
+ h, err := NewHugetlb(root)
+ if err != nil && !os.IsNotExist(err) {
+ return nil, err
+ }
+ s := []Subsystem{
+ NewNamed(root, "systemd"),
+ NewFreezer(root),
+ NewPids(root),
+ NewNetCls(root),
+ NewNetPrio(root),
+ NewPerfEvent(root),
+ NewCpuset(root),
+ NewCpu(root),
+ NewCpuacct(root),
+ NewMemory(root),
+ NewBlkio(root),
+ NewRdma(root),
+ }
+ // only add the devices cgroup if we are not in a user namespace
+ // because modifications are not allowed
+ if !RunningInUserNS() {
+ s = append(s, NewDevices(root))
+ }
+ // add the hugetlb cgroup if error wasn't due to missing hugetlb
+ // cgroup support on the host
+ if err == nil {
+ s = append(s, h)
+ }
+ return s, nil
+}
+
+// remove will remove a cgroup path handling EAGAIN and EBUSY errors and
+// retrying the remove after a exp timeout
+func remove(path string) error {
+ delay := 10 * time.Millisecond
+ for i := 0; i < 5; i++ {
+ if i != 0 {
+ time.Sleep(delay)
+ delay *= 2
+ }
+ if err := os.RemoveAll(path); err == nil {
+ return nil
+ }
+ }
+ return fmt.Errorf("cgroups: unable to remove path %q", path)
+}
+
+// readPids will read all the pids of processes or tasks in a cgroup by the provided path
+func readPids(path string, subsystem Name, pType procType) ([]Process, error) {
+ f, err := os.Open(filepath.Join(path, pType))
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ var (
+ out []Process
+ s = bufio.NewScanner(f)
+ )
+ for s.Scan() {
+ if t := s.Text(); t != "" {
+ pid, err := strconv.Atoi(t)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, Process{
+ Pid: pid,
+ Subsystem: subsystem,
+ Path: path,
+ })
+ }
+ }
+ if err := s.Err(); err != nil {
+ // failed to read all pids?
+ return nil, err
+ }
+ return out, nil
+}
+
+func hugePageSizes() ([]string, error) {
+ var (
+ pageSizes []string
+ sizeList = []string{"B", "KB", "MB", "GB", "TB", "PB"}
+ )
+ files, err := ioutil.ReadDir("/sys/kernel/mm/hugepages")
+ if err != nil {
+ return nil, err
+ }
+ for _, st := range files {
+ nameArray := strings.Split(st.Name(), "-")
+ pageSize, err := units.RAMInBytes(nameArray[1])
+ if err != nil {
+ return nil, err
+ }
+ pageSizes = append(pageSizes, units.CustomSize("%g%s", float64(pageSize), 1024.0, sizeList))
+ }
+ return pageSizes, nil
+}
+
+func readUint(path string) (uint64, error) {
+ v, err := ioutil.ReadFile(path)
+ if err != nil {
+ return 0, err
+ }
+ return parseUint(strings.TrimSpace(string(v)), 10, 64)
+}
+
+func parseUint(s string, base, bitSize int) (uint64, error) {
+ v, err := strconv.ParseUint(s, base, bitSize)
+ if err != nil {
+ intValue, intErr := strconv.ParseInt(s, base, bitSize)
+ // 1. Handle negative values greater than MinInt64 (and)
+ // 2. Handle negative values lesser than MinInt64
+ if intErr == nil && intValue < 0 {
+ return 0, nil
+ } else if intErr != nil &&
+ intErr.(*strconv.NumError).Err == strconv.ErrRange &&
+ intValue < 0 {
+ return 0, nil
+ }
+ return 0, err
+ }
+ return v, nil
+}
+
+func parseKV(raw string) (string, uint64, error) {
+ parts := strings.Fields(raw)
+ switch len(parts) {
+ case 2:
+ v, err := parseUint(parts[1], 10, 64)
+ if err != nil {
+ return "", 0, err
+ }
+ return parts[0], v, nil
+ default:
+ return "", 0, ErrInvalidFormat
+ }
+}
+
+// ParseCgroupFile parses the given cgroup file, typically /proc/self/cgroup
+// or /proc/<pid>/cgroup, into a map of subsystems to cgroup paths, e.g.
+// "cpu": "/user.slice/user-1000.slice"
+// "pids": "/user.slice/user-1000.slice"
+// etc.
+//
+// The resulting map does not have an element for cgroup v2 unified hierarchy.
+// Use ParseCgroupFileUnified to get the unified path.
+func ParseCgroupFile(path string) (map[string]string, error) {
+ x, _, err := ParseCgroupFileUnified(path)
+ return x, err
+}
+
+// ParseCgroupFileUnified returns legacy subsystem paths as the first value,
+// and returns the unified path as the second value.
+func ParseCgroupFileUnified(path string) (map[string]string, string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, "", err
+ }
+ defer f.Close()
+ return parseCgroupFromReaderUnified(f)
+}
+
+func parseCgroupFromReaderUnified(r io.Reader) (map[string]string, string, error) {
+ var (
+ cgroups = make(map[string]string)
+ unified = ""
+ s = bufio.NewScanner(r)
+ )
+ for s.Scan() {
+ var (
+ text = s.Text()
+ parts = strings.SplitN(text, ":", 3)
+ )
+ if len(parts) < 3 {
+ return nil, unified, fmt.Errorf("invalid cgroup entry: %q", text)
+ }
+ for _, subs := range strings.Split(parts[1], ",") {
+ if subs == "" {
+ unified = parts[2]
+ } else {
+ cgroups[subs] = parts[2]
+ }
+ }
+ }
+ if err := s.Err(); err != nil {
+ return nil, unified, err
+ }
+ return cgroups, unified, nil
+}
+
+func getCgroupDestination(subsystem string) (string, error) {
+ f, err := os.Open("/proc/self/mountinfo")
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ s := bufio.NewScanner(f)
+ for s.Scan() {
+ fields := strings.Split(s.Text(), " ")
+ if len(fields) < 10 {
+ // broken mountinfo?
+ continue
+ }
+ if fields[len(fields)-3] != "cgroup" {
+ continue
+ }
+ for _, opt := range strings.Split(fields[len(fields)-1], ",") {
+ if opt == subsystem {
+ return fields[3], nil
+ }
+ }
+ }
+ if err := s.Err(); err != nil {
+ return "", err
+ }
+ return "", ErrNoCgroupMountDestination
+}
+
+func pathers(subystems []Subsystem) []pather {
+ var out []pather
+ for _, s := range subystems {
+ if p, ok := s.(pather); ok {
+ out = append(out, p)
+ }
+ }
+ return out
+}
+
+func initializeSubsystem(s Subsystem, path Path, resources *specs.LinuxResources) error {
+ if c, ok := s.(creator); ok {
+ p, err := path(s.Name())
+ if err != nil {
+ return err
+ }
+ if err := c.Create(p, resources); err != nil {
+ return err
+ }
+ } else if c, ok := s.(pather); ok {
+ p, err := path(s.Name())
+ if err != nil {
+ return err
+ }
+ // do the default create if the group does not have a custom one
+ if err := os.MkdirAll(c.Path(p), defaultDirPerm); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func cleanPath(path string) string {
+ if path == "" {
+ return ""
+ }
+ path = filepath.Clean(path)
+ if !filepath.IsAbs(path) {
+ path, _ = filepath.Rel(string(os.PathSeparator), filepath.Clean(string(os.PathSeparator)+path))
+ }
+ return path
+}
+
+func retryingWriteFile(path string, data []byte, mode os.FileMode) error {
+ // Retry writes on EINTR; see:
+ // https://github.com/golang/go/issues/38033
+ for {
+ err := ioutil.WriteFile(path, data, mode)
+ if err == nil {
+ return nil
+ } else if !errors.Is(err, syscall.EINTR) {
+ return err
+ }
+ }
+}
diff --git a/vendor/github.com/containerd/cgroups/v1.go b/vendor/github.com/containerd/cgroups/v1.go
@@ -0,0 +1,73 @@
+/*
+ Copyright The containerd 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 cgroups
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// V1 returns all the groups in the default cgroups mountpoint in a single hierarchy
+func V1() ([]Subsystem, error) {
+ root, err := v1MountPoint()
+ if err != nil {
+ return nil, err
+ }
+ subsystems, err := defaults(root)
+ if err != nil {
+ return nil, err
+ }
+ var enabled []Subsystem
+ for _, s := range pathers(subsystems) {
+ // check and remove the default groups that do not exist
+ if _, err := os.Lstat(s.Path("/")); err == nil {
+ enabled = append(enabled, s)
+ }
+ }
+ return enabled, nil
+}
+
+// v1MountPoint returns the mount point where the cgroup
+// mountpoints are mounted in a single hiearchy
+func v1MountPoint() (string, error) {
+ f, err := os.Open("/proc/self/mountinfo")
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ var (
+ text = scanner.Text()
+ fields = strings.Split(text, " ")
+ numFields = len(fields)
+ )
+ if numFields < 10 {
+ return "", fmt.Errorf("mountinfo: bad entry %q", text)
+ }
+ if fields[numFields-3] == "cgroup" {
+ return filepath.Dir(fields[4]), nil
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ return "", err
+ }
+ return "", ErrMountPointNotExist
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/cpu.go b/vendor/github.com/containerd/cgroups/v2/cpu.go
@@ -0,0 +1,83 @@
+/*
+ Copyright The containerd 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 v2
+
+import (
+ "math"
+ "strconv"
+ "strings"
+)
+
+type CPUMax string
+
+func NewCPUMax(quota *int64, period *uint64) CPUMax {
+ max := "max"
+ if quota != nil {
+ max = strconv.FormatInt(*quota, 10)
+ }
+ return CPUMax(strings.Join([]string{max, strconv.FormatUint(*period, 10)}, " "))
+}
+
+type CPU struct {
+ Weight *uint64
+ Max CPUMax
+ Cpus string
+ Mems string
+}
+
+func (c CPUMax) extractQuotaAndPeriod() (int64, uint64) {
+ var (
+ quota int64
+ period uint64
+ )
+ values := strings.Split(string(c), " ")
+ if values[0] == "max" {
+ quota = math.MaxInt64
+ } else {
+ quota, _ = strconv.ParseInt(values[0], 10, 64)
+ }
+ period, _ = strconv.ParseUint(values[1], 10, 64)
+ return quota, period
+}
+
+func (r *CPU) Values() (o []Value) {
+ if r.Weight != nil {
+ o = append(o, Value{
+ filename: "cpu.weight",
+ value: *r.Weight,
+ })
+ }
+ if r.Max != "" {
+ o = append(o, Value{
+ filename: "cpu.max",
+ value: r.Max,
+ })
+ }
+ if r.Cpus != "" {
+ o = append(o, Value{
+ filename: "cpuset.cpus",
+ value: r.Cpus,
+ })
+ }
+ if r.Mems != "" {
+ o = append(o, Value{
+ filename: "cpuset.mems",
+ value: r.Mems,
+ })
+ }
+ return o
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/devicefilter.go b/vendor/github.com/containerd/cgroups/v2/devicefilter.go
@@ -0,0 +1,200 @@
+/*
+ Copyright The containerd 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.
+*/
+
+// Devicefilter containes eBPF device filter program
+//
+// The implementation is based on https://github.com/containers/crun/blob/0.10.2/src/libcrun/ebpf.c
+//
+// Although ebpf.c is originally licensed under LGPL-3.0-or-later, the author (Giuseppe Scrivano)
+// agreed to relicense the file in Apache License 2.0: https://github.com/opencontainers/runc/issues/2144#issuecomment-543116397
+//
+// This particular Go implementation based on runc version
+// https://github.com/opencontainers/runc/blob/master/libcontainer/cgroups/ebpf/devicefilter/devicefilter.go
+
+package v2
+
+import (
+ "errors"
+ "fmt"
+ "math"
+
+ "github.com/cilium/ebpf/asm"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "golang.org/x/sys/unix"
+)
+
+const (
+ // license string format is same as kernel MODULE_LICENSE macro
+ license = "Apache"
+)
+
+// DeviceFilter returns eBPF device filter program and its license string
+func DeviceFilter(devices []specs.LinuxDeviceCgroup) (asm.Instructions, string, error) {
+ p := &program{}
+ p.init()
+ for i := len(devices) - 1; i >= 0; i-- {
+ if err := p.appendDevice(devices[i]); err != nil {
+ return nil, "", err
+ }
+ }
+ insts, err := p.finalize()
+ return insts, license, err
+}
+
+type program struct {
+ insts asm.Instructions
+ hasWildCard bool
+ blockID int
+}
+
+func (p *program) init() {
+ // struct bpf_cgroup_dev_ctx: https://elixir.bootlin.com/linux/v5.3.6/source/include/uapi/linux/bpf.h#L3423
+ /*
+ u32 access_type
+ u32 major
+ u32 minor
+ */
+ // R2 <- type (lower 16 bit of u32 access_type at R1[0])
+ p.insts = append(p.insts,
+ asm.LoadMem(asm.R2, asm.R1, 0, asm.Half))
+
+ // R3 <- access (upper 16 bit of u32 access_type at R1[0])
+ p.insts = append(p.insts,
+ asm.LoadMem(asm.R3, asm.R1, 0, asm.Word),
+ // RSh: bitwise shift right
+ asm.RSh.Imm32(asm.R3, 16))
+
+ // R4 <- major (u32 major at R1[4])
+ p.insts = append(p.insts,
+ asm.LoadMem(asm.R4, asm.R1, 4, asm.Word))
+
+ // R5 <- minor (u32 minor at R1[8])
+ p.insts = append(p.insts,
+ asm.LoadMem(asm.R5, asm.R1, 8, asm.Word))
+}
+
+// appendDevice needs to be called from the last element of OCI linux.resources.devices to the head element.
+func (p *program) appendDevice(dev specs.LinuxDeviceCgroup) error {
+ if p.blockID < 0 {
+ return errors.New("the program is finalized")
+ }
+ if p.hasWildCard {
+ // All entries after wildcard entry are ignored
+ return nil
+ }
+
+ bpfType := int32(-1)
+ hasType := true
+ switch dev.Type {
+ case string('c'):
+ bpfType = int32(unix.BPF_DEVCG_DEV_CHAR)
+ case string('b'):
+ bpfType = int32(unix.BPF_DEVCG_DEV_BLOCK)
+ case string('a'):
+ hasType = false
+ default:
+ // if not specified in OCI json, typ is set to DeviceTypeAll
+ return fmt.Errorf("invalid DeviceType %q", dev.Type)
+ }
+ if *dev.Major > math.MaxUint32 {
+ return fmt.Errorf("invalid major %d", *dev.Major)
+ }
+ if *dev.Minor > math.MaxUint32 {
+ return fmt.Errorf("invalid minor %d", *dev.Major)
+ }
+ hasMajor := *dev.Major >= 0 // if not specified in OCI json, major is set to -1
+ hasMinor := *dev.Minor >= 0
+ bpfAccess := int32(0)
+ for _, r := range dev.Access {
+ switch r {
+ case 'r':
+ bpfAccess |= unix.BPF_DEVCG_ACC_READ
+ case 'w':
+ bpfAccess |= unix.BPF_DEVCG_ACC_WRITE
+ case 'm':
+ bpfAccess |= unix.BPF_DEVCG_ACC_MKNOD
+ default:
+ return fmt.Errorf("unknown device access %v", r)
+ }
+ }
+ // If the access is rwm, skip the check.
+ hasAccess := bpfAccess != (unix.BPF_DEVCG_ACC_READ | unix.BPF_DEVCG_ACC_WRITE | unix.BPF_DEVCG_ACC_MKNOD)
+
+ blockSym := fmt.Sprintf("block-%d", p.blockID)
+ nextBlockSym := fmt.Sprintf("block-%d", p.blockID+1)
+ prevBlockLastIdx := len(p.insts) - 1
+ if hasType {
+ p.insts = append(p.insts,
+ // if (R2 != bpfType) goto next
+ asm.JNE.Imm(asm.R2, bpfType, nextBlockSym),
+ )
+ }
+ if hasAccess {
+ p.insts = append(p.insts,
+ // if (R3 & bpfAccess == 0 /* use R1 as a temp var */) goto next
+ asm.Mov.Reg32(asm.R1, asm.R3),
+ asm.And.Imm32(asm.R1, bpfAccess),
+ asm.JEq.Imm(asm.R1, 0, nextBlockSym),
+ )
+ }
+ if hasMajor {
+ p.insts = append(p.insts,
+ // if (R4 != major) goto next
+ asm.JNE.Imm(asm.R4, int32(*dev.Major), nextBlockSym),
+ )
+ }
+ if hasMinor {
+ p.insts = append(p.insts,
+ // if (R5 != minor) goto next
+ asm.JNE.Imm(asm.R5, int32(*dev.Minor), nextBlockSym),
+ )
+ }
+ if !hasType && !hasAccess && !hasMajor && !hasMinor {
+ p.hasWildCard = true
+ }
+ p.insts = append(p.insts, acceptBlock(dev.Allow)...)
+ // set blockSym to the first instruction we added in this iteration
+ p.insts[prevBlockLastIdx+1] = p.insts[prevBlockLastIdx+1].Sym(blockSym)
+ p.blockID++
+ return nil
+}
+
+func (p *program) finalize() (asm.Instructions, error) {
+ if p.hasWildCard {
+ // acceptBlock with asm.Return() is already inserted
+ return p.insts, nil
+ }
+ blockSym := fmt.Sprintf("block-%d", p.blockID)
+ p.insts = append(p.insts,
+ // R0 <- 0
+ asm.Mov.Imm32(asm.R0, 0).Sym(blockSym),
+ asm.Return(),
+ )
+ p.blockID = -1
+ return p.insts, nil
+}
+
+func acceptBlock(accept bool) asm.Instructions {
+ v := int32(0)
+ if accept {
+ v = 1
+ }
+ return []asm.Instruction{
+ // R0 <- v
+ asm.Mov.Imm32(asm.R0, v),
+ asm.Return(),
+ }
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/ebpf.go b/vendor/github.com/containerd/cgroups/v2/ebpf.go
@@ -0,0 +1,96 @@
+/*
+ Copyright The containerd 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 v2
+
+import (
+ "fmt"
+
+ "github.com/cilium/ebpf"
+ "github.com/cilium/ebpf/asm"
+ "github.com/cilium/ebpf/link"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "golang.org/x/sys/unix"
+)
+
+// LoadAttachCgroupDeviceFilter installs eBPF device filter program to /sys/fs/cgroup/<foo> directory.
+//
+// Requires the system to be running in cgroup2 unified-mode with kernel >= 4.15 .
+//
+// https://github.com/torvalds/linux/commit/ebc614f687369f9df99828572b1d85a7c2de3d92
+func LoadAttachCgroupDeviceFilter(insts asm.Instructions, license string, dirFD int) (func() error, error) {
+ nilCloser := func() error {
+ return nil
+ }
+ spec := &ebpf.ProgramSpec{
+ Type: ebpf.CGroupDevice,
+ Instructions: insts,
+ License: license,
+ }
+ prog, err := ebpf.NewProgram(spec)
+ if err != nil {
+ return nilCloser, err
+ }
+ err = link.RawAttachProgram(link.RawAttachProgramOptions{
+ Target: dirFD,
+ Program: prog,
+ Attach: ebpf.AttachCGroupDevice,
+ Flags: unix.BPF_F_ALLOW_MULTI,
+ })
+ if err != nil {
+ return nilCloser, fmt.Errorf("failed to call BPF_PROG_ATTACH (BPF_CGROUP_DEVICE, BPF_F_ALLOW_MULTI): %w", err)
+ }
+ closer := func() error {
+ err = link.RawDetachProgram(link.RawDetachProgramOptions{
+ Target: dirFD,
+ Program: prog,
+ Attach: ebpf.AttachCGroupDevice,
+ })
+ if err != nil {
+ return fmt.Errorf("failed to call BPF_PROG_DETACH (BPF_CGROUP_DEVICE): %w", err)
+ }
+ return nil
+ }
+ return closer, nil
+}
+
+func isRWM(cgroupPermissions string) bool {
+ r := false
+ w := false
+ m := false
+ for _, rn := range cgroupPermissions {
+ switch rn {
+ case 'r':
+ r = true
+ case 'w':
+ w = true
+ case 'm':
+ m = true
+ }
+ }
+ return r && w && m
+}
+
+// the logic is from runc
+// https://github.com/opencontainers/runc/blob/master/libcontainer/cgroups/fs/devices_v2.go#L44
+func canSkipEBPFError(devices []specs.LinuxDeviceCgroup) bool {
+ for _, dev := range devices {
+ if dev.Allow || !isRWM(dev.Access) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/errors.go b/vendor/github.com/containerd/cgroups/v2/errors.go
@@ -0,0 +1,26 @@
+/*
+ Copyright The containerd 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 v2
+
+import (
+ "errors"
+)
+
+var (
+ ErrInvalidFormat = errors.New("cgroups: parsing file with invalid format failed")
+ ErrInvalidGroupPath = errors.New("cgroups: invalid group path")
+)
diff --git a/vendor/github.com/containerd/cgroups/v2/hugetlb.go b/vendor/github.com/containerd/cgroups/v2/hugetlb.go
@@ -0,0 +1,37 @@
+/*
+ Copyright The containerd 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 v2
+
+import "strings"
+
+type HugeTlb []HugeTlbEntry
+
+type HugeTlbEntry struct {
+ HugePageSize string
+ Limit uint64
+}
+
+func (r *HugeTlb) Values() (o []Value) {
+ for _, e := range *r {
+ o = append(o, Value{
+ filename: strings.Join([]string{"hugetlb", e.HugePageSize, "max"}, "."),
+ value: e.Limit,
+ })
+ }
+
+ return o
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/io.go b/vendor/github.com/containerd/cgroups/v2/io.go
@@ -0,0 +1,64 @@
+/*
+ Copyright The containerd 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 v2
+
+import "fmt"
+
+type IOType string
+
+const (
+ ReadBPS IOType = "rbps"
+ WriteBPS IOType = "wbps"
+ ReadIOPS IOType = "riops"
+ WriteIOPS IOType = "wiops"
+)
+
+type BFQ struct {
+ Weight uint16
+}
+
+type Entry struct {
+ Type IOType
+ Major int64
+ Minor int64
+ Rate uint64
+}
+
+func (e Entry) String() string {
+ return fmt.Sprintf("%d:%d %s=%d", e.Major, e.Minor, e.Type, e.Rate)
+}
+
+type IO struct {
+ BFQ BFQ
+ Max []Entry
+}
+
+func (i *IO) Values() (o []Value) {
+ if i.BFQ.Weight != 0 {
+ o = append(o, Value{
+ filename: "io.bfq.weight",
+ value: i.BFQ.Weight,
+ })
+ }
+ for _, e := range i.Max {
+ o = append(o, Value{
+ filename: "io.max",
+ value: e.String(),
+ })
+ }
+ return o
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/manager.go b/vendor/github.com/containerd/cgroups/v2/manager.go
@@ -0,0 +1,863 @@
+/*
+ Copyright The containerd 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 v2
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "math"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/containerd/cgroups/v2/stats"
+
+ systemdDbus "github.com/coreos/go-systemd/v22/dbus"
+ "github.com/godbus/dbus/v5"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/sirupsen/logrus"
+ "golang.org/x/sys/unix"
+)
+
+const (
+ subtreeControl = "cgroup.subtree_control"
+ controllersFile = "cgroup.controllers"
+ defaultCgroup2Path = "/sys/fs/cgroup"
+ defaultSlice = "system.slice"
+)
+
+var (
+ canDelegate bool
+)
+
+type Event struct {
+ Low uint64
+ High uint64
+ Max uint64
+ OOM uint64
+ OOMKill uint64
+}
+
+// Resources for a cgroups v2 unified hierarchy
+type Resources struct {
+ CPU *CPU
+ Memory *Memory
+ Pids *Pids
+ IO *IO
+ RDMA *RDMA
+ HugeTlb *HugeTlb
+ // When len(Devices) is zero, devices are not controlled
+ Devices []specs.LinuxDeviceCgroup
+}
+
+// Values returns the raw filenames and values that
+// can be written to the unified hierarchy
+func (r *Resources) Values() (o []Value) {
+ if r.CPU != nil {
+ o = append(o, r.CPU.Values()...)
+ }
+ if r.Memory != nil {
+ o = append(o, r.Memory.Values()...)
+ }
+ if r.Pids != nil {
+ o = append(o, r.Pids.Values()...)
+ }
+ if r.IO != nil {
+ o = append(o, r.IO.Values()...)
+ }
+ if r.RDMA != nil {
+ o = append(o, r.RDMA.Values()...)
+ }
+ if r.HugeTlb != nil {
+ o = append(o, r.HugeTlb.Values()...)
+ }
+ return o
+}
+
+// EnabledControllers returns the list of all not nil resource controllers
+func (r *Resources) EnabledControllers() (c []string) {
+ if r.CPU != nil {
+ c = append(c, "cpu")
+ c = append(c, "cpuset")
+ }
+ if r.Memory != nil {
+ c = append(c, "memory")
+ }
+ if r.Pids != nil {
+ c = append(c, "pids")
+ }
+ if r.IO != nil {
+ c = append(c, "io")
+ }
+ if r.RDMA != nil {
+ c = append(c, "rdma")
+ }
+ if r.HugeTlb != nil {
+ c = append(c, "hugetlb")
+ }
+ return
+}
+
+// Value of a cgroup setting
+type Value struct {
+ filename string
+ value interface{}
+}
+
+// write the value to the full, absolute path, of a unified hierarchy
+func (c *Value) write(path string, perm os.FileMode) error {
+ var data []byte
+ switch t := c.value.(type) {
+ case uint64:
+ data = []byte(strconv.FormatUint(t, 10))
+ case uint16:
+ data = []byte(strconv.FormatUint(uint64(t), 10))
+ case int64:
+ data = []byte(strconv.FormatInt(t, 10))
+ case []byte:
+ data = t
+ case string:
+ data = []byte(t)
+ case CPUMax:
+ data = []byte(t)
+ default:
+ return ErrInvalidFormat
+ }
+
+ // Retry writes on EINTR; see:
+ // https://github.com/golang/go/issues/38033
+ for {
+ err := ioutil.WriteFile(
+ filepath.Join(path, c.filename),
+ data,
+ perm,
+ )
+ if err == nil {
+ return nil
+ } else if !errors.Is(err, syscall.EINTR) {
+ return err
+ }
+ }
+}
+
+func writeValues(path string, values []Value) error {
+ for _, o := range values {
+ if err := o.write(path, defaultFilePerm); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func NewManager(mountpoint string, group string, resources *Resources) (*Manager, error) {
+ if resources == nil {
+ return nil, errors.New("resources reference is nil")
+ }
+ if err := VerifyGroupPath(group); err != nil {
+ return nil, err
+ }
+ path := filepath.Join(mountpoint, group)
+ if err := os.MkdirAll(path, defaultDirPerm); err != nil {
+ return nil, err
+ }
+ m := Manager{
+ unifiedMountpoint: mountpoint,
+ path: path,
+ }
+ if err := m.ToggleControllers(resources.EnabledControllers(), Enable); err != nil {
+ // clean up cgroup dir on failure
+ os.Remove(path)
+ return nil, err
+ }
+ if err := setResources(path, resources); err != nil {
+ os.Remove(path)
+ return nil, err
+ }
+ return &m, nil
+}
+
+func LoadManager(mountpoint string, group string) (*Manager, error) {
+ if err := VerifyGroupPath(group); err != nil {
+ return nil, err
+ }
+ path := filepath.Join(mountpoint, group)
+ return &Manager{
+ unifiedMountpoint: mountpoint,
+ path: path,
+ }, nil
+}
+
+type Manager struct {
+ unifiedMountpoint string
+ path string
+}
+
+func setResources(path string, resources *Resources) error {
+ if resources != nil {
+ if err := writeValues(path, resources.Values()); err != nil {
+ return err
+ }
+ if err := setDevices(path, resources.Devices); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (c *Manager) RootControllers() ([]string, error) {
+ b, err := ioutil.ReadFile(filepath.Join(c.unifiedMountpoint, controllersFile))
+ if err != nil {
+ return nil, err
+ }
+ return strings.Fields(string(b)), nil
+}
+
+func (c *Manager) Controllers() ([]string, error) {
+ b, err := ioutil.ReadFile(filepath.Join(c.path, controllersFile))
+ if err != nil {
+ return nil, err
+ }
+ return strings.Fields(string(b)), nil
+}
+
+func (c *Manager) Update(resources *Resources) error {
+ return setResources(c.path, resources)
+}
+
+type ControllerToggle int
+
+const (
+ Enable ControllerToggle = iota + 1
+ Disable
+)
+
+func toggleFunc(controllers []string, prefix string) []string {
+ out := make([]string, len(controllers))
+ for i, c := range controllers {
+ out[i] = prefix + c
+ }
+ return out
+}
+
+func (c *Manager) ToggleControllers(controllers []string, t ControllerToggle) error {
+ // when c.path is like /foo/bar/baz, the following files need to be written:
+ // * /sys/fs/cgroup/cgroup.subtree_control
+ // * /sys/fs/cgroup/foo/cgroup.subtree_control
+ // * /sys/fs/cgroup/foo/bar/cgroup.subtree_control
+ // Note that /sys/fs/cgroup/foo/bar/baz/cgroup.subtree_control does not need to be written.
+ split := strings.Split(c.path, "/")
+ var lastErr error
+ for i := range split {
+ f := strings.Join(split[:i], "/")
+ if !strings.HasPrefix(f, c.unifiedMountpoint) || f == c.path {
+ continue
+ }
+ filePath := filepath.Join(f, subtreeControl)
+ if err := c.writeSubtreeControl(filePath, controllers, t); err != nil {
+ // When running as rootless, the user may face EPERM on parent groups, but it is neglible when the
+ // controller is already written.
+ // So we only return the last error.
+ lastErr = fmt.Errorf("failed to write subtree controllers %+v to %q: %w", controllers, filePath, err)
+ } else {
+ lastErr = nil
+ }
+ }
+ return lastErr
+}
+
+func (c *Manager) writeSubtreeControl(filePath string, controllers []string, t ControllerToggle) error {
+ f, err := os.OpenFile(filePath, os.O_WRONLY, 0)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ switch t {
+ case Enable:
+ controllers = toggleFunc(controllers, "+")
+ case Disable:
+ controllers = toggleFunc(controllers, "-")
+ }
+ _, err = f.WriteString(strings.Join(controllers, " "))
+ return err
+}
+
+func (c *Manager) NewChild(name string, resources *Resources) (*Manager, error) {
+ if strings.HasPrefix(name, "/") {
+ return nil, errors.New("name must be relative")
+ }
+ path := filepath.Join(c.path, name)
+ if err := os.MkdirAll(path, defaultDirPerm); err != nil {
+ return nil, err
+ }
+ m := Manager{
+ unifiedMountpoint: c.unifiedMountpoint,
+ path: path,
+ }
+ if resources != nil {
+ if err := m.ToggleControllers(resources.EnabledControllers(), Enable); err != nil {
+ // clean up cgroup dir on failure
+ os.Remove(path)
+ return nil, err
+ }
+ }
+ if err := setResources(path, resources); err != nil {
+ // clean up cgroup dir on failure
+ os.Remove(path)
+ return nil, err
+ }
+ return &m, nil
+}
+
+func (c *Manager) AddProc(pid uint64) error {
+ v := Value{
+ filename: cgroupProcs,
+ value: pid,
+ }
+ return writeValues(c.path, []Value{v})
+}
+
+func (c *Manager) Delete() error {
+ return remove(c.path)
+}
+
+func (c *Manager) Procs(recursive bool) ([]uint64, error) {
+ var processes []uint64
+ err := filepath.Walk(c.path, func(p string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ if !recursive && info.IsDir() {
+ if p == c.path {
+ return nil
+ }
+ return filepath.SkipDir
+ }
+ _, name := filepath.Split(p)
+ if name != cgroupProcs {
+ return nil
+ }
+ procs, err := parseCgroupProcsFile(p)
+ if err != nil {
+ return err
+ }
+ processes = append(processes, procs...)
+ return nil
+ })
+ return processes, err
+}
+
+var singleValueFiles = []string{
+ "pids.current",
+ "pids.max",
+}
+
+func (c *Manager) Stat() (*stats.Metrics, error) {
+ controllers, err := c.Controllers()
+ if err != nil {
+ return nil, err
+ }
+ out := make(map[string]interface{})
+ for _, controller := range controllers {
+ switch controller {
+ case "cpu", "memory":
+ if err := readKVStatsFile(c.path, controller+".stat", out); err != nil {
+ if os.IsNotExist(err) {
+ continue
+ }
+ return nil, err
+ }
+ }
+ }
+ for _, name := range singleValueFiles {
+ if err := readSingleFile(c.path, name, out); err != nil {
+ if os.IsNotExist(err) {
+ continue
+ }
+ return nil, err
+ }
+ }
+ memoryEvents := make(map[string]interface{})
+ if err := readKVStatsFile(c.path, "memory.events", memoryEvents); err != nil {
+ if !os.IsNotExist(err) {
+ return nil, err
+ }
+ }
+ var metrics stats.Metrics
+
+ metrics.Pids = &stats.PidsStat{
+ Current: getPidValue("pids.current", out),
+ Limit: getPidValue("pids.max", out),
+ }
+ metrics.CPU = &stats.CPUStat{
+ UsageUsec: getUint64Value("usage_usec", out),
+ UserUsec: getUint64Value("user_usec", out),
+ SystemUsec: getUint64Value("system_usec", out),
+ NrPeriods: getUint64Value("nr_periods", out),
+ NrThrottled: getUint64Value("nr_throttled", out),
+ ThrottledUsec: getUint64Value("throttled_usec", out),
+ }
+ metrics.Memory = &stats.MemoryStat{
+ Anon: getUint64Value("anon", out),
+ File: getUint64Value("file", out),
+ KernelStack: getUint64Value("kernel_stack", out),
+ Slab: getUint64Value("slab", out),
+ Sock: getUint64Value("sock", out),
+ Shmem: getUint64Value("shmem", out),
+ FileMapped: getUint64Value("file_mapped", out),
+ FileDirty: getUint64Value("file_dirty", out),
+ FileWriteback: getUint64Value("file_writeback", out),
+ AnonThp: getUint64Value("anon_thp", out),
+ InactiveAnon: getUint64Value("inactive_anon", out),
+ ActiveAnon: getUint64Value("active_anon", out),
+ InactiveFile: getUint64Value("inactive_file", out),
+ ActiveFile: getUint64Value("active_file", out),
+ Unevictable: getUint64Value("unevictable", out),
+ SlabReclaimable: getUint64Value("slab_reclaimable", out),
+ SlabUnreclaimable: getUint64Value("slab_unreclaimable", out),
+ Pgfault: getUint64Value("pgfault", out),
+ Pgmajfault: getUint64Value("pgmajfault", out),
+ WorkingsetRefault: getUint64Value("workingset_refault", out),
+ WorkingsetActivate: getUint64Value("workingset_activate", out),
+ WorkingsetNodereclaim: getUint64Value("workingset_nodereclaim", out),
+ Pgrefill: getUint64Value("pgrefill", out),
+ Pgscan: getUint64Value("pgscan", out),
+ Pgsteal: getUint64Value("pgsteal", out),
+ Pgactivate: getUint64Value("pgactivate", out),
+ Pgdeactivate: getUint64Value("pgdeactivate", out),
+ Pglazyfree: getUint64Value("pglazyfree", out),
+ Pglazyfreed: getUint64Value("pglazyfreed", out),
+ ThpFaultAlloc: getUint64Value("thp_fault_alloc", out),
+ ThpCollapseAlloc: getUint64Value("thp_collapse_alloc", out),
+ Usage: getStatFileContentUint64(filepath.Join(c.path, "memory.current")),
+ UsageLimit: getStatFileContentUint64(filepath.Join(c.path, "memory.max")),
+ SwapUsage: getStatFileContentUint64(filepath.Join(c.path, "memory.swap.current")),
+ SwapLimit: getStatFileContentUint64(filepath.Join(c.path, "memory.swap.max")),
+ }
+ if len(memoryEvents) > 0 {
+ metrics.MemoryEvents = &stats.MemoryEvents{
+ Low: getUint64Value("low", memoryEvents),
+ High: getUint64Value("high", memoryEvents),
+ Max: getUint64Value("max", memoryEvents),
+ Oom: getUint64Value("oom", memoryEvents),
+ OomKill: getUint64Value("oom_kill", memoryEvents),
+ }
+ }
+ metrics.Io = &stats.IOStat{Usage: readIoStats(c.path)}
+ metrics.Rdma = &stats.RdmaStat{
+ Current: rdmaStats(filepath.Join(c.path, "rdma.current")),
+ Limit: rdmaStats(filepath.Join(c.path, "rdma.max")),
+ }
+ metrics.Hugetlb = readHugeTlbStats(c.path)
+
+ return &metrics, nil
+}
+
+func getUint64Value(key string, out map[string]interface{}) uint64 {
+ v, ok := out[key]
+ if !ok {
+ return 0
+ }
+ switch t := v.(type) {
+ case uint64:
+ return t
+ }
+ return 0
+}
+
+func getPidValue(key string, out map[string]interface{}) uint64 {
+ v, ok := out[key]
+ if !ok {
+ return 0
+ }
+ switch t := v.(type) {
+ case uint64:
+ return t
+ case string:
+ if t == "max" {
+ return math.MaxUint64
+ }
+ }
+ return 0
+}
+
+func readSingleFile(path string, file string, out map[string]interface{}) error {
+ f, err := os.Open(filepath.Join(path, file))
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ data, err := ioutil.ReadAll(f)
+ if err != nil {
+ return err
+ }
+ s := strings.TrimSpace(string(data))
+ v, err := parseUint(s, 10, 64)
+ if err != nil {
+ // if we cannot parse as a uint, parse as a string
+ out[file] = s
+ return nil
+ }
+ out[file] = v
+ return nil
+}
+
+func readKVStatsFile(path string, file string, out map[string]interface{}) error {
+ f, err := os.Open(filepath.Join(path, file))
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+
+ s := bufio.NewScanner(f)
+ for s.Scan() {
+ name, value, err := parseKV(s.Text())
+ if err != nil {
+ return fmt.Errorf("error while parsing %s (line=%q): %w", filepath.Join(path, file), s.Text(), err)
+ }
+ out[name] = value
+ }
+ return s.Err()
+}
+
+func (c *Manager) Freeze() error {
+ return c.freeze(c.path, Frozen)
+}
+
+func (c *Manager) Thaw() error {
+ return c.freeze(c.path, Thawed)
+}
+
+func (c *Manager) freeze(path string, state State) error {
+ values := state.Values()
+ for {
+ if err := writeValues(path, values); err != nil {
+ return err
+ }
+ current, err := fetchState(path)
+ if err != nil {
+ return err
+ }
+ if current == state {
+ return nil
+ }
+ time.Sleep(1 * time.Millisecond)
+ }
+}
+
+func (c *Manager) isCgroupEmpty() bool {
+ // In case of any error we return true so that we exit and don't leak resources
+ out := make(map[string]interface{})
+ if err := readKVStatsFile(c.path, "cgroup.events", out); err != nil {
+ return true
+ }
+ if v, ok := out["populated"]; ok {
+ populated, ok := v.(uint64)
+ if !ok {
+ return true
+ }
+ return populated == 0
+ }
+ return true
+}
+
+// MemoryEventFD returns inotify file descriptor and 'memory.events' inotify watch descriptor
+func (c *Manager) MemoryEventFD() (int, uint32, error) {
+ fpath := filepath.Join(c.path, "memory.events")
+ fd, err := syscall.InotifyInit()
+ if err != nil {
+ return 0, 0, errors.New("failed to create inotify fd")
+ }
+ wd, err := syscall.InotifyAddWatch(fd, fpath, unix.IN_MODIFY)
+ if err != nil {
+ syscall.Close(fd)
+ return 0, 0, fmt.Errorf("failed to add inotify watch for %q: %w", fpath, err)
+ }
+ // monitor to detect process exit/cgroup deletion
+ evpath := filepath.Join(c.path, "cgroup.events")
+ if _, err = syscall.InotifyAddWatch(fd, evpath, unix.IN_MODIFY); err != nil {
+ syscall.Close(fd)
+ return 0, 0, fmt.Errorf("failed to add inotify watch for %q: %w", evpath, err)
+ }
+
+ return fd, uint32(wd), nil
+}
+
+func (c *Manager) EventChan() (<-chan Event, <-chan error) {
+ ec := make(chan Event)
+ errCh := make(chan error, 1)
+ go c.waitForEvents(ec, errCh)
+
+ return ec, errCh
+}
+
+func parseMemoryEvents(out map[string]interface{}) (Event, error) {
+ e := Event{}
+ if v, ok := out["high"]; ok {
+ e.High, ok = v.(uint64)
+ if !ok {
+ return Event{}, fmt.Errorf("cannot convert high to uint64: %+v", v)
+ }
+ }
+ if v, ok := out["low"]; ok {
+ e.Low, ok = v.(uint64)
+ if !ok {
+ return Event{}, fmt.Errorf("cannot convert low to uint64: %+v", v)
+ }
+ }
+ if v, ok := out["max"]; ok {
+ e.Max, ok = v.(uint64)
+ if !ok {
+ return Event{}, fmt.Errorf("cannot convert max to uint64: %+v", v)
+ }
+ }
+ if v, ok := out["oom"]; ok {
+ e.OOM, ok = v.(uint64)
+ if !ok {
+ return Event{}, fmt.Errorf("cannot convert oom to uint64: %+v", v)
+ }
+ }
+ if v, ok := out["oom_kill"]; ok {
+ e.OOMKill, ok = v.(uint64)
+ if !ok {
+ return Event{}, fmt.Errorf("cannot convert oom_kill to uint64: %+v", v)
+ }
+ }
+ return e, nil
+}
+
+func (c *Manager) waitForEvents(ec chan<- Event, errCh chan<- error) {
+ defer close(errCh)
+
+ fd, _, err := c.MemoryEventFD()
+ if err != nil {
+ errCh <- err
+ return
+ }
+ defer syscall.Close(fd)
+
+ for {
+ buffer := make([]byte, syscall.SizeofInotifyEvent*10)
+ bytesRead, err := syscall.Read(fd, buffer)
+ if err != nil {
+ errCh <- err
+ return
+ }
+ if bytesRead >= syscall.SizeofInotifyEvent {
+ out := make(map[string]interface{})
+ if err := readKVStatsFile(c.path, "memory.events", out); err != nil {
+ // When cgroup is deleted read may return -ENODEV instead of -ENOENT from open.
+ if _, statErr := os.Lstat(filepath.Join(c.path, "memory.events")); !os.IsNotExist(statErr) {
+ errCh <- err
+ }
+ return
+ }
+ e, err := parseMemoryEvents(out)
+ if err != nil {
+ errCh <- err
+ return
+ }
+ ec <- e
+ if c.isCgroupEmpty() {
+ return
+ }
+ }
+ }
+}
+
+func setDevices(path string, devices []specs.LinuxDeviceCgroup) error {
+ if len(devices) == 0 {
+ return nil
+ }
+ insts, license, err := DeviceFilter(devices)
+ if err != nil {
+ return err
+ }
+ dirFD, err := unix.Open(path, unix.O_DIRECTORY|unix.O_RDONLY|unix.O_CLOEXEC, 0600)
+ if err != nil {
+ return fmt.Errorf("cannot get dir FD for %s", path)
+ }
+ defer unix.Close(dirFD)
+ if _, err := LoadAttachCgroupDeviceFilter(insts, license, dirFD); err != nil {
+ if !canSkipEBPFError(devices) {
+ return err
+ }
+ }
+ return nil
+}
+
+// getSystemdFullPath returns the full systemd path when creating a systemd slice group.
+// the reason this is necessary is because the "-" character has a special meaning in
+// systemd slice. For example, when creating a slice called "my-group-112233.slice",
+// systemd will create a hierarchy like this:
+// /sys/fs/cgroup/my.slice/my-group.slice/my-group-112233.slice
+func getSystemdFullPath(slice, group string) string {
+ return filepath.Join(defaultCgroup2Path, dashesToPath(slice), dashesToPath(group))
+}
+
+// dashesToPath converts a slice name with dashes to it's corresponding systemd filesystem path.
+func dashesToPath(in string) string {
+ path := ""
+ if strings.HasSuffix(in, ".slice") && strings.Contains(in, "-") {
+ parts := strings.Split(in, "-")
+ for i := range parts {
+ s := strings.Join(parts[0:i+1], "-")
+ if !strings.HasSuffix(s, ".slice") {
+ s += ".slice"
+ }
+ path = filepath.Join(path, s)
+ }
+ } else {
+ path = filepath.Join(path, in)
+ }
+ return path
+}
+
+func NewSystemd(slice, group string, pid int, resources *Resources) (*Manager, error) {
+ if slice == "" {
+ slice = defaultSlice
+ }
+ ctx := context.TODO()
+ path := getSystemdFullPath(slice, group)
+ conn, err := systemdDbus.NewWithContext(ctx)
+ if err != nil {
+ return &Manager{}, err
+ }
+ defer conn.Close()
+
+ properties := []systemdDbus.Property{
+ systemdDbus.PropDescription("cgroup " + group),
+ newSystemdProperty("DefaultDependencies", false),
+ newSystemdProperty("MemoryAccounting", true),
+ newSystemdProperty("CPUAccounting", true),
+ newSystemdProperty("IOAccounting", true),
+ }
+
+ // if we create a slice, the parent is defined via a Wants=
+ if strings.HasSuffix(group, ".slice") {
+ properties = append(properties, systemdDbus.PropWants(defaultSlice))
+ } else {
+ // otherwise, we use Slice=
+ properties = append(properties, systemdDbus.PropSlice(defaultSlice))
+ }
+
+ // only add pid if its valid, -1 is used w/ general slice creation.
+ if pid != -1 {
+ properties = append(properties, newSystemdProperty("PIDs", []uint32{uint32(pid)}))
+ }
+
+ if resources.Memory != nil && resources.Memory.Min != nil && *resources.Memory.Min != 0 {
+ properties = append(properties,
+ newSystemdProperty("MemoryMin", uint64(*resources.Memory.Min)))
+ }
+
+ if resources.Memory != nil && resources.Memory.Max != nil && *resources.Memory.Max != 0 {
+ properties = append(properties,
+ newSystemdProperty("MemoryMax", uint64(*resources.Memory.Max)))
+ }
+
+ if resources.CPU != nil && resources.CPU.Weight != nil && *resources.CPU.Weight != 0 {
+ properties = append(properties,
+ newSystemdProperty("CPUWeight", *resources.CPU.Weight))
+ }
+
+ if resources.CPU != nil && resources.CPU.Max != "" {
+ quota, period := resources.CPU.Max.extractQuotaAndPeriod()
+ // cpu.cfs_quota_us and cpu.cfs_period_us are controlled by systemd.
+ // corresponds to USEC_INFINITY in systemd
+ // if USEC_INFINITY is provided, CPUQuota is left unbound by systemd
+ // always setting a property value ensures we can apply a quota and remove it later
+ cpuQuotaPerSecUSec := uint64(math.MaxUint64)
+ if quota > 0 {
+ // systemd converts CPUQuotaPerSecUSec (microseconds per CPU second) to CPUQuota
+ // (integer percentage of CPU) internally. This means that if a fractional percent of
+ // CPU is indicated by Resources.CpuQuota, we need to round up to the nearest
+ // 10ms (1% of a second) such that child cgroups can set the cpu.cfs_quota_us they expect.
+ cpuQuotaPerSecUSec = uint64(quota*1000000) / period
+ if cpuQuotaPerSecUSec%10000 != 0 {
+ cpuQuotaPerSecUSec = ((cpuQuotaPerSecUSec / 10000) + 1) * 10000
+ }
+ }
+ properties = append(properties,
+ newSystemdProperty("CPUQuotaPerSecUSec", cpuQuotaPerSecUSec))
+ }
+
+ // If we can delegate, we add the property back in
+ if canDelegate {
+ properties = append(properties, newSystemdProperty("Delegate", true))
+ }
+
+ if resources.Pids != nil && resources.Pids.Max > 0 {
+ properties = append(properties,
+ newSystemdProperty("TasksAccounting", true),
+ newSystemdProperty("TasksMax", uint64(resources.Pids.Max)))
+ }
+
+ statusChan := make(chan string, 1)
+ if _, err := conn.StartTransientUnitContext(ctx, group, "replace", properties, statusChan); err == nil {
+ select {
+ case <-statusChan:
+ case <-time.After(time.Second):
+ logrus.Warnf("Timed out while waiting for StartTransientUnit(%s) completion signal from dbus. Continuing...", group)
+ }
+ } else if !isUnitExists(err) {
+ return &Manager{}, err
+ }
+
+ return &Manager{
+ path: path,
+ }, nil
+}
+
+func LoadSystemd(slice, group string) (*Manager, error) {
+ if slice == "" {
+ slice = defaultSlice
+ }
+ path := getSystemdFullPath(slice, group)
+ return &Manager{
+ path: path,
+ }, nil
+}
+
+func (c *Manager) DeleteSystemd() error {
+ ctx := context.TODO()
+ conn, err := systemdDbus.NewWithContext(ctx)
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+ group := systemdUnitFromPath(c.path)
+ ch := make(chan string)
+ _, err = conn.StopUnitContext(ctx, group, "replace", ch)
+ if err != nil {
+ return err
+ }
+ <-ch
+ return nil
+}
+
+func newSystemdProperty(name string, units interface{}) systemdDbus.Property {
+ return systemdDbus.Property{
+ Name: name,
+ Value: dbus.MakeVariant(units),
+ }
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/memory.go b/vendor/github.com/containerd/cgroups/v2/memory.go
@@ -0,0 +1,59 @@
+/*
+ Copyright The containerd 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 v2
+
+type Memory struct {
+ Swap *int64
+ Min *int64
+ Max *int64
+ Low *int64
+ High *int64
+}
+
+func (r *Memory) Values() (o []Value) {
+ if r.Swap != nil {
+ o = append(o, Value{
+ filename: "memory.swap.max",
+ value: *r.Swap,
+ })
+ }
+ if r.Min != nil {
+ o = append(o, Value{
+ filename: "memory.min",
+ value: *r.Min,
+ })
+ }
+ if r.Max != nil {
+ o = append(o, Value{
+ filename: "memory.max",
+ value: *r.Max,
+ })
+ }
+ if r.Low != nil {
+ o = append(o, Value{
+ filename: "memory.low",
+ value: *r.Low,
+ })
+ }
+ if r.High != nil {
+ o = append(o, Value{
+ filename: "memory.high",
+ value: *r.High,
+ })
+ }
+ return o
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/paths.go b/vendor/github.com/containerd/cgroups/v2/paths.go
@@ -0,0 +1,60 @@
+/*
+ Copyright The containerd 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 v2
+
+import (
+ "fmt"
+ "path/filepath"
+ "strings"
+)
+
+// NestedGroupPath will nest the cgroups based on the calling processes cgroup
+// placing its child processes inside its own path
+func NestedGroupPath(suffix string) (string, error) {
+ path, err := parseCgroupFile("/proc/self/cgroup")
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(path, suffix), nil
+}
+
+// PidGroupPath will return the correct cgroup paths for an existing process running inside a cgroup
+// This is commonly used for the Load function to restore an existing container
+func PidGroupPath(pid int) (string, error) {
+ p := fmt.Sprintf("/proc/%d/cgroup", pid)
+ return parseCgroupFile(p)
+}
+
+// VerifyGroupPath verifies the format of group path string g.
+// The format is same as the third field in /proc/PID/cgroup.
+// e.g. "/user.slice/user-1001.slice/session-1.scope"
+//
+// g must be a "clean" absolute path starts with "/", and must not contain "/sys/fs/cgroup" prefix.
+//
+// VerifyGroupPath doesn't verify whether g actually exists on the system.
+func VerifyGroupPath(g string) error {
+ if !strings.HasPrefix(g, "/") {
+ return ErrInvalidGroupPath
+ }
+ if filepath.Clean(g) != g {
+ return ErrInvalidGroupPath
+ }
+ if strings.HasPrefix(g, "/sys/fs/cgroup") {
+ return ErrInvalidGroupPath
+ }
+ return nil
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/pids.go b/vendor/github.com/containerd/cgroups/v2/pids.go
@@ -0,0 +1,37 @@
+/*
+ Copyright The containerd 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 v2
+
+import "strconv"
+
+type Pids struct {
+ Max int64
+}
+
+func (r *Pids) Values() (o []Value) {
+ if r.Max != 0 {
+ limit := "max"
+ if r.Max > 0 {
+ limit = strconv.FormatInt(r.Max, 10)
+ }
+ o = append(o, Value{
+ filename: "pids.max",
+ value: limit,
+ })
+ }
+ return o
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/rdma.go b/vendor/github.com/containerd/cgroups/v2/rdma.go
@@ -0,0 +1,46 @@
+/*
+ Copyright The containerd 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 v2
+
+import (
+ "fmt"
+)
+
+type RDMA struct {
+ Limit []RDMAEntry
+}
+
+type RDMAEntry struct {
+ Device string
+ HcaHandles uint32
+ HcaObjects uint32
+}
+
+func (r RDMAEntry) String() string {
+ return fmt.Sprintf("%s hca_handle=%d hca_object=%d", r.Device, r.HcaHandles, r.HcaObjects)
+}
+
+func (r *RDMA) Values() (o []Value) {
+ for _, e := range r.Limit {
+ o = append(o, Value{
+ filename: "rdma.max",
+ value: e.String(),
+ })
+ }
+
+ return o
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/state.go b/vendor/github.com/containerd/cgroups/v2/state.go
@@ -0,0 +1,65 @@
+/*
+ Copyright The containerd 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 v2
+
+import (
+ "io/ioutil"
+ "path/filepath"
+ "strings"
+)
+
+// State is a type that represents the state of the current cgroup
+type State string
+
+const (
+ Unknown State = ""
+ Thawed State = "thawed"
+ Frozen State = "frozen"
+ Deleted State = "deleted"
+
+ cgroupFreeze = "cgroup.freeze"
+)
+
+func (s State) Values() []Value {
+ v := Value{
+ filename: cgroupFreeze,
+ }
+ switch s {
+ case Frozen:
+ v.value = "1"
+ case Thawed:
+ v.value = "0"
+ }
+ return []Value{
+ v,
+ }
+}
+
+func fetchState(path string) (State, error) {
+ current, err := ioutil.ReadFile(filepath.Join(path, cgroupFreeze))
+ if err != nil {
+ return Unknown, err
+ }
+ switch strings.TrimSpace(string(current)) {
+ case "1":
+ return Frozen, nil
+ case "0":
+ return Thawed, nil
+ default:
+ return Unknown, nil
+ }
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/stats/doc.go b/vendor/github.com/containerd/cgroups/v2/stats/doc.go
@@ -0,0 +1,17 @@
+/*
+ Copyright The containerd 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 stats
diff --git a/vendor/github.com/containerd/cgroups/v2/stats/metrics.pb.go b/vendor/github.com/containerd/cgroups/v2/stats/metrics.pb.go
@@ -0,0 +1,3992 @@
+// Code generated by protoc-gen-gogo. DO NOT EDIT.
+// source: github.com/containerd/cgroups/v2/stats/metrics.proto
+
+package stats
+
+import (
+ fmt "fmt"
+ _ "github.com/gogo/protobuf/gogoproto"
+ proto "github.com/gogo/protobuf/proto"
+ io "io"
+ math "math"
+ math_bits "math/bits"
+ reflect "reflect"
+ strings "strings"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
+
+type Metrics struct {
+ Pids *PidsStat `protobuf:"bytes,1,opt,name=pids,proto3" json:"pids,omitempty"`
+ CPU *CPUStat `protobuf:"bytes,2,opt,name=cpu,proto3" json:"cpu,omitempty"`
+ Memory *MemoryStat `protobuf:"bytes,4,opt,name=memory,proto3" json:"memory,omitempty"`
+ Rdma *RdmaStat `protobuf:"bytes,5,opt,name=rdma,proto3" json:"rdma,omitempty"`
+ Io *IOStat `protobuf:"bytes,6,opt,name=io,proto3" json:"io,omitempty"`
+ Hugetlb []*HugeTlbStat `protobuf:"bytes,7,rep,name=hugetlb,proto3" json:"hugetlb,omitempty"`
+ MemoryEvents *MemoryEvents `protobuf:"bytes,8,opt,name=memory_events,json=memoryEvents,proto3" json:"memory_events,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *Metrics) Reset() { *m = Metrics{} }
+func (*Metrics) ProtoMessage() {}
+func (*Metrics) Descriptor() ([]byte, []int) {
+ return fileDescriptor_2fc6005842049e6b, []int{0}
+}
+func (m *Metrics) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *Metrics) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_Metrics.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *Metrics) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_Metrics.Merge(m, src)
+}
+func (m *Metrics) XXX_Size() int {
+ return m.Size()
+}
+func (m *Metrics) XXX_DiscardUnknown() {
+ xxx_messageInfo_Metrics.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_Metrics proto.InternalMessageInfo
+
+type PidsStat struct {
+ Current uint64 `protobuf:"varint,1,opt,name=current,proto3" json:"current,omitempty"`
+ Limit uint64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *PidsStat) Reset() { *m = PidsStat{} }
+func (*PidsStat) ProtoMessage() {}
+func (*PidsStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_2fc6005842049e6b, []int{1}
+}
+func (m *PidsStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *PidsStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_PidsStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *PidsStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_PidsStat.Merge(m, src)
+}
+func (m *PidsStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *PidsStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_PidsStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_PidsStat proto.InternalMessageInfo
+
+type CPUStat struct {
+ UsageUsec uint64 `protobuf:"varint,1,opt,name=usage_usec,json=usageUsec,proto3" json:"usage_usec,omitempty"`
+ UserUsec uint64 `protobuf:"varint,2,opt,name=user_usec,json=userUsec,proto3" json:"user_usec,omitempty"`
+ SystemUsec uint64 `protobuf:"varint,3,opt,name=system_usec,json=systemUsec,proto3" json:"system_usec,omitempty"`
+ NrPeriods uint64 `protobuf:"varint,4,opt,name=nr_periods,json=nrPeriods,proto3" json:"nr_periods,omitempty"`
+ NrThrottled uint64 `protobuf:"varint,5,opt,name=nr_throttled,json=nrThrottled,proto3" json:"nr_throttled,omitempty"`
+ ThrottledUsec uint64 `protobuf:"varint,6,opt,name=throttled_usec,json=throttledUsec,proto3" json:"throttled_usec,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *CPUStat) Reset() { *m = CPUStat{} }
+func (*CPUStat) ProtoMessage() {}
+func (*CPUStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_2fc6005842049e6b, []int{2}
+}
+func (m *CPUStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *CPUStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_CPUStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *CPUStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_CPUStat.Merge(m, src)
+}
+func (m *CPUStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *CPUStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_CPUStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_CPUStat proto.InternalMessageInfo
+
+type MemoryStat struct {
+ Anon uint64 `protobuf:"varint,1,opt,name=anon,proto3" json:"anon,omitempty"`
+ File uint64 `protobuf:"varint,2,opt,name=file,proto3" json:"file,omitempty"`
+ KernelStack uint64 `protobuf:"varint,3,opt,name=kernel_stack,json=kernelStack,proto3" json:"kernel_stack,omitempty"`
+ Slab uint64 `protobuf:"varint,4,opt,name=slab,proto3" json:"slab,omitempty"`
+ Sock uint64 `protobuf:"varint,5,opt,name=sock,proto3" json:"sock,omitempty"`
+ Shmem uint64 `protobuf:"varint,6,opt,name=shmem,proto3" json:"shmem,omitempty"`
+ FileMapped uint64 `protobuf:"varint,7,opt,name=file_mapped,json=fileMapped,proto3" json:"file_mapped,omitempty"`
+ FileDirty uint64 `protobuf:"varint,8,opt,name=file_dirty,json=fileDirty,proto3" json:"file_dirty,omitempty"`
+ FileWriteback uint64 `protobuf:"varint,9,opt,name=file_writeback,json=fileWriteback,proto3" json:"file_writeback,omitempty"`
+ AnonThp uint64 `protobuf:"varint,10,opt,name=anon_thp,json=anonThp,proto3" json:"anon_thp,omitempty"`
+ InactiveAnon uint64 `protobuf:"varint,11,opt,name=inactive_anon,json=inactiveAnon,proto3" json:"inactive_anon,omitempty"`
+ ActiveAnon uint64 `protobuf:"varint,12,opt,name=active_anon,json=activeAnon,proto3" json:"active_anon,omitempty"`
+ InactiveFile uint64 `protobuf:"varint,13,opt,name=inactive_file,json=inactiveFile,proto3" json:"inactive_file,omitempty"`
+ ActiveFile uint64 `protobuf:"varint,14,opt,name=active_file,json=activeFile,proto3" json:"active_file,omitempty"`
+ Unevictable uint64 `protobuf:"varint,15,opt,name=unevictable,proto3" json:"unevictable,omitempty"`
+ SlabReclaimable uint64 `protobuf:"varint,16,opt,name=slab_reclaimable,json=slabReclaimable,proto3" json:"slab_reclaimable,omitempty"`
+ SlabUnreclaimable uint64 `protobuf:"varint,17,opt,name=slab_unreclaimable,json=slabUnreclaimable,proto3" json:"slab_unreclaimable,omitempty"`
+ Pgfault uint64 `protobuf:"varint,18,opt,name=pgfault,proto3" json:"pgfault,omitempty"`
+ Pgmajfault uint64 `protobuf:"varint,19,opt,name=pgmajfault,proto3" json:"pgmajfault,omitempty"`
+ WorkingsetRefault uint64 `protobuf:"varint,20,opt,name=workingset_refault,json=workingsetRefault,proto3" json:"workingset_refault,omitempty"`
+ WorkingsetActivate uint64 `protobuf:"varint,21,opt,name=workingset_activate,json=workingsetActivate,proto3" json:"workingset_activate,omitempty"`
+ WorkingsetNodereclaim uint64 `protobuf:"varint,22,opt,name=workingset_nodereclaim,json=workingsetNodereclaim,proto3" json:"workingset_nodereclaim,omitempty"`
+ Pgrefill uint64 `protobuf:"varint,23,opt,name=pgrefill,proto3" json:"pgrefill,omitempty"`
+ Pgscan uint64 `protobuf:"varint,24,opt,name=pgscan,proto3" json:"pgscan,omitempty"`
+ Pgsteal uint64 `protobuf:"varint,25,opt,name=pgsteal,proto3" json:"pgsteal,omitempty"`
+ Pgactivate uint64 `protobuf:"varint,26,opt,name=pgactivate,proto3" json:"pgactivate,omitempty"`
+ Pgdeactivate uint64 `protobuf:"varint,27,opt,name=pgdeactivate,proto3" json:"pgdeactivate,omitempty"`
+ Pglazyfree uint64 `protobuf:"varint,28,opt,name=pglazyfree,proto3" json:"pglazyfree,omitempty"`
+ Pglazyfreed uint64 `protobuf:"varint,29,opt,name=pglazyfreed,proto3" json:"pglazyfreed,omitempty"`
+ ThpFaultAlloc uint64 `protobuf:"varint,30,opt,name=thp_fault_alloc,json=thpFaultAlloc,proto3" json:"thp_fault_alloc,omitempty"`
+ ThpCollapseAlloc uint64 `protobuf:"varint,31,opt,name=thp_collapse_alloc,json=thpCollapseAlloc,proto3" json:"thp_collapse_alloc,omitempty"`
+ Usage uint64 `protobuf:"varint,32,opt,name=usage,proto3" json:"usage,omitempty"`
+ UsageLimit uint64 `protobuf:"varint,33,opt,name=usage_limit,json=usageLimit,proto3" json:"usage_limit,omitempty"`
+ SwapUsage uint64 `protobuf:"varint,34,opt,name=swap_usage,json=swapUsage,proto3" json:"swap_usage,omitempty"`
+ SwapLimit uint64 `protobuf:"varint,35,opt,name=swap_limit,json=swapLimit,proto3" json:"swap_limit,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *MemoryStat) Reset() { *m = MemoryStat{} }
+func (*MemoryStat) ProtoMessage() {}
+func (*MemoryStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_2fc6005842049e6b, []int{3}
+}
+func (m *MemoryStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *MemoryStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_MemoryStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *MemoryStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MemoryStat.Merge(m, src)
+}
+func (m *MemoryStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *MemoryStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_MemoryStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_MemoryStat proto.InternalMessageInfo
+
+type MemoryEvents struct {
+ Low uint64 `protobuf:"varint,1,opt,name=low,proto3" json:"low,omitempty"`
+ High uint64 `protobuf:"varint,2,opt,name=high,proto3" json:"high,omitempty"`
+ Max uint64 `protobuf:"varint,3,opt,name=max,proto3" json:"max,omitempty"`
+ Oom uint64 `protobuf:"varint,4,opt,name=oom,proto3" json:"oom,omitempty"`
+ OomKill uint64 `protobuf:"varint,5,opt,name=oom_kill,json=oomKill,proto3" json:"oom_kill,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *MemoryEvents) Reset() { *m = MemoryEvents{} }
+func (*MemoryEvents) ProtoMessage() {}
+func (*MemoryEvents) Descriptor() ([]byte, []int) {
+ return fileDescriptor_2fc6005842049e6b, []int{4}
+}
+func (m *MemoryEvents) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *MemoryEvents) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_MemoryEvents.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *MemoryEvents) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MemoryEvents.Merge(m, src)
+}
+func (m *MemoryEvents) XXX_Size() int {
+ return m.Size()
+}
+func (m *MemoryEvents) XXX_DiscardUnknown() {
+ xxx_messageInfo_MemoryEvents.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_MemoryEvents proto.InternalMessageInfo
+
+type RdmaStat struct {
+ Current []*RdmaEntry `protobuf:"bytes,1,rep,name=current,proto3" json:"current,omitempty"`
+ Limit []*RdmaEntry `protobuf:"bytes,2,rep,name=limit,proto3" json:"limit,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *RdmaStat) Reset() { *m = RdmaStat{} }
+func (*RdmaStat) ProtoMessage() {}
+func (*RdmaStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_2fc6005842049e6b, []int{5}
+}
+func (m *RdmaStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *RdmaStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_RdmaStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *RdmaStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_RdmaStat.Merge(m, src)
+}
+func (m *RdmaStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *RdmaStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_RdmaStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_RdmaStat proto.InternalMessageInfo
+
+type RdmaEntry struct {
+ Device string `protobuf:"bytes,1,opt,name=device,proto3" json:"device,omitempty"`
+ HcaHandles uint32 `protobuf:"varint,2,opt,name=hca_handles,json=hcaHandles,proto3" json:"hca_handles,omitempty"`
+ HcaObjects uint32 `protobuf:"varint,3,opt,name=hca_objects,json=hcaObjects,proto3" json:"hca_objects,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *RdmaEntry) Reset() { *m = RdmaEntry{} }
+func (*RdmaEntry) ProtoMessage() {}
+func (*RdmaEntry) Descriptor() ([]byte, []int) {
+ return fileDescriptor_2fc6005842049e6b, []int{6}
+}
+func (m *RdmaEntry) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *RdmaEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_RdmaEntry.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *RdmaEntry) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_RdmaEntry.Merge(m, src)
+}
+func (m *RdmaEntry) XXX_Size() int {
+ return m.Size()
+}
+func (m *RdmaEntry) XXX_DiscardUnknown() {
+ xxx_messageInfo_RdmaEntry.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_RdmaEntry proto.InternalMessageInfo
+
+type IOStat struct {
+ Usage []*IOEntry `protobuf:"bytes,1,rep,name=usage,proto3" json:"usage,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *IOStat) Reset() { *m = IOStat{} }
+func (*IOStat) ProtoMessage() {}
+func (*IOStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_2fc6005842049e6b, []int{7}
+}
+func (m *IOStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *IOStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_IOStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *IOStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_IOStat.Merge(m, src)
+}
+func (m *IOStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *IOStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_IOStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_IOStat proto.InternalMessageInfo
+
+type IOEntry struct {
+ Major uint64 `protobuf:"varint,1,opt,name=major,proto3" json:"major,omitempty"`
+ Minor uint64 `protobuf:"varint,2,opt,name=minor,proto3" json:"minor,omitempty"`
+ Rbytes uint64 `protobuf:"varint,3,opt,name=rbytes,proto3" json:"rbytes,omitempty"`
+ Wbytes uint64 `protobuf:"varint,4,opt,name=wbytes,proto3" json:"wbytes,omitempty"`
+ Rios uint64 `protobuf:"varint,5,opt,name=rios,proto3" json:"rios,omitempty"`
+ Wios uint64 `protobuf:"varint,6,opt,name=wios,proto3" json:"wios,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *IOEntry) Reset() { *m = IOEntry{} }
+func (*IOEntry) ProtoMessage() {}
+func (*IOEntry) Descriptor() ([]byte, []int) {
+ return fileDescriptor_2fc6005842049e6b, []int{8}
+}
+func (m *IOEntry) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *IOEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_IOEntry.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *IOEntry) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_IOEntry.Merge(m, src)
+}
+func (m *IOEntry) XXX_Size() int {
+ return m.Size()
+}
+func (m *IOEntry) XXX_DiscardUnknown() {
+ xxx_messageInfo_IOEntry.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_IOEntry proto.InternalMessageInfo
+
+type HugeTlbStat struct {
+ Current uint64 `protobuf:"varint,1,opt,name=current,proto3" json:"current,omitempty"`
+ Max uint64 `protobuf:"varint,2,opt,name=max,proto3" json:"max,omitempty"`
+ Pagesize string `protobuf:"bytes,3,opt,name=pagesize,proto3" json:"pagesize,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *HugeTlbStat) Reset() { *m = HugeTlbStat{} }
+func (*HugeTlbStat) ProtoMessage() {}
+func (*HugeTlbStat) Descriptor() ([]byte, []int) {
+ return fileDescriptor_2fc6005842049e6b, []int{9}
+}
+func (m *HugeTlbStat) XXX_Unmarshal(b []byte) error {
+ return m.Unmarshal(b)
+}
+func (m *HugeTlbStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ if deterministic {
+ return xxx_messageInfo_HugeTlbStat.Marshal(b, m, deterministic)
+ } else {
+ b = b[:cap(b)]
+ n, err := m.MarshalToSizedBuffer(b)
+ if err != nil {
+ return nil, err
+ }
+ return b[:n], nil
+ }
+}
+func (m *HugeTlbStat) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_HugeTlbStat.Merge(m, src)
+}
+func (m *HugeTlbStat) XXX_Size() int {
+ return m.Size()
+}
+func (m *HugeTlbStat) XXX_DiscardUnknown() {
+ xxx_messageInfo_HugeTlbStat.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_HugeTlbStat proto.InternalMessageInfo
+
+func init() {
+ proto.RegisterType((*Metrics)(nil), "io.containerd.cgroups.v2.Metrics")
+ proto.RegisterType((*PidsStat)(nil), "io.containerd.cgroups.v2.PidsStat")
+ proto.RegisterType((*CPUStat)(nil), "io.containerd.cgroups.v2.CPUStat")
+ proto.RegisterType((*MemoryStat)(nil), "io.containerd.cgroups.v2.MemoryStat")
+ proto.RegisterType((*MemoryEvents)(nil), "io.containerd.cgroups.v2.MemoryEvents")
+ proto.RegisterType((*RdmaStat)(nil), "io.containerd.cgroups.v2.RdmaStat")
+ proto.RegisterType((*RdmaEntry)(nil), "io.containerd.cgroups.v2.RdmaEntry")
+ proto.RegisterType((*IOStat)(nil), "io.containerd.cgroups.v2.IOStat")
+ proto.RegisterType((*IOEntry)(nil), "io.containerd.cgroups.v2.IOEntry")
+ proto.RegisterType((*HugeTlbStat)(nil), "io.containerd.cgroups.v2.HugeTlbStat")
+}
+
+func init() {
+ proto.RegisterFile("github.com/containerd/cgroups/v2/stats/metrics.proto", fileDescriptor_2fc6005842049e6b)
+}
+
+var fileDescriptor_2fc6005842049e6b = []byte{
+ // 1198 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x56, 0x4d, 0x73, 0xd4, 0x46,
+ 0x13, 0x66, 0xed, 0xc5, 0xeb, 0xed, 0xb5, 0xc1, 0x0c, 0x86, 0x57, 0xc0, 0xcb, 0xda, 0x5e, 0x02,
+ 0x45, 0xaa, 0x92, 0xdd, 0x94, 0xf3, 0x55, 0x49, 0x91, 0x4a, 0x19, 0x02, 0x45, 0x8a, 0x10, 0x5c,
+ 0x02, 0x57, 0x8e, 0xaa, 0x59, 0x69, 0x2c, 0x0d, 0x96, 0x34, 0xaa, 0x99, 0x91, 0x1d, 0x73, 0xca,
+ 0x21, 0xd7, 0x54, 0x7e, 0x4d, 0xfe, 0x03, 0xb7, 0xe4, 0x98, 0x53, 0x2a, 0xf8, 0x97, 0xa4, 0xba,
+ 0x67, 0x64, 0x29, 0x07, 0x43, 0x6e, 0xd3, 0x4f, 0x3f, 0xdd, 0xea, 0x8f, 0x99, 0x6e, 0xc1, 0x27,
+ 0xa9, 0xb4, 0x59, 0x3d, 0x9f, 0xc6, 0xaa, 0x98, 0xc5, 0xaa, 0xb4, 0x5c, 0x96, 0x42, 0x27, 0xb3,
+ 0x38, 0xd5, 0xaa, 0xae, 0xcc, 0xec, 0x70, 0x7b, 0x66, 0x2c, 0xb7, 0x66, 0x56, 0x08, 0xab, 0x65,
+ 0x6c, 0xa6, 0x95, 0x56, 0x56, 0xb1, 0x40, 0xaa, 0x69, 0xcb, 0x9e, 0x7a, 0xf6, 0xf4, 0x70, 0xfb,
+ 0xfa, 0x7a, 0xaa, 0x52, 0x45, 0xa4, 0x19, 0x9e, 0x1c, 0x7f, 0xf2, 0xdb, 0x22, 0x0c, 0x9e, 0x3a,
+ 0x0f, 0xec, 0x33, 0xe8, 0x57, 0x32, 0x31, 0x41, 0x6f, 0xb3, 0x77, 0x77, 0xb4, 0x3d, 0x99, 0x9e,
+ 0xe5, 0x6a, 0xba, 0x2b, 0x13, 0xf3, 0xdc, 0x72, 0x1b, 0x12, 0x9f, 0xdd, 0x83, 0xc5, 0xb8, 0xaa,
+ 0x83, 0x05, 0x32, 0xdb, 0x3a, 0xdb, 0xec, 0xc1, 0xee, 0x1e, 0x5a, 0xdd, 0x1f, 0x9c, 0xfc, 0xb5,
+ 0xb1, 0xf8, 0x60, 0x77, 0x2f, 0x44, 0x33, 0x76, 0x0f, 0x96, 0x0a, 0x51, 0x28, 0x7d, 0x1c, 0xf4,
+ 0xc9, 0xc1, 0x7b, 0x67, 0x3b, 0x78, 0x4a, 0x3c, 0xfa, 0xb2, 0xb7, 0xc1, 0x98, 0x75, 0x52, 0xf0,
+ 0xe0, 0xfc, 0xbb, 0x62, 0x0e, 0x93, 0x82, 0xbb, 0x98, 0x91, 0xcf, 0x3e, 0x82, 0x05, 0xa9, 0x82,
+ 0x25, 0xb2, 0xda, 0x3c, 0xdb, 0xea, 0xdb, 0x67, 0x64, 0xb3, 0x20, 0x15, 0xfb, 0x1a, 0x06, 0x59,
+ 0x9d, 0x0a, 0x9b, 0xcf, 0x83, 0xc1, 0xe6, 0xe2, 0xdd, 0xd1, 0xf6, 0xed, 0xb3, 0xcd, 0x1e, 0xd7,
+ 0xa9, 0x78, 0x91, 0xcf, 0xc9, 0xb6, 0xb1, 0x62, 0x4f, 0x60, 0xd5, 0x05, 0x1d, 0x89, 0x43, 0x51,
+ 0x5a, 0x13, 0x2c, 0xd3, 0xd7, 0xef, 0xbc, 0x2b, 0xdf, 0x87, 0xc4, 0x0e, 0x57, 0x8a, 0x8e, 0x34,
+ 0xf9, 0x12, 0x96, 0x9b, 0x2e, 0xb0, 0x00, 0x06, 0x71, 0xad, 0xb5, 0x28, 0x2d, 0xb5, 0xae, 0x1f,
+ 0x36, 0x22, 0x5b, 0x87, 0xf3, 0xb9, 0x2c, 0xa4, 0xa5, 0xde, 0xf4, 0x43, 0x27, 0x4c, 0x7e, 0xef,
+ 0xc1, 0xc0, 0xf7, 0x82, 0xdd, 0x04, 0xa8, 0x0d, 0x4f, 0x45, 0x54, 0x1b, 0x11, 0x7b, 0xf3, 0x21,
+ 0x21, 0x7b, 0x46, 0xc4, 0xec, 0x06, 0x0c, 0x6b, 0x23, 0xb4, 0xd3, 0x3a, 0x27, 0xcb, 0x08, 0x90,
+ 0x72, 0x03, 0x46, 0xe6, 0xd8, 0x58, 0x51, 0x38, 0xf5, 0x22, 0xa9, 0xc1, 0x41, 0x44, 0xb8, 0x09,
+ 0x50, 0xea, 0xa8, 0x12, 0x5a, 0xaa, 0xc4, 0x50, 0x7b, 0xfb, 0xe1, 0xb0, 0xd4, 0xbb, 0x0e, 0x60,
+ 0x5b, 0xb0, 0x52, 0xea, 0xc8, 0x66, 0x5a, 0x59, 0x9b, 0x8b, 0x84, 0x7a, 0xd8, 0x0f, 0x47, 0xa5,
+ 0x7e, 0xd1, 0x40, 0xec, 0x36, 0x5c, 0x38, 0xd5, 0xbb, 0xaf, 0x2c, 0x11, 0x69, 0xf5, 0x14, 0xc5,
+ 0x0f, 0x4d, 0x7e, 0x1d, 0x02, 0xb4, 0x97, 0x83, 0x31, 0xe8, 0xf3, 0x52, 0x95, 0x3e, 0x1d, 0x3a,
+ 0x23, 0xb6, 0x2f, 0x73, 0xe1, 0x93, 0xa0, 0x33, 0x06, 0x70, 0x20, 0x74, 0x29, 0xf2, 0xc8, 0x58,
+ 0x1e, 0x1f, 0xf8, 0x0c, 0x46, 0x0e, 0x7b, 0x8e, 0x10, 0x9a, 0x99, 0x9c, 0xcf, 0x7d, 0xf0, 0x74,
+ 0x26, 0x4c, 0xc5, 0x07, 0x3e, 0x5e, 0x3a, 0x63, 0xa5, 0x4d, 0x56, 0x88, 0xc2, 0xc7, 0xe7, 0x04,
+ 0xac, 0x10, 0x7e, 0x28, 0x2a, 0x78, 0x55, 0x89, 0x24, 0x18, 0xb8, 0x0a, 0x21, 0xf4, 0x94, 0x10,
+ 0xac, 0x10, 0x11, 0x12, 0xa9, 0xed, 0x31, 0x5d, 0x88, 0x7e, 0x38, 0x44, 0xe4, 0x1b, 0x04, 0x30,
+ 0x7d, 0x52, 0x1f, 0x69, 0x69, 0xc5, 0x1c, 0x43, 0x1c, 0xba, 0xf4, 0x11, 0xfd, 0xa1, 0x01, 0xd9,
+ 0x35, 0x58, 0xc6, 0x1c, 0x23, 0x9b, 0x55, 0x01, 0xb8, 0x1b, 0x80, 0xf2, 0x8b, 0xac, 0x62, 0xb7,
+ 0x60, 0x55, 0x96, 0x3c, 0xb6, 0xf2, 0x50, 0x44, 0x54, 0x93, 0x11, 0xe9, 0x57, 0x1a, 0x70, 0x07,
+ 0x6b, 0xb3, 0x01, 0xa3, 0x2e, 0x65, 0xc5, 0x85, 0xd9, 0x21, 0x74, 0xbd, 0x50, 0x15, 0x57, 0xff,
+ 0xed, 0xe5, 0x11, 0x56, 0xb3, 0xf5, 0x42, 0x94, 0x0b, 0x5d, 0x2f, 0x44, 0xd8, 0x84, 0x51, 0x5d,
+ 0x8a, 0x43, 0x19, 0x5b, 0x3e, 0xcf, 0x45, 0x70, 0xd1, 0x55, 0xbb, 0x03, 0xb1, 0xf7, 0x61, 0x0d,
+ 0x2b, 0x1c, 0x69, 0x11, 0xe7, 0x5c, 0x16, 0x44, 0x5b, 0x23, 0xda, 0x45, 0xc4, 0xc3, 0x16, 0x66,
+ 0x1f, 0x02, 0x23, 0x6a, 0x5d, 0x76, 0xc9, 0x97, 0x88, 0x7c, 0x09, 0x35, 0x7b, 0x5d, 0x05, 0xbe,
+ 0x91, 0x2a, 0xdd, 0xe7, 0x75, 0x6e, 0x03, 0xe6, 0x2a, 0xe4, 0x45, 0x36, 0x06, 0xa8, 0xd2, 0x82,
+ 0xbf, 0x74, 0xca, 0xcb, 0x2e, 0xea, 0x16, 0xc1, 0x0f, 0x1d, 0x29, 0x7d, 0x20, 0xcb, 0xd4, 0x08,
+ 0x1b, 0x69, 0xe1, 0x78, 0xeb, 0xee, 0x43, 0xad, 0x26, 0x74, 0x0a, 0x36, 0x83, 0xcb, 0x1d, 0x3a,
+ 0x65, 0xcf, 0xad, 0x08, 0xae, 0x10, 0xbf, 0xe3, 0x69, 0xc7, 0x6b, 0xd8, 0xa7, 0x70, 0xb5, 0x63,
+ 0x50, 0xaa, 0x44, 0xf8, 0xb8, 0x83, 0xab, 0x64, 0x73, 0xa5, 0xd5, 0x7e, 0xdf, 0x2a, 0xd9, 0x75,
+ 0x58, 0xae, 0x52, 0x2d, 0xf6, 0x65, 0x9e, 0x07, 0xff, 0x73, 0x0f, 0xb3, 0x91, 0xd9, 0x55, 0x58,
+ 0xaa, 0x52, 0x13, 0xf3, 0x32, 0x08, 0x48, 0xe3, 0x25, 0x57, 0x04, 0x63, 0x05, 0xcf, 0x83, 0x6b,
+ 0x4d, 0x11, 0x48, 0x74, 0x45, 0x38, 0x0d, 0xf6, 0x7a, 0x53, 0x84, 0x06, 0x61, 0x13, 0x58, 0xa9,
+ 0xd2, 0x44, 0x9c, 0x32, 0x6e, 0xb8, 0xfe, 0x77, 0x31, 0xe7, 0x23, 0xe7, 0xaf, 0x8e, 0xf7, 0xb5,
+ 0x10, 0xc1, 0xff, 0x1b, 0x1f, 0x0d, 0x82, 0xed, 0x6f, 0xa5, 0x24, 0xb8, 0xe9, 0xda, 0xdf, 0x81,
+ 0xd8, 0x1d, 0xb8, 0x68, 0xb3, 0x2a, 0xa2, 0x42, 0x46, 0x3c, 0xcf, 0x55, 0x1c, 0x8c, 0x9b, 0xe7,
+ 0x5e, 0x3d, 0x42, 0x74, 0x07, 0x41, 0xf6, 0x01, 0x30, 0xe4, 0xc5, 0x2a, 0xcf, 0x79, 0x65, 0x84,
+ 0xa7, 0x6e, 0x10, 0x75, 0xcd, 0x66, 0xd5, 0x03, 0xaf, 0x70, 0xec, 0x75, 0x38, 0x4f, 0x03, 0x2d,
+ 0xd8, 0x74, 0x4f, 0x93, 0x04, 0xbc, 0xad, 0x6e, 0xf0, 0xb9, 0x01, 0xb9, 0xe5, 0xc2, 0x25, 0xe8,
+ 0x3b, 0x44, 0xf0, 0x69, 0x9a, 0x23, 0x5e, 0x45, 0xce, 0x76, 0xe2, 0x9e, 0x26, 0x22, 0x7b, 0x64,
+ 0xdf, 0xa8, 0x9d, 0xf9, 0xad, 0x56, 0x4d, 0xd6, 0x13, 0x03, 0x2b, 0xdd, 0xe9, 0xcd, 0xd6, 0x60,
+ 0x31, 0x57, 0x47, 0x7e, 0x22, 0xe1, 0x11, 0xa7, 0x48, 0x26, 0xd3, 0xac, 0x19, 0x48, 0x78, 0x46,
+ 0x56, 0xc1, 0x7f, 0xf4, 0x73, 0x08, 0x8f, 0x88, 0x28, 0x55, 0xf8, 0xf1, 0x83, 0x47, 0x7c, 0xec,
+ 0x4a, 0x15, 0xd1, 0x01, 0x36, 0xde, 0x4d, 0xa0, 0x81, 0x52, 0xc5, 0x13, 0x99, 0xe7, 0x93, 0x9f,
+ 0x7b, 0xb0, 0xdc, 0xec, 0x39, 0xf6, 0x55, 0x77, 0x2b, 0xe0, 0xbe, 0xba, 0xf5, 0xf6, 0xe5, 0xf8,
+ 0xb0, 0xb4, 0xfa, 0xb8, 0x5d, 0x1d, 0x5f, 0xb4, 0xab, 0xe3, 0x3f, 0x1b, 0xfb, 0xfd, 0x22, 0x60,
+ 0x78, 0x8a, 0xe1, 0x5d, 0x4c, 0xf0, 0x81, 0x0b, 0xca, 0x7d, 0x18, 0x7a, 0x09, 0xeb, 0x9f, 0xc5,
+ 0x3c, 0xca, 0x78, 0x99, 0xe4, 0xc2, 0x50, 0x15, 0x56, 0x43, 0xc8, 0x62, 0xfe, 0xd8, 0x21, 0x0d,
+ 0x41, 0xcd, 0x5f, 0x8a, 0xd8, 0x1a, 0xaa, 0x89, 0x23, 0x3c, 0x73, 0xc8, 0x64, 0x07, 0x96, 0xdc,
+ 0x7a, 0x66, 0x9f, 0x37, 0x1d, 0x76, 0x89, 0x6e, 0xbd, 0x6d, 0x9f, 0xfb, 0x48, 0x89, 0x3f, 0xf9,
+ 0xa5, 0x07, 0x03, 0x0f, 0xe1, 0x35, 0x29, 0xf8, 0x4b, 0xa5, 0x7d, 0x8f, 0x9c, 0x40, 0xa8, 0x2c,
+ 0x95, 0x6e, 0x36, 0x28, 0x09, 0x98, 0x94, 0x9e, 0x1f, 0x5b, 0x61, 0x7c, 0xab, 0xbc, 0x84, 0xf8,
+ 0x91, 0xc3, 0x5d, 0xc3, 0xbc, 0x84, 0xbd, 0xd6, 0x52, 0x99, 0x66, 0x63, 0xe0, 0x19, 0xb1, 0x23,
+ 0xc4, 0xdc, 0xc2, 0xa0, 0xf3, 0x64, 0x0f, 0x46, 0x9d, 0x5f, 0x87, 0xb7, 0x2c, 0x76, 0x7f, 0x51,
+ 0x16, 0xda, 0x8b, 0x82, 0xf3, 0x80, 0xa7, 0xc2, 0xc8, 0x57, 0x82, 0x82, 0x1a, 0x86, 0xa7, 0xf2,
+ 0xfd, 0xe0, 0xf5, 0x9b, 0xf1, 0xb9, 0x3f, 0xdf, 0x8c, 0xcf, 0xfd, 0x74, 0x32, 0xee, 0xbd, 0x3e,
+ 0x19, 0xf7, 0xfe, 0x38, 0x19, 0xf7, 0xfe, 0x3e, 0x19, 0xf7, 0xe6, 0x4b, 0xf4, 0x17, 0xf8, 0xf1,
+ 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x4f, 0x2b, 0x30, 0xd6, 0x6d, 0x0a, 0x00, 0x00,
+}
+
+func (m *Metrics) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *Metrics) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *Metrics) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.MemoryEvents != nil {
+ {
+ size, err := m.MemoryEvents.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x42
+ }
+ if len(m.Hugetlb) > 0 {
+ for iNdEx := len(m.Hugetlb) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.Hugetlb[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x3a
+ }
+ }
+ if m.Io != nil {
+ {
+ size, err := m.Io.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x32
+ }
+ if m.Rdma != nil {
+ {
+ size, err := m.Rdma.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x2a
+ }
+ if m.Memory != nil {
+ {
+ size, err := m.Memory.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x22
+ }
+ if m.CPU != nil {
+ {
+ size, err := m.CPU.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x12
+ }
+ if m.Pids != nil {
+ {
+ size, err := m.Pids.MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0xa
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *PidsStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *PidsStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *PidsStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.Limit != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Limit))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Current != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Current))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *CPUStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *CPUStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *CPUStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.ThrottledUsec != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.ThrottledUsec))
+ i--
+ dAtA[i] = 0x30
+ }
+ if m.NrThrottled != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.NrThrottled))
+ i--
+ dAtA[i] = 0x28
+ }
+ if m.NrPeriods != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.NrPeriods))
+ i--
+ dAtA[i] = 0x20
+ }
+ if m.SystemUsec != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.SystemUsec))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.UserUsec != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.UserUsec))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.UsageUsec != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.UsageUsec))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *MemoryStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *MemoryStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *MemoryStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.SwapLimit != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.SwapLimit))
+ i--
+ dAtA[i] = 0x2
+ i--
+ dAtA[i] = 0x98
+ }
+ if m.SwapUsage != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.SwapUsage))
+ i--
+ dAtA[i] = 0x2
+ i--
+ dAtA[i] = 0x90
+ }
+ if m.UsageLimit != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.UsageLimit))
+ i--
+ dAtA[i] = 0x2
+ i--
+ dAtA[i] = 0x88
+ }
+ if m.Usage != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Usage))
+ i--
+ dAtA[i] = 0x2
+ i--
+ dAtA[i] = 0x80
+ }
+ if m.ThpCollapseAlloc != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.ThpCollapseAlloc))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xf8
+ }
+ if m.ThpFaultAlloc != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.ThpFaultAlloc))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xf0
+ }
+ if m.Pglazyfreed != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Pglazyfreed))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xe8
+ }
+ if m.Pglazyfree != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Pglazyfree))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xe0
+ }
+ if m.Pgdeactivate != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Pgdeactivate))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xd8
+ }
+ if m.Pgactivate != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Pgactivate))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xd0
+ }
+ if m.Pgsteal != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Pgsteal))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xc8
+ }
+ if m.Pgscan != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Pgscan))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xc0
+ }
+ if m.Pgrefill != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Pgrefill))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xb8
+ }
+ if m.WorkingsetNodereclaim != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.WorkingsetNodereclaim))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xb0
+ }
+ if m.WorkingsetActivate != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.WorkingsetActivate))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xa8
+ }
+ if m.WorkingsetRefault != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.WorkingsetRefault))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0xa0
+ }
+ if m.Pgmajfault != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Pgmajfault))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0x98
+ }
+ if m.Pgfault != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Pgfault))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0x90
+ }
+ if m.SlabUnreclaimable != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.SlabUnreclaimable))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0x88
+ }
+ if m.SlabReclaimable != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.SlabReclaimable))
+ i--
+ dAtA[i] = 0x1
+ i--
+ dAtA[i] = 0x80
+ }
+ if m.Unevictable != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Unevictable))
+ i--
+ dAtA[i] = 0x78
+ }
+ if m.ActiveFile != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.ActiveFile))
+ i--
+ dAtA[i] = 0x70
+ }
+ if m.InactiveFile != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.InactiveFile))
+ i--
+ dAtA[i] = 0x68
+ }
+ if m.ActiveAnon != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.ActiveAnon))
+ i--
+ dAtA[i] = 0x60
+ }
+ if m.InactiveAnon != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.InactiveAnon))
+ i--
+ dAtA[i] = 0x58
+ }
+ if m.AnonThp != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.AnonThp))
+ i--
+ dAtA[i] = 0x50
+ }
+ if m.FileWriteback != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.FileWriteback))
+ i--
+ dAtA[i] = 0x48
+ }
+ if m.FileDirty != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.FileDirty))
+ i--
+ dAtA[i] = 0x40
+ }
+ if m.FileMapped != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.FileMapped))
+ i--
+ dAtA[i] = 0x38
+ }
+ if m.Shmem != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Shmem))
+ i--
+ dAtA[i] = 0x30
+ }
+ if m.Sock != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Sock))
+ i--
+ dAtA[i] = 0x28
+ }
+ if m.Slab != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Slab))
+ i--
+ dAtA[i] = 0x20
+ }
+ if m.KernelStack != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.KernelStack))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.File != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.File))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Anon != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Anon))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *MemoryEvents) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *MemoryEvents) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *MemoryEvents) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.OomKill != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.OomKill))
+ i--
+ dAtA[i] = 0x28
+ }
+ if m.Oom != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Oom))
+ i--
+ dAtA[i] = 0x20
+ }
+ if m.Max != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Max))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.High != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.High))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Low != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Low))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *RdmaStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RdmaStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *RdmaStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if len(m.Limit) > 0 {
+ for iNdEx := len(m.Limit) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.Limit[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0x12
+ }
+ }
+ if len(m.Current) > 0 {
+ for iNdEx := len(m.Current) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.Current[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0xa
+ }
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *RdmaEntry) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *RdmaEntry) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *RdmaEntry) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.HcaObjects != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.HcaObjects))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.HcaHandles != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.HcaHandles))
+ i--
+ dAtA[i] = 0x10
+ }
+ if len(m.Device) > 0 {
+ i -= len(m.Device)
+ copy(dAtA[i:], m.Device)
+ i = encodeVarintMetrics(dAtA, i, uint64(len(m.Device)))
+ i--
+ dAtA[i] = 0xa
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *IOStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *IOStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *IOStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if len(m.Usage) > 0 {
+ for iNdEx := len(m.Usage) - 1; iNdEx >= 0; iNdEx-- {
+ {
+ size, err := m.Usage[iNdEx].MarshalToSizedBuffer(dAtA[:i])
+ if err != nil {
+ return 0, err
+ }
+ i -= size
+ i = encodeVarintMetrics(dAtA, i, uint64(size))
+ }
+ i--
+ dAtA[i] = 0xa
+ }
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *IOEntry) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *IOEntry) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *IOEntry) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if m.Wios != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Wios))
+ i--
+ dAtA[i] = 0x30
+ }
+ if m.Rios != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Rios))
+ i--
+ dAtA[i] = 0x28
+ }
+ if m.Wbytes != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Wbytes))
+ i--
+ dAtA[i] = 0x20
+ }
+ if m.Rbytes != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Rbytes))
+ i--
+ dAtA[i] = 0x18
+ }
+ if m.Minor != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Minor))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Major != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Major))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func (m *HugeTlbStat) Marshal() (dAtA []byte, err error) {
+ size := m.Size()
+ dAtA = make([]byte, size)
+ n, err := m.MarshalToSizedBuffer(dAtA[:size])
+ if err != nil {
+ return nil, err
+ }
+ return dAtA[:n], nil
+}
+
+func (m *HugeTlbStat) MarshalTo(dAtA []byte) (int, error) {
+ size := m.Size()
+ return m.MarshalToSizedBuffer(dAtA[:size])
+}
+
+func (m *HugeTlbStat) MarshalToSizedBuffer(dAtA []byte) (int, error) {
+ i := len(dAtA)
+ _ = i
+ var l int
+ _ = l
+ if m.XXX_unrecognized != nil {
+ i -= len(m.XXX_unrecognized)
+ copy(dAtA[i:], m.XXX_unrecognized)
+ }
+ if len(m.Pagesize) > 0 {
+ i -= len(m.Pagesize)
+ copy(dAtA[i:], m.Pagesize)
+ i = encodeVarintMetrics(dAtA, i, uint64(len(m.Pagesize)))
+ i--
+ dAtA[i] = 0x1a
+ }
+ if m.Max != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Max))
+ i--
+ dAtA[i] = 0x10
+ }
+ if m.Current != 0 {
+ i = encodeVarintMetrics(dAtA, i, uint64(m.Current))
+ i--
+ dAtA[i] = 0x8
+ }
+ return len(dAtA) - i, nil
+}
+
+func encodeVarintMetrics(dAtA []byte, offset int, v uint64) int {
+ offset -= sovMetrics(v)
+ base := offset
+ for v >= 1<<7 {
+ dAtA[offset] = uint8(v&0x7f | 0x80)
+ v >>= 7
+ offset++
+ }
+ dAtA[offset] = uint8(v)
+ return base
+}
+func (m *Metrics) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Pids != nil {
+ l = m.Pids.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.CPU != nil {
+ l = m.CPU.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.Memory != nil {
+ l = m.Memory.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.Rdma != nil {
+ l = m.Rdma.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.Io != nil {
+ l = m.Io.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if len(m.Hugetlb) > 0 {
+ for _, e := range m.Hugetlb {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if m.MemoryEvents != nil {
+ l = m.MemoryEvents.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *PidsStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Current != 0 {
+ n += 1 + sovMetrics(uint64(m.Current))
+ }
+ if m.Limit != 0 {
+ n += 1 + sovMetrics(uint64(m.Limit))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *CPUStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.UsageUsec != 0 {
+ n += 1 + sovMetrics(uint64(m.UsageUsec))
+ }
+ if m.UserUsec != 0 {
+ n += 1 + sovMetrics(uint64(m.UserUsec))
+ }
+ if m.SystemUsec != 0 {
+ n += 1 + sovMetrics(uint64(m.SystemUsec))
+ }
+ if m.NrPeriods != 0 {
+ n += 1 + sovMetrics(uint64(m.NrPeriods))
+ }
+ if m.NrThrottled != 0 {
+ n += 1 + sovMetrics(uint64(m.NrThrottled))
+ }
+ if m.ThrottledUsec != 0 {
+ n += 1 + sovMetrics(uint64(m.ThrottledUsec))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *MemoryStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Anon != 0 {
+ n += 1 + sovMetrics(uint64(m.Anon))
+ }
+ if m.File != 0 {
+ n += 1 + sovMetrics(uint64(m.File))
+ }
+ if m.KernelStack != 0 {
+ n += 1 + sovMetrics(uint64(m.KernelStack))
+ }
+ if m.Slab != 0 {
+ n += 1 + sovMetrics(uint64(m.Slab))
+ }
+ if m.Sock != 0 {
+ n += 1 + sovMetrics(uint64(m.Sock))
+ }
+ if m.Shmem != 0 {
+ n += 1 + sovMetrics(uint64(m.Shmem))
+ }
+ if m.FileMapped != 0 {
+ n += 1 + sovMetrics(uint64(m.FileMapped))
+ }
+ if m.FileDirty != 0 {
+ n += 1 + sovMetrics(uint64(m.FileDirty))
+ }
+ if m.FileWriteback != 0 {
+ n += 1 + sovMetrics(uint64(m.FileWriteback))
+ }
+ if m.AnonThp != 0 {
+ n += 1 + sovMetrics(uint64(m.AnonThp))
+ }
+ if m.InactiveAnon != 0 {
+ n += 1 + sovMetrics(uint64(m.InactiveAnon))
+ }
+ if m.ActiveAnon != 0 {
+ n += 1 + sovMetrics(uint64(m.ActiveAnon))
+ }
+ if m.InactiveFile != 0 {
+ n += 1 + sovMetrics(uint64(m.InactiveFile))
+ }
+ if m.ActiveFile != 0 {
+ n += 1 + sovMetrics(uint64(m.ActiveFile))
+ }
+ if m.Unevictable != 0 {
+ n += 1 + sovMetrics(uint64(m.Unevictable))
+ }
+ if m.SlabReclaimable != 0 {
+ n += 2 + sovMetrics(uint64(m.SlabReclaimable))
+ }
+ if m.SlabUnreclaimable != 0 {
+ n += 2 + sovMetrics(uint64(m.SlabUnreclaimable))
+ }
+ if m.Pgfault != 0 {
+ n += 2 + sovMetrics(uint64(m.Pgfault))
+ }
+ if m.Pgmajfault != 0 {
+ n += 2 + sovMetrics(uint64(m.Pgmajfault))
+ }
+ if m.WorkingsetRefault != 0 {
+ n += 2 + sovMetrics(uint64(m.WorkingsetRefault))
+ }
+ if m.WorkingsetActivate != 0 {
+ n += 2 + sovMetrics(uint64(m.WorkingsetActivate))
+ }
+ if m.WorkingsetNodereclaim != 0 {
+ n += 2 + sovMetrics(uint64(m.WorkingsetNodereclaim))
+ }
+ if m.Pgrefill != 0 {
+ n += 2 + sovMetrics(uint64(m.Pgrefill))
+ }
+ if m.Pgscan != 0 {
+ n += 2 + sovMetrics(uint64(m.Pgscan))
+ }
+ if m.Pgsteal != 0 {
+ n += 2 + sovMetrics(uint64(m.Pgsteal))
+ }
+ if m.Pgactivate != 0 {
+ n += 2 + sovMetrics(uint64(m.Pgactivate))
+ }
+ if m.Pgdeactivate != 0 {
+ n += 2 + sovMetrics(uint64(m.Pgdeactivate))
+ }
+ if m.Pglazyfree != 0 {
+ n += 2 + sovMetrics(uint64(m.Pglazyfree))
+ }
+ if m.Pglazyfreed != 0 {
+ n += 2 + sovMetrics(uint64(m.Pglazyfreed))
+ }
+ if m.ThpFaultAlloc != 0 {
+ n += 2 + sovMetrics(uint64(m.ThpFaultAlloc))
+ }
+ if m.ThpCollapseAlloc != 0 {
+ n += 2 + sovMetrics(uint64(m.ThpCollapseAlloc))
+ }
+ if m.Usage != 0 {
+ n += 2 + sovMetrics(uint64(m.Usage))
+ }
+ if m.UsageLimit != 0 {
+ n += 2 + sovMetrics(uint64(m.UsageLimit))
+ }
+ if m.SwapUsage != 0 {
+ n += 2 + sovMetrics(uint64(m.SwapUsage))
+ }
+ if m.SwapLimit != 0 {
+ n += 2 + sovMetrics(uint64(m.SwapLimit))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *MemoryEvents) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Low != 0 {
+ n += 1 + sovMetrics(uint64(m.Low))
+ }
+ if m.High != 0 {
+ n += 1 + sovMetrics(uint64(m.High))
+ }
+ if m.Max != 0 {
+ n += 1 + sovMetrics(uint64(m.Max))
+ }
+ if m.Oom != 0 {
+ n += 1 + sovMetrics(uint64(m.Oom))
+ }
+ if m.OomKill != 0 {
+ n += 1 + sovMetrics(uint64(m.OomKill))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *RdmaStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if len(m.Current) > 0 {
+ for _, e := range m.Current {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if len(m.Limit) > 0 {
+ for _, e := range m.Limit {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *RdmaEntry) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ l = len(m.Device)
+ if l > 0 {
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.HcaHandles != 0 {
+ n += 1 + sovMetrics(uint64(m.HcaHandles))
+ }
+ if m.HcaObjects != 0 {
+ n += 1 + sovMetrics(uint64(m.HcaObjects))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *IOStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if len(m.Usage) > 0 {
+ for _, e := range m.Usage {
+ l = e.Size()
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *IOEntry) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Major != 0 {
+ n += 1 + sovMetrics(uint64(m.Major))
+ }
+ if m.Minor != 0 {
+ n += 1 + sovMetrics(uint64(m.Minor))
+ }
+ if m.Rbytes != 0 {
+ n += 1 + sovMetrics(uint64(m.Rbytes))
+ }
+ if m.Wbytes != 0 {
+ n += 1 + sovMetrics(uint64(m.Wbytes))
+ }
+ if m.Rios != 0 {
+ n += 1 + sovMetrics(uint64(m.Rios))
+ }
+ if m.Wios != 0 {
+ n += 1 + sovMetrics(uint64(m.Wios))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func (m *HugeTlbStat) Size() (n int) {
+ if m == nil {
+ return 0
+ }
+ var l int
+ _ = l
+ if m.Current != 0 {
+ n += 1 + sovMetrics(uint64(m.Current))
+ }
+ if m.Max != 0 {
+ n += 1 + sovMetrics(uint64(m.Max))
+ }
+ l = len(m.Pagesize)
+ if l > 0 {
+ n += 1 + l + sovMetrics(uint64(l))
+ }
+ if m.XXX_unrecognized != nil {
+ n += len(m.XXX_unrecognized)
+ }
+ return n
+}
+
+func sovMetrics(x uint64) (n int) {
+ return (math_bits.Len64(x|1) + 6) / 7
+}
+func sozMetrics(x uint64) (n int) {
+ return sovMetrics(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+func (this *Metrics) String() string {
+ if this == nil {
+ return "nil"
+ }
+ repeatedStringForHugetlb := "[]*HugeTlbStat{"
+ for _, f := range this.Hugetlb {
+ repeatedStringForHugetlb += strings.Replace(f.String(), "HugeTlbStat", "HugeTlbStat", 1) + ","
+ }
+ repeatedStringForHugetlb += "}"
+ s := strings.Join([]string{`&Metrics{`,
+ `Pids:` + strings.Replace(this.Pids.String(), "PidsStat", "PidsStat", 1) + `,`,
+ `CPU:` + strings.Replace(this.CPU.String(), "CPUStat", "CPUStat", 1) + `,`,
+ `Memory:` + strings.Replace(this.Memory.String(), "MemoryStat", "MemoryStat", 1) + `,`,
+ `Rdma:` + strings.Replace(this.Rdma.String(), "RdmaStat", "RdmaStat", 1) + `,`,
+ `Io:` + strings.Replace(this.Io.String(), "IOStat", "IOStat", 1) + `,`,
+ `Hugetlb:` + repeatedStringForHugetlb + `,`,
+ `MemoryEvents:` + strings.Replace(this.MemoryEvents.String(), "MemoryEvents", "MemoryEvents", 1) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *PidsStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&PidsStat{`,
+ `Current:` + fmt.Sprintf("%v", this.Current) + `,`,
+ `Limit:` + fmt.Sprintf("%v", this.Limit) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *CPUStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&CPUStat{`,
+ `UsageUsec:` + fmt.Sprintf("%v", this.UsageUsec) + `,`,
+ `UserUsec:` + fmt.Sprintf("%v", this.UserUsec) + `,`,
+ `SystemUsec:` + fmt.Sprintf("%v", this.SystemUsec) + `,`,
+ `NrPeriods:` + fmt.Sprintf("%v", this.NrPeriods) + `,`,
+ `NrThrottled:` + fmt.Sprintf("%v", this.NrThrottled) + `,`,
+ `ThrottledUsec:` + fmt.Sprintf("%v", this.ThrottledUsec) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *MemoryStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&MemoryStat{`,
+ `Anon:` + fmt.Sprintf("%v", this.Anon) + `,`,
+ `File:` + fmt.Sprintf("%v", this.File) + `,`,
+ `KernelStack:` + fmt.Sprintf("%v", this.KernelStack) + `,`,
+ `Slab:` + fmt.Sprintf("%v", this.Slab) + `,`,
+ `Sock:` + fmt.Sprintf("%v", this.Sock) + `,`,
+ `Shmem:` + fmt.Sprintf("%v", this.Shmem) + `,`,
+ `FileMapped:` + fmt.Sprintf("%v", this.FileMapped) + `,`,
+ `FileDirty:` + fmt.Sprintf("%v", this.FileDirty) + `,`,
+ `FileWriteback:` + fmt.Sprintf("%v", this.FileWriteback) + `,`,
+ `AnonThp:` + fmt.Sprintf("%v", this.AnonThp) + `,`,
+ `InactiveAnon:` + fmt.Sprintf("%v", this.InactiveAnon) + `,`,
+ `ActiveAnon:` + fmt.Sprintf("%v", this.ActiveAnon) + `,`,
+ `InactiveFile:` + fmt.Sprintf("%v", this.InactiveFile) + `,`,
+ `ActiveFile:` + fmt.Sprintf("%v", this.ActiveFile) + `,`,
+ `Unevictable:` + fmt.Sprintf("%v", this.Unevictable) + `,`,
+ `SlabReclaimable:` + fmt.Sprintf("%v", this.SlabReclaimable) + `,`,
+ `SlabUnreclaimable:` + fmt.Sprintf("%v", this.SlabUnreclaimable) + `,`,
+ `Pgfault:` + fmt.Sprintf("%v", this.Pgfault) + `,`,
+ `Pgmajfault:` + fmt.Sprintf("%v", this.Pgmajfault) + `,`,
+ `WorkingsetRefault:` + fmt.Sprintf("%v", this.WorkingsetRefault) + `,`,
+ `WorkingsetActivate:` + fmt.Sprintf("%v", this.WorkingsetActivate) + `,`,
+ `WorkingsetNodereclaim:` + fmt.Sprintf("%v", this.WorkingsetNodereclaim) + `,`,
+ `Pgrefill:` + fmt.Sprintf("%v", this.Pgrefill) + `,`,
+ `Pgscan:` + fmt.Sprintf("%v", this.Pgscan) + `,`,
+ `Pgsteal:` + fmt.Sprintf("%v", this.Pgsteal) + `,`,
+ `Pgactivate:` + fmt.Sprintf("%v", this.Pgactivate) + `,`,
+ `Pgdeactivate:` + fmt.Sprintf("%v", this.Pgdeactivate) + `,`,
+ `Pglazyfree:` + fmt.Sprintf("%v", this.Pglazyfree) + `,`,
+ `Pglazyfreed:` + fmt.Sprintf("%v", this.Pglazyfreed) + `,`,
+ `ThpFaultAlloc:` + fmt.Sprintf("%v", this.ThpFaultAlloc) + `,`,
+ `ThpCollapseAlloc:` + fmt.Sprintf("%v", this.ThpCollapseAlloc) + `,`,
+ `Usage:` + fmt.Sprintf("%v", this.Usage) + `,`,
+ `UsageLimit:` + fmt.Sprintf("%v", this.UsageLimit) + `,`,
+ `SwapUsage:` + fmt.Sprintf("%v", this.SwapUsage) + `,`,
+ `SwapLimit:` + fmt.Sprintf("%v", this.SwapLimit) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *MemoryEvents) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&MemoryEvents{`,
+ `Low:` + fmt.Sprintf("%v", this.Low) + `,`,
+ `High:` + fmt.Sprintf("%v", this.High) + `,`,
+ `Max:` + fmt.Sprintf("%v", this.Max) + `,`,
+ `Oom:` + fmt.Sprintf("%v", this.Oom) + `,`,
+ `OomKill:` + fmt.Sprintf("%v", this.OomKill) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RdmaStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ repeatedStringForCurrent := "[]*RdmaEntry{"
+ for _, f := range this.Current {
+ repeatedStringForCurrent += strings.Replace(f.String(), "RdmaEntry", "RdmaEntry", 1) + ","
+ }
+ repeatedStringForCurrent += "}"
+ repeatedStringForLimit := "[]*RdmaEntry{"
+ for _, f := range this.Limit {
+ repeatedStringForLimit += strings.Replace(f.String(), "RdmaEntry", "RdmaEntry", 1) + ","
+ }
+ repeatedStringForLimit += "}"
+ s := strings.Join([]string{`&RdmaStat{`,
+ `Current:` + repeatedStringForCurrent + `,`,
+ `Limit:` + repeatedStringForLimit + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *RdmaEntry) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&RdmaEntry{`,
+ `Device:` + fmt.Sprintf("%v", this.Device) + `,`,
+ `HcaHandles:` + fmt.Sprintf("%v", this.HcaHandles) + `,`,
+ `HcaObjects:` + fmt.Sprintf("%v", this.HcaObjects) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *IOStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ repeatedStringForUsage := "[]*IOEntry{"
+ for _, f := range this.Usage {
+ repeatedStringForUsage += strings.Replace(f.String(), "IOEntry", "IOEntry", 1) + ","
+ }
+ repeatedStringForUsage += "}"
+ s := strings.Join([]string{`&IOStat{`,
+ `Usage:` + repeatedStringForUsage + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *IOEntry) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&IOEntry{`,
+ `Major:` + fmt.Sprintf("%v", this.Major) + `,`,
+ `Minor:` + fmt.Sprintf("%v", this.Minor) + `,`,
+ `Rbytes:` + fmt.Sprintf("%v", this.Rbytes) + `,`,
+ `Wbytes:` + fmt.Sprintf("%v", this.Wbytes) + `,`,
+ `Rios:` + fmt.Sprintf("%v", this.Rios) + `,`,
+ `Wios:` + fmt.Sprintf("%v", this.Wios) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func (this *HugeTlbStat) String() string {
+ if this == nil {
+ return "nil"
+ }
+ s := strings.Join([]string{`&HugeTlbStat{`,
+ `Current:` + fmt.Sprintf("%v", this.Current) + `,`,
+ `Max:` + fmt.Sprintf("%v", this.Max) + `,`,
+ `Pagesize:` + fmt.Sprintf("%v", this.Pagesize) + `,`,
+ `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
+ `}`,
+ }, "")
+ return s
+}
+func valueToStringMetrics(v interface{}) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("*%v", pv)
+}
+func (m *Metrics) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: Metrics: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: Metrics: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pids", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Pids == nil {
+ m.Pids = &PidsStat{}
+ }
+ if err := m.Pids.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field CPU", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.CPU == nil {
+ m.CPU = &CPUStat{}
+ }
+ if err := m.CPU.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 4:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Memory", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Memory == nil {
+ m.Memory = &MemoryStat{}
+ }
+ if err := m.Memory.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 5:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Rdma", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Rdma == nil {
+ m.Rdma = &RdmaStat{}
+ }
+ if err := m.Rdma.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 6:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Io", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.Io == nil {
+ m.Io = &IOStat{}
+ }
+ if err := m.Io.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 7:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Hugetlb", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Hugetlb = append(m.Hugetlb, &HugeTlbStat{})
+ if err := m.Hugetlb[len(m.Hugetlb)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 8:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field MemoryEvents", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ if m.MemoryEvents == nil {
+ m.MemoryEvents = &MemoryEvents{}
+ }
+ if err := m.MemoryEvents.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *PidsStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: PidsStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: PidsStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Current", wireType)
+ }
+ m.Current = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Current |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType)
+ }
+ m.Limit = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Limit |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *CPUStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: CPUStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: CPUStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field UsageUsec", wireType)
+ }
+ m.UsageUsec = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.UsageUsec |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field UserUsec", wireType)
+ }
+ m.UserUsec = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.UserUsec |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SystemUsec", wireType)
+ }
+ m.SystemUsec = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.SystemUsec |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NrPeriods", wireType)
+ }
+ m.NrPeriods = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.NrPeriods |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field NrThrottled", wireType)
+ }
+ m.NrThrottled = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.NrThrottled |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ThrottledUsec", wireType)
+ }
+ m.ThrottledUsec = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ThrottledUsec |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *MemoryStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: MemoryStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: MemoryStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Anon", wireType)
+ }
+ m.Anon = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Anon |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field File", wireType)
+ }
+ m.File = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.File |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field KernelStack", wireType)
+ }
+ m.KernelStack = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.KernelStack |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Slab", wireType)
+ }
+ m.Slab = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Slab |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Sock", wireType)
+ }
+ m.Sock = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Sock |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Shmem", wireType)
+ }
+ m.Shmem = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Shmem |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 7:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field FileMapped", wireType)
+ }
+ m.FileMapped = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.FileMapped |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 8:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field FileDirty", wireType)
+ }
+ m.FileDirty = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.FileDirty |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 9:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field FileWriteback", wireType)
+ }
+ m.FileWriteback = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.FileWriteback |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 10:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field AnonThp", wireType)
+ }
+ m.AnonThp = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.AnonThp |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 11:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field InactiveAnon", wireType)
+ }
+ m.InactiveAnon = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.InactiveAnon |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 12:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ActiveAnon", wireType)
+ }
+ m.ActiveAnon = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ActiveAnon |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 13:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field InactiveFile", wireType)
+ }
+ m.InactiveFile = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.InactiveFile |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 14:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ActiveFile", wireType)
+ }
+ m.ActiveFile = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ActiveFile |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 15:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Unevictable", wireType)
+ }
+ m.Unevictable = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Unevictable |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 16:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SlabReclaimable", wireType)
+ }
+ m.SlabReclaimable = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.SlabReclaimable |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 17:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SlabUnreclaimable", wireType)
+ }
+ m.SlabUnreclaimable = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.SlabUnreclaimable |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 18:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pgfault", wireType)
+ }
+ m.Pgfault = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Pgfault |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 19:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pgmajfault", wireType)
+ }
+ m.Pgmajfault = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Pgmajfault |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 20:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field WorkingsetRefault", wireType)
+ }
+ m.WorkingsetRefault = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.WorkingsetRefault |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 21:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field WorkingsetActivate", wireType)
+ }
+ m.WorkingsetActivate = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.WorkingsetActivate |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 22:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field WorkingsetNodereclaim", wireType)
+ }
+ m.WorkingsetNodereclaim = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.WorkingsetNodereclaim |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 23:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pgrefill", wireType)
+ }
+ m.Pgrefill = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Pgrefill |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 24:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pgscan", wireType)
+ }
+ m.Pgscan = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Pgscan |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 25:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pgsteal", wireType)
+ }
+ m.Pgsteal = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Pgsteal |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 26:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pgactivate", wireType)
+ }
+ m.Pgactivate = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Pgactivate |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 27:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pgdeactivate", wireType)
+ }
+ m.Pgdeactivate = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Pgdeactivate |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 28:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pglazyfree", wireType)
+ }
+ m.Pglazyfree = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Pglazyfree |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 29:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pglazyfreed", wireType)
+ }
+ m.Pglazyfreed = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Pglazyfreed |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 30:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ThpFaultAlloc", wireType)
+ }
+ m.ThpFaultAlloc = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ThpFaultAlloc |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 31:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field ThpCollapseAlloc", wireType)
+ }
+ m.ThpCollapseAlloc = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.ThpCollapseAlloc |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 32:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Usage", wireType)
+ }
+ m.Usage = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Usage |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 33:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field UsageLimit", wireType)
+ }
+ m.UsageLimit = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.UsageLimit |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 34:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SwapUsage", wireType)
+ }
+ m.SwapUsage = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.SwapUsage |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 35:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field SwapLimit", wireType)
+ }
+ m.SwapLimit = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.SwapLimit |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *MemoryEvents) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: MemoryEvents: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: MemoryEvents: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Low", wireType)
+ }
+ m.Low = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Low |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field High", wireType)
+ }
+ m.High = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.High |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Max", wireType)
+ }
+ m.Max = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Max |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Oom", wireType)
+ }
+ m.Oom = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Oom |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field OomKill", wireType)
+ }
+ m.OomKill = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.OomKill |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RdmaStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RdmaStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RdmaStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Current", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Current = append(m.Current, &RdmaEntry{})
+ if err := m.Current[len(m.Current)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ case 2:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Limit = append(m.Limit, &RdmaEntry{})
+ if err := m.Limit[len(m.Limit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *RdmaEntry) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: RdmaEntry: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: RdmaEntry: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Device", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Device = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field HcaHandles", wireType)
+ }
+ m.HcaHandles = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.HcaHandles |= uint32(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field HcaObjects", wireType)
+ }
+ m.HcaObjects = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.HcaObjects |= uint32(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *IOStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: IOStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: IOStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Usage", wireType)
+ }
+ var msglen int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ msglen |= int(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if msglen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + msglen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Usage = append(m.Usage, &IOEntry{})
+ if err := m.Usage[len(m.Usage)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
+ return err
+ }
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *IOEntry) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: IOEntry: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: IOEntry: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Major", wireType)
+ }
+ m.Major = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Major |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Minor", wireType)
+ }
+ m.Minor = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Minor |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Rbytes", wireType)
+ }
+ m.Rbytes = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Rbytes |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 4:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Wbytes", wireType)
+ }
+ m.Wbytes = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Wbytes |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 5:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Rios", wireType)
+ }
+ m.Rios = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Rios |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 6:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Wios", wireType)
+ }
+ m.Wios = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Wios |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func (m *HugeTlbStat) Unmarshal(dAtA []byte) error {
+ l := len(dAtA)
+ iNdEx := 0
+ for iNdEx < l {
+ preIndex := iNdEx
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ fieldNum := int32(wire >> 3)
+ wireType := int(wire & 0x7)
+ if wireType == 4 {
+ return fmt.Errorf("proto: HugeTlbStat: wiretype end group for non-group")
+ }
+ if fieldNum <= 0 {
+ return fmt.Errorf("proto: HugeTlbStat: illegal tag %d (wire type %d)", fieldNum, wire)
+ }
+ switch fieldNum {
+ case 1:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Current", wireType)
+ }
+ m.Current = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Current |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 2:
+ if wireType != 0 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Max", wireType)
+ }
+ m.Max = 0
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ m.Max |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ case 3:
+ if wireType != 2 {
+ return fmt.Errorf("proto: wrong wireType = %d for field Pagesize", wireType)
+ }
+ var stringLen uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ stringLen |= uint64(b&0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ intStringLen := int(stringLen)
+ if intStringLen < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ postIndex := iNdEx + intStringLen
+ if postIndex < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if postIndex > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.Pagesize = string(dAtA[iNdEx:postIndex])
+ iNdEx = postIndex
+ default:
+ iNdEx = preIndex
+ skippy, err := skipMetrics(dAtA[iNdEx:])
+ if err != nil {
+ return err
+ }
+ if (skippy < 0) || (iNdEx+skippy) < 0 {
+ return ErrInvalidLengthMetrics
+ }
+ if (iNdEx + skippy) > l {
+ return io.ErrUnexpectedEOF
+ }
+ m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
+ iNdEx += skippy
+ }
+ }
+
+ if iNdEx > l {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
+func skipMetrics(dAtA []byte) (n int, err error) {
+ l := len(dAtA)
+ iNdEx := 0
+ depth := 0
+ for iNdEx < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ iNdEx++
+ if dAtA[iNdEx-1] < 0x80 {
+ break
+ }
+ }
+ case 1:
+ iNdEx += 8
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if shift >= 64 {
+ return 0, ErrIntOverflowMetrics
+ }
+ if iNdEx >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := dAtA[iNdEx]
+ iNdEx++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ if length < 0 {
+ return 0, ErrInvalidLengthMetrics
+ }
+ iNdEx += length
+ case 3:
+ depth++
+ case 4:
+ if depth == 0 {
+ return 0, ErrUnexpectedEndOfGroupMetrics
+ }
+ depth--
+ case 5:
+ iNdEx += 4
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ if iNdEx < 0 {
+ return 0, ErrInvalidLengthMetrics
+ }
+ if depth == 0 {
+ return iNdEx, nil
+ }
+ }
+ return 0, io.ErrUnexpectedEOF
+}
+
+var (
+ ErrInvalidLengthMetrics = fmt.Errorf("proto: negative length found during unmarshaling")
+ ErrIntOverflowMetrics = fmt.Errorf("proto: integer overflow")
+ ErrUnexpectedEndOfGroupMetrics = fmt.Errorf("proto: unexpected end of group")
+)
diff --git a/vendor/github.com/containerd/cgroups/v2/stats/metrics.pb.txt b/vendor/github.com/containerd/cgroups/v2/stats/metrics.pb.txt
@@ -0,0 +1,539 @@
+file {
+ name: "github.com/containerd/cgroups/v2/stats/metrics.proto"
+ package: "io.containerd.cgroups.v2"
+ dependency: "gogoproto/gogo.proto"
+ message_type {
+ name: "Metrics"
+ field {
+ name: "pids"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v2.PidsStat"
+ json_name: "pids"
+ }
+ field {
+ name: "cpu"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v2.CPUStat"
+ options {
+ 65004: "CPU"
+ }
+ json_name: "cpu"
+ }
+ field {
+ name: "memory"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v2.MemoryStat"
+ json_name: "memory"
+ }
+ field {
+ name: "rdma"
+ number: 5
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v2.RdmaStat"
+ json_name: "rdma"
+ }
+ field {
+ name: "io"
+ number: 6
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v2.IOStat"
+ json_name: "io"
+ }
+ field {
+ name: "hugetlb"
+ number: 7
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v2.HugeTlbStat"
+ json_name: "hugetlb"
+ }
+ field {
+ name: "memory_events"
+ number: 8
+ label: LABEL_OPTIONAL
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v2.MemoryEvents"
+ json_name: "memoryEvents"
+ }
+ }
+ message_type {
+ name: "PidsStat"
+ field {
+ name: "current"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "current"
+ }
+ field {
+ name: "limit"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "limit"
+ }
+ }
+ message_type {
+ name: "CPUStat"
+ field {
+ name: "usage_usec"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "usageUsec"
+ }
+ field {
+ name: "user_usec"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "userUsec"
+ }
+ field {
+ name: "system_usec"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "systemUsec"
+ }
+ field {
+ name: "nr_periods"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "nrPeriods"
+ }
+ field {
+ name: "nr_throttled"
+ number: 5
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "nrThrottled"
+ }
+ field {
+ name: "throttled_usec"
+ number: 6
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "throttledUsec"
+ }
+ }
+ message_type {
+ name: "MemoryStat"
+ field {
+ name: "anon"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "anon"
+ }
+ field {
+ name: "file"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "file"
+ }
+ field {
+ name: "kernel_stack"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "kernelStack"
+ }
+ field {
+ name: "slab"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "slab"
+ }
+ field {
+ name: "sock"
+ number: 5
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "sock"
+ }
+ field {
+ name: "shmem"
+ number: 6
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "shmem"
+ }
+ field {
+ name: "file_mapped"
+ number: 7
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "fileMapped"
+ }
+ field {
+ name: "file_dirty"
+ number: 8
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "fileDirty"
+ }
+ field {
+ name: "file_writeback"
+ number: 9
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "fileWriteback"
+ }
+ field {
+ name: "anon_thp"
+ number: 10
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "anonThp"
+ }
+ field {
+ name: "inactive_anon"
+ number: 11
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "inactiveAnon"
+ }
+ field {
+ name: "active_anon"
+ number: 12
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "activeAnon"
+ }
+ field {
+ name: "inactive_file"
+ number: 13
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "inactiveFile"
+ }
+ field {
+ name: "active_file"
+ number: 14
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "activeFile"
+ }
+ field {
+ name: "unevictable"
+ number: 15
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "unevictable"
+ }
+ field {
+ name: "slab_reclaimable"
+ number: 16
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "slabReclaimable"
+ }
+ field {
+ name: "slab_unreclaimable"
+ number: 17
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "slabUnreclaimable"
+ }
+ field {
+ name: "pgfault"
+ number: 18
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgfault"
+ }
+ field {
+ name: "pgmajfault"
+ number: 19
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgmajfault"
+ }
+ field {
+ name: "workingset_refault"
+ number: 20
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "workingsetRefault"
+ }
+ field {
+ name: "workingset_activate"
+ number: 21
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "workingsetActivate"
+ }
+ field {
+ name: "workingset_nodereclaim"
+ number: 22
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "workingsetNodereclaim"
+ }
+ field {
+ name: "pgrefill"
+ number: 23
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgrefill"
+ }
+ field {
+ name: "pgscan"
+ number: 24
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgscan"
+ }
+ field {
+ name: "pgsteal"
+ number: 25
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgsteal"
+ }
+ field {
+ name: "pgactivate"
+ number: 26
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgactivate"
+ }
+ field {
+ name: "pgdeactivate"
+ number: 27
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pgdeactivate"
+ }
+ field {
+ name: "pglazyfree"
+ number: 28
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pglazyfree"
+ }
+ field {
+ name: "pglazyfreed"
+ number: 29
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "pglazyfreed"
+ }
+ field {
+ name: "thp_fault_alloc"
+ number: 30
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "thpFaultAlloc"
+ }
+ field {
+ name: "thp_collapse_alloc"
+ number: 31
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "thpCollapseAlloc"
+ }
+ field {
+ name: "usage"
+ number: 32
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "usage"
+ }
+ field {
+ name: "usage_limit"
+ number: 33
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "usageLimit"
+ }
+ field {
+ name: "swap_usage"
+ number: 34
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "swapUsage"
+ }
+ field {
+ name: "swap_limit"
+ number: 35
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "swapLimit"
+ }
+ }
+ message_type {
+ name: "MemoryEvents"
+ field {
+ name: "low"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "low"
+ }
+ field {
+ name: "high"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "high"
+ }
+ field {
+ name: "max"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "max"
+ }
+ field {
+ name: "oom"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "oom"
+ }
+ field {
+ name: "oom_kill"
+ number: 5
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "oomKill"
+ }
+ }
+ message_type {
+ name: "RdmaStat"
+ field {
+ name: "current"
+ number: 1
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v2.RdmaEntry"
+ json_name: "current"
+ }
+ field {
+ name: "limit"
+ number: 2
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v2.RdmaEntry"
+ json_name: "limit"
+ }
+ }
+ message_type {
+ name: "RdmaEntry"
+ field {
+ name: "device"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_STRING
+ json_name: "device"
+ }
+ field {
+ name: "hca_handles"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT32
+ json_name: "hcaHandles"
+ }
+ field {
+ name: "hca_objects"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT32
+ json_name: "hcaObjects"
+ }
+ }
+ message_type {
+ name: "IOStat"
+ field {
+ name: "usage"
+ number: 1
+ label: LABEL_REPEATED
+ type: TYPE_MESSAGE
+ type_name: ".io.containerd.cgroups.v2.IOEntry"
+ json_name: "usage"
+ }
+ }
+ message_type {
+ name: "IOEntry"
+ field {
+ name: "major"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "major"
+ }
+ field {
+ name: "minor"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "minor"
+ }
+ field {
+ name: "rbytes"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "rbytes"
+ }
+ field {
+ name: "wbytes"
+ number: 4
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "wbytes"
+ }
+ field {
+ name: "rios"
+ number: 5
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "rios"
+ }
+ field {
+ name: "wios"
+ number: 6
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "wios"
+ }
+ }
+ message_type {
+ name: "HugeTlbStat"
+ field {
+ name: "current"
+ number: 1
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "current"
+ }
+ field {
+ name: "max"
+ number: 2
+ label: LABEL_OPTIONAL
+ type: TYPE_UINT64
+ json_name: "max"
+ }
+ field {
+ name: "pagesize"
+ number: 3
+ label: LABEL_OPTIONAL
+ type: TYPE_STRING
+ json_name: "pagesize"
+ }
+ }
+ syntax: "proto3"
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/stats/metrics.proto b/vendor/github.com/containerd/cgroups/v2/stats/metrics.proto
@@ -0,0 +1,105 @@
+syntax = "proto3";
+
+package io.containerd.cgroups.v2;
+
+ import "gogoproto/gogo.proto";
+
+message Metrics {
+ PidsStat pids = 1;
+ CPUStat cpu = 2 [(gogoproto.customname) = "CPU"];
+ MemoryStat memory = 4;
+ RdmaStat rdma = 5;
+ IOStat io = 6;
+ repeated HugeTlbStat hugetlb = 7;
+ MemoryEvents memory_events = 8;
+}
+
+message PidsStat {
+ uint64 current = 1;
+ uint64 limit = 2;
+}
+
+message CPUStat {
+ uint64 usage_usec = 1;
+ uint64 user_usec = 2;
+ uint64 system_usec = 3;
+ uint64 nr_periods = 4;
+ uint64 nr_throttled = 5;
+ uint64 throttled_usec = 6;
+}
+
+message MemoryStat {
+ uint64 anon = 1;
+ uint64 file = 2;
+ uint64 kernel_stack = 3;
+ uint64 slab = 4;
+ uint64 sock = 5;
+ uint64 shmem = 6;
+ uint64 file_mapped = 7;
+ uint64 file_dirty = 8;
+ uint64 file_writeback = 9;
+ uint64 anon_thp = 10;
+ uint64 inactive_anon = 11;
+ uint64 active_anon = 12;
+ uint64 inactive_file = 13;
+ uint64 active_file = 14;
+ uint64 unevictable = 15;
+ uint64 slab_reclaimable = 16;
+ uint64 slab_unreclaimable = 17;
+ uint64 pgfault = 18;
+ uint64 pgmajfault = 19;
+ uint64 workingset_refault = 20;
+ uint64 workingset_activate = 21;
+ uint64 workingset_nodereclaim = 22;
+ uint64 pgrefill = 23;
+ uint64 pgscan = 24;
+ uint64 pgsteal = 25;
+ uint64 pgactivate = 26;
+ uint64 pgdeactivate = 27;
+ uint64 pglazyfree = 28;
+ uint64 pglazyfreed = 29;
+ uint64 thp_fault_alloc = 30;
+ uint64 thp_collapse_alloc = 31;
+ uint64 usage = 32;
+ uint64 usage_limit = 33;
+ uint64 swap_usage = 34;
+ uint64 swap_limit = 35;
+}
+
+message MemoryEvents {
+ uint64 low = 1;
+ uint64 high = 2;
+ uint64 max = 3;
+ uint64 oom = 4;
+ uint64 oom_kill = 5;
+}
+
+message RdmaStat {
+ repeated RdmaEntry current = 1;
+ repeated RdmaEntry limit = 2;
+}
+
+message RdmaEntry {
+ string device = 1;
+ uint32 hca_handles = 2;
+ uint32 hca_objects = 3;
+}
+
+message IOStat {
+ repeated IOEntry usage = 1;
+}
+
+message IOEntry {
+ uint64 major = 1;
+ uint64 minor = 2;
+ uint64 rbytes = 3;
+ uint64 wbytes = 4;
+ uint64 rios = 5;
+ uint64 wios = 6;
+}
+
+message HugeTlbStat {
+ uint64 current = 1;
+ uint64 max = 2;
+ string pagesize = 3;
+}
diff --git a/vendor/github.com/containerd/cgroups/v2/utils.go b/vendor/github.com/containerd/cgroups/v2/utils.go
@@ -0,0 +1,436 @@
+/*
+ Copyright The containerd 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 v2
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "math"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/containerd/cgroups/v2/stats"
+
+ "github.com/godbus/dbus/v5"
+ "github.com/opencontainers/runtime-spec/specs-go"
+ "github.com/sirupsen/logrus"
+)
+
+const (
+ cgroupProcs = "cgroup.procs"
+ defaultDirPerm = 0755
+)
+
+// defaultFilePerm is a var so that the test framework can change the filemode
+// of all files created when the tests are running. The difference between the
+// tests and real world use is that files like "cgroup.procs" will exist when writing
+// to a read cgroup filesystem and do not exist prior when running in the tests.
+// this is set to a non 0 value in the test code
+var defaultFilePerm = os.FileMode(0)
+
+// remove will remove a cgroup path handling EAGAIN and EBUSY errors and
+// retrying the remove after a exp timeout
+func remove(path string) error {
+ var err error
+ delay := 10 * time.Millisecond
+ for i := 0; i < 5; i++ {
+ if i != 0 {
+ time.Sleep(delay)
+ delay *= 2
+ }
+ if err = os.RemoveAll(path); err == nil {
+ return nil
+ }
+ }
+ return fmt.Errorf("cgroups: unable to remove path %q: %w", path, err)
+}
+
+// parseCgroupProcsFile parses /sys/fs/cgroup/$GROUPPATH/cgroup.procs
+func parseCgroupProcsFile(path string) ([]uint64, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ var (
+ out []uint64
+ s = bufio.NewScanner(f)
+ )
+ for s.Scan() {
+ if t := s.Text(); t != "" {
+ pid, err := strconv.ParseUint(t, 10, 0)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, pid)
+ }
+ }
+ if err := s.Err(); err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func parseKV(raw string) (string, interface{}, error) {
+ parts := strings.Fields(raw)
+ switch len(parts) {
+ case 2:
+ v, err := parseUint(parts[1], 10, 64)
+ if err != nil {
+ // if we cannot parse as a uint, parse as a string
+ return parts[0], parts[1], nil
+ }
+ return parts[0], v, nil
+ default:
+ return "", 0, ErrInvalidFormat
+ }
+}
+
+func parseUint(s string, base, bitSize int) (uint64, error) {
+ v, err := strconv.ParseUint(s, base, bitSize)
+ if err != nil {
+ intValue, intErr := strconv.ParseInt(s, base, bitSize)
+ // 1. Handle negative values greater than MinInt64 (and)
+ // 2. Handle negative values lesser than MinInt64
+ if intErr == nil && intValue < 0 {
+ return 0, nil
+ } else if intErr != nil &&
+ intErr.(*strconv.NumError).Err == strconv.ErrRange &&
+ intValue < 0 {
+ return 0, nil
+ }
+ return 0, err
+ }
+ return v, nil
+}
+
+// parseCgroupFile parses /proc/PID/cgroup file and return string
+func parseCgroupFile(path string) (string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ return parseCgroupFromReader(f)
+}
+
+func parseCgroupFromReader(r io.Reader) (string, error) {
+ var (
+ s = bufio.NewScanner(r)
+ )
+ for s.Scan() {
+ var (
+ text = s.Text()
+ parts = strings.SplitN(text, ":", 3)
+ )
+ if len(parts) < 3 {
+ return "", fmt.Errorf("invalid cgroup entry: %q", text)
+ }
+ // text is like "0::/user.slice/user-1001.slice/session-1.scope"
+ if parts[0] == "0" && parts[1] == "" {
+ return parts[2], nil
+ }
+ }
+ if err := s.Err(); err != nil {
+ return "", err
+ }
+ return "", fmt.Errorf("cgroup path not found")
+}
+
+// ToResources converts the oci LinuxResources struct into a
+// v2 Resources type for use with this package.
+//
+// converting cgroups configuration from v1 to v2
+// ref: https://github.com/containers/crun/blob/master/crun.1.md#cgroup-v2
+func ToResources(spec *specs.LinuxResources) *Resources {
+ var resources Resources
+ if cpu := spec.CPU; cpu != nil {
+ resources.CPU = &CPU{
+ Cpus: cpu.Cpus,
+ Mems: cpu.Mems,
+ }
+ if shares := cpu.Shares; shares != nil {
+ convertedWeight := 1 + ((*shares-2)*9999)/262142
+ resources.CPU.Weight = &convertedWeight
+ }
+ if period := cpu.Period; period != nil {
+ resources.CPU.Max = NewCPUMax(cpu.Quota, period)
+ }
+ }
+ if mem := spec.Memory; mem != nil {
+ resources.Memory = &Memory{}
+ if swap := mem.Swap; swap != nil {
+ resources.Memory.Swap = swap
+ }
+ if l := mem.Limit; l != nil {
+ resources.Memory.Max = l
+ }
+ if l := mem.Reservation; l != nil {
+ resources.Memory.Low = l
+ }
+ }
+ if hugetlbs := spec.HugepageLimits; hugetlbs != nil {
+ hugeTlbUsage := HugeTlb{}
+ for _, hugetlb := range hugetlbs {
+ hugeTlbUsage = append(hugeTlbUsage, HugeTlbEntry{
+ HugePageSize: hugetlb.Pagesize,
+ Limit: hugetlb.Limit,
+ })
+ }
+ resources.HugeTlb = &hugeTlbUsage
+ }
+ if pids := spec.Pids; pids != nil {
+ resources.Pids = &Pids{
+ Max: pids.Limit,
+ }
+ }
+ if i := spec.BlockIO; i != nil {
+ resources.IO = &IO{}
+ if i.Weight != nil {
+ resources.IO.BFQ.Weight = 1 + (*i.Weight-10)*9999/990
+ }
+ for t, devices := range map[IOType][]specs.LinuxThrottleDevice{
+ ReadBPS: i.ThrottleReadBpsDevice,
+ WriteBPS: i.ThrottleWriteBpsDevice,
+ ReadIOPS: i.ThrottleReadIOPSDevice,
+ WriteIOPS: i.ThrottleWriteIOPSDevice,
+ } {
+ for _, d := range devices {
+ resources.IO.Max = append(resources.IO.Max, Entry{
+ Type: t,
+ Major: d.Major,
+ Minor: d.Minor,
+ Rate: d.Rate,
+ })
+ }
+ }
+ }
+ if i := spec.Rdma; i != nil {
+ resources.RDMA = &RDMA{}
+ for device, value := range spec.Rdma {
+ if device != "" && (value.HcaHandles != nil && value.HcaObjects != nil) {
+ resources.RDMA.Limit = append(resources.RDMA.Limit, RDMAEntry{
+ Device: device,
+ HcaHandles: *value.HcaHandles,
+ HcaObjects: *value.HcaObjects,
+ })
+ }
+ }
+ }
+
+ return &resources
+}
+
+// Gets uint64 parsed content of single value cgroup stat file
+func getStatFileContentUint64(filePath string) uint64 {
+ contents, err := ioutil.ReadFile(filePath)
+ if err != nil {
+ return 0
+ }
+ trimmed := strings.TrimSpace(string(contents))
+ if trimmed == "max" {
+ return math.MaxUint64
+ }
+
+ res, err := parseUint(trimmed, 10, 64)
+ if err != nil {
+ logrus.Errorf("unable to parse %q as a uint from Cgroup file %q", string(contents), filePath)
+ return res
+ }
+
+ return res
+}
+
+func readIoStats(path string) []*stats.IOEntry {
+ // more details on the io.stat file format: https://www.kernel.org/doc/Documentation/cgroup-v2.txt
+ var usage []*stats.IOEntry
+ fpath := filepath.Join(path, "io.stat")
+ currentData, err := ioutil.ReadFile(fpath)
+ if err != nil {
+ return usage
+ }
+ entries := strings.Split(string(currentData), "\n")
+
+ for _, entry := range entries {
+ parts := strings.Split(entry, " ")
+ if len(parts) < 2 {
+ continue
+ }
+ majmin := strings.Split(parts[0], ":")
+ if len(majmin) != 2 {
+ continue
+ }
+ major, err := strconv.ParseUint(majmin[0], 10, 0)
+ if err != nil {
+ return usage
+ }
+ minor, err := strconv.ParseUint(majmin[1], 10, 0)
+ if err != nil {
+ return usage
+ }
+ parts = parts[1:]
+ ioEntry := stats.IOEntry{
+ Major: major,
+ Minor: minor,
+ }
+ for _, s := range parts {
+ keyPairValue := strings.Split(s, "=")
+ if len(keyPairValue) != 2 {
+ continue
+ }
+ v, err := strconv.ParseUint(keyPairValue[1], 10, 0)
+ if err != nil {
+ continue
+ }
+ switch keyPairValue[0] {
+ case "rbytes":
+ ioEntry.Rbytes = v
+ case "wbytes":
+ ioEntry.Wbytes = v
+ case "rios":
+ ioEntry.Rios = v
+ case "wios":
+ ioEntry.Wios = v
+ }
+ }
+ usage = append(usage, &ioEntry)
+ }
+ return usage
+}
+
+func rdmaStats(filepath string) []*stats.RdmaEntry {
+ currentData, err := ioutil.ReadFile(filepath)
+ if err != nil {
+ return []*stats.RdmaEntry{}
+ }
+ return toRdmaEntry(strings.Split(string(currentData), "\n"))
+}
+
+func parseRdmaKV(raw string, entry *stats.RdmaEntry) {
+ var value uint64
+ var err error
+
+ parts := strings.Split(raw, "=")
+ switch len(parts) {
+ case 2:
+ if parts[1] == "max" {
+ value = math.MaxUint32
+ } else {
+ value, err = parseUint(parts[1], 10, 32)
+ if err != nil {
+ return
+ }
+ }
+ if parts[0] == "hca_handle" {
+ entry.HcaHandles = uint32(value)
+ } else if parts[0] == "hca_object" {
+ entry.HcaObjects = uint32(value)
+ }
+ }
+}
+
+func toRdmaEntry(strEntries []string) []*stats.RdmaEntry {
+ var rdmaEntries []*stats.RdmaEntry
+ for i := range strEntries {
+ parts := strings.Fields(strEntries[i])
+ switch len(parts) {
+ case 3:
+ entry := new(stats.RdmaEntry)
+ entry.Device = parts[0]
+ parseRdmaKV(parts[1], entry)
+ parseRdmaKV(parts[2], entry)
+
+ rdmaEntries = append(rdmaEntries, entry)
+ default:
+ continue
+ }
+ }
+ return rdmaEntries
+}
+
+// isUnitExists returns true if the error is that a systemd unit already exists.
+func isUnitExists(err error) bool {
+ if err != nil {
+ if dbusError, ok := err.(dbus.Error); ok {
+ return strings.Contains(dbusError.Name, "org.freedesktop.systemd1.UnitExists")
+ }
+ }
+ return false
+}
+
+func systemdUnitFromPath(path string) string {
+ _, unit := filepath.Split(path)
+ return unit
+}
+
+func readHugeTlbStats(path string) []*stats.HugeTlbStat {
+ var usage = []*stats.HugeTlbStat{}
+ var keyUsage = make(map[string]*stats.HugeTlbStat)
+ f, err := os.Open(path)
+ if err != nil {
+ return usage
+ }
+ files, err := f.Readdir(-1)
+ f.Close()
+ if err != nil {
+ return usage
+ }
+
+ for _, file := range files {
+ if strings.Contains(file.Name(), "hugetlb") &&
+ (strings.HasSuffix(file.Name(), "max") || strings.HasSuffix(file.Name(), "current")) {
+ var hugeTlb *stats.HugeTlbStat
+ var ok bool
+ fileName := strings.Split(file.Name(), ".")
+ pageSize := fileName[1]
+ if hugeTlb, ok = keyUsage[pageSize]; !ok {
+ hugeTlb = &stats.HugeTlbStat{}
+ }
+ hugeTlb.Pagesize = pageSize
+ out, err := ioutil.ReadFile(filepath.Join(path, file.Name()))
+ if err != nil {
+ continue
+ }
+ var value uint64
+ stringVal := strings.TrimSpace(string(out))
+ if stringVal == "max" {
+ value = math.MaxUint64
+ } else {
+ value, err = strconv.ParseUint(stringVal, 10, 64)
+ }
+ if err != nil {
+ continue
+ }
+ switch fileName[2] {
+ case "max":
+ hugeTlb.Max = value
+ case "current":
+ hugeTlb.Current = value
+ }
+ keyUsage[pageSize] = hugeTlb
+ }
+ }
+ for _, entry := range keyUsage {
+ usage = append(usage, entry)
+ }
+ return usage
+}
diff --git a/vendor/github.com/coreos/go-systemd/v22/LICENSE b/vendor/github.com/coreos/go-systemd/v22/LICENSE
@@ -0,0 +1,191 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and
+distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright
+owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities
+that control, are controlled by, or are under common control with that entity.
+For the purposes of this definition, "control" means (i) the power, direct or
+indirect, to cause the direction or management of such entity, whether by
+contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
+outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising
+permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including
+but not limited to software source code, documentation source, and configuration
+files.
+
+"Object" form shall mean any form resulting from mechanical transformation or
+translation of a Source form, including but not limited to compiled object code,
+generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made
+available under the License, as indicated by a copyright notice that is included
+in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that
+is based on (or derived from) the Work and for which the editorial revisions,
+annotations, elaborations, or other modifications represent, as a whole, an
+original work of authorship. For the purposes of this License, Derivative Works
+shall not include works that remain separable from, or merely link (or bind by
+name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version
+of the Work and any modifications or additions to that Work or Derivative Works
+thereof, that is intentionally submitted to Licensor for inclusion in the Work
+by the copyright owner or by an individual or Legal Entity authorized to submit
+on behalf of the copyright owner. For the purposes of this definition,
+"submitted" means any form of electronic, verbal, or written communication sent
+to the Licensor or its representatives, including but not limited to
+communication on electronic mailing lists, source code control systems, and
+issue tracking systems that are managed by, or on behalf of, the Licensor for
+the purpose of discussing and improving the Work, but excluding communication
+that is conspicuously marked or otherwise designated in writing by the copyright
+owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
+of whom a Contribution has been received by Licensor and subsequently
+incorporated within the Work.
+
+2. Grant of Copyright License.
+
+Subject to the terms and conditions of this License, each Contributor hereby
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+irrevocable copyright license to reproduce, prepare Derivative Works of,
+publicly display, publicly perform, sublicense, and distribute the Work and such
+Derivative Works in Source or Object form.
+
+3. Grant of Patent License.
+
+Subject to the terms and conditions of this License, each Contributor hereby
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+irrevocable (except as stated in this section) patent license to make, have
+made, use, offer to sell, sell, import, and otherwise transfer the Work, where
+such license applies only to those patent claims licensable by such Contributor
+that are necessarily infringed by their Contribution(s) alone or by combination
+of their Contribution(s) with the Work to which such Contribution(s) was
+submitted. If You institute patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Work or a
+Contribution incorporated within the Work constitutes direct or contributory
+patent infringement, then any patent licenses granted to You under this License
+for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution.
+
+You may reproduce and distribute copies of the Work or Derivative Works thereof
+in any medium, with or without modifications, and in Source or Object form,
+provided that You meet the following conditions:
+
+You must give any other recipients of the Work or Derivative Works a copy of
+this License; and
+You must cause any modified files to carry prominent notices stating that You
+changed the files; and
+You must retain, in the Source form of any Derivative Works that You distribute,
+all copyright, patent, trademark, and attribution notices from the Source form
+of the Work, excluding those notices that do not pertain to any part of the
+Derivative Works; and
+If the Work includes a "NOTICE" text file as part of its distribution, then any
+Derivative Works that You distribute must include a readable copy of the
+attribution notices contained within such NOTICE file, excluding those notices
+that do not pertain to any part of the Derivative Works, in at least one of the
+following places: within a NOTICE text file distributed as part of the
+Derivative Works; within the Source form or documentation, if provided along
+with the Derivative Works; or, within a display generated by the Derivative
+Works, if and wherever such third-party notices normally appear. The contents of
+the NOTICE file are for informational purposes only and do not modify the
+License. You may add Your own attribution notices within Derivative Works that
+You distribute, alongside or as an addendum to the NOTICE text from the Work,
+provided that such additional attribution notices cannot be construed as
+modifying the License.
+You may add Your own copyright statement to Your modifications and may provide
+additional or different license terms and conditions for use, reproduction, or
+distribution of Your modifications, or for any such Derivative Works as a whole,
+provided Your use, reproduction, and distribution of the Work otherwise complies
+with the conditions stated in this License.
+
+5. Submission of Contributions.
+
+Unless You explicitly state otherwise, any Contribution intentionally submitted
+for inclusion in the Work by You to the Licensor shall be under the terms and
+conditions of this License, without any additional terms or conditions.
+Notwithstanding the above, nothing herein shall supersede or modify the terms of
+any separate license agreement you may have executed with Licensor regarding
+such Contributions.
+
+6. Trademarks.
+
+This License does not grant permission to use the trade names, trademarks,
+service marks, or product names of the Licensor, except as required for
+reasonable and customary use in describing the origin of the Work and
+reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty.
+
+Unless required by applicable law or agreed to in writing, Licensor provides the
+Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
+including, without limitation, any warranties or conditions of TITLE,
+NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
+solely responsible for determining the appropriateness of using or
+redistributing the Work and assume any risks associated with Your exercise of
+permissions under this License.
+
+8. Limitation of Liability.
+
+In no event and under no legal theory, whether in tort (including negligence),
+contract, or otherwise, unless required by applicable law (such as deliberate
+and grossly negligent acts) or agreed to in writing, shall any Contributor be
+liable to You for damages, including any direct, indirect, special, incidental,
+or consequential damages of any character arising as a result of this License or
+out of the use or inability to use the Work (including but not limited to
+damages for loss of goodwill, work stoppage, computer failure or malfunction, or
+any and all other commercial damages or losses), even if such Contributor has
+been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability.
+
+While redistributing the Work or Derivative Works thereof, You may choose to
+offer, and charge a fee for, acceptance of support, warranty, indemnity, or
+other liability obligations and/or rights consistent with this License. However,
+in accepting such obligations, You may act only on Your own behalf and on Your
+sole responsibility, not on behalf of any other Contributor, and only if You
+agree to indemnify, defend, and hold each Contributor harmless for any liability
+incurred by, or claims asserted against, such Contributor by reason of your
+accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work
+
+To apply the Apache License to your work, attach the following boilerplate
+notice, with the fields enclosed by brackets "[]" replaced with your own
+identifying information. (Don't include the brackets!) The text should be
+enclosed in the appropriate comment syntax for the file format. We also
+recommend that a file or class name and description of purpose be included on
+the same "printed page" as the copyright notice for easier identification within
+third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/coreos/go-systemd/v22/NOTICE b/vendor/github.com/coreos/go-systemd/v22/NOTICE
@@ -0,0 +1,5 @@
+CoreOS Project
+Copyright 2018 CoreOS, Inc
+
+This product includes software developed at CoreOS, Inc.
+(http://www.coreos.com/).
diff --git a/vendor/github.com/coreos/go-systemd/v22/dbus/dbus.go b/vendor/github.com/coreos/go-systemd/v22/dbus/dbus.go
@@ -0,0 +1,261 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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.
+
+// Integration with the systemd D-Bus API. See http://www.freedesktop.org/wiki/Software/systemd/dbus/
+package dbus
+
+import (
+ "context"
+ "encoding/hex"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/godbus/dbus/v5"
+)
+
+const (
+ alpha = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`
+ num = `0123456789`
+ alphanum = alpha + num
+ signalBuffer = 100
+)
+
+// needsEscape checks whether a byte in a potential dbus ObjectPath needs to be escaped
+func needsEscape(i int, b byte) bool {
+ // Escape everything that is not a-z-A-Z-0-9
+ // Also escape 0-9 if it's the first character
+ return strings.IndexByte(alphanum, b) == -1 ||
+ (i == 0 && strings.IndexByte(num, b) != -1)
+}
+
+// PathBusEscape sanitizes a constituent string of a dbus ObjectPath using the
+// rules that systemd uses for serializing special characters.
+func PathBusEscape(path string) string {
+ // Special case the empty string
+ if len(path) == 0 {
+ return "_"
+ }
+ n := []byte{}
+ for i := 0; i < len(path); i++ {
+ c := path[i]
+ if needsEscape(i, c) {
+ e := fmt.Sprintf("_%x", c)
+ n = append(n, []byte(e)...)
+ } else {
+ n = append(n, c)
+ }
+ }
+ return string(n)
+}
+
+// pathBusUnescape is the inverse of PathBusEscape.
+func pathBusUnescape(path string) string {
+ if path == "_" {
+ return ""
+ }
+ n := []byte{}
+ for i := 0; i < len(path); i++ {
+ c := path[i]
+ if c == '_' && i+2 < len(path) {
+ res, err := hex.DecodeString(path[i+1 : i+3])
+ if err == nil {
+ n = append(n, res...)
+ }
+ i += 2
+ } else {
+ n = append(n, c)
+ }
+ }
+ return string(n)
+}
+
+// Conn is a connection to systemd's dbus endpoint.
+type Conn struct {
+ // sysconn/sysobj are only used to call dbus methods
+ sysconn *dbus.Conn
+ sysobj dbus.BusObject
+
+ // sigconn/sigobj are only used to receive dbus signals
+ sigconn *dbus.Conn
+ sigobj dbus.BusObject
+
+ jobListener struct {
+ jobs map[dbus.ObjectPath]chan<- string
+ sync.Mutex
+ }
+ subStateSubscriber struct {
+ updateCh chan<- *SubStateUpdate
+ errCh chan<- error
+ sync.Mutex
+ ignore map[dbus.ObjectPath]int64
+ cleanIgnore int64
+ }
+ propertiesSubscriber struct {
+ updateCh chan<- *PropertiesUpdate
+ errCh chan<- error
+ sync.Mutex
+ }
+}
+
+// Deprecated: use NewWithContext instead.
+func New() (*Conn, error) {
+ return NewWithContext(context.Background())
+}
+
+// NewWithContext establishes a connection to any available bus and authenticates.
+// Callers should call Close() when done with the connection.
+func NewWithContext(ctx context.Context) (*Conn, error) {
+ conn, err := NewSystemConnectionContext(ctx)
+ if err != nil && os.Geteuid() == 0 {
+ return NewSystemdConnectionContext(ctx)
+ }
+ return conn, err
+}
+
+// Deprecated: use NewSystemConnectionContext instead.
+func NewSystemConnection() (*Conn, error) {
+ return NewSystemConnectionContext(context.Background())
+}
+
+// NewSystemConnectionContext establishes a connection to the system bus and authenticates.
+// Callers should call Close() when done with the connection.
+func NewSystemConnectionContext(ctx context.Context) (*Conn, error) {
+ return NewConnection(func() (*dbus.Conn, error) {
+ return dbusAuthHelloConnection(ctx, dbus.SystemBusPrivate)
+ })
+}
+
+// Deprecated: use NewUserConnectionContext instead.
+func NewUserConnection() (*Conn, error) {
+ return NewUserConnectionContext(context.Background())
+}
+
+// NewUserConnectionContext establishes a connection to the session bus and
+// authenticates. This can be used to connect to systemd user instances.
+// Callers should call Close() when done with the connection.
+func NewUserConnectionContext(ctx context.Context) (*Conn, error) {
+ return NewConnection(func() (*dbus.Conn, error) {
+ return dbusAuthHelloConnection(ctx, dbus.SessionBusPrivate)
+ })
+}
+
+// Deprecated: use NewSystemdConnectionContext instead.
+func NewSystemdConnection() (*Conn, error) {
+ return NewSystemdConnectionContext(context.Background())
+}
+
+// NewSystemdConnectionContext establishes a private, direct connection to systemd.
+// This can be used for communicating with systemd without a dbus daemon.
+// Callers should call Close() when done with the connection.
+func NewSystemdConnectionContext(ctx context.Context) (*Conn, error) {
+ return NewConnection(func() (*dbus.Conn, error) {
+ // We skip Hello when talking directly to systemd.
+ return dbusAuthConnection(ctx, func(opts ...dbus.ConnOption) (*dbus.Conn, error) {
+ return dbus.Dial("unix:path=/run/systemd/private", opts...)
+ })
+ })
+}
+
+// Close closes an established connection.
+func (c *Conn) Close() {
+ c.sysconn.Close()
+ c.sigconn.Close()
+}
+
+// NewConnection establishes a connection to a bus using a caller-supplied function.
+// This allows connecting to remote buses through a user-supplied mechanism.
+// The supplied function may be called multiple times, and should return independent connections.
+// The returned connection must be fully initialised: the org.freedesktop.DBus.Hello call must have succeeded,
+// and any authentication should be handled by the function.
+func NewConnection(dialBus func() (*dbus.Conn, error)) (*Conn, error) {
+ sysconn, err := dialBus()
+ if err != nil {
+ return nil, err
+ }
+
+ sigconn, err := dialBus()
+ if err != nil {
+ sysconn.Close()
+ return nil, err
+ }
+
+ c := &Conn{
+ sysconn: sysconn,
+ sysobj: systemdObject(sysconn),
+ sigconn: sigconn,
+ sigobj: systemdObject(sigconn),
+ }
+
+ c.subStateSubscriber.ignore = make(map[dbus.ObjectPath]int64)
+ c.jobListener.jobs = make(map[dbus.ObjectPath]chan<- string)
+
+ // Setup the listeners on jobs so that we can get completions
+ c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
+ "type='signal', interface='org.freedesktop.systemd1.Manager', member='JobRemoved'")
+
+ c.dispatch()
+ return c, nil
+}
+
+// GetManagerProperty returns the value of a property on the org.freedesktop.systemd1.Manager
+// interface. The value is returned in its string representation, as defined at
+// https://developer.gnome.org/glib/unstable/gvariant-text.html.
+func (c *Conn) GetManagerProperty(prop string) (string, error) {
+ variant, err := c.sysobj.GetProperty("org.freedesktop.systemd1.Manager." + prop)
+ if err != nil {
+ return "", err
+ }
+ return variant.String(), nil
+}
+
+func dbusAuthConnection(ctx context.Context, createBus func(opts ...dbus.ConnOption) (*dbus.Conn, error)) (*dbus.Conn, error) {
+ conn, err := createBus(dbus.WithContext(ctx))
+ if err != nil {
+ return nil, err
+ }
+
+ // Only use EXTERNAL method, and hardcode the uid (not username)
+ // to avoid a username lookup (which requires a dynamically linked
+ // libc)
+ methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}
+
+ err = conn.Auth(methods)
+ if err != nil {
+ conn.Close()
+ return nil, err
+ }
+
+ return conn, nil
+}
+
+func dbusAuthHelloConnection(ctx context.Context, createBus func(opts ...dbus.ConnOption) (*dbus.Conn, error)) (*dbus.Conn, error) {
+ conn, err := dbusAuthConnection(ctx, createBus)
+ if err != nil {
+ return nil, err
+ }
+
+ if err = conn.Hello(); err != nil {
+ conn.Close()
+ return nil, err
+ }
+
+ return conn, nil
+}
+
+func systemdObject(conn *dbus.Conn) dbus.BusObject {
+ return conn.Object("org.freedesktop.systemd1", dbus.ObjectPath("/org/freedesktop/systemd1"))
+}
diff --git a/vendor/github.com/coreos/go-systemd/v22/dbus/methods.go b/vendor/github.com/coreos/go-systemd/v22/dbus/methods.go
@@ -0,0 +1,830 @@
+// Copyright 2015, 2018 CoreOS, Inc.
+//
+// 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 dbus
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "path"
+ "strconv"
+
+ "github.com/godbus/dbus/v5"
+)
+
+// Who can be used to specify which process to kill in the unit via the KillUnitWithTarget API
+type Who string
+
+const (
+ // All sends the signal to all processes in the unit
+ All Who = "all"
+ // Main sends the signal to the main process of the unit
+ Main Who = "main"
+ // Control sends the signal to the control process of the unit
+ Control Who = "control"
+)
+
+func (c *Conn) jobComplete(signal *dbus.Signal) {
+ var id uint32
+ var job dbus.ObjectPath
+ var unit string
+ var result string
+ dbus.Store(signal.Body, &id, &job, &unit, &result)
+ c.jobListener.Lock()
+ out, ok := c.jobListener.jobs[job]
+ if ok {
+ out <- result
+ delete(c.jobListener.jobs, job)
+ }
+ c.jobListener.Unlock()
+}
+
+func (c *Conn) startJob(ctx context.Context, ch chan<- string, job string, args ...interface{}) (int, error) {
+ if ch != nil {
+ c.jobListener.Lock()
+ defer c.jobListener.Unlock()
+ }
+
+ var p dbus.ObjectPath
+ err := c.sysobj.CallWithContext(ctx, job, 0, args...).Store(&p)
+ if err != nil {
+ return 0, err
+ }
+
+ if ch != nil {
+ c.jobListener.jobs[p] = ch
+ }
+
+ // ignore error since 0 is fine if conversion fails
+ jobID, _ := strconv.Atoi(path.Base(string(p)))
+
+ return jobID, nil
+}
+
+// Deprecated: use StartUnitContext instead.
+func (c *Conn) StartUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.StartUnitContext(context.Background(), name, mode, ch)
+}
+
+// StartUnitContext enqueues a start job and depending jobs, if any (unless otherwise
+// specified by the mode string).
+//
+// Takes the unit to activate, plus a mode string. The mode needs to be one of
+// replace, fail, isolate, ignore-dependencies, ignore-requirements. If
+// "replace" the call will start the unit and its dependencies, possibly
+// replacing already queued jobs that conflict with this. If "fail" the call
+// will start the unit and its dependencies, but will fail if this would change
+// an already queued job. If "isolate" the call will start the unit in question
+// and terminate all units that aren't dependencies of it. If
+// "ignore-dependencies" it will start a unit but ignore all its dependencies.
+// If "ignore-requirements" it will start a unit but only ignore the
+// requirement dependencies. It is not recommended to make use of the latter
+// two options.
+//
+// If the provided channel is non-nil, a result string will be sent to it upon
+// job completion: one of done, canceled, timeout, failed, dependency, skipped.
+// done indicates successful execution of a job. canceled indicates that a job
+// has been canceled before it finished execution. timeout indicates that the
+// job timeout was reached. failed indicates that the job failed. dependency
+// indicates that a job this job has been depending on failed and the job hence
+// has been removed too. skipped indicates that a job was skipped because it
+// didn't apply to the units current state.
+//
+// If no error occurs, the ID of the underlying systemd job will be returned. There
+// does exist the possibility for no error to be returned, but for the returned job
+// ID to be 0. In this case, the actual underlying ID is not 0 and this datapoint
+// should not be considered authoritative.
+//
+// If an error does occur, it will be returned to the user alongside a job ID of 0.
+func (c *Conn) StartUnitContext(ctx context.Context, name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ctx, ch, "org.freedesktop.systemd1.Manager.StartUnit", name, mode)
+}
+
+// Deprecated: use StopUnitContext instead.
+func (c *Conn) StopUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.StopUnitContext(context.Background(), name, mode, ch)
+}
+
+// StopUnitContext is similar to StartUnitContext, but stops the specified unit
+// rather than starting it.
+func (c *Conn) StopUnitContext(ctx context.Context, name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ctx, ch, "org.freedesktop.systemd1.Manager.StopUnit", name, mode)
+}
+
+// Deprecated: use ReloadUnitContext instead.
+func (c *Conn) ReloadUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.ReloadUnitContext(context.Background(), name, mode, ch)
+}
+
+// ReloadUnitContext reloads a unit. Reloading is done only if the unit
+// is already running, and fails otherwise.
+func (c *Conn) ReloadUnitContext(ctx context.Context, name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ctx, ch, "org.freedesktop.systemd1.Manager.ReloadUnit", name, mode)
+}
+
+// Deprecated: use RestartUnitContext instead.
+func (c *Conn) RestartUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.RestartUnitContext(context.Background(), name, mode, ch)
+}
+
+// RestartUnitContext restarts a service. If a service is restarted that isn't
+// running it will be started.
+func (c *Conn) RestartUnitContext(ctx context.Context, name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ctx, ch, "org.freedesktop.systemd1.Manager.RestartUnit", name, mode)
+}
+
+// Deprecated: use TryRestartUnitContext instead.
+func (c *Conn) TryRestartUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.TryRestartUnitContext(context.Background(), name, mode, ch)
+}
+
+// TryRestartUnitContext is like RestartUnitContext, except that a service that
+// isn't running is not affected by the restart.
+func (c *Conn) TryRestartUnitContext(ctx context.Context, name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ctx, ch, "org.freedesktop.systemd1.Manager.TryRestartUnit", name, mode)
+}
+
+// Deprecated: use ReloadOrRestartUnitContext instead.
+func (c *Conn) ReloadOrRestartUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.ReloadOrRestartUnitContext(context.Background(), name, mode, ch)
+}
+
+// ReloadOrRestartUnitContext attempts a reload if the unit supports it and use
+// a restart otherwise.
+func (c *Conn) ReloadOrRestartUnitContext(ctx context.Context, name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ctx, ch, "org.freedesktop.systemd1.Manager.ReloadOrRestartUnit", name, mode)
+}
+
+// Deprecated: use ReloadOrTryRestartUnitContext instead.
+func (c *Conn) ReloadOrTryRestartUnit(name string, mode string, ch chan<- string) (int, error) {
+ return c.ReloadOrTryRestartUnitContext(context.Background(), name, mode, ch)
+}
+
+// ReloadOrTryRestartUnitContext attempts a reload if the unit supports it,
+// and use a "Try" flavored restart otherwise.
+func (c *Conn) ReloadOrTryRestartUnitContext(ctx context.Context, name string, mode string, ch chan<- string) (int, error) {
+ return c.startJob(ctx, ch, "org.freedesktop.systemd1.Manager.ReloadOrTryRestartUnit", name, mode)
+}
+
+// Deprecated: use StartTransientUnitContext instead.
+func (c *Conn) StartTransientUnit(name string, mode string, properties []Property, ch chan<- string) (int, error) {
+ return c.StartTransientUnitContext(context.Background(), name, mode, properties, ch)
+}
+
+// StartTransientUnitContext may be used to create and start a transient unit, which
+// will be released as soon as it is not running or referenced anymore or the
+// system is rebooted. name is the unit name including suffix, and must be
+// unique. mode is the same as in StartUnitContext, properties contains properties
+// of the unit.
+func (c *Conn) StartTransientUnitContext(ctx context.Context, name string, mode string, properties []Property, ch chan<- string) (int, error) {
+ return c.startJob(ctx, ch, "org.freedesktop.systemd1.Manager.StartTransientUnit", name, mode, properties, make([]PropertyCollection, 0))
+}
+
+// Deprecated: use KillUnitContext instead.
+func (c *Conn) KillUnit(name string, signal int32) {
+ c.KillUnitContext(context.Background(), name, signal)
+}
+
+// KillUnitContext takes the unit name and a UNIX signal number to send.
+// All of the unit's processes are killed.
+func (c *Conn) KillUnitContext(ctx context.Context, name string, signal int32) {
+ c.KillUnitWithTarget(ctx, name, All, signal)
+}
+
+// KillUnitWithTarget is like KillUnitContext, but allows you to specify which
+// process in the unit to send the signal to.
+func (c *Conn) KillUnitWithTarget(ctx context.Context, name string, target Who, signal int32) error {
+ return c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.KillUnit", 0, name, string(target), signal).Store()
+}
+
+// Deprecated: use ResetFailedUnitContext instead.
+func (c *Conn) ResetFailedUnit(name string) error {
+ return c.ResetFailedUnitContext(context.Background(), name)
+}
+
+// ResetFailedUnitContext resets the "failed" state of a specific unit.
+func (c *Conn) ResetFailedUnitContext(ctx context.Context, name string) error {
+ return c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.ResetFailedUnit", 0, name).Store()
+}
+
+// Deprecated: use SystemStateContext instead.
+func (c *Conn) SystemState() (*Property, error) {
+ return c.SystemStateContext(context.Background())
+}
+
+// SystemStateContext returns the systemd state. Equivalent to
+// systemctl is-system-running.
+func (c *Conn) SystemStateContext(ctx context.Context) (*Property, error) {
+ var err error
+ var prop dbus.Variant
+
+ obj := c.sysconn.Object("org.freedesktop.systemd1", "/org/freedesktop/systemd1")
+ err = obj.CallWithContext(ctx, "org.freedesktop.DBus.Properties.Get", 0, "org.freedesktop.systemd1.Manager", "SystemState").Store(&prop)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Property{Name: "SystemState", Value: prop}, nil
+}
+
+// getProperties takes the unit path and returns all of its dbus object properties, for the given dbus interface.
+func (c *Conn) getProperties(ctx context.Context, path dbus.ObjectPath, dbusInterface string) (map[string]interface{}, error) {
+ var err error
+ var props map[string]dbus.Variant
+
+ if !path.IsValid() {
+ return nil, fmt.Errorf("invalid unit name: %v", path)
+ }
+
+ obj := c.sysconn.Object("org.freedesktop.systemd1", path)
+ err = obj.CallWithContext(ctx, "org.freedesktop.DBus.Properties.GetAll", 0, dbusInterface).Store(&props)
+ if err != nil {
+ return nil, err
+ }
+
+ out := make(map[string]interface{}, len(props))
+ for k, v := range props {
+ out[k] = v.Value()
+ }
+
+ return out, nil
+}
+
+// Deprecated: use GetUnitPropertiesContext instead.
+func (c *Conn) GetUnitProperties(unit string) (map[string]interface{}, error) {
+ return c.GetUnitPropertiesContext(context.Background(), unit)
+}
+
+// GetUnitPropertiesContext takes the (unescaped) unit name and returns all of
+// its dbus object properties.
+func (c *Conn) GetUnitPropertiesContext(ctx context.Context, unit string) (map[string]interface{}, error) {
+ path := unitPath(unit)
+ return c.getProperties(ctx, path, "org.freedesktop.systemd1.Unit")
+}
+
+// Deprecated: use GetUnitPathPropertiesContext instead.
+func (c *Conn) GetUnitPathProperties(path dbus.ObjectPath) (map[string]interface{}, error) {
+ return c.GetUnitPathPropertiesContext(context.Background(), path)
+}
+
+// GetUnitPathPropertiesContext takes the (escaped) unit path and returns all
+// of its dbus object properties.
+func (c *Conn) GetUnitPathPropertiesContext(ctx context.Context, path dbus.ObjectPath) (map[string]interface{}, error) {
+ return c.getProperties(ctx, path, "org.freedesktop.systemd1.Unit")
+}
+
+// Deprecated: use GetAllPropertiesContext instead.
+func (c *Conn) GetAllProperties(unit string) (map[string]interface{}, error) {
+ return c.GetAllPropertiesContext(context.Background(), unit)
+}
+
+// GetAllPropertiesContext takes the (unescaped) unit name and returns all of
+// its dbus object properties.
+func (c *Conn) GetAllPropertiesContext(ctx context.Context, unit string) (map[string]interface{}, error) {
+ path := unitPath(unit)
+ return c.getProperties(ctx, path, "")
+}
+
+func (c *Conn) getProperty(ctx context.Context, unit string, dbusInterface string, propertyName string) (*Property, error) {
+ var err error
+ var prop dbus.Variant
+
+ path := unitPath(unit)
+ if !path.IsValid() {
+ return nil, errors.New("invalid unit name: " + unit)
+ }
+
+ obj := c.sysconn.Object("org.freedesktop.systemd1", path)
+ err = obj.CallWithContext(ctx, "org.freedesktop.DBus.Properties.Get", 0, dbusInterface, propertyName).Store(&prop)
+ if err != nil {
+ return nil, err
+ }
+
+ return &Property{Name: propertyName, Value: prop}, nil
+}
+
+// Deprecated: use GetUnitPropertyContext instead.
+func (c *Conn) GetUnitProperty(unit string, propertyName string) (*Property, error) {
+ return c.GetUnitPropertyContext(context.Background(), unit, propertyName)
+}
+
+// GetUnitPropertyContext takes an (unescaped) unit name, and a property name,
+// and returns the property value.
+func (c *Conn) GetUnitPropertyContext(ctx context.Context, unit string, propertyName string) (*Property, error) {
+ return c.getProperty(ctx, unit, "org.freedesktop.systemd1.Unit", propertyName)
+}
+
+// Deprecated: use GetServicePropertyContext instead.
+func (c *Conn) GetServiceProperty(service string, propertyName string) (*Property, error) {
+ return c.GetServicePropertyContext(context.Background(), service, propertyName)
+}
+
+// GetServiceProperty returns property for given service name and property name.
+func (c *Conn) GetServicePropertyContext(ctx context.Context, service string, propertyName string) (*Property, error) {
+ return c.getProperty(ctx, service, "org.freedesktop.systemd1.Service", propertyName)
+}
+
+// Deprecated: use GetUnitTypePropertiesContext instead.
+func (c *Conn) GetUnitTypeProperties(unit string, unitType string) (map[string]interface{}, error) {
+ return c.GetUnitTypePropertiesContext(context.Background(), unit, unitType)
+}
+
+// GetUnitTypePropertiesContext returns the extra properties for a unit, specific to the unit type.
+// Valid values for unitType: Service, Socket, Target, Device, Mount, Automount, Snapshot, Timer, Swap, Path, Slice, Scope.
+// Returns "dbus.Error: Unknown interface" error if the unitType is not the correct type of the unit.
+func (c *Conn) GetUnitTypePropertiesContext(ctx context.Context, unit string, unitType string) (map[string]interface{}, error) {
+ path := unitPath(unit)
+ return c.getProperties(ctx, path, "org.freedesktop.systemd1."+unitType)
+}
+
+// Deprecated: use SetUnitPropertiesContext instead.
+func (c *Conn) SetUnitProperties(name string, runtime bool, properties ...Property) error {
+ return c.SetUnitPropertiesContext(context.Background(), name, runtime, properties...)
+}
+
+// SetUnitPropertiesContext may be used to modify certain unit properties at runtime.
+// Not all properties may be changed at runtime, but many resource management
+// settings (primarily those in systemd.cgroup(5)) may. The changes are applied
+// instantly, and stored on disk for future boots, unless runtime is true, in which
+// case the settings only apply until the next reboot. name is the name of the unit
+// to modify. properties are the settings to set, encoded as an array of property
+// name and value pairs.
+func (c *Conn) SetUnitPropertiesContext(ctx context.Context, name string, runtime bool, properties ...Property) error {
+ return c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.SetUnitProperties", 0, name, runtime, properties).Store()
+}
+
+// Deprecated: use GetUnitTypePropertyContext instead.
+func (c *Conn) GetUnitTypeProperty(unit string, unitType string, propertyName string) (*Property, error) {
+ return c.GetUnitTypePropertyContext(context.Background(), unit, unitType, propertyName)
+}
+
+// GetUnitTypePropertyContext takes a property name, a unit name, and a unit type,
+// and returns a property value. For valid values of unitType, see GetUnitTypePropertiesContext.
+func (c *Conn) GetUnitTypePropertyContext(ctx context.Context, unit string, unitType string, propertyName string) (*Property, error) {
+ return c.getProperty(ctx, unit, "org.freedesktop.systemd1."+unitType, propertyName)
+}
+
+type UnitStatus struct {
+ Name string // The primary unit name as string
+ Description string // The human readable description string
+ LoadState string // The load state (i.e. whether the unit file has been loaded successfully)
+ ActiveState string // The active state (i.e. whether the unit is currently started or not)
+ SubState string // The sub state (a more fine-grained version of the active state that is specific to the unit type, which the active state is not)
+ Followed string // A unit that is being followed in its state by this unit, if there is any, otherwise the empty string.
+ Path dbus.ObjectPath // The unit object path
+ JobId uint32 // If there is a job queued for the job unit the numeric job id, 0 otherwise
+ JobType string // The job type as string
+ JobPath dbus.ObjectPath // The job object path
+}
+
+type storeFunc func(retvalues ...interface{}) error
+
+func (c *Conn) listUnitsInternal(f storeFunc) ([]UnitStatus, error) {
+ result := make([][]interface{}, 0)
+ err := f(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ status := make([]UnitStatus, len(result))
+ statusInterface := make([]interface{}, len(status))
+ for i := range status {
+ statusInterface[i] = &status[i]
+ }
+
+ err = dbus.Store(resultInterface, statusInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return status, nil
+}
+
+// Deprecated: use ListUnitsContext instead.
+func (c *Conn) ListUnits() ([]UnitStatus, error) {
+ return c.ListUnitsContext(context.Background())
+}
+
+// ListUnitsContext returns an array with all currently loaded units. Note that
+// units may be known by multiple names at the same time, and hence there might
+// be more unit names loaded than actual units behind them.
+// Also note that a unit is only loaded if it is active and/or enabled.
+// Units that are both disabled and inactive will thus not be returned.
+func (c *Conn) ListUnitsContext(ctx context.Context) ([]UnitStatus, error) {
+ return c.listUnitsInternal(c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.ListUnits", 0).Store)
+}
+
+// Deprecated: use ListUnitsFilteredContext instead.
+func (c *Conn) ListUnitsFiltered(states []string) ([]UnitStatus, error) {
+ return c.ListUnitsFilteredContext(context.Background(), states)
+}
+
+// ListUnitsFilteredContext returns an array with units filtered by state.
+// It takes a list of units' statuses to filter.
+func (c *Conn) ListUnitsFilteredContext(ctx context.Context, states []string) ([]UnitStatus, error) {
+ return c.listUnitsInternal(c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.ListUnitsFiltered", 0, states).Store)
+}
+
+// Deprecated: use ListUnitsByPatternsContext instead.
+func (c *Conn) ListUnitsByPatterns(states []string, patterns []string) ([]UnitStatus, error) {
+ return c.ListUnitsByPatternsContext(context.Background(), states, patterns)
+}
+
+// ListUnitsByPatternsContext returns an array with units.
+// It takes a list of units' statuses and names to filter.
+// Note that units may be known by multiple names at the same time,
+// and hence there might be more unit names loaded than actual units behind them.
+func (c *Conn) ListUnitsByPatternsContext(ctx context.Context, states []string, patterns []string) ([]UnitStatus, error) {
+ return c.listUnitsInternal(c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.ListUnitsByPatterns", 0, states, patterns).Store)
+}
+
+// Deprecated: use ListUnitsByNamesContext instead.
+func (c *Conn) ListUnitsByNames(units []string) ([]UnitStatus, error) {
+ return c.ListUnitsByNamesContext(context.Background(), units)
+}
+
+// ListUnitsByNamesContext returns an array with units. It takes a list of units'
+// names and returns an UnitStatus array. Comparing to ListUnitsByPatternsContext
+// method, this method returns statuses even for inactive or non-existing
+// units. Input array should contain exact unit names, but not patterns.
+//
+// Requires systemd v230 or higher.
+func (c *Conn) ListUnitsByNamesContext(ctx context.Context, units []string) ([]UnitStatus, error) {
+ return c.listUnitsInternal(c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.ListUnitsByNames", 0, units).Store)
+}
+
+type UnitFile struct {
+ Path string
+ Type string
+}
+
+func (c *Conn) listUnitFilesInternal(f storeFunc) ([]UnitFile, error) {
+ result := make([][]interface{}, 0)
+ err := f(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ files := make([]UnitFile, len(result))
+ fileInterface := make([]interface{}, len(files))
+ for i := range files {
+ fileInterface[i] = &files[i]
+ }
+
+ err = dbus.Store(resultInterface, fileInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return files, nil
+}
+
+// Deprecated: use ListUnitFilesContext instead.
+func (c *Conn) ListUnitFiles() ([]UnitFile, error) {
+ return c.ListUnitFilesContext(context.Background())
+}
+
+// ListUnitFiles returns an array of all available units on disk.
+func (c *Conn) ListUnitFilesContext(ctx context.Context) ([]UnitFile, error) {
+ return c.listUnitFilesInternal(c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.ListUnitFiles", 0).Store)
+}
+
+// Deprecated: use ListUnitFilesByPatternsContext instead.
+func (c *Conn) ListUnitFilesByPatterns(states []string, patterns []string) ([]UnitFile, error) {
+ return c.ListUnitFilesByPatternsContext(context.Background(), states, patterns)
+}
+
+// ListUnitFilesByPatternsContext returns an array of all available units on disk matched the patterns.
+func (c *Conn) ListUnitFilesByPatternsContext(ctx context.Context, states []string, patterns []string) ([]UnitFile, error) {
+ return c.listUnitFilesInternal(c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.ListUnitFilesByPatterns", 0, states, patterns).Store)
+}
+
+type LinkUnitFileChange EnableUnitFileChange
+
+// Deprecated: use LinkUnitFilesContext instead.
+func (c *Conn) LinkUnitFiles(files []string, runtime bool, force bool) ([]LinkUnitFileChange, error) {
+ return c.LinkUnitFilesContext(context.Background(), files, runtime, force)
+}
+
+// LinkUnitFilesContext links unit files (that are located outside of the
+// usual unit search paths) into the unit search path.
+//
+// It takes a list of absolute paths to unit files to link and two
+// booleans.
+//
+// The first boolean controls whether the unit shall be
+// enabled for runtime only (true, /run), or persistently (false,
+// /etc).
+//
+// The second controls whether symlinks pointing to other units shall
+// be replaced if necessary.
+//
+// This call returns a list of the changes made. The list consists of
+// structures with three strings: the type of the change (one of symlink
+// or unlink), the file name of the symlink and the destination of the
+// symlink.
+func (c *Conn) LinkUnitFilesContext(ctx context.Context, files []string, runtime bool, force bool) ([]LinkUnitFileChange, error) {
+ result := make([][]interface{}, 0)
+ err := c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.LinkUnitFiles", 0, files, runtime, force).Store(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ changes := make([]LinkUnitFileChange, len(result))
+ changesInterface := make([]interface{}, len(changes))
+ for i := range changes {
+ changesInterface[i] = &changes[i]
+ }
+
+ err = dbus.Store(resultInterface, changesInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return changes, nil
+}
+
+// Deprecated: use EnableUnitFilesContext instead.
+func (c *Conn) EnableUnitFiles(files []string, runtime bool, force bool) (bool, []EnableUnitFileChange, error) {
+ return c.EnableUnitFilesContext(context.Background(), files, runtime, force)
+}
+
+// EnableUnitFilesContext may be used to enable one or more units in the system
+// (by creating symlinks to them in /etc or /run).
+//
+// It takes a list of unit files to enable (either just file names or full
+// absolute paths if the unit files are residing outside the usual unit
+// search paths), and two booleans: the first controls whether the unit shall
+// be enabled for runtime only (true, /run), or persistently (false, /etc).
+// The second one controls whether symlinks pointing to other units shall
+// be replaced if necessary.
+//
+// This call returns one boolean and an array with the changes made. The
+// boolean signals whether the unit files contained any enablement
+// information (i.e. an [Install]) section. The changes list consists of
+// structures with three strings: the type of the change (one of symlink
+// or unlink), the file name of the symlink and the destination of the
+// symlink.
+func (c *Conn) EnableUnitFilesContext(ctx context.Context, files []string, runtime bool, force bool) (bool, []EnableUnitFileChange, error) {
+ var carries_install_info bool
+
+ result := make([][]interface{}, 0)
+ err := c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.EnableUnitFiles", 0, files, runtime, force).Store(&carries_install_info, &result)
+ if err != nil {
+ return false, nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ changes := make([]EnableUnitFileChange, len(result))
+ changesInterface := make([]interface{}, len(changes))
+ for i := range changes {
+ changesInterface[i] = &changes[i]
+ }
+
+ err = dbus.Store(resultInterface, changesInterface...)
+ if err != nil {
+ return false, nil, err
+ }
+
+ return carries_install_info, changes, nil
+}
+
+type EnableUnitFileChange struct {
+ Type string // Type of the change (one of symlink or unlink)
+ Filename string // File name of the symlink
+ Destination string // Destination of the symlink
+}
+
+// Deprecated: use DisableUnitFilesContext instead.
+func (c *Conn) DisableUnitFiles(files []string, runtime bool) ([]DisableUnitFileChange, error) {
+ return c.DisableUnitFilesContext(context.Background(), files, runtime)
+}
+
+// DisableUnitFilesContext may be used to disable one or more units in the
+// system (by removing symlinks to them from /etc or /run).
+//
+// It takes a list of unit files to disable (either just file names or full
+// absolute paths if the unit files are residing outside the usual unit
+// search paths), and one boolean: whether the unit was enabled for runtime
+// only (true, /run), or persistently (false, /etc).
+//
+// This call returns an array with the changes made. The changes list
+// consists of structures with three strings: the type of the change (one of
+// symlink or unlink), the file name of the symlink and the destination of the
+// symlink.
+func (c *Conn) DisableUnitFilesContext(ctx context.Context, files []string, runtime bool) ([]DisableUnitFileChange, error) {
+ result := make([][]interface{}, 0)
+ err := c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.DisableUnitFiles", 0, files, runtime).Store(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ changes := make([]DisableUnitFileChange, len(result))
+ changesInterface := make([]interface{}, len(changes))
+ for i := range changes {
+ changesInterface[i] = &changes[i]
+ }
+
+ err = dbus.Store(resultInterface, changesInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return changes, nil
+}
+
+type DisableUnitFileChange struct {
+ Type string // Type of the change (one of symlink or unlink)
+ Filename string // File name of the symlink
+ Destination string // Destination of the symlink
+}
+
+// Deprecated: use MaskUnitFilesContext instead.
+func (c *Conn) MaskUnitFiles(files []string, runtime bool, force bool) ([]MaskUnitFileChange, error) {
+ return c.MaskUnitFilesContext(context.Background(), files, runtime, force)
+}
+
+// MaskUnitFilesContext masks one or more units in the system.
+//
+// The files argument contains a list of units to mask (either just file names
+// or full absolute paths if the unit files are residing outside the usual unit
+// search paths).
+//
+// The runtime argument is used to specify whether the unit was enabled for
+// runtime only (true, /run/systemd/..), or persistently (false,
+// /etc/systemd/..).
+func (c *Conn) MaskUnitFilesContext(ctx context.Context, files []string, runtime bool, force bool) ([]MaskUnitFileChange, error) {
+ result := make([][]interface{}, 0)
+ err := c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.MaskUnitFiles", 0, files, runtime, force).Store(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ changes := make([]MaskUnitFileChange, len(result))
+ changesInterface := make([]interface{}, len(changes))
+ for i := range changes {
+ changesInterface[i] = &changes[i]
+ }
+
+ err = dbus.Store(resultInterface, changesInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return changes, nil
+}
+
+type MaskUnitFileChange struct {
+ Type string // Type of the change (one of symlink or unlink)
+ Filename string // File name of the symlink
+ Destination string // Destination of the symlink
+}
+
+// Deprecated: use UnmaskUnitFilesContext instead.
+func (c *Conn) UnmaskUnitFiles(files []string, runtime bool) ([]UnmaskUnitFileChange, error) {
+ return c.UnmaskUnitFilesContext(context.Background(), files, runtime)
+}
+
+// UnmaskUnitFilesContext unmasks one or more units in the system.
+//
+// It takes the list of unit files to mask (either just file names or full
+// absolute paths if the unit files are residing outside the usual unit search
+// paths), and a boolean runtime flag to specify whether the unit was enabled
+// for runtime only (true, /run/systemd/..), or persistently (false,
+// /etc/systemd/..).
+func (c *Conn) UnmaskUnitFilesContext(ctx context.Context, files []string, runtime bool) ([]UnmaskUnitFileChange, error) {
+ result := make([][]interface{}, 0)
+ err := c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.UnmaskUnitFiles", 0, files, runtime).Store(&result)
+ if err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ changes := make([]UnmaskUnitFileChange, len(result))
+ changesInterface := make([]interface{}, len(changes))
+ for i := range changes {
+ changesInterface[i] = &changes[i]
+ }
+
+ err = dbus.Store(resultInterface, changesInterface...)
+ if err != nil {
+ return nil, err
+ }
+
+ return changes, nil
+}
+
+type UnmaskUnitFileChange struct {
+ Type string // Type of the change (one of symlink or unlink)
+ Filename string // File name of the symlink
+ Destination string // Destination of the symlink
+}
+
+// Deprecated: use ReloadContext instead.
+func (c *Conn) Reload() error {
+ return c.ReloadContext(context.Background())
+}
+
+// ReloadContext instructs systemd to scan for and reload unit files. This is
+// an equivalent to systemctl daemon-reload.
+func (c *Conn) ReloadContext(ctx context.Context) error {
+ return c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.Reload", 0).Store()
+}
+
+func unitPath(name string) dbus.ObjectPath {
+ return dbus.ObjectPath("/org/freedesktop/systemd1/unit/" + PathBusEscape(name))
+}
+
+// unitName returns the unescaped base element of the supplied escaped path.
+func unitName(dpath dbus.ObjectPath) string {
+ return pathBusUnescape(path.Base(string(dpath)))
+}
+
+// JobStatus holds a currently queued job definition.
+type JobStatus struct {
+ Id uint32 // The numeric job id
+ Unit string // The primary unit name for this job
+ JobType string // The job type as string
+ Status string // The job state as string
+ JobPath dbus.ObjectPath // The job object path
+ UnitPath dbus.ObjectPath // The unit object path
+}
+
+// Deprecated: use ListJobsContext instead.
+func (c *Conn) ListJobs() ([]JobStatus, error) {
+ return c.ListJobsContext(context.Background())
+}
+
+// ListJobsContext returns an array with all currently queued jobs.
+func (c *Conn) ListJobsContext(ctx context.Context) ([]JobStatus, error) {
+ return c.listJobsInternal(ctx)
+}
+
+func (c *Conn) listJobsInternal(ctx context.Context) ([]JobStatus, error) {
+ result := make([][]interface{}, 0)
+ if err := c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.ListJobs", 0).Store(&result); err != nil {
+ return nil, err
+ }
+
+ resultInterface := make([]interface{}, len(result))
+ for i := range result {
+ resultInterface[i] = result[i]
+ }
+
+ status := make([]JobStatus, len(result))
+ statusInterface := make([]interface{}, len(status))
+ for i := range status {
+ statusInterface[i] = &status[i]
+ }
+
+ if err := dbus.Store(resultInterface, statusInterface...); err != nil {
+ return nil, err
+ }
+
+ return status, nil
+}
diff --git a/vendor/github.com/coreos/go-systemd/v22/dbus/properties.go b/vendor/github.com/coreos/go-systemd/v22/dbus/properties.go
@@ -0,0 +1,237 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 dbus
+
+import (
+ "github.com/godbus/dbus/v5"
+)
+
+// From the systemd docs:
+//
+// The properties array of StartTransientUnit() may take many of the settings
+// that may also be configured in unit files. Not all parameters are currently
+// accepted though, but we plan to cover more properties with future release.
+// Currently you may set the Description, Slice and all dependency types of
+// units, as well as RemainAfterExit, ExecStart for service units,
+// TimeoutStopUSec and PIDs for scope units, and CPUAccounting, CPUShares,
+// BlockIOAccounting, BlockIOWeight, BlockIOReadBandwidth,
+// BlockIOWriteBandwidth, BlockIODeviceWeight, MemoryAccounting, MemoryLimit,
+// DevicePolicy, DeviceAllow for services/scopes/slices. These fields map
+// directly to their counterparts in unit files and as normal D-Bus object
+// properties. The exception here is the PIDs field of scope units which is
+// used for construction of the scope only and specifies the initial PIDs to
+// add to the scope object.
+
+type Property struct {
+ Name string
+ Value dbus.Variant
+}
+
+type PropertyCollection struct {
+ Name string
+ Properties []Property
+}
+
+type execStart struct {
+ Path string // the binary path to execute
+ Args []string // an array with all arguments to pass to the executed command, starting with argument 0
+ UncleanIsFailure bool // a boolean whether it should be considered a failure if the process exits uncleanly
+}
+
+// PropExecStart sets the ExecStart service property. The first argument is a
+// slice with the binary path to execute followed by the arguments to pass to
+// the executed command. See
+// http://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecStart=
+func PropExecStart(command []string, uncleanIsFailure bool) Property {
+ execStarts := []execStart{
+ {
+ Path: command[0],
+ Args: command,
+ UncleanIsFailure: uncleanIsFailure,
+ },
+ }
+
+ return Property{
+ Name: "ExecStart",
+ Value: dbus.MakeVariant(execStarts),
+ }
+}
+
+// PropRemainAfterExit sets the RemainAfterExit service property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.service.html#RemainAfterExit=
+func PropRemainAfterExit(b bool) Property {
+ return Property{
+ Name: "RemainAfterExit",
+ Value: dbus.MakeVariant(b),
+ }
+}
+
+// PropType sets the Type service property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.service.html#Type=
+func PropType(t string) Property {
+ return Property{
+ Name: "Type",
+ Value: dbus.MakeVariant(t),
+ }
+}
+
+// PropDescription sets the Description unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit#Description=
+func PropDescription(desc string) Property {
+ return Property{
+ Name: "Description",
+ Value: dbus.MakeVariant(desc),
+ }
+}
+
+func propDependency(name string, units []string) Property {
+ return Property{
+ Name: name,
+ Value: dbus.MakeVariant(units),
+ }
+}
+
+// PropRequires sets the Requires unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Requires=
+func PropRequires(units ...string) Property {
+ return propDependency("Requires", units)
+}
+
+// PropRequiresOverridable sets the RequiresOverridable unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiresOverridable=
+func PropRequiresOverridable(units ...string) Property {
+ return propDependency("RequiresOverridable", units)
+}
+
+// PropRequisite sets the Requisite unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Requisite=
+func PropRequisite(units ...string) Property {
+ return propDependency("Requisite", units)
+}
+
+// PropRequisiteOverridable sets the RequisiteOverridable unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequisiteOverridable=
+func PropRequisiteOverridable(units ...string) Property {
+ return propDependency("RequisiteOverridable", units)
+}
+
+// PropWants sets the Wants unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Wants=
+func PropWants(units ...string) Property {
+ return propDependency("Wants", units)
+}
+
+// PropBindsTo sets the BindsTo unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#BindsTo=
+func PropBindsTo(units ...string) Property {
+ return propDependency("BindsTo", units)
+}
+
+// PropRequiredBy sets the RequiredBy unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiredBy=
+func PropRequiredBy(units ...string) Property {
+ return propDependency("RequiredBy", units)
+}
+
+// PropRequiredByOverridable sets the RequiredByOverridable unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiredByOverridable=
+func PropRequiredByOverridable(units ...string) Property {
+ return propDependency("RequiredByOverridable", units)
+}
+
+// PropWantedBy sets the WantedBy unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#WantedBy=
+func PropWantedBy(units ...string) Property {
+ return propDependency("WantedBy", units)
+}
+
+// PropBoundBy sets the BoundBy unit property. See
+// http://www.freedesktop.org/software/systemd/main/systemd.unit.html#BoundBy=
+func PropBoundBy(units ...string) Property {
+ return propDependency("BoundBy", units)
+}
+
+// PropConflicts sets the Conflicts unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Conflicts=
+func PropConflicts(units ...string) Property {
+ return propDependency("Conflicts", units)
+}
+
+// PropConflictedBy sets the ConflictedBy unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#ConflictedBy=
+func PropConflictedBy(units ...string) Property {
+ return propDependency("ConflictedBy", units)
+}
+
+// PropBefore sets the Before unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Before=
+func PropBefore(units ...string) Property {
+ return propDependency("Before", units)
+}
+
+// PropAfter sets the After unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#After=
+func PropAfter(units ...string) Property {
+ return propDependency("After", units)
+}
+
+// PropOnFailure sets the OnFailure unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#OnFailure=
+func PropOnFailure(units ...string) Property {
+ return propDependency("OnFailure", units)
+}
+
+// PropTriggers sets the Triggers unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Triggers=
+func PropTriggers(units ...string) Property {
+ return propDependency("Triggers", units)
+}
+
+// PropTriggeredBy sets the TriggeredBy unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#TriggeredBy=
+func PropTriggeredBy(units ...string) Property {
+ return propDependency("TriggeredBy", units)
+}
+
+// PropPropagatesReloadTo sets the PropagatesReloadTo unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#PropagatesReloadTo=
+func PropPropagatesReloadTo(units ...string) Property {
+ return propDependency("PropagatesReloadTo", units)
+}
+
+// PropRequiresMountsFor sets the RequiresMountsFor unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiresMountsFor=
+func PropRequiresMountsFor(units ...string) Property {
+ return propDependency("RequiresMountsFor", units)
+}
+
+// PropSlice sets the Slice unit property. See
+// http://www.freedesktop.org/software/systemd/man/systemd.resource-control.html#Slice=
+func PropSlice(slice string) Property {
+ return Property{
+ Name: "Slice",
+ Value: dbus.MakeVariant(slice),
+ }
+}
+
+// PropPids sets the PIDs field of scope units used in the initial construction
+// of the scope only and specifies the initial PIDs to add to the scope object.
+// See https://www.freedesktop.org/wiki/Software/systemd/ControlGroupInterface/#properties
+func PropPids(pids ...uint32) Property {
+ return Property{
+ Name: "PIDs",
+ Value: dbus.MakeVariant(pids),
+ }
+}
diff --git a/vendor/github.com/coreos/go-systemd/v22/dbus/set.go b/vendor/github.com/coreos/go-systemd/v22/dbus/set.go
@@ -0,0 +1,47 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 dbus
+
+type set struct {
+ data map[string]bool
+}
+
+func (s *set) Add(value string) {
+ s.data[value] = true
+}
+
+func (s *set) Remove(value string) {
+ delete(s.data, value)
+}
+
+func (s *set) Contains(value string) (exists bool) {
+ _, exists = s.data[value]
+ return
+}
+
+func (s *set) Length() int {
+ return len(s.data)
+}
+
+func (s *set) Values() (values []string) {
+ for val := range s.data {
+ values = append(values, val)
+ }
+ return
+}
+
+func newSet() *set {
+ return &set{make(map[string]bool)}
+}
diff --git a/vendor/github.com/coreos/go-systemd/v22/dbus/subscription.go b/vendor/github.com/coreos/go-systemd/v22/dbus/subscription.go
@@ -0,0 +1,333 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 dbus
+
+import (
+ "errors"
+ "log"
+ "time"
+
+ "github.com/godbus/dbus/v5"
+)
+
+const (
+ cleanIgnoreInterval = int64(10 * time.Second)
+ ignoreInterval = int64(30 * time.Millisecond)
+)
+
+// Subscribe sets up this connection to subscribe to all systemd dbus events.
+// This is required before calling SubscribeUnits. When the connection closes
+// systemd will automatically stop sending signals so there is no need to
+// explicitly call Unsubscribe().
+func (c *Conn) Subscribe() error {
+ c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
+ "type='signal',interface='org.freedesktop.systemd1.Manager',member='UnitNew'")
+ c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
+ "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'")
+
+ return c.sigobj.Call("org.freedesktop.systemd1.Manager.Subscribe", 0).Store()
+}
+
+// Unsubscribe this connection from systemd dbus events.
+func (c *Conn) Unsubscribe() error {
+ return c.sigobj.Call("org.freedesktop.systemd1.Manager.Unsubscribe", 0).Store()
+}
+
+func (c *Conn) dispatch() {
+ ch := make(chan *dbus.Signal, signalBuffer)
+
+ c.sigconn.Signal(ch)
+
+ go func() {
+ for {
+ signal, ok := <-ch
+ if !ok {
+ return
+ }
+
+ if signal.Name == "org.freedesktop.systemd1.Manager.JobRemoved" {
+ c.jobComplete(signal)
+ }
+
+ if c.subStateSubscriber.updateCh == nil &&
+ c.propertiesSubscriber.updateCh == nil {
+ continue
+ }
+
+ var unitPath dbus.ObjectPath
+ switch signal.Name {
+ case "org.freedesktop.systemd1.Manager.JobRemoved":
+ unitName := signal.Body[2].(string)
+ c.sysobj.Call("org.freedesktop.systemd1.Manager.GetUnit", 0, unitName).Store(&unitPath)
+ case "org.freedesktop.systemd1.Manager.UnitNew":
+ unitPath = signal.Body[1].(dbus.ObjectPath)
+ case "org.freedesktop.DBus.Properties.PropertiesChanged":
+ if signal.Body[0].(string) == "org.freedesktop.systemd1.Unit" {
+ unitPath = signal.Path
+
+ if len(signal.Body) >= 2 {
+ if changed, ok := signal.Body[1].(map[string]dbus.Variant); ok {
+ c.sendPropertiesUpdate(unitPath, changed)
+ }
+ }
+ }
+ }
+
+ if unitPath == dbus.ObjectPath("") {
+ continue
+ }
+
+ c.sendSubStateUpdate(unitPath)
+ }
+ }()
+}
+
+// SubscribeUnits returns two unbuffered channels which will receive all changed units every
+// interval. Deleted units are sent as nil.
+func (c *Conn) SubscribeUnits(interval time.Duration) (<-chan map[string]*UnitStatus, <-chan error) {
+ return c.SubscribeUnitsCustom(interval, 0, func(u1, u2 *UnitStatus) bool { return *u1 != *u2 }, nil)
+}
+
+// SubscribeUnitsCustom is like SubscribeUnits but lets you specify the buffer
+// size of the channels, the comparison function for detecting changes and a filter
+// function for cutting down on the noise that your channel receives.
+func (c *Conn) SubscribeUnitsCustom(interval time.Duration, buffer int, isChanged func(*UnitStatus, *UnitStatus) bool, filterUnit func(string) bool) (<-chan map[string]*UnitStatus, <-chan error) {
+ old := make(map[string]*UnitStatus)
+ statusChan := make(chan map[string]*UnitStatus, buffer)
+ errChan := make(chan error, buffer)
+
+ go func() {
+ for {
+ timerChan := time.After(interval)
+
+ units, err := c.ListUnits()
+ if err == nil {
+ cur := make(map[string]*UnitStatus)
+ for i := range units {
+ if filterUnit != nil && filterUnit(units[i].Name) {
+ continue
+ }
+ cur[units[i].Name] = &units[i]
+ }
+
+ // add all new or changed units
+ changed := make(map[string]*UnitStatus)
+ for n, u := range cur {
+ if oldU, ok := old[n]; !ok || isChanged(oldU, u) {
+ changed[n] = u
+ }
+ delete(old, n)
+ }
+
+ // add all deleted units
+ for oldN := range old {
+ changed[oldN] = nil
+ }
+
+ old = cur
+
+ if len(changed) != 0 {
+ statusChan <- changed
+ }
+ } else {
+ errChan <- err
+ }
+
+ <-timerChan
+ }
+ }()
+
+ return statusChan, errChan
+}
+
+type SubStateUpdate struct {
+ UnitName string
+ SubState string
+}
+
+// SetSubStateSubscriber writes to updateCh when any unit's substate changes.
+// Although this writes to updateCh on every state change, the reported state
+// may be more recent than the change that generated it (due to an unavoidable
+// race in the systemd dbus interface). That is, this method provides a good
+// way to keep a current view of all units' states, but is not guaranteed to
+// show every state transition they go through. Furthermore, state changes
+// will only be written to the channel with non-blocking writes. If updateCh
+// is full, it attempts to write an error to errCh; if errCh is full, the error
+// passes silently.
+func (c *Conn) SetSubStateSubscriber(updateCh chan<- *SubStateUpdate, errCh chan<- error) {
+ if c == nil {
+ msg := "nil receiver"
+ select {
+ case errCh <- errors.New(msg):
+ default:
+ log.Printf("full error channel while reporting: %s\n", msg)
+ }
+ return
+ }
+
+ c.subStateSubscriber.Lock()
+ defer c.subStateSubscriber.Unlock()
+ c.subStateSubscriber.updateCh = updateCh
+ c.subStateSubscriber.errCh = errCh
+}
+
+func (c *Conn) sendSubStateUpdate(unitPath dbus.ObjectPath) {
+ c.subStateSubscriber.Lock()
+ defer c.subStateSubscriber.Unlock()
+
+ if c.subStateSubscriber.updateCh == nil {
+ return
+ }
+
+ isIgnored := c.shouldIgnore(unitPath)
+ defer c.cleanIgnore()
+ if isIgnored {
+ return
+ }
+
+ info, err := c.GetUnitPathProperties(unitPath)
+ if err != nil {
+ select {
+ case c.subStateSubscriber.errCh <- err:
+ default:
+ log.Printf("full error channel while reporting: %s\n", err)
+ }
+ return
+ }
+ defer c.updateIgnore(unitPath, info)
+
+ name, ok := info["Id"].(string)
+ if !ok {
+ msg := "failed to cast info.Id"
+ select {
+ case c.subStateSubscriber.errCh <- errors.New(msg):
+ default:
+ log.Printf("full error channel while reporting: %s\n", err)
+ }
+ return
+ }
+ substate, ok := info["SubState"].(string)
+ if !ok {
+ msg := "failed to cast info.SubState"
+ select {
+ case c.subStateSubscriber.errCh <- errors.New(msg):
+ default:
+ log.Printf("full error channel while reporting: %s\n", msg)
+ }
+ return
+ }
+
+ update := &SubStateUpdate{name, substate}
+ select {
+ case c.subStateSubscriber.updateCh <- update:
+ default:
+ msg := "update channel is full"
+ select {
+ case c.subStateSubscriber.errCh <- errors.New(msg):
+ default:
+ log.Printf("full error channel while reporting: %s\n", msg)
+ }
+ return
+ }
+}
+
+// The ignore functions work around a wart in the systemd dbus interface.
+// Requesting the properties of an unloaded unit will cause systemd to send a
+// pair of UnitNew/UnitRemoved signals. Because we need to get a unit's
+// properties on UnitNew (as that's the only indication of a new unit coming up
+// for the first time), we would enter an infinite loop if we did not attempt
+// to detect and ignore these spurious signals. The signal themselves are
+// indistinguishable from relevant ones, so we (somewhat hackishly) ignore an
+// unloaded unit's signals for a short time after requesting its properties.
+// This means that we will miss e.g. a transient unit being restarted
+// *immediately* upon failure and also a transient unit being started
+// immediately after requesting its status (with systemctl status, for example,
+// because this causes a UnitNew signal to be sent which then causes us to fetch
+// the properties).
+
+func (c *Conn) shouldIgnore(path dbus.ObjectPath) bool {
+ t, ok := c.subStateSubscriber.ignore[path]
+ return ok && t >= time.Now().UnixNano()
+}
+
+func (c *Conn) updateIgnore(path dbus.ObjectPath, info map[string]interface{}) {
+ loadState, ok := info["LoadState"].(string)
+ if !ok {
+ return
+ }
+
+ // unit is unloaded - it will trigger bad systemd dbus behavior
+ if loadState == "not-found" {
+ c.subStateSubscriber.ignore[path] = time.Now().UnixNano() + ignoreInterval
+ }
+}
+
+// without this, ignore would grow unboundedly over time
+func (c *Conn) cleanIgnore() {
+ now := time.Now().UnixNano()
+ if c.subStateSubscriber.cleanIgnore < now {
+ c.subStateSubscriber.cleanIgnore = now + cleanIgnoreInterval
+
+ for p, t := range c.subStateSubscriber.ignore {
+ if t < now {
+ delete(c.subStateSubscriber.ignore, p)
+ }
+ }
+ }
+}
+
+// PropertiesUpdate holds a map of a unit's changed properties
+type PropertiesUpdate struct {
+ UnitName string
+ Changed map[string]dbus.Variant
+}
+
+// SetPropertiesSubscriber writes to updateCh when any unit's properties
+// change. Every property change reported by systemd will be sent; that is, no
+// transitions will be "missed" (as they might be with SetSubStateSubscriber).
+// However, state changes will only be written to the channel with non-blocking
+// writes. If updateCh is full, it attempts to write an error to errCh; if
+// errCh is full, the error passes silently.
+func (c *Conn) SetPropertiesSubscriber(updateCh chan<- *PropertiesUpdate, errCh chan<- error) {
+ c.propertiesSubscriber.Lock()
+ defer c.propertiesSubscriber.Unlock()
+ c.propertiesSubscriber.updateCh = updateCh
+ c.propertiesSubscriber.errCh = errCh
+}
+
+// we don't need to worry about shouldIgnore() here because
+// sendPropertiesUpdate doesn't call GetProperties()
+func (c *Conn) sendPropertiesUpdate(unitPath dbus.ObjectPath, changedProps map[string]dbus.Variant) {
+ c.propertiesSubscriber.Lock()
+ defer c.propertiesSubscriber.Unlock()
+
+ if c.propertiesSubscriber.updateCh == nil {
+ return
+ }
+
+ update := &PropertiesUpdate{unitName(unitPath), changedProps}
+
+ select {
+ case c.propertiesSubscriber.updateCh <- update:
+ default:
+ msg := "update channel is full"
+ select {
+ case c.propertiesSubscriber.errCh <- errors.New(msg):
+ default:
+ log.Printf("full error channel while reporting: %s\n", msg)
+ }
+ return
+ }
+}
diff --git a/vendor/github.com/coreos/go-systemd/v22/dbus/subscription_set.go b/vendor/github.com/coreos/go-systemd/v22/dbus/subscription_set.go
@@ -0,0 +1,57 @@
+// Copyright 2015 CoreOS, Inc.
+//
+// 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 dbus
+
+import (
+ "time"
+)
+
+// SubscriptionSet returns a subscription set which is like conn.Subscribe but
+// can filter to only return events for a set of units.
+type SubscriptionSet struct {
+ *set
+ conn *Conn
+}
+
+func (s *SubscriptionSet) filter(unit string) bool {
+ return !s.Contains(unit)
+}
+
+// Subscribe starts listening for dbus events for all of the units in the set.
+// Returns channels identical to conn.SubscribeUnits.
+func (s *SubscriptionSet) Subscribe() (<-chan map[string]*UnitStatus, <-chan error) {
+ // TODO: Make fully evented by using systemd 209 with properties changed values
+ return s.conn.SubscribeUnitsCustom(time.Second, 0,
+ mismatchUnitStatus,
+ func(unit string) bool { return s.filter(unit) },
+ )
+}
+
+// NewSubscriptionSet returns a new subscription set.
+func (conn *Conn) NewSubscriptionSet() *SubscriptionSet {
+ return &SubscriptionSet{newSet(), conn}
+}
+
+// mismatchUnitStatus returns true if the provided UnitStatus objects
+// are not equivalent. false is returned if the objects are equivalent.
+// Only the Name, Description and state-related fields are used in
+// the comparison.
+func mismatchUnitStatus(u1, u2 *UnitStatus) bool {
+ return u1.Name != u2.Name ||
+ u1.Description != u2.Description ||
+ u1.LoadState != u2.LoadState ||
+ u1.ActiveState != u2.ActiveState ||
+ u1.SubState != u2.SubState
+}
diff --git a/vendor/github.com/docker/go-units/CONTRIBUTING.md b/vendor/github.com/docker/go-units/CONTRIBUTING.md
@@ -0,0 +1,67 @@
+# Contributing to go-units
+
+Want to hack on go-units? Awesome! Here are instructions to get you started.
+
+go-units is a part of the [Docker](https://www.docker.com) project, and follows
+the same rules and principles. If you're already familiar with the way
+Docker does things, you'll feel right at home.
+
+Otherwise, go read Docker's
+[contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md),
+[issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md),
+[review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and
+[branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md).
+
+### Sign your work
+
+The sign-off is a simple line at the end of the explanation for the patch. Your
+signature certifies that you wrote the patch or otherwise have the right to pass
+it on as an open-source patch. The rules are pretty simple: if you can certify
+the below (from [developercertificate.org](http://developercertificate.org/)):
+
+```
+Developer Certificate of Origin
+Version 1.1
+
+Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
+660 York Street, Suite 102,
+San Francisco, CA 94110 USA
+
+Everyone is permitted to copy and distribute verbatim copies of this
+license document, but changing it is not allowed.
+
+Developer's Certificate of Origin 1.1
+
+By making a contribution to this project, I certify that:
+
+(a) The contribution was created in whole or in part by me and I
+ have the right to submit it under the open source license
+ indicated in the file; or
+
+(b) The contribution is based upon previous work that, to the best
+ of my knowledge, is covered under an appropriate open source
+ license and I have the right under that license to submit that
+ work with modifications, whether created in whole or in part
+ by me, under the same open source license (unless I am
+ permitted to submit under a different license), as indicated
+ in the file; or
+
+(c) The contribution was provided directly to me by some other
+ person who certified (a), (b) or (c) and I have not modified
+ it.
+
+(d) I understand and agree that this project and the contribution
+ are public and that a record of the contribution (including all
+ personal information I submit with it, including my sign-off) is
+ maintained indefinitely and may be redistributed consistent with
+ this project or the open source license(s) involved.
+```
+
+Then you just add a line to every git commit message:
+
+ Signed-off-by: Joe Smith <joe.smith@email.com>
+
+Use your real name (sorry, no pseudonyms or anonymous contributions.)
+
+If you set your `user.name` and `user.email` git configs, you can sign your
+commit automatically with `git commit -s`.
diff --git a/vendor/github.com/docker/go-units/LICENSE b/vendor/github.com/docker/go-units/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2015 Docker, Inc.
+
+ 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
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/docker/go-units/MAINTAINERS b/vendor/github.com/docker/go-units/MAINTAINERS
@@ -0,0 +1,46 @@
+# go-units maintainers file
+#
+# This file describes who runs the docker/go-units project and how.
+# This is a living document - if you see something out of date or missing, speak up!
+#
+# It is structured to be consumable by both humans and programs.
+# To extract its contents programmatically, use any TOML-compliant parser.
+#
+# This file is compiled into the MAINTAINERS file in docker/opensource.
+#
+[Org]
+ [Org."Core maintainers"]
+ people = [
+ "akihirosuda",
+ "dnephin",
+ "thajeztah",
+ "vdemeester",
+ ]
+
+[people]
+
+# A reference list of all people associated with the project.
+# All other sections should refer to people by their canonical key
+# in the people section.
+
+ # ADD YOURSELF HERE IN ALPHABETICAL ORDER
+
+ [people.akihirosuda]
+ Name = "Akihiro Suda"
+ Email = "akihiro.suda.cz@hco.ntt.co.jp"
+ GitHub = "AkihiroSuda"
+
+ [people.dnephin]
+ Name = "Daniel Nephin"
+ Email = "dnephin@gmail.com"
+ GitHub = "dnephin"
+
+ [people.thajeztah]
+ Name = "Sebastiaan van Stijn"
+ Email = "github@gone.nl"
+ GitHub = "thaJeztah"
+
+ [people.vdemeester]
+ Name = "Vincent Demeester"
+ Email = "vincent@sbr.pm"
+ GitHub = "vdemeester"
+\ No newline at end of file
diff --git a/vendor/github.com/docker/go-units/README.md b/vendor/github.com/docker/go-units/README.md
@@ -0,0 +1,16 @@
+[![GoDoc](https://godoc.org/github.com/docker/go-units?status.svg)](https://godoc.org/github.com/docker/go-units)
+
+# Introduction
+
+go-units is a library to transform human friendly measurements into machine friendly values.
+
+## Usage
+
+See the [docs in godoc](https://godoc.org/github.com/docker/go-units) for examples and documentation.
+
+## Copyright and license
+
+Copyright © 2015 Docker, Inc.
+
+go-units is licensed under the Apache License, Version 2.0.
+See [LICENSE](LICENSE) for the full text of the license.
diff --git a/vendor/github.com/docker/go-units/circle.yml b/vendor/github.com/docker/go-units/circle.yml
@@ -0,0 +1,11 @@
+dependencies:
+ post:
+ # install golint
+ - go get golang.org/x/lint/golint
+
+test:
+ pre:
+ # run analysis before tests
+ - go vet ./...
+ - test -z "$(golint ./... | tee /dev/stderr)"
+ - test -z "$(gofmt -s -l . | tee /dev/stderr)"
diff --git a/vendor/github.com/docker/go-units/duration.go b/vendor/github.com/docker/go-units/duration.go
@@ -0,0 +1,35 @@
+// Package units provides helper function to parse and print size and time units
+// in human-readable format.
+package units
+
+import (
+ "fmt"
+ "time"
+)
+
+// HumanDuration returns a human-readable approximation of a duration
+// (eg. "About a minute", "4 hours ago", etc.).
+func HumanDuration(d time.Duration) string {
+ if seconds := int(d.Seconds()); seconds < 1 {
+ return "Less than a second"
+ } else if seconds == 1 {
+ return "1 second"
+ } else if seconds < 60 {
+ return fmt.Sprintf("%d seconds", seconds)
+ } else if minutes := int(d.Minutes()); minutes == 1 {
+ return "About a minute"
+ } else if minutes < 60 {
+ return fmt.Sprintf("%d minutes", minutes)
+ } else if hours := int(d.Hours() + 0.5); hours == 1 {
+ return "About an hour"
+ } else if hours < 48 {
+ return fmt.Sprintf("%d hours", hours)
+ } else if hours < 24*7*2 {
+ return fmt.Sprintf("%d days", hours/24)
+ } else if hours < 24*30*2 {
+ return fmt.Sprintf("%d weeks", hours/24/7)
+ } else if hours < 24*365*2 {
+ return fmt.Sprintf("%d months", hours/24/30)
+ }
+ return fmt.Sprintf("%d years", int(d.Hours())/24/365)
+}
diff --git a/vendor/github.com/docker/go-units/size.go b/vendor/github.com/docker/go-units/size.go
@@ -0,0 +1,108 @@
+package units
+
+import (
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+// See: http://en.wikipedia.org/wiki/Binary_prefix
+const (
+ // Decimal
+
+ KB = 1000
+ MB = 1000 * KB
+ GB = 1000 * MB
+ TB = 1000 * GB
+ PB = 1000 * TB
+
+ // Binary
+
+ KiB = 1024
+ MiB = 1024 * KiB
+ GiB = 1024 * MiB
+ TiB = 1024 * GiB
+ PiB = 1024 * TiB
+)
+
+type unitMap map[string]int64
+
+var (
+ decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB}
+ binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB}
+ sizeRegex = regexp.MustCompile(`^(\d+(\.\d+)*) ?([kKmMgGtTpP])?[iI]?[bB]?$`)
+)
+
+var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
+var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
+
+func getSizeAndUnit(size float64, base float64, _map []string) (float64, string) {
+ i := 0
+ unitsLimit := len(_map) - 1
+ for size >= base && i < unitsLimit {
+ size = size / base
+ i++
+ }
+ return size, _map[i]
+}
+
+// CustomSize returns a human-readable approximation of a size
+// using custom format.
+func CustomSize(format string, size float64, base float64, _map []string) string {
+ size, unit := getSizeAndUnit(size, base, _map)
+ return fmt.Sprintf(format, size, unit)
+}
+
+// HumanSizeWithPrecision allows the size to be in any precision,
+// instead of 4 digit precision used in units.HumanSize.
+func HumanSizeWithPrecision(size float64, precision int) string {
+ size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs)
+ return fmt.Sprintf("%.*g%s", precision, size, unit)
+}
+
+// HumanSize returns a human-readable approximation of a size
+// capped at 4 valid numbers (eg. "2.746 MB", "796 KB").
+func HumanSize(size float64) string {
+ return HumanSizeWithPrecision(size, 4)
+}
+
+// BytesSize returns a human-readable size in bytes, kibibytes,
+// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB").
+func BytesSize(size float64) string {
+ return CustomSize("%.4g%s", size, 1024.0, binaryAbbrs)
+}
+
+// FromHumanSize returns an integer from a human-readable specification of a
+// size using SI standard (eg. "44kB", "17MB").
+func FromHumanSize(size string) (int64, error) {
+ return parseSize(size, decimalMap)
+}
+
+// RAMInBytes parses a human-readable string representing an amount of RAM
+// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and
+// returns the number of bytes, or -1 if the string is unparseable.
+// Units are case-insensitive, and the 'b' suffix is optional.
+func RAMInBytes(size string) (int64, error) {
+ return parseSize(size, binaryMap)
+}
+
+// Parses the human-readable size string into the amount it represents.
+func parseSize(sizeStr string, uMap unitMap) (int64, error) {
+ matches := sizeRegex.FindStringSubmatch(sizeStr)
+ if len(matches) != 4 {
+ return -1, fmt.Errorf("invalid size: '%s'", sizeStr)
+ }
+
+ size, err := strconv.ParseFloat(matches[1], 64)
+ if err != nil {
+ return -1, err
+ }
+
+ unitPrefix := strings.ToLower(matches[3])
+ if mul, ok := uMap[unitPrefix]; ok {
+ size *= float64(mul)
+ }
+
+ return int64(size), nil
+}
diff --git a/vendor/github.com/docker/go-units/ulimit.go b/vendor/github.com/docker/go-units/ulimit.go
@@ -0,0 +1,123 @@
+package units
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+)
+
+// Ulimit is a human friendly version of Rlimit.
+type Ulimit struct {
+ Name string
+ Hard int64
+ Soft int64
+}
+
+// Rlimit specifies the resource limits, such as max open files.
+type Rlimit struct {
+ Type int `json:"type,omitempty"`
+ Hard uint64 `json:"hard,omitempty"`
+ Soft uint64 `json:"soft,omitempty"`
+}
+
+const (
+ // magic numbers for making the syscall
+ // some of these are defined in the syscall package, but not all.
+ // Also since Windows client doesn't get access to the syscall package, need to
+ // define these here
+ rlimitAs = 9
+ rlimitCore = 4
+ rlimitCPU = 0
+ rlimitData = 2
+ rlimitFsize = 1
+ rlimitLocks = 10
+ rlimitMemlock = 8
+ rlimitMsgqueue = 12
+ rlimitNice = 13
+ rlimitNofile = 7
+ rlimitNproc = 6
+ rlimitRss = 5
+ rlimitRtprio = 14
+ rlimitRttime = 15
+ rlimitSigpending = 11
+ rlimitStack = 3
+)
+
+var ulimitNameMapping = map[string]int{
+ //"as": rlimitAs, // Disabled since this doesn't seem usable with the way Docker inits a container.
+ "core": rlimitCore,
+ "cpu": rlimitCPU,
+ "data": rlimitData,
+ "fsize": rlimitFsize,
+ "locks": rlimitLocks,
+ "memlock": rlimitMemlock,
+ "msgqueue": rlimitMsgqueue,
+ "nice": rlimitNice,
+ "nofile": rlimitNofile,
+ "nproc": rlimitNproc,
+ "rss": rlimitRss,
+ "rtprio": rlimitRtprio,
+ "rttime": rlimitRttime,
+ "sigpending": rlimitSigpending,
+ "stack": rlimitStack,
+}
+
+// ParseUlimit parses and returns a Ulimit from the specified string.
+func ParseUlimit(val string) (*Ulimit, error) {
+ parts := strings.SplitN(val, "=", 2)
+ if len(parts) != 2 {
+ return nil, fmt.Errorf("invalid ulimit argument: %s", val)
+ }
+
+ if _, exists := ulimitNameMapping[parts[0]]; !exists {
+ return nil, fmt.Errorf("invalid ulimit type: %s", parts[0])
+ }
+
+ var (
+ soft int64
+ hard = &soft // default to soft in case no hard was set
+ temp int64
+ err error
+ )
+ switch limitVals := strings.Split(parts[1], ":"); len(limitVals) {
+ case 2:
+ temp, err = strconv.ParseInt(limitVals[1], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ hard = &temp
+ fallthrough
+ case 1:
+ soft, err = strconv.ParseInt(limitVals[0], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ default:
+ return nil, fmt.Errorf("too many limit value arguments - %s, can only have up to two, `soft[:hard]`", parts[1])
+ }
+
+ if *hard != -1 {
+ if soft == -1 {
+ return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: soft: -1 (unlimited), hard: %d", *hard)
+ }
+ if soft > *hard {
+ return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: %d > %d", soft, *hard)
+ }
+ }
+
+ return &Ulimit{Name: parts[0], Soft: soft, Hard: *hard}, nil
+}
+
+// GetRlimit returns the RLimit corresponding to Ulimit.
+func (u *Ulimit) GetRlimit() (*Rlimit, error) {
+ t, exists := ulimitNameMapping[u.Name]
+ if !exists {
+ return nil, fmt.Errorf("invalid ulimit name %s", u.Name)
+ }
+
+ return &Rlimit{Type: t, Soft: uint64(u.Soft), Hard: uint64(u.Hard)}, nil
+}
+
+func (u *Ulimit) String() string {
+ return fmt.Sprintf("%s=%d:%d", u.Name, u.Soft, u.Hard)
+}
diff --git a/vendor/github.com/godbus/dbus/v5/CONTRIBUTING.md b/vendor/github.com/godbus/dbus/v5/CONTRIBUTING.md
@@ -0,0 +1,50 @@
+# How to Contribute
+
+## Getting Started
+
+- Fork the repository on GitHub
+- Read the [README](README.markdown) for build and test instructions
+- Play with the project, submit bugs, submit patches!
+
+## Contribution Flow
+
+This is a rough outline of what a contributor's workflow looks like:
+
+- Create a topic branch from where you want to base your work (usually master).
+- Make commits of logical units.
+- Make sure your commit messages are in the proper format (see below).
+- Push your changes to a topic branch in your fork of the repository.
+- Make sure the tests pass, and add any new tests as appropriate.
+- Submit a pull request to the original repository.
+
+Thanks for your contributions!
+
+### Format of the Commit Message
+
+We follow a rough convention for commit messages that is designed to answer two
+questions: what changed and why. The subject line should feature the what and
+the body of the commit should describe the why.
+
+```
+scripts: add the test-cluster command
+
+this uses tmux to setup a test cluster that you can easily kill and
+start for debugging.
+
+Fixes #38
+```
+
+The format can be described more formally as follows:
+
+```
+<subsystem>: <what changed>
+<BLANK LINE>
+<why this change was made>
+<BLANK LINE>
+<footer>
+```
+
+The first line is the subject and should be no longer than 70 characters, the
+second line is always blank, and other lines should be wrapped at 80 characters.
+This allows the message to be easier to read on GitHub as well as in various
+git tools.
diff --git a/vendor/github.com/godbus/dbus/v5/LICENSE b/vendor/github.com/godbus/dbus/v5/LICENSE
@@ -0,0 +1,25 @@
+Copyright (c) 2013, Georg Reinke (<guelfey at gmail dot com>), Google
+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.
+
+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/godbus/dbus/v5/MAINTAINERS b/vendor/github.com/godbus/dbus/v5/MAINTAINERS
@@ -0,0 +1,3 @@
+Brandon Philips <brandon@ifup.org> (@philips)
+Brian Waldon <brian@waldon.cc> (@bcwaldon)
+John Southworth <jsouthwo@brocade.com> (@jsouthworth)
diff --git a/vendor/github.com/godbus/dbus/v5/README.markdown b/vendor/github.com/godbus/dbus/v5/README.markdown
@@ -0,0 +1,46 @@
+![Build Status](https://github.com/godbus/dbus/workflows/Go/badge.svg)
+
+dbus
+----
+
+dbus is a simple library that implements native Go client bindings for the
+D-Bus message bus system.
+
+### Features
+
+* Complete native implementation of the D-Bus message protocol
+* Go-like API (channels for signals / asynchronous method calls, Goroutine-safe connections)
+* Subpackages that help with the introspection / property interfaces
+
+### Installation
+
+This packages requires Go 1.7. If you installed it and set up your GOPATH, just run:
+
+```
+go get github.com/godbus/dbus
+```
+
+If you want to use the subpackages, you can install them the same way.
+
+### Usage
+
+The complete package documentation and some simple examples are available at
+[godoc.org](http://godoc.org/github.com/godbus/dbus). Also, the
+[_examples](https://github.com/godbus/dbus/tree/master/_examples) directory
+gives a short overview over the basic usage.
+
+#### Projects using godbus
+- [notify](https://github.com/esiqveland/notify) provides desktop notifications over dbus into a library.
+- [go-bluetooth](https://github.com/muka/go-bluetooth) provides a bluetooth client over bluez dbus API.
+- [playerbm](https://github.com/altdesktop/playerbm) a bookmark utility for media players.
+- [iwd](https://github.com/shibumi/iwd) go bindings for the internet wireless daemon "iwd".
+
+Please note that the API is considered unstable for now and may change without
+further notice.
+
+### License
+
+go.dbus is available under the Simplified BSD License; see LICENSE for the full
+text.
+
+Nearly all of the credit for this library goes to github.com/guelfey/go.dbus.
diff --git a/vendor/github.com/godbus/dbus/v5/auth.go b/vendor/github.com/godbus/dbus/v5/auth.go
@@ -0,0 +1,252 @@
+package dbus
+
+import (
+ "bufio"
+ "bytes"
+ "errors"
+ "io"
+ "os"
+ "strconv"
+)
+
+// AuthStatus represents the Status of an authentication mechanism.
+type AuthStatus byte
+
+const (
+ // AuthOk signals that authentication is finished; the next command
+ // from the server should be an OK.
+ AuthOk AuthStatus = iota
+
+ // AuthContinue signals that additional data is needed; the next command
+ // from the server should be a DATA.
+ AuthContinue
+
+ // AuthError signals an error; the server sent invalid data or some
+ // other unexpected thing happened and the current authentication
+ // process should be aborted.
+ AuthError
+)
+
+type authState byte
+
+const (
+ waitingForData authState = iota
+ waitingForOk
+ waitingForReject
+)
+
+// Auth defines the behaviour of an authentication mechanism.
+type Auth interface {
+ // Return the name of the mechanism, the argument to the first AUTH command
+ // and the next status.
+ FirstData() (name, resp []byte, status AuthStatus)
+
+ // Process the given DATA command, and return the argument to the DATA
+ // command and the next status. If len(resp) == 0, no DATA command is sent.
+ HandleData(data []byte) (resp []byte, status AuthStatus)
+}
+
+// Auth authenticates the connection, trying the given list of authentication
+// mechanisms (in that order). If nil is passed, the EXTERNAL and
+// DBUS_COOKIE_SHA1 mechanisms are tried for the current user. For private
+// connections, this method must be called before sending any messages to the
+// bus. Auth must not be called on shared connections.
+func (conn *Conn) Auth(methods []Auth) error {
+ if methods == nil {
+ uid := strconv.Itoa(os.Getuid())
+ methods = []Auth{AuthExternal(uid), AuthCookieSha1(uid, getHomeDir())}
+ }
+ in := bufio.NewReader(conn.transport)
+ err := conn.transport.SendNullByte()
+ if err != nil {
+ return err
+ }
+ err = authWriteLine(conn.transport, []byte("AUTH"))
+ if err != nil {
+ return err
+ }
+ s, err := authReadLine(in)
+ if err != nil {
+ return err
+ }
+ if len(s) < 2 || !bytes.Equal(s[0], []byte("REJECTED")) {
+ return errors.New("dbus: authentication protocol error")
+ }
+ s = s[1:]
+ for _, v := range s {
+ for _, m := range methods {
+ if name, data, status := m.FirstData(); bytes.Equal(v, name) {
+ var ok bool
+ err = authWriteLine(conn.transport, []byte("AUTH"), v, data)
+ if err != nil {
+ return err
+ }
+ switch status {
+ case AuthOk:
+ err, ok = conn.tryAuth(m, waitingForOk, in)
+ case AuthContinue:
+ err, ok = conn.tryAuth(m, waitingForData, in)
+ default:
+ panic("dbus: invalid authentication status")
+ }
+ if err != nil {
+ return err
+ }
+ if ok {
+ if conn.transport.SupportsUnixFDs() {
+ err = authWriteLine(conn, []byte("NEGOTIATE_UNIX_FD"))
+ if err != nil {
+ return err
+ }
+ line, err := authReadLine(in)
+ if err != nil {
+ return err
+ }
+ switch {
+ case bytes.Equal(line[0], []byte("AGREE_UNIX_FD")):
+ conn.EnableUnixFDs()
+ conn.unixFD = true
+ case bytes.Equal(line[0], []byte("ERROR")):
+ default:
+ return errors.New("dbus: authentication protocol error")
+ }
+ }
+ err = authWriteLine(conn.transport, []byte("BEGIN"))
+ if err != nil {
+ return err
+ }
+ go conn.inWorker()
+ return nil
+ }
+ }
+ }
+ }
+ return errors.New("dbus: authentication failed")
+}
+
+// tryAuth tries to authenticate with m as the mechanism, using state as the
+// initial authState and in for reading input. It returns (nil, true) on
+// success, (nil, false) on a REJECTED and (someErr, false) if some other
+// error occurred.
+func (conn *Conn) tryAuth(m Auth, state authState, in *bufio.Reader) (error, bool) {
+ for {
+ s, err := authReadLine(in)
+ if err != nil {
+ return err, false
+ }
+ switch {
+ case state == waitingForData && string(s[0]) == "DATA":
+ if len(s) != 2 {
+ err = authWriteLine(conn.transport, []byte("ERROR"))
+ if err != nil {
+ return err, false
+ }
+ continue
+ }
+ data, status := m.HandleData(s[1])
+ switch status {
+ case AuthOk, AuthContinue:
+ if len(data) != 0 {
+ err = authWriteLine(conn.transport, []byte("DATA"), data)
+ if err != nil {
+ return err, false
+ }
+ }
+ if status == AuthOk {
+ state = waitingForOk
+ }
+ case AuthError:
+ err = authWriteLine(conn.transport, []byte("ERROR"))
+ if err != nil {
+ return err, false
+ }
+ }
+ case state == waitingForData && string(s[0]) == "REJECTED":
+ return nil, false
+ case state == waitingForData && string(s[0]) == "ERROR":
+ err = authWriteLine(conn.transport, []byte("CANCEL"))
+ if err != nil {
+ return err, false
+ }
+ state = waitingForReject
+ case state == waitingForData && string(s[0]) == "OK":
+ if len(s) != 2 {
+ err = authWriteLine(conn.transport, []byte("CANCEL"))
+ if err != nil {
+ return err, false
+ }
+ state = waitingForReject
+ }
+ conn.uuid = string(s[1])
+ return nil, true
+ case state == waitingForData:
+ err = authWriteLine(conn.transport, []byte("ERROR"))
+ if err != nil {
+ return err, false
+ }
+ case state == waitingForOk && string(s[0]) == "OK":
+ if len(s) != 2 {
+ err = authWriteLine(conn.transport, []byte("CANCEL"))
+ if err != nil {
+ return err, false
+ }
+ state = waitingForReject
+ }
+ conn.uuid = string(s[1])
+ return nil, true
+ case state == waitingForOk && string(s[0]) == "REJECTED":
+ return nil, false
+ case state == waitingForOk && (string(s[0]) == "DATA" ||
+ string(s[0]) == "ERROR"):
+
+ err = authWriteLine(conn.transport, []byte("CANCEL"))
+ if err != nil {
+ return err, false
+ }
+ state = waitingForReject
+ case state == waitingForOk:
+ err = authWriteLine(conn.transport, []byte("ERROR"))
+ if err != nil {
+ return err, false
+ }
+ case state == waitingForReject && string(s[0]) == "REJECTED":
+ return nil, false
+ case state == waitingForReject:
+ return errors.New("dbus: authentication protocol error"), false
+ default:
+ panic("dbus: invalid auth state")
+ }
+ }
+}
+
+// authReadLine reads a line and separates it into its fields.
+func authReadLine(in *bufio.Reader) ([][]byte, error) {
+ data, err := in.ReadBytes('\n')
+ if err != nil {
+ return nil, err
+ }
+ data = bytes.TrimSuffix(data, []byte("\r\n"))
+ return bytes.Split(data, []byte{' '}), nil
+}
+
+// authWriteLine writes the given line in the authentication protocol format
+// (elements of data separated by a " " and terminated by "\r\n").
+func authWriteLine(out io.Writer, data ...[]byte) error {
+ buf := make([]byte, 0)
+ for i, v := range data {
+ buf = append(buf, v...)
+ if i != len(data)-1 {
+ buf = append(buf, ' ')
+ }
+ }
+ buf = append(buf, '\r')
+ buf = append(buf, '\n')
+ n, err := out.Write(buf)
+ if err != nil {
+ return err
+ }
+ if n != len(buf) {
+ return io.ErrUnexpectedEOF
+ }
+ return nil
+}
diff --git a/vendor/github.com/godbus/dbus/v5/auth_anonymous.go b/vendor/github.com/godbus/dbus/v5/auth_anonymous.go
@@ -0,0 +1,16 @@
+package dbus
+
+// AuthAnonymous returns an Auth that uses the ANONYMOUS mechanism.
+func AuthAnonymous() Auth {
+ return &authAnonymous{}
+}
+
+type authAnonymous struct{}
+
+func (a *authAnonymous) FirstData() (name, resp []byte, status AuthStatus) {
+ return []byte("ANONYMOUS"), nil, AuthOk
+}
+
+func (a *authAnonymous) HandleData(data []byte) (resp []byte, status AuthStatus) {
+ return nil, AuthError
+}
diff --git a/vendor/github.com/godbus/dbus/v5/auth_external.go b/vendor/github.com/godbus/dbus/v5/auth_external.go
@@ -0,0 +1,26 @@
+package dbus
+
+import (
+ "encoding/hex"
+)
+
+// AuthExternal returns an Auth that authenticates as the given user with the
+// EXTERNAL mechanism.
+func AuthExternal(user string) Auth {
+ return authExternal{user}
+}
+
+// AuthExternal implements the EXTERNAL authentication mechanism.
+type authExternal struct {
+ user string
+}
+
+func (a authExternal) FirstData() ([]byte, []byte, AuthStatus) {
+ b := make([]byte, 2*len(a.user))
+ hex.Encode(b, []byte(a.user))
+ return []byte("EXTERNAL"), b, AuthOk
+}
+
+func (a authExternal) HandleData(b []byte) ([]byte, AuthStatus) {
+ return nil, AuthError
+}
diff --git a/vendor/github.com/godbus/dbus/v5/auth_sha1.go b/vendor/github.com/godbus/dbus/v5/auth_sha1.go
@@ -0,0 +1,102 @@
+package dbus
+
+import (
+ "bufio"
+ "bytes"
+ "crypto/rand"
+ "crypto/sha1"
+ "encoding/hex"
+ "os"
+)
+
+// AuthCookieSha1 returns an Auth that authenticates as the given user with the
+// DBUS_COOKIE_SHA1 mechanism. The home parameter should specify the home
+// directory of the user.
+func AuthCookieSha1(user, home string) Auth {
+ return authCookieSha1{user, home}
+}
+
+type authCookieSha1 struct {
+ user, home string
+}
+
+func (a authCookieSha1) FirstData() ([]byte, []byte, AuthStatus) {
+ b := make([]byte, 2*len(a.user))
+ hex.Encode(b, []byte(a.user))
+ return []byte("DBUS_COOKIE_SHA1"), b, AuthContinue
+}
+
+func (a authCookieSha1) HandleData(data []byte) ([]byte, AuthStatus) {
+ challenge := make([]byte, len(data)/2)
+ _, err := hex.Decode(challenge, data)
+ if err != nil {
+ return nil, AuthError
+ }
+ b := bytes.Split(challenge, []byte{' '})
+ if len(b) != 3 {
+ return nil, AuthError
+ }
+ context := b[0]
+ id := b[1]
+ svchallenge := b[2]
+ cookie := a.getCookie(context, id)
+ if cookie == nil {
+ return nil, AuthError
+ }
+ clchallenge := a.generateChallenge()
+ if clchallenge == nil {
+ return nil, AuthError
+ }
+ hash := sha1.New()
+ hash.Write(bytes.Join([][]byte{svchallenge, clchallenge, cookie}, []byte{':'}))
+ hexhash := make([]byte, 2*hash.Size())
+ hex.Encode(hexhash, hash.Sum(nil))
+ data = append(clchallenge, ' ')
+ data = append(data, hexhash...)
+ resp := make([]byte, 2*len(data))
+ hex.Encode(resp, data)
+ return resp, AuthOk
+}
+
+// getCookie searches for the cookie identified by id in context and returns
+// the cookie content or nil. (Since HandleData can't return a specific error,
+// but only whether an error occurred, this function also doesn't bother to
+// return an error.)
+func (a authCookieSha1) getCookie(context, id []byte) []byte {
+ file, err := os.Open(a.home + "/.dbus-keyrings/" + string(context))
+ if err != nil {
+ return nil
+ }
+ defer file.Close()
+ rd := bufio.NewReader(file)
+ for {
+ line, err := rd.ReadBytes('\n')
+ if err != nil {
+ return nil
+ }
+ line = line[:len(line)-1]
+ b := bytes.Split(line, []byte{' '})
+ if len(b) != 3 {
+ return nil
+ }
+ if bytes.Equal(b[0], id) {
+ return b[2]
+ }
+ }
+}
+
+// generateChallenge returns a random, hex-encoded challenge, or nil on error
+// (see above).
+func (a authCookieSha1) generateChallenge() []byte {
+ b := make([]byte, 16)
+ n, err := rand.Read(b)
+ if err != nil {
+ return nil
+ }
+ if n != 16 {
+ return nil
+ }
+ enc := make([]byte, 32)
+ hex.Encode(enc, b)
+ return enc
+}
diff --git a/vendor/github.com/godbus/dbus/v5/call.go b/vendor/github.com/godbus/dbus/v5/call.go
@@ -0,0 +1,69 @@
+package dbus
+
+import (
+ "context"
+ "errors"
+)
+
+var errSignature = errors.New("dbus: mismatched signature")
+
+// Call represents a pending or completed method call.
+type Call struct {
+ Destination string
+ Path ObjectPath
+ Method string
+ Args []interface{}
+
+ // Strobes when the call is complete.
+ Done chan *Call
+
+ // After completion, the error status. If this is non-nil, it may be an
+ // error message from the peer (with Error as its type) or some other error.
+ Err error
+
+ // Holds the response once the call is done.
+ Body []interface{}
+
+ // ResponseSequence stores the sequence number of the DBus message containing
+ // the call response (or error). This can be compared to the sequence number
+ // of other call responses and signals on this connection to determine their
+ // relative ordering on the underlying DBus connection.
+ // For errors, ResponseSequence is populated only if the error came from a
+ // DBusMessage that was received or if there was an error receiving. In case of
+ // failure to make the call, ResponseSequence will be NoSequence.
+ ResponseSequence Sequence
+
+ // tracks context and canceler
+ ctx context.Context
+ ctxCanceler context.CancelFunc
+}
+
+func (c *Call) Context() context.Context {
+ if c.ctx == nil {
+ return context.Background()
+ }
+
+ return c.ctx
+}
+
+func (c *Call) ContextCancel() {
+ if c.ctxCanceler != nil {
+ c.ctxCanceler()
+ }
+}
+
+// Store stores the body of the reply into the provided pointers. It returns
+// an error if the signatures of the body and retvalues don't match, or if
+// the error status is not nil.
+func (c *Call) Store(retvalues ...interface{}) error {
+ if c.Err != nil {
+ return c.Err
+ }
+
+ return Store(c.Body, retvalues...)
+}
+
+func (c *Call) done() {
+ c.Done <- c
+ c.ContextCancel()
+}
diff --git a/vendor/github.com/godbus/dbus/v5/conn.go b/vendor/github.com/godbus/dbus/v5/conn.go
@@ -0,0 +1,959 @@
+package dbus
+
+import (
+ "context"
+ "errors"
+ "io"
+ "os"
+ "strings"
+ "sync"
+)
+
+var (
+ systemBus *Conn
+ systemBusLck sync.Mutex
+ sessionBus *Conn
+ sessionBusLck sync.Mutex
+)
+
+// ErrClosed is the error returned by calls on a closed connection.
+var ErrClosed = errors.New("dbus: connection closed by user")
+
+// Conn represents a connection to a message bus (usually, the system or
+// session bus).
+//
+// Connections are either shared or private. Shared connections
+// are shared between calls to the functions that return them. As a result,
+// the methods Close, Auth and Hello must not be called on them.
+//
+// Multiple goroutines may invoke methods on a connection simultaneously.
+type Conn struct {
+ transport
+
+ ctx context.Context
+ cancelCtx context.CancelFunc
+
+ closeOnce sync.Once
+ closeErr error
+
+ busObj BusObject
+ unixFD bool
+ uuid string
+
+ handler Handler
+ signalHandler SignalHandler
+ serialGen SerialGenerator
+ inInt Interceptor
+ outInt Interceptor
+ auth []Auth
+
+ names *nameTracker
+ calls *callTracker
+ outHandler *outputHandler
+
+ eavesdropped chan<- *Message
+ eavesdroppedLck sync.Mutex
+}
+
+// SessionBus returns a shared connection to the session bus, connecting to it
+// if not already done.
+func SessionBus() (conn *Conn, err error) {
+ sessionBusLck.Lock()
+ defer sessionBusLck.Unlock()
+ if sessionBus != nil &&
+ sessionBus.Connected() {
+ return sessionBus, nil
+ }
+ defer func() {
+ if conn != nil {
+ sessionBus = conn
+ }
+ }()
+ conn, err = ConnectSessionBus()
+ return
+}
+
+func getSessionBusAddress() (string, error) {
+ if address := os.Getenv("DBUS_SESSION_BUS_ADDRESS"); address != "" && address != "autolaunch:" {
+ return address, nil
+
+ } else if address := tryDiscoverDbusSessionBusAddress(); address != "" {
+ os.Setenv("DBUS_SESSION_BUS_ADDRESS", address)
+ return address, nil
+ }
+ return getSessionBusPlatformAddress()
+}
+
+// SessionBusPrivate returns a new private connection to the session bus.
+func SessionBusPrivate(opts ...ConnOption) (*Conn, error) {
+ address, err := getSessionBusAddress()
+ if err != nil {
+ return nil, err
+ }
+
+ return Dial(address, opts...)
+}
+
+// SessionBusPrivate returns a new private connection to the session bus.
+//
+// Deprecated: use SessionBusPrivate with options instead.
+func SessionBusPrivateHandler(handler Handler, signalHandler SignalHandler) (*Conn, error) {
+ return SessionBusPrivate(WithHandler(handler), WithSignalHandler(signalHandler))
+}
+
+// SystemBus returns a shared connection to the system bus, connecting to it if
+// not already done.
+func SystemBus() (conn *Conn, err error) {
+ systemBusLck.Lock()
+ defer systemBusLck.Unlock()
+ if systemBus != nil &&
+ systemBus.Connected() {
+ return systemBus, nil
+ }
+ defer func() {
+ if conn != nil {
+ systemBus = conn
+ }
+ }()
+ conn, err = ConnectSystemBus()
+ return
+}
+
+// ConnectSessionBus connects to the session bus.
+func ConnectSessionBus(opts ...ConnOption) (*Conn, error) {
+ address, err := getSessionBusAddress()
+ if err != nil {
+ return nil, err
+ }
+ return Connect(address, opts...)
+}
+
+// ConnectSystemBus connects to the system bus.
+func ConnectSystemBus(opts ...ConnOption) (*Conn, error) {
+ return Connect(getSystemBusPlatformAddress(), opts...)
+}
+
+// Connect connects to the given address.
+//
+// Returned connection is ready to use and doesn't require calling
+// Auth and Hello methods to make it usable.
+func Connect(address string, opts ...ConnOption) (*Conn, error) {
+ conn, err := Dial(address, opts...)
+ if err != nil {
+ return nil, err
+ }
+ if err = conn.Auth(conn.auth); err != nil {
+ _ = conn.Close()
+ return nil, err
+ }
+ if err = conn.Hello(); err != nil {
+ _ = conn.Close()
+ return nil, err
+ }
+ return conn, nil
+}
+
+// SystemBusPrivate returns a new private connection to the system bus.
+// Note: this connection is not ready to use. One must perform Auth and Hello
+// on the connection before it is useable.
+func SystemBusPrivate(opts ...ConnOption) (*Conn, error) {
+ return Dial(getSystemBusPlatformAddress(), opts...)
+}
+
+// SystemBusPrivateHandler returns a new private connection to the system bus, using the provided handlers.
+//
+// Deprecated: use SystemBusPrivate with options instead.
+func SystemBusPrivateHandler(handler Handler, signalHandler SignalHandler) (*Conn, error) {
+ return SystemBusPrivate(WithHandler(handler), WithSignalHandler(signalHandler))
+}
+
+// Dial establishes a new private connection to the message bus specified by address.
+func Dial(address string, opts ...ConnOption) (*Conn, error) {
+ tr, err := getTransport(address)
+ if err != nil {
+ return nil, err
+ }
+ return newConn(tr, opts...)
+}
+
+// DialHandler establishes a new private connection to the message bus specified by address, using the supplied handlers.
+//
+// Deprecated: use Dial with options instead.
+func DialHandler(address string, handler Handler, signalHandler SignalHandler) (*Conn, error) {
+ return Dial(address, WithSignalHandler(signalHandler))
+}
+
+// ConnOption is a connection option.
+type ConnOption func(conn *Conn) error
+
+// WithHandler overrides the default handler.
+func WithHandler(handler Handler) ConnOption {
+ return func(conn *Conn) error {
+ conn.handler = handler
+ return nil
+ }
+}
+
+// WithSignalHandler overrides the default signal handler.
+func WithSignalHandler(handler SignalHandler) ConnOption {
+ return func(conn *Conn) error {
+ conn.signalHandler = handler
+ return nil
+ }
+}
+
+// WithSerialGenerator overrides the default signals generator.
+func WithSerialGenerator(gen SerialGenerator) ConnOption {
+ return func(conn *Conn) error {
+ conn.serialGen = gen
+ return nil
+ }
+}
+
+// WithAuth sets authentication methods for the auth conversation.
+func WithAuth(methods ...Auth) ConnOption {
+ return func(conn *Conn) error {
+ conn.auth = methods
+ return nil
+ }
+}
+
+// Interceptor intercepts incoming and outgoing messages.
+type Interceptor func(msg *Message)
+
+// WithIncomingInterceptor sets the given interceptor for incoming messages.
+func WithIncomingInterceptor(interceptor Interceptor) ConnOption {
+ return func(conn *Conn) error {
+ conn.inInt = interceptor
+ return nil
+ }
+}
+
+// WithOutgoingInterceptor sets the given interceptor for outgoing messages.
+func WithOutgoingInterceptor(interceptor Interceptor) ConnOption {
+ return func(conn *Conn) error {
+ conn.outInt = interceptor
+ return nil
+ }
+}
+
+// WithContext overrides the default context for the connection.
+func WithContext(ctx context.Context) ConnOption {
+ return func(conn *Conn) error {
+ conn.ctx = ctx
+ return nil
+ }
+}
+
+// NewConn creates a new private *Conn from an already established connection.
+func NewConn(conn io.ReadWriteCloser, opts ...ConnOption) (*Conn, error) {
+ return newConn(genericTransport{conn}, opts...)
+}
+
+// NewConnHandler creates a new private *Conn from an already established connection, using the supplied handlers.
+//
+// Deprecated: use NewConn with options instead.
+func NewConnHandler(conn io.ReadWriteCloser, handler Handler, signalHandler SignalHandler) (*Conn, error) {
+ return NewConn(genericTransport{conn}, WithHandler(handler), WithSignalHandler(signalHandler))
+}
+
+// newConn creates a new *Conn from a transport.
+func newConn(tr transport, opts ...ConnOption) (*Conn, error) {
+ conn := new(Conn)
+ conn.transport = tr
+ for _, opt := range opts {
+ if err := opt(conn); err != nil {
+ return nil, err
+ }
+ }
+ if conn.ctx == nil {
+ conn.ctx = context.Background()
+ }
+ conn.ctx, conn.cancelCtx = context.WithCancel(conn.ctx)
+ go func() {
+ <-conn.ctx.Done()
+ conn.Close()
+ }()
+
+ conn.calls = newCallTracker()
+ if conn.handler == nil {
+ conn.handler = NewDefaultHandler()
+ }
+ if conn.signalHandler == nil {
+ conn.signalHandler = NewDefaultSignalHandler()
+ }
+ if conn.serialGen == nil {
+ conn.serialGen = newSerialGenerator()
+ }
+ conn.outHandler = &outputHandler{conn: conn}
+ conn.names = newNameTracker()
+ conn.busObj = conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus")
+ return conn, nil
+}
+
+// BusObject returns the object owned by the bus daemon which handles
+// administrative requests.
+func (conn *Conn) BusObject() BusObject {
+ return conn.busObj
+}
+
+// Close closes the connection. Any blocked operations will return with errors
+// and the channels passed to Eavesdrop and Signal are closed. This method must
+// not be called on shared connections.
+func (conn *Conn) Close() error {
+ conn.closeOnce.Do(func() {
+ conn.outHandler.close()
+ if term, ok := conn.signalHandler.(Terminator); ok {
+ term.Terminate()
+ }
+
+ if term, ok := conn.handler.(Terminator); ok {
+ term.Terminate()
+ }
+
+ conn.eavesdroppedLck.Lock()
+ if conn.eavesdropped != nil {
+ close(conn.eavesdropped)
+ }
+ conn.eavesdroppedLck.Unlock()
+
+ conn.cancelCtx()
+
+ conn.closeErr = conn.transport.Close()
+ })
+ return conn.closeErr
+}
+
+// Context returns the context associated with the connection. The
+// context will be cancelled when the connection is closed.
+func (conn *Conn) Context() context.Context {
+ return conn.ctx
+}
+
+// Connected returns whether conn is connected
+func (conn *Conn) Connected() bool {
+ return conn.ctx.Err() == nil
+}
+
+// Eavesdrop causes conn to send all incoming messages to the given channel
+// without further processing. Method replies, errors and signals will not be
+// sent to the appropriate channels and method calls will not be handled. If nil
+// is passed, the normal behaviour is restored.
+//
+// The caller has to make sure that ch is sufficiently buffered;
+// if a message arrives when a write to ch is not possible, the message is
+// discarded.
+func (conn *Conn) Eavesdrop(ch chan<- *Message) {
+ conn.eavesdroppedLck.Lock()
+ conn.eavesdropped = ch
+ conn.eavesdroppedLck.Unlock()
+}
+
+// getSerial returns an unused serial.
+func (conn *Conn) getSerial() uint32 {
+ return conn.serialGen.GetSerial()
+}
+
+// Hello sends the initial org.freedesktop.DBus.Hello call. This method must be
+// called after authentication, but before sending any other messages to the
+// bus. Hello must not be called for shared connections.
+func (conn *Conn) Hello() error {
+ var s string
+ err := conn.busObj.Call("org.freedesktop.DBus.Hello", 0).Store(&s)
+ if err != nil {
+ return err
+ }
+ conn.names.acquireUniqueConnectionName(s)
+ return nil
+}
+
+// inWorker runs in an own goroutine, reading incoming messages from the
+// transport and dispatching them appropriately.
+func (conn *Conn) inWorker() {
+ sequenceGen := newSequenceGenerator()
+ for {
+ msg, err := conn.ReadMessage()
+ if err != nil {
+ if _, ok := err.(InvalidMessageError); !ok {
+ // Some read error occurred (usually EOF); we can't really do
+ // anything but to shut down all stuff and returns errors to all
+ // pending replies.
+ conn.Close()
+ conn.calls.finalizeAllWithError(sequenceGen, err)
+ return
+ }
+ // invalid messages are ignored
+ continue
+ }
+ conn.eavesdroppedLck.Lock()
+ if conn.eavesdropped != nil {
+ select {
+ case conn.eavesdropped <- msg:
+ default:
+ }
+ conn.eavesdroppedLck.Unlock()
+ continue
+ }
+ conn.eavesdroppedLck.Unlock()
+ dest, _ := msg.Headers[FieldDestination].value.(string)
+ found := dest == "" ||
+ !conn.names.uniqueNameIsKnown() ||
+ conn.names.isKnownName(dest)
+ if !found {
+ // Eavesdropped a message, but no channel for it is registered.
+ // Ignore it.
+ continue
+ }
+
+ if conn.inInt != nil {
+ conn.inInt(msg)
+ }
+ sequence := sequenceGen.next()
+ switch msg.Type {
+ case TypeError:
+ conn.serialGen.RetireSerial(conn.calls.handleDBusError(sequence, msg))
+ case TypeMethodReply:
+ conn.serialGen.RetireSerial(conn.calls.handleReply(sequence, msg))
+ case TypeSignal:
+ conn.handleSignal(sequence, msg)
+ case TypeMethodCall:
+ go conn.handleCall(msg)
+ }
+
+ }
+}
+
+func (conn *Conn) handleSignal(sequence Sequence, msg *Message) {
+ iface := msg.Headers[FieldInterface].value.(string)
+ member := msg.Headers[FieldMember].value.(string)
+ // as per http://dbus.freedesktop.org/doc/dbus-specification.html ,
+ // sender is optional for signals.
+ sender, _ := msg.Headers[FieldSender].value.(string)
+ if iface == "org.freedesktop.DBus" && sender == "org.freedesktop.DBus" {
+ if member == "NameLost" {
+ // If we lost the name on the bus, remove it from our
+ // tracking list.
+ name, ok := msg.Body[0].(string)
+ if !ok {
+ panic("Unable to read the lost name")
+ }
+ conn.names.loseName(name)
+ } else if member == "NameAcquired" {
+ // If we acquired the name on the bus, add it to our
+ // tracking list.
+ name, ok := msg.Body[0].(string)
+ if !ok {
+ panic("Unable to read the acquired name")
+ }
+ conn.names.acquireName(name)
+ }
+ }
+ signal := &Signal{
+ Sender: sender,
+ Path: msg.Headers[FieldPath].value.(ObjectPath),
+ Name: iface + "." + member,
+ Body: msg.Body,
+ Sequence: sequence,
+ }
+ conn.signalHandler.DeliverSignal(iface, member, signal)
+}
+
+// Names returns the list of all names that are currently owned by this
+// connection. The slice is always at least one element long, the first element
+// being the unique name of the connection.
+func (conn *Conn) Names() []string {
+ return conn.names.listKnownNames()
+}
+
+// Object returns the object identified by the given destination name and path.
+func (conn *Conn) Object(dest string, path ObjectPath) BusObject {
+ return &Object{conn, dest, path}
+}
+
+func (conn *Conn) sendMessageAndIfClosed(msg *Message, ifClosed func()) {
+ if msg.serial == 0 {
+ msg.serial = conn.getSerial()
+ }
+ if conn.outInt != nil {
+ conn.outInt(msg)
+ }
+ err := conn.outHandler.sendAndIfClosed(msg, ifClosed)
+ conn.calls.handleSendError(msg, err)
+ if err != nil {
+ conn.serialGen.RetireSerial(msg.serial)
+ } else if msg.Type != TypeMethodCall {
+ conn.serialGen.RetireSerial(msg.serial)
+ }
+}
+
+// Send sends the given message to the message bus. You usually don't need to
+// use this; use the higher-level equivalents (Call / Go, Emit and Export)
+// instead. If msg is a method call and NoReplyExpected is not set, a non-nil
+// call is returned and the same value is sent to ch (which must be buffered)
+// once the call is complete. Otherwise, ch is ignored and a Call structure is
+// returned of which only the Err member is valid.
+func (conn *Conn) Send(msg *Message, ch chan *Call) *Call {
+ return conn.send(context.Background(), msg, ch)
+}
+
+// SendWithContext acts like Send but takes a context
+func (conn *Conn) SendWithContext(ctx context.Context, msg *Message, ch chan *Call) *Call {
+ return conn.send(ctx, msg, ch)
+}
+
+func (conn *Conn) send(ctx context.Context, msg *Message, ch chan *Call) *Call {
+ if ctx == nil {
+ panic("nil context")
+ }
+ if ch == nil {
+ ch = make(chan *Call, 1)
+ } else if cap(ch) == 0 {
+ panic("dbus: unbuffered channel passed to (*Conn).Send")
+ }
+
+ var call *Call
+ ctx, canceler := context.WithCancel(ctx)
+ msg.serial = conn.getSerial()
+ if msg.Type == TypeMethodCall && msg.Flags&FlagNoReplyExpected == 0 {
+ call = new(Call)
+ call.Destination, _ = msg.Headers[FieldDestination].value.(string)
+ call.Path, _ = msg.Headers[FieldPath].value.(ObjectPath)
+ iface, _ := msg.Headers[FieldInterface].value.(string)
+ member, _ := msg.Headers[FieldMember].value.(string)
+ call.Method = iface + "." + member
+ call.Args = msg.Body
+ call.Done = ch
+ call.ctx = ctx
+ call.ctxCanceler = canceler
+ conn.calls.track(msg.serial, call)
+ go func() {
+ <-ctx.Done()
+ conn.calls.handleSendError(msg, ctx.Err())
+ }()
+ conn.sendMessageAndIfClosed(msg, func() {
+ conn.calls.handleSendError(msg, ErrClosed)
+ canceler()
+ })
+ } else {
+ canceler()
+ call = &Call{Err: nil, Done: ch}
+ ch <- call
+ conn.sendMessageAndIfClosed(msg, func() {
+ call = &Call{Err: ErrClosed}
+ })
+ }
+ return call
+}
+
+// sendError creates an error message corresponding to the parameters and sends
+// it to conn.out.
+func (conn *Conn) sendError(err error, dest string, serial uint32) {
+ var e *Error
+ switch em := err.(type) {
+ case Error:
+ e = &em
+ case *Error:
+ e = em
+ case DBusError:
+ name, body := em.DBusError()
+ e = NewError(name, body)
+ default:
+ e = MakeFailedError(err)
+ }
+ msg := new(Message)
+ msg.Type = TypeError
+ msg.Headers = make(map[HeaderField]Variant)
+ if dest != "" {
+ msg.Headers[FieldDestination] = MakeVariant(dest)
+ }
+ msg.Headers[FieldErrorName] = MakeVariant(e.Name)
+ msg.Headers[FieldReplySerial] = MakeVariant(serial)
+ msg.Body = e.Body
+ if len(e.Body) > 0 {
+ msg.Headers[FieldSignature] = MakeVariant(SignatureOf(e.Body...))
+ }
+ conn.sendMessageAndIfClosed(msg, nil)
+}
+
+// sendReply creates a method reply message corresponding to the parameters and
+// sends it to conn.out.
+func (conn *Conn) sendReply(dest string, serial uint32, values ...interface{}) {
+ msg := new(Message)
+ msg.Type = TypeMethodReply
+ msg.Headers = make(map[HeaderField]Variant)
+ if dest != "" {
+ msg.Headers[FieldDestination] = MakeVariant(dest)
+ }
+ msg.Headers[FieldReplySerial] = MakeVariant(serial)
+ msg.Body = values
+ if len(values) > 0 {
+ msg.Headers[FieldSignature] = MakeVariant(SignatureOf(values...))
+ }
+ conn.sendMessageAndIfClosed(msg, nil)
+}
+
+// AddMatchSignal registers the given match rule to receive broadcast
+// signals based on their contents.
+func (conn *Conn) AddMatchSignal(options ...MatchOption) error {
+ return conn.AddMatchSignalContext(context.Background(), options...)
+}
+
+// AddMatchSignalContext acts like AddMatchSignal but takes a context.
+func (conn *Conn) AddMatchSignalContext(ctx context.Context, options ...MatchOption) error {
+ options = append([]MatchOption{withMatchType("signal")}, options...)
+ return conn.busObj.CallWithContext(
+ ctx,
+ "org.freedesktop.DBus.AddMatch", 0,
+ formatMatchOptions(options),
+ ).Store()
+}
+
+// RemoveMatchSignal removes the first rule that matches previously registered with AddMatchSignal.
+func (conn *Conn) RemoveMatchSignal(options ...MatchOption) error {
+ return conn.RemoveMatchSignalContext(context.Background(), options...)
+}
+
+// RemoveMatchSignalContext acts like RemoveMatchSignal but takes a context.
+func (conn *Conn) RemoveMatchSignalContext(ctx context.Context, options ...MatchOption) error {
+ options = append([]MatchOption{withMatchType("signal")}, options...)
+ return conn.busObj.CallWithContext(
+ ctx,
+ "org.freedesktop.DBus.RemoveMatch", 0,
+ formatMatchOptions(options),
+ ).Store()
+}
+
+// Signal registers the given channel to be passed all received signal messages.
+//
+// Multiple of these channels can be registered at the same time.
+//
+// These channels are "overwritten" by Eavesdrop; i.e., if there currently is a
+// channel for eavesdropped messages, this channel receives all signals, and
+// none of the channels passed to Signal will receive any signals.
+//
+// Panics if the signal handler is not a `SignalRegistrar`.
+func (conn *Conn) Signal(ch chan<- *Signal) {
+ handler, ok := conn.signalHandler.(SignalRegistrar)
+ if !ok {
+ panic("cannot use this method with a non SignalRegistrar handler")
+ }
+ handler.AddSignal(ch)
+}
+
+// RemoveSignal removes the given channel from the list of the registered channels.
+//
+// Panics if the signal handler is not a `SignalRegistrar`.
+func (conn *Conn) RemoveSignal(ch chan<- *Signal) {
+ handler, ok := conn.signalHandler.(SignalRegistrar)
+ if !ok {
+ panic("cannot use this method with a non SignalRegistrar handler")
+ }
+ handler.RemoveSignal(ch)
+}
+
+// SupportsUnixFDs returns whether the underlying transport supports passing of
+// unix file descriptors. If this is false, method calls containing unix file
+// descriptors will return an error and emitted signals containing them will
+// not be sent.
+func (conn *Conn) SupportsUnixFDs() bool {
+ return conn.unixFD
+}
+
+// Error represents a D-Bus message of type Error.
+type Error struct {
+ Name string
+ Body []interface{}
+}
+
+func NewError(name string, body []interface{}) *Error {
+ return &Error{name, body}
+}
+
+func (e Error) Error() string {
+ if len(e.Body) >= 1 {
+ s, ok := e.Body[0].(string)
+ if ok {
+ return s
+ }
+ }
+ return e.Name
+}
+
+// Signal represents a D-Bus message of type Signal. The name member is given in
+// "interface.member" notation, e.g. org.freedesktop.D-Bus.NameLost.
+type Signal struct {
+ Sender string
+ Path ObjectPath
+ Name string
+ Body []interface{}
+ Sequence Sequence
+}
+
+// transport is a D-Bus transport.
+type transport interface {
+ // Read and Write raw data (for example, for the authentication protocol).
+ io.ReadWriteCloser
+
+ // Send the initial null byte used for the EXTERNAL mechanism.
+ SendNullByte() error
+
+ // Returns whether this transport supports passing Unix FDs.
+ SupportsUnixFDs() bool
+
+ // Signal the transport that Unix FD passing is enabled for this connection.
+ EnableUnixFDs()
+
+ // Read / send a message, handling things like Unix FDs.
+ ReadMessage() (*Message, error)
+ SendMessage(*Message) error
+}
+
+var (
+ transports = make(map[string]func(string) (transport, error))
+)
+
+func getTransport(address string) (transport, error) {
+ var err error
+ var t transport
+
+ addresses := strings.Split(address, ";")
+ for _, v := range addresses {
+ i := strings.IndexRune(v, ':')
+ if i == -1 {
+ err = errors.New("dbus: invalid bus address (no transport)")
+ continue
+ }
+ f := transports[v[:i]]
+ if f == nil {
+ err = errors.New("dbus: invalid bus address (invalid or unsupported transport)")
+ continue
+ }
+ t, err = f(v[i+1:])
+ if err == nil {
+ return t, nil
+ }
+ }
+ return nil, err
+}
+
+// getKey gets a key from a the list of keys. Returns "" on error / not found...
+func getKey(s, key string) string {
+ for _, keyEqualsValue := range strings.Split(s, ",") {
+ keyValue := strings.SplitN(keyEqualsValue, "=", 2)
+ if len(keyValue) == 2 && keyValue[0] == key {
+ return keyValue[1]
+ }
+ }
+ return ""
+}
+
+type outputHandler struct {
+ conn *Conn
+ sendLck sync.Mutex
+ closed struct {
+ isClosed bool
+ lck sync.RWMutex
+ }
+}
+
+func (h *outputHandler) sendAndIfClosed(msg *Message, ifClosed func()) error {
+ h.closed.lck.RLock()
+ defer h.closed.lck.RUnlock()
+ if h.closed.isClosed {
+ if ifClosed != nil {
+ ifClosed()
+ }
+ return nil
+ }
+ h.sendLck.Lock()
+ defer h.sendLck.Unlock()
+ return h.conn.SendMessage(msg)
+}
+
+func (h *outputHandler) close() {
+ h.closed.lck.Lock()
+ defer h.closed.lck.Unlock()
+ h.closed.isClosed = true
+}
+
+type serialGenerator struct {
+ lck sync.Mutex
+ nextSerial uint32
+ serialUsed map[uint32]bool
+}
+
+func newSerialGenerator() *serialGenerator {
+ return &serialGenerator{
+ serialUsed: map[uint32]bool{0: true},
+ nextSerial: 1,
+ }
+}
+
+func (gen *serialGenerator) GetSerial() uint32 {
+ gen.lck.Lock()
+ defer gen.lck.Unlock()
+ n := gen.nextSerial
+ for gen.serialUsed[n] {
+ n++
+ }
+ gen.serialUsed[n] = true
+ gen.nextSerial = n + 1
+ return n
+}
+
+func (gen *serialGenerator) RetireSerial(serial uint32) {
+ gen.lck.Lock()
+ defer gen.lck.Unlock()
+ delete(gen.serialUsed, serial)
+}
+
+type nameTracker struct {
+ lck sync.RWMutex
+ unique string
+ names map[string]struct{}
+}
+
+func newNameTracker() *nameTracker {
+ return &nameTracker{names: map[string]struct{}{}}
+}
+func (tracker *nameTracker) acquireUniqueConnectionName(name string) {
+ tracker.lck.Lock()
+ defer tracker.lck.Unlock()
+ tracker.unique = name
+}
+func (tracker *nameTracker) acquireName(name string) {
+ tracker.lck.Lock()
+ defer tracker.lck.Unlock()
+ tracker.names[name] = struct{}{}
+}
+func (tracker *nameTracker) loseName(name string) {
+ tracker.lck.Lock()
+ defer tracker.lck.Unlock()
+ delete(tracker.names, name)
+}
+
+func (tracker *nameTracker) uniqueNameIsKnown() bool {
+ tracker.lck.RLock()
+ defer tracker.lck.RUnlock()
+ return tracker.unique != ""
+}
+func (tracker *nameTracker) isKnownName(name string) bool {
+ tracker.lck.RLock()
+ defer tracker.lck.RUnlock()
+ _, ok := tracker.names[name]
+ return ok || name == tracker.unique
+}
+func (tracker *nameTracker) listKnownNames() []string {
+ tracker.lck.RLock()
+ defer tracker.lck.RUnlock()
+ out := make([]string, 0, len(tracker.names)+1)
+ out = append(out, tracker.unique)
+ for k := range tracker.names {
+ out = append(out, k)
+ }
+ return out
+}
+
+type callTracker struct {
+ calls map[uint32]*Call
+ lck sync.RWMutex
+}
+
+func newCallTracker() *callTracker {
+ return &callTracker{calls: map[uint32]*Call{}}
+}
+
+func (tracker *callTracker) track(sn uint32, call *Call) {
+ tracker.lck.Lock()
+ tracker.calls[sn] = call
+ tracker.lck.Unlock()
+}
+
+func (tracker *callTracker) handleReply(sequence Sequence, msg *Message) uint32 {
+ serial := msg.Headers[FieldReplySerial].value.(uint32)
+ tracker.lck.RLock()
+ _, ok := tracker.calls[serial]
+ tracker.lck.RUnlock()
+ if ok {
+ tracker.finalizeWithBody(serial, sequence, msg.Body)
+ }
+ return serial
+}
+
+func (tracker *callTracker) handleDBusError(sequence Sequence, msg *Message) uint32 {
+ serial := msg.Headers[FieldReplySerial].value.(uint32)
+ tracker.lck.RLock()
+ _, ok := tracker.calls[serial]
+ tracker.lck.RUnlock()
+ if ok {
+ name, _ := msg.Headers[FieldErrorName].value.(string)
+ tracker.finalizeWithError(serial, sequence, Error{name, msg.Body})
+ }
+ return serial
+}
+
+func (tracker *callTracker) handleSendError(msg *Message, err error) {
+ if err == nil {
+ return
+ }
+ tracker.lck.RLock()
+ _, ok := tracker.calls[msg.serial]
+ tracker.lck.RUnlock()
+ if ok {
+ tracker.finalizeWithError(msg.serial, NoSequence, err)
+ }
+}
+
+// finalize was the only func that did not strobe Done
+func (tracker *callTracker) finalize(sn uint32) {
+ tracker.lck.Lock()
+ defer tracker.lck.Unlock()
+ c, ok := tracker.calls[sn]
+ if ok {
+ delete(tracker.calls, sn)
+ c.ContextCancel()
+ }
+}
+
+func (tracker *callTracker) finalizeWithBody(sn uint32, sequence Sequence, body []interface{}) {
+ tracker.lck.Lock()
+ c, ok := tracker.calls[sn]
+ if ok {
+ delete(tracker.calls, sn)
+ }
+ tracker.lck.Unlock()
+ if ok {
+ c.Body = body
+ c.ResponseSequence = sequence
+ c.done()
+ }
+}
+
+func (tracker *callTracker) finalizeWithError(sn uint32, sequence Sequence, err error) {
+ tracker.lck.Lock()
+ c, ok := tracker.calls[sn]
+ if ok {
+ delete(tracker.calls, sn)
+ }
+ tracker.lck.Unlock()
+ if ok {
+ c.Err = err
+ c.ResponseSequence = sequence
+ c.done()
+ }
+}
+
+func (tracker *callTracker) finalizeAllWithError(sequenceGen *sequenceGenerator, err error) {
+ tracker.lck.Lock()
+ closedCalls := make([]*Call, 0, len(tracker.calls))
+ for sn := range tracker.calls {
+ closedCalls = append(closedCalls, tracker.calls[sn])
+ }
+ tracker.calls = map[uint32]*Call{}
+ tracker.lck.Unlock()
+ for _, call := range closedCalls {
+ call.Err = err
+ call.ResponseSequence = sequenceGen.next()
+ call.done()
+ }
+}
diff --git a/vendor/github.com/godbus/dbus/v5/conn_darwin.go b/vendor/github.com/godbus/dbus/v5/conn_darwin.go
@@ -0,0 +1,37 @@
+package dbus
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+)
+
+const defaultSystemBusAddress = "unix:path=/opt/local/var/run/dbus/system_bus_socket"
+
+func getSessionBusPlatformAddress() (string, error) {
+ cmd := exec.Command("launchctl", "getenv", "DBUS_LAUNCHD_SESSION_BUS_SOCKET")
+ b, err := cmd.CombinedOutput()
+
+ if err != nil {
+ return "", err
+ }
+
+ if len(b) == 0 {
+ return "", errors.New("dbus: couldn't determine address of session bus")
+ }
+
+ return "unix:path=" + string(b[:len(b)-1]), nil
+}
+
+func getSystemBusPlatformAddress() string {
+ address := os.Getenv("DBUS_LAUNCHD_SESSION_BUS_SOCKET")
+ if address != "" {
+ return fmt.Sprintf("unix:path=%s", address)
+ }
+ return defaultSystemBusAddress
+}
+
+func tryDiscoverDbusSessionBusAddress() string {
+ return ""
+}
diff --git a/vendor/github.com/godbus/dbus/v5/conn_other.go b/vendor/github.com/godbus/dbus/v5/conn_other.go
@@ -0,0 +1,93 @@
+// +build !darwin
+
+package dbus
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "os/user"
+ "path"
+ "strings"
+)
+
+var execCommand = exec.Command
+
+func getSessionBusPlatformAddress() (string, error) {
+ cmd := execCommand("dbus-launch")
+ b, err := cmd.CombinedOutput()
+
+ if err != nil {
+ return "", err
+ }
+
+ i := bytes.IndexByte(b, '=')
+ j := bytes.IndexByte(b, '\n')
+
+ if i == -1 || j == -1 || i > j {
+ return "", errors.New("dbus: couldn't determine address of session bus")
+ }
+
+ env, addr := string(b[0:i]), string(b[i+1:j])
+ os.Setenv(env, addr)
+
+ return addr, nil
+}
+
+// tryDiscoverDbusSessionBusAddress tries to discover an existing dbus session
+// and return the value of its DBUS_SESSION_BUS_ADDRESS.
+// It tries different techniques employed by different operating systems,
+// returning the first valid address it finds, or an empty string.
+//
+// * /run/user/<uid>/bus if this exists, it *is* the bus socket. present on
+// Ubuntu 18.04
+// * /run/user/<uid>/dbus-session: if this exists, it can be parsed for the bus
+// address. present on Ubuntu 16.04
+//
+// See https://dbus.freedesktop.org/doc/dbus-launch.1.html
+func tryDiscoverDbusSessionBusAddress() string {
+ if runtimeDirectory, err := getRuntimeDirectory(); err == nil {
+
+ if runUserBusFile := path.Join(runtimeDirectory, "bus"); fileExists(runUserBusFile) {
+ // if /run/user/<uid>/bus exists, that file itself
+ // *is* the unix socket, so return its path
+ return fmt.Sprintf("unix:path=%s", runUserBusFile)
+ }
+ if runUserSessionDbusFile := path.Join(runtimeDirectory, "dbus-session"); fileExists(runUserSessionDbusFile) {
+ // if /run/user/<uid>/dbus-session exists, it's a
+ // text file // containing the address of the socket, e.g.:
+ // DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-E1c73yNqrG
+
+ if f, err := ioutil.ReadFile(runUserSessionDbusFile); err == nil {
+ fileContent := string(f)
+
+ prefix := "DBUS_SESSION_BUS_ADDRESS="
+
+ if strings.HasPrefix(fileContent, prefix) {
+ address := strings.TrimRight(strings.TrimPrefix(fileContent, prefix), "\n\r")
+ return address
+ }
+ }
+ }
+ }
+ return ""
+}
+
+func getRuntimeDirectory() (string, error) {
+ if currentUser, err := user.Current(); err != nil {
+ return "", err
+ } else {
+ return fmt.Sprintf("/run/user/%s", currentUser.Uid), nil
+ }
+}
+
+func fileExists(filename string) bool {
+ if _, err := os.Stat(filename); !os.IsNotExist(err) {
+ return true
+ } else {
+ return false
+ }
+}
diff --git a/vendor/github.com/godbus/dbus/v5/conn_unix.go b/vendor/github.com/godbus/dbus/v5/conn_unix.go
@@ -0,0 +1,17 @@
+//+build !windows,!solaris,!darwin
+
+package dbus
+
+import (
+ "os"
+)
+
+const defaultSystemBusAddress = "unix:path=/var/run/dbus/system_bus_socket"
+
+func getSystemBusPlatformAddress() string {
+ address := os.Getenv("DBUS_SYSTEM_BUS_ADDRESS")
+ if address != "" {
+ return address
+ }
+ return defaultSystemBusAddress
+}
diff --git a/vendor/github.com/godbus/dbus/v5/conn_windows.go b/vendor/github.com/godbus/dbus/v5/conn_windows.go
@@ -0,0 +1,15 @@
+//+build windows
+
+package dbus
+
+import "os"
+
+const defaultSystemBusAddress = "tcp:host=127.0.0.1,port=12434"
+
+func getSystemBusPlatformAddress() string {
+ address := os.Getenv("DBUS_SYSTEM_BUS_ADDRESS")
+ if address != "" {
+ return address
+ }
+ return defaultSystemBusAddress
+}
diff --git a/vendor/github.com/godbus/dbus/v5/dbus.go b/vendor/github.com/godbus/dbus/v5/dbus.go
@@ -0,0 +1,432 @@
+package dbus
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "strings"
+)
+
+var (
+ byteType = reflect.TypeOf(byte(0))
+ boolType = reflect.TypeOf(false)
+ uint8Type = reflect.TypeOf(uint8(0))
+ int16Type = reflect.TypeOf(int16(0))
+ uint16Type = reflect.TypeOf(uint16(0))
+ intType = reflect.TypeOf(int(0))
+ uintType = reflect.TypeOf(uint(0))
+ int32Type = reflect.TypeOf(int32(0))
+ uint32Type = reflect.TypeOf(uint32(0))
+ int64Type = reflect.TypeOf(int64(0))
+ uint64Type = reflect.TypeOf(uint64(0))
+ float64Type = reflect.TypeOf(float64(0))
+ stringType = reflect.TypeOf("")
+ signatureType = reflect.TypeOf(Signature{""})
+ objectPathType = reflect.TypeOf(ObjectPath(""))
+ variantType = reflect.TypeOf(Variant{Signature{""}, nil})
+ interfacesType = reflect.TypeOf([]interface{}{})
+ interfaceType = reflect.TypeOf((*interface{})(nil)).Elem()
+ unixFDType = reflect.TypeOf(UnixFD(0))
+ unixFDIndexType = reflect.TypeOf(UnixFDIndex(0))
+ errType = reflect.TypeOf((*error)(nil)).Elem()
+)
+
+// An InvalidTypeError signals that a value which cannot be represented in the
+// D-Bus wire format was passed to a function.
+type InvalidTypeError struct {
+ Type reflect.Type
+}
+
+func (e InvalidTypeError) Error() string {
+ return "dbus: invalid type " + e.Type.String()
+}
+
+// Store copies the values contained in src to dest, which must be a slice of
+// pointers. It converts slices of interfaces from src to corresponding structs
+// in dest. An error is returned if the lengths of src and dest or the types of
+// their elements don't match.
+func Store(src []interface{}, dest ...interface{}) error {
+ if len(src) != len(dest) {
+ return errors.New("dbus.Store: length mismatch")
+ }
+
+ for i := range src {
+ if err := storeInterfaces(src[i], dest[i]); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func storeInterfaces(src, dest interface{}) error {
+ return store(reflect.ValueOf(dest), reflect.ValueOf(src))
+}
+
+func store(dest, src reflect.Value) error {
+ if dest.Kind() == reflect.Ptr {
+ if dest.IsNil() {
+ dest.Set(reflect.New(dest.Type().Elem()))
+ }
+ return store(dest.Elem(), src)
+ }
+ switch src.Kind() {
+ case reflect.Slice:
+ return storeSlice(dest, src)
+ case reflect.Map:
+ return storeMap(dest, src)
+ default:
+ return storeBase(dest, src)
+ }
+}
+
+func storeBase(dest, src reflect.Value) error {
+ return setDest(dest, src)
+}
+
+func setDest(dest, src reflect.Value) error {
+ if !isVariant(src.Type()) && isVariant(dest.Type()) {
+ //special conversion for dbus.Variant
+ dest.Set(reflect.ValueOf(MakeVariant(src.Interface())))
+ return nil
+ }
+ if isVariant(src.Type()) && !isVariant(dest.Type()) {
+ src = getVariantValue(src)
+ return store(dest, src)
+ }
+ if !src.Type().ConvertibleTo(dest.Type()) {
+ return fmt.Errorf(
+ "dbus.Store: type mismatch: cannot convert %s to %s",
+ src.Type(), dest.Type())
+ }
+ dest.Set(src.Convert(dest.Type()))
+ return nil
+}
+
+func kindsAreCompatible(dest, src reflect.Type) bool {
+ switch {
+ case isVariant(dest):
+ return true
+ case dest.Kind() == reflect.Interface:
+ return true
+ default:
+ return dest.Kind() == src.Kind()
+ }
+}
+
+func isConvertibleTo(dest, src reflect.Type) bool {
+ switch {
+ case isVariant(dest):
+ return true
+ case dest.Kind() == reflect.Interface:
+ return true
+ case dest.Kind() == reflect.Slice:
+ return src.Kind() == reflect.Slice &&
+ isConvertibleTo(dest.Elem(), src.Elem())
+ case dest.Kind() == reflect.Struct:
+ return src == interfacesType
+ default:
+ return src.ConvertibleTo(dest)
+ }
+}
+
+func storeMap(dest, src reflect.Value) error {
+ switch {
+ case !kindsAreCompatible(dest.Type(), src.Type()):
+ return fmt.Errorf(
+ "dbus.Store: type mismatch: "+
+ "map: cannot store a value of %s into %s",
+ src.Type(), dest.Type())
+ case isVariant(dest.Type()):
+ return storeMapIntoVariant(dest, src)
+ case dest.Kind() == reflect.Interface:
+ return storeMapIntoInterface(dest, src)
+ case isConvertibleTo(dest.Type().Key(), src.Type().Key()) &&
+ isConvertibleTo(dest.Type().Elem(), src.Type().Elem()):
+ return storeMapIntoMap(dest, src)
+ default:
+ return fmt.Errorf(
+ "dbus.Store: type mismatch: "+
+ "map: cannot convert a value of %s into %s",
+ src.Type(), dest.Type())
+ }
+}
+
+func storeMapIntoVariant(dest, src reflect.Value) error {
+ dv := reflect.MakeMap(src.Type())
+ err := store(dv, src)
+ if err != nil {
+ return err
+ }
+ return storeBase(dest, dv)
+}
+
+func storeMapIntoInterface(dest, src reflect.Value) error {
+ var dv reflect.Value
+ if isVariant(src.Type().Elem()) {
+ //Convert variants to interface{} recursively when converting
+ //to interface{}
+ dv = reflect.MakeMap(
+ reflect.MapOf(src.Type().Key(), interfaceType))
+ } else {
+ dv = reflect.MakeMap(src.Type())
+ }
+ err := store(dv, src)
+ if err != nil {
+ return err
+ }
+ return storeBase(dest, dv)
+}
+
+func storeMapIntoMap(dest, src reflect.Value) error {
+ if dest.IsNil() {
+ dest.Set(reflect.MakeMap(dest.Type()))
+ }
+ keys := src.MapKeys()
+ for _, key := range keys {
+ dkey := key.Convert(dest.Type().Key())
+ dval := reflect.New(dest.Type().Elem()).Elem()
+ err := store(dval, getVariantValue(src.MapIndex(key)))
+ if err != nil {
+ return err
+ }
+ dest.SetMapIndex(dkey, dval)
+ }
+ return nil
+}
+
+func storeSlice(dest, src reflect.Value) error {
+ switch {
+ case src.Type() == interfacesType && dest.Kind() == reflect.Struct:
+ //The decoder always decodes structs as slices of interface{}
+ return storeStruct(dest, src)
+ case !kindsAreCompatible(dest.Type(), src.Type()):
+ return fmt.Errorf(
+ "dbus.Store: type mismatch: "+
+ "slice: cannot store a value of %s into %s",
+ src.Type(), dest.Type())
+ case isVariant(dest.Type()):
+ return storeSliceIntoVariant(dest, src)
+ case dest.Kind() == reflect.Interface:
+ return storeSliceIntoInterface(dest, src)
+ case isConvertibleTo(dest.Type().Elem(), src.Type().Elem()):
+ return storeSliceIntoSlice(dest, src)
+ default:
+ return fmt.Errorf(
+ "dbus.Store: type mismatch: "+
+ "slice: cannot convert a value of %s into %s",
+ src.Type(), dest.Type())
+ }
+}
+
+func storeStruct(dest, src reflect.Value) error {
+ if isVariant(dest.Type()) {
+ return storeBase(dest, src)
+ }
+ dval := make([]interface{}, 0, dest.NumField())
+ dtype := dest.Type()
+ for i := 0; i < dest.NumField(); i++ {
+ field := dest.Field(i)
+ ftype := dtype.Field(i)
+ if ftype.PkgPath != "" {
+ continue
+ }
+ if ftype.Tag.Get("dbus") == "-" {
+ continue
+ }
+ dval = append(dval, field.Addr().Interface())
+ }
+ if src.Len() != len(dval) {
+ return fmt.Errorf(
+ "dbus.Store: type mismatch: "+
+ "destination struct does not have "+
+ "enough fields need: %d have: %d",
+ src.Len(), len(dval))
+ }
+ return Store(src.Interface().([]interface{}), dval...)
+}
+
+func storeSliceIntoVariant(dest, src reflect.Value) error {
+ dv := reflect.MakeSlice(src.Type(), src.Len(), src.Cap())
+ err := store(dv, src)
+ if err != nil {
+ return err
+ }
+ return storeBase(dest, dv)
+}
+
+func storeSliceIntoInterface(dest, src reflect.Value) error {
+ var dv reflect.Value
+ if isVariant(src.Type().Elem()) {
+ //Convert variants to interface{} recursively when converting
+ //to interface{}
+ dv = reflect.MakeSlice(reflect.SliceOf(interfaceType),
+ src.Len(), src.Cap())
+ } else {
+ dv = reflect.MakeSlice(src.Type(), src.Len(), src.Cap())
+ }
+ err := store(dv, src)
+ if err != nil {
+ return err
+ }
+ return storeBase(dest, dv)
+}
+
+func storeSliceIntoSlice(dest, src reflect.Value) error {
+ if dest.IsNil() || dest.Len() < src.Len() {
+ dest.Set(reflect.MakeSlice(dest.Type(), src.Len(), src.Cap()))
+ }
+ if dest.Len() != src.Len() {
+ return fmt.Errorf(
+ "dbus.Store: type mismatch: "+
+ "slices are different lengths "+
+ "need: %d have: %d",
+ src.Len(), dest.Len())
+ }
+ for i := 0; i < src.Len(); i++ {
+ err := store(dest.Index(i), getVariantValue(src.Index(i)))
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func getVariantValue(in reflect.Value) reflect.Value {
+ if isVariant(in.Type()) {
+ return reflect.ValueOf(in.Interface().(Variant).Value())
+ }
+ return in
+}
+
+func isVariant(t reflect.Type) bool {
+ return t == variantType
+}
+
+// An ObjectPath is an object path as defined by the D-Bus spec.
+type ObjectPath string
+
+// IsValid returns whether the object path is valid.
+func (o ObjectPath) IsValid() bool {
+ s := string(o)
+ if len(s) == 0 {
+ return false
+ }
+ if s[0] != '/' {
+ return false
+ }
+ if s[len(s)-1] == '/' && len(s) != 1 {
+ return false
+ }
+ // probably not used, but technically possible
+ if s == "/" {
+ return true
+ }
+ split := strings.Split(s[1:], "/")
+ for _, v := range split {
+ if len(v) == 0 {
+ return false
+ }
+ for _, c := range v {
+ if !isMemberChar(c) {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// A UnixFD is a Unix file descriptor sent over the wire. See the package-level
+// documentation for more information about Unix file descriptor passsing.
+type UnixFD int32
+
+// A UnixFDIndex is the representation of a Unix file descriptor in a message.
+type UnixFDIndex uint32
+
+// alignment returns the alignment of values of type t.
+func alignment(t reflect.Type) int {
+ switch t {
+ case variantType:
+ return 1
+ case objectPathType:
+ return 4
+ case signatureType:
+ return 1
+ case interfacesType:
+ return 4
+ }
+ switch t.Kind() {
+ case reflect.Uint8:
+ return 1
+ case reflect.Uint16, reflect.Int16:
+ return 2
+ case reflect.Uint, reflect.Int, reflect.Uint32, reflect.Int32, reflect.String, reflect.Array, reflect.Slice, reflect.Map:
+ return 4
+ case reflect.Uint64, reflect.Int64, reflect.Float64, reflect.Struct:
+ return 8
+ case reflect.Ptr:
+ return alignment(t.Elem())
+ }
+ return 1
+}
+
+// isKeyType returns whether t is a valid type for a D-Bus dict.
+func isKeyType(t reflect.Type) bool {
+ switch t.Kind() {
+ case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
+ reflect.Int16, reflect.Int32, reflect.Int64, reflect.Float64,
+ reflect.String, reflect.Uint, reflect.Int:
+
+ return true
+ }
+ return false
+}
+
+// isValidInterface returns whether s is a valid name for an interface.
+func isValidInterface(s string) bool {
+ if len(s) == 0 || len(s) > 255 || s[0] == '.' {
+ return false
+ }
+ elem := strings.Split(s, ".")
+ if len(elem) < 2 {
+ return false
+ }
+ for _, v := range elem {
+ if len(v) == 0 {
+ return false
+ }
+ if v[0] >= '0' && v[0] <= '9' {
+ return false
+ }
+ for _, c := range v {
+ if !isMemberChar(c) {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// isValidMember returns whether s is a valid name for a member.
+func isValidMember(s string) bool {
+ if len(s) == 0 || len(s) > 255 {
+ return false
+ }
+ i := strings.Index(s, ".")
+ if i != -1 {
+ return false
+ }
+ if s[0] >= '0' && s[0] <= '9' {
+ return false
+ }
+ for _, c := range s {
+ if !isMemberChar(c) {
+ return false
+ }
+ }
+ return true
+}
+
+func isMemberChar(c rune) bool {
+ return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
+ (c >= 'a' && c <= 'z') || c == '_'
+}
diff --git a/vendor/github.com/godbus/dbus/v5/decoder.go b/vendor/github.com/godbus/dbus/v5/decoder.go
@@ -0,0 +1,286 @@
+package dbus
+
+import (
+ "encoding/binary"
+ "io"
+ "reflect"
+)
+
+type decoder struct {
+ in io.Reader
+ order binary.ByteOrder
+ pos int
+}
+
+// newDecoder returns a new decoder that reads values from in. The input is
+// expected to be in the given byte order.
+func newDecoder(in io.Reader, order binary.ByteOrder) *decoder {
+ dec := new(decoder)
+ dec.in = in
+ dec.order = order
+ return dec
+}
+
+// align aligns the input to the given boundary and panics on error.
+func (dec *decoder) align(n int) {
+ if dec.pos%n != 0 {
+ newpos := (dec.pos + n - 1) & ^(n - 1)
+ empty := make([]byte, newpos-dec.pos)
+ if _, err := io.ReadFull(dec.in, empty); err != nil {
+ panic(err)
+ }
+ dec.pos = newpos
+ }
+}
+
+// Calls binary.Read(dec.in, dec.order, v) and panics on read errors.
+func (dec *decoder) binread(v interface{}) {
+ if err := binary.Read(dec.in, dec.order, v); err != nil {
+ panic(err)
+ }
+}
+
+func (dec *decoder) Decode(sig Signature) (vs []interface{}, err error) {
+ defer func() {
+ var ok bool
+ v := recover()
+ if err, ok = v.(error); ok {
+ if err == io.EOF || err == io.ErrUnexpectedEOF {
+ err = FormatError("unexpected EOF")
+ }
+ }
+ }()
+ vs = make([]interface{}, 0)
+ s := sig.str
+ for s != "" {
+ err, rem := validSingle(s, 0)
+ if err != nil {
+ return nil, err
+ }
+ v := dec.decode(s[:len(s)-len(rem)], 0)
+ vs = append(vs, v)
+ s = rem
+ }
+ return vs, nil
+}
+
+func (dec *decoder) decode(s string, depth int) interface{} {
+ dec.align(alignment(typeFor(s)))
+ switch s[0] {
+ case 'y':
+ var b [1]byte
+ if _, err := dec.in.Read(b[:]); err != nil {
+ panic(err)
+ }
+ dec.pos++
+ return b[0]
+ case 'b':
+ i := dec.decode("u", depth).(uint32)
+ switch {
+ case i == 0:
+ return false
+ case i == 1:
+ return true
+ default:
+ panic(FormatError("invalid value for boolean"))
+ }
+ case 'n':
+ var i int16
+ dec.binread(&i)
+ dec.pos += 2
+ return i
+ case 'i':
+ var i int32
+ dec.binread(&i)
+ dec.pos += 4
+ return i
+ case 'x':
+ var i int64
+ dec.binread(&i)
+ dec.pos += 8
+ return i
+ case 'q':
+ var i uint16
+ dec.binread(&i)
+ dec.pos += 2
+ return i
+ case 'u':
+ var i uint32
+ dec.binread(&i)
+ dec.pos += 4
+ return i
+ case 't':
+ var i uint64
+ dec.binread(&i)
+ dec.pos += 8
+ return i
+ case 'd':
+ var f float64
+ dec.binread(&f)
+ dec.pos += 8
+ return f
+ case 's':
+ length := dec.decode("u", depth).(uint32)
+ b := make([]byte, int(length)+1)
+ if _, err := io.ReadFull(dec.in, b); err != nil {
+ panic(err)
+ }
+ dec.pos += int(length) + 1
+ return string(b[:len(b)-1])
+ case 'o':
+ return ObjectPath(dec.decode("s", depth).(string))
+ case 'g':
+ length := dec.decode("y", depth).(byte)
+ b := make([]byte, int(length)+1)
+ if _, err := io.ReadFull(dec.in, b); err != nil {
+ panic(err)
+ }
+ dec.pos += int(length) + 1
+ sig, err := ParseSignature(string(b[:len(b)-1]))
+ if err != nil {
+ panic(err)
+ }
+ return sig
+ case 'v':
+ if depth >= 64 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ var variant Variant
+ sig := dec.decode("g", depth).(Signature)
+ if len(sig.str) == 0 {
+ panic(FormatError("variant signature is empty"))
+ }
+ err, rem := validSingle(sig.str, 0)
+ if err != nil {
+ panic(err)
+ }
+ if rem != "" {
+ panic(FormatError("variant signature has multiple types"))
+ }
+ variant.sig = sig
+ variant.value = dec.decode(sig.str, depth+1)
+ return variant
+ case 'h':
+ return UnixFDIndex(dec.decode("u", depth).(uint32))
+ case 'a':
+ if len(s) > 1 && s[1] == '{' {
+ ksig := s[2:3]
+ vsig := s[3 : len(s)-1]
+ v := reflect.MakeMap(reflect.MapOf(typeFor(ksig), typeFor(vsig)))
+ if depth >= 63 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ length := dec.decode("u", depth).(uint32)
+ // Even for empty maps, the correct padding must be included
+ dec.align(8)
+ spos := dec.pos
+ for dec.pos < spos+int(length) {
+ dec.align(8)
+ if !isKeyType(v.Type().Key()) {
+ panic(InvalidTypeError{v.Type()})
+ }
+ kv := dec.decode(ksig, depth+2)
+ vv := dec.decode(vsig, depth+2)
+ v.SetMapIndex(reflect.ValueOf(kv), reflect.ValueOf(vv))
+ }
+ return v.Interface()
+ }
+ if depth >= 64 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ sig := s[1:]
+ length := dec.decode("u", depth).(uint32)
+ // capacity can be determined only for fixed-size element types
+ var capacity int
+ if s := sigByteSize(sig); s != 0 {
+ capacity = int(length) / s
+ }
+ v := reflect.MakeSlice(reflect.SliceOf(typeFor(sig)), 0, capacity)
+ // Even for empty arrays, the correct padding must be included
+ align := alignment(typeFor(s[1:]))
+ if len(s) > 1 && s[1] == '(' {
+ //Special case for arrays of structs
+ //structs decode as a slice of interface{} values
+ //but the dbus alignment does not match this
+ align = 8
+ }
+ dec.align(align)
+ spos := dec.pos
+ for dec.pos < spos+int(length) {
+ ev := dec.decode(s[1:], depth+1)
+ v = reflect.Append(v, reflect.ValueOf(ev))
+ }
+ return v.Interface()
+ case '(':
+ if depth >= 64 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ dec.align(8)
+ v := make([]interface{}, 0)
+ s = s[1 : len(s)-1]
+ for s != "" {
+ err, rem := validSingle(s, 0)
+ if err != nil {
+ panic(err)
+ }
+ ev := dec.decode(s[:len(s)-len(rem)], depth+1)
+ v = append(v, ev)
+ s = rem
+ }
+ return v
+ default:
+ panic(SignatureError{Sig: s})
+ }
+}
+
+// sigByteSize tries to calculates size of the given signature in bytes.
+//
+// It returns zero when it can't, for example when it contains non-fixed size
+// types such as strings, maps and arrays that require reading of the transmitted
+// data, for that we would need to implement the unread method for Decoder first.
+func sigByteSize(sig string) int {
+ var total int
+ for offset := 0; offset < len(sig); {
+ switch sig[offset] {
+ case 'y':
+ total += 1
+ offset += 1
+ case 'n', 'q':
+ total += 2
+ offset += 1
+ case 'b', 'i', 'u', 'h':
+ total += 4
+ offset += 1
+ case 'x', 't', 'd':
+ total += 8
+ offset += 1
+ case '(':
+ i := 1
+ depth := 1
+ for i < len(sig[offset:]) && depth != 0 {
+ if sig[offset+i] == '(' {
+ depth++
+ } else if sig[offset+i] == ')' {
+ depth--
+ }
+ i++
+ }
+ s := sigByteSize(sig[offset+1 : offset+i-1])
+ if s == 0 {
+ return 0
+ }
+ total += s
+ offset += i
+ default:
+ return 0
+ }
+ }
+ return total
+}
+
+// A FormatError is an error in the wire format.
+type FormatError string
+
+func (e FormatError) Error() string {
+ return "dbus: wire format error: " + string(e)
+}
diff --git a/vendor/github.com/godbus/dbus/v5/default_handler.go b/vendor/github.com/godbus/dbus/v5/default_handler.go
@@ -0,0 +1,342 @@
+package dbus
+
+import (
+ "bytes"
+ "reflect"
+ "strings"
+ "sync"
+)
+
+func newIntrospectIntf(h *defaultHandler) *exportedIntf {
+ methods := make(map[string]Method)
+ methods["Introspect"] = exportedMethod{
+ reflect.ValueOf(func(msg Message) (string, *Error) {
+ path := msg.Headers[FieldPath].value.(ObjectPath)
+ return h.introspectPath(path), nil
+ }),
+ }
+ return newExportedIntf(methods, true)
+}
+
+//NewDefaultHandler returns an instance of the default
+//call handler. This is useful if you want to implement only
+//one of the two handlers but not both.
+//
+// Deprecated: this is the default value, don't use it, it will be unexported.
+func NewDefaultHandler() *defaultHandler {
+ h := &defaultHandler{
+ objects: make(map[ObjectPath]*exportedObj),
+ defaultIntf: make(map[string]*exportedIntf),
+ }
+ h.defaultIntf["org.freedesktop.DBus.Introspectable"] = newIntrospectIntf(h)
+ return h
+}
+
+type defaultHandler struct {
+ sync.RWMutex
+ objects map[ObjectPath]*exportedObj
+ defaultIntf map[string]*exportedIntf
+}
+
+func (h *defaultHandler) PathExists(path ObjectPath) bool {
+ _, ok := h.objects[path]
+ return ok
+}
+
+func (h *defaultHandler) introspectPath(path ObjectPath) string {
+ subpath := make(map[string]struct{})
+ var xml bytes.Buffer
+ xml.WriteString("<node>")
+ for obj := range h.objects {
+ p := string(path)
+ if p != "/" {
+ p += "/"
+ }
+ if strings.HasPrefix(string(obj), p) {
+ node_name := strings.Split(string(obj[len(p):]), "/")[0]
+ subpath[node_name] = struct{}{}
+ }
+ }
+ for s := range subpath {
+ xml.WriteString("\n\t<node name=\"" + s + "\"/>")
+ }
+ xml.WriteString("\n</node>")
+ return xml.String()
+}
+
+func (h *defaultHandler) LookupObject(path ObjectPath) (ServerObject, bool) {
+ h.RLock()
+ defer h.RUnlock()
+ object, ok := h.objects[path]
+ if ok {
+ return object, ok
+ }
+
+ // If an object wasn't found for this exact path,
+ // look for a matching subtree registration
+ subtreeObject := newExportedObject()
+ path = path[:strings.LastIndex(string(path), "/")]
+ for len(path) > 0 {
+ object, ok = h.objects[path]
+ if ok {
+ for name, iface := range object.interfaces {
+ // Only include this handler if it registered for the subtree
+ if iface.isFallbackInterface() {
+ subtreeObject.interfaces[name] = iface
+ }
+ }
+ break
+ }
+
+ path = path[:strings.LastIndex(string(path), "/")]
+ }
+
+ for name, intf := range h.defaultIntf {
+ if _, exists := subtreeObject.interfaces[name]; exists {
+ continue
+ }
+ subtreeObject.interfaces[name] = intf
+ }
+
+ return subtreeObject, true
+}
+
+func (h *defaultHandler) AddObject(path ObjectPath, object *exportedObj) {
+ h.Lock()
+ h.objects[path] = object
+ h.Unlock()
+}
+
+func (h *defaultHandler) DeleteObject(path ObjectPath) {
+ h.Lock()
+ delete(h.objects, path)
+ h.Unlock()
+}
+
+type exportedMethod struct {
+ reflect.Value
+}
+
+func (m exportedMethod) Call(args ...interface{}) ([]interface{}, error) {
+ t := m.Type()
+
+ params := make([]reflect.Value, len(args))
+ for i := 0; i < len(args); i++ {
+ params[i] = reflect.ValueOf(args[i]).Elem()
+ }
+
+ ret := m.Value.Call(params)
+ var err error
+ nilErr := false // The reflection will find almost-nils, let's only pass back clean ones!
+ if t.NumOut() > 0 {
+ if e, ok := ret[t.NumOut()-1].Interface().(*Error); ok { // godbus *Error
+ nilErr = ret[t.NumOut()-1].IsNil()
+ ret = ret[:t.NumOut()-1]
+ err = e
+ } else if ret[t.NumOut()-1].Type().Implements(errType) { // Go error
+ i := ret[t.NumOut()-1].Interface()
+ if i == nil {
+ nilErr = ret[t.NumOut()-1].IsNil()
+ } else {
+ err = i.(error)
+ }
+ ret = ret[:t.NumOut()-1]
+ }
+ }
+ out := make([]interface{}, len(ret))
+ for i, val := range ret {
+ out[i] = val.Interface()
+ }
+ if nilErr || err == nil {
+ //concrete type to interface nil is a special case
+ return out, nil
+ }
+ return out, err
+}
+
+func (m exportedMethod) NumArguments() int {
+ return m.Value.Type().NumIn()
+}
+
+func (m exportedMethod) ArgumentValue(i int) interface{} {
+ return reflect.Zero(m.Type().In(i)).Interface()
+}
+
+func (m exportedMethod) NumReturns() int {
+ return m.Value.Type().NumOut()
+}
+
+func (m exportedMethod) ReturnValue(i int) interface{} {
+ return reflect.Zero(m.Type().Out(i)).Interface()
+}
+
+func newExportedObject() *exportedObj {
+ return &exportedObj{
+ interfaces: make(map[string]*exportedIntf),
+ }
+}
+
+type exportedObj struct {
+ mu sync.RWMutex
+ interfaces map[string]*exportedIntf
+}
+
+func (obj *exportedObj) LookupInterface(name string) (Interface, bool) {
+ if name == "" {
+ return obj, true
+ }
+ obj.mu.RLock()
+ defer obj.mu.RUnlock()
+ intf, exists := obj.interfaces[name]
+ return intf, exists
+}
+
+func (obj *exportedObj) AddInterface(name string, iface *exportedIntf) {
+ obj.mu.Lock()
+ defer obj.mu.Unlock()
+ obj.interfaces[name] = iface
+}
+
+func (obj *exportedObj) DeleteInterface(name string) {
+ obj.mu.Lock()
+ defer obj.mu.Unlock()
+ delete(obj.interfaces, name)
+}
+
+func (obj *exportedObj) LookupMethod(name string) (Method, bool) {
+ obj.mu.RLock()
+ defer obj.mu.RUnlock()
+ for _, intf := range obj.interfaces {
+ method, exists := intf.LookupMethod(name)
+ if exists {
+ return method, exists
+ }
+ }
+ return nil, false
+}
+
+func (obj *exportedObj) isFallbackInterface() bool {
+ return false
+}
+
+func newExportedIntf(methods map[string]Method, includeSubtree bool) *exportedIntf {
+ return &exportedIntf{
+ methods: methods,
+ includeSubtree: includeSubtree,
+ }
+}
+
+type exportedIntf struct {
+ methods map[string]Method
+
+ // Whether or not this export is for the entire subtree
+ includeSubtree bool
+}
+
+func (obj *exportedIntf) LookupMethod(name string) (Method, bool) {
+ out, exists := obj.methods[name]
+ return out, exists
+}
+
+func (obj *exportedIntf) isFallbackInterface() bool {
+ return obj.includeSubtree
+}
+
+//NewDefaultSignalHandler returns an instance of the default
+//signal handler. This is useful if you want to implement only
+//one of the two handlers but not both.
+//
+// Deprecated: this is the default value, don't use it, it will be unexported.
+func NewDefaultSignalHandler() *defaultSignalHandler {
+ return &defaultSignalHandler{}
+}
+
+type defaultSignalHandler struct {
+ mu sync.RWMutex
+ closed bool
+ signals []*signalChannelData
+}
+
+func (sh *defaultSignalHandler) DeliverSignal(intf, name string, signal *Signal) {
+ sh.mu.RLock()
+ defer sh.mu.RUnlock()
+ if sh.closed {
+ return
+ }
+ for _, scd := range sh.signals {
+ scd.deliver(signal)
+ }
+}
+
+func (sh *defaultSignalHandler) Terminate() {
+ sh.mu.Lock()
+ defer sh.mu.Unlock()
+ if sh.closed {
+ return
+ }
+
+ for _, scd := range sh.signals {
+ scd.close()
+ close(scd.ch)
+ }
+ sh.closed = true
+ sh.signals = nil
+}
+
+func (sh *defaultSignalHandler) AddSignal(ch chan<- *Signal) {
+ sh.mu.Lock()
+ defer sh.mu.Unlock()
+ if sh.closed {
+ return
+ }
+ sh.signals = append(sh.signals, &signalChannelData{
+ ch: ch,
+ done: make(chan struct{}),
+ })
+}
+
+func (sh *defaultSignalHandler) RemoveSignal(ch chan<- *Signal) {
+ sh.mu.Lock()
+ defer sh.mu.Unlock()
+ if sh.closed {
+ return
+ }
+ for i := len(sh.signals) - 1; i >= 0; i-- {
+ if ch == sh.signals[i].ch {
+ sh.signals[i].close()
+ copy(sh.signals[i:], sh.signals[i+1:])
+ sh.signals[len(sh.signals)-1] = nil
+ sh.signals = sh.signals[:len(sh.signals)-1]
+ }
+ }
+}
+
+type signalChannelData struct {
+ wg sync.WaitGroup
+ ch chan<- *Signal
+ done chan struct{}
+}
+
+func (scd *signalChannelData) deliver(signal *Signal) {
+ select {
+ case scd.ch <- signal:
+ case <-scd.done:
+ return
+ default:
+ scd.wg.Add(1)
+ go scd.deferredDeliver(signal)
+ }
+}
+
+func (scd *signalChannelData) deferredDeliver(signal *Signal) {
+ select {
+ case scd.ch <- signal:
+ case <-scd.done:
+ }
+ scd.wg.Done()
+}
+
+func (scd *signalChannelData) close() {
+ close(scd.done)
+ scd.wg.Wait() // wait until all spawned goroutines return
+}
diff --git a/vendor/github.com/godbus/dbus/v5/doc.go b/vendor/github.com/godbus/dbus/v5/doc.go
@@ -0,0 +1,69 @@
+/*
+Package dbus implements bindings to the D-Bus message bus system.
+
+To use the message bus API, you first need to connect to a bus (usually the
+session or system bus). The acquired connection then can be used to call methods
+on remote objects and emit or receive signals. Using the Export method, you can
+arrange D-Bus methods calls to be directly translated to method calls on a Go
+value.
+
+Conversion Rules
+
+For outgoing messages, Go types are automatically converted to the
+corresponding D-Bus types. The following types are directly encoded as their
+respective D-Bus equivalents:
+
+ Go type | D-Bus type
+ ------------+-----------
+ byte | BYTE
+ bool | BOOLEAN
+ int16 | INT16
+ uint16 | UINT16
+ int | INT32
+ uint | UINT32
+ int32 | INT32
+ uint32 | UINT32
+ int64 | INT64
+ uint64 | UINT64
+ float64 | DOUBLE
+ string | STRING
+ ObjectPath | OBJECT_PATH
+ Signature | SIGNATURE
+ Variant | VARIANT
+ interface{} | VARIANT
+ UnixFDIndex | UNIX_FD
+
+Slices and arrays encode as ARRAYs of their element type.
+
+Maps encode as DICTs, provided that their key type can be used as a key for
+a DICT.
+
+Structs other than Variant and Signature encode as a STRUCT containing their
+exported fields. Fields whose tags contain `dbus:"-"` and unexported fields will
+be skipped.
+
+Pointers encode as the value they're pointed to.
+
+Types convertible to one of the base types above will be mapped as the
+base type.
+
+Trying to encode any other type or a slice, map or struct containing an
+unsupported type will result in an InvalidTypeError.
+
+For incoming messages, the inverse of these rules are used, with the exception
+of STRUCTs. Incoming STRUCTS are represented as a slice of empty interfaces
+containing the struct fields in the correct order. The Store function can be
+used to convert such values to Go structs.
+
+Unix FD passing
+
+Handling Unix file descriptors deserves special mention. To use them, you should
+first check that they are supported on a connection by calling SupportsUnixFDs.
+If it returns true, all method of Connection will translate messages containing
+UnixFD's to messages that are accompanied by the given file descriptors with the
+UnixFD values being substituted by the correct indices. Similarly, the indices
+of incoming messages are automatically resolved. It shouldn't be necessary to use
+UnixFDIndex.
+
+*/
+package dbus
diff --git a/vendor/github.com/godbus/dbus/v5/encoder.go b/vendor/github.com/godbus/dbus/v5/encoder.go
@@ -0,0 +1,210 @@
+package dbus
+
+import (
+ "bytes"
+ "encoding/binary"
+ "io"
+ "reflect"
+)
+
+// An encoder encodes values to the D-Bus wire format.
+type encoder struct {
+ out io.Writer
+ order binary.ByteOrder
+ pos int
+}
+
+// NewEncoder returns a new encoder that writes to out in the given byte order.
+func newEncoder(out io.Writer, order binary.ByteOrder) *encoder {
+ return newEncoderAtOffset(out, 0, order)
+}
+
+// newEncoderAtOffset returns a new encoder that writes to out in the given
+// byte order. Specify the offset to initialize pos for proper alignment
+// computation.
+func newEncoderAtOffset(out io.Writer, offset int, order binary.ByteOrder) *encoder {
+ enc := new(encoder)
+ enc.out = out
+ enc.order = order
+ enc.pos = offset
+ return enc
+}
+
+// Aligns the next output to be on a multiple of n. Panics on write errors.
+func (enc *encoder) align(n int) {
+ pad := enc.padding(0, n)
+ if pad > 0 {
+ empty := make([]byte, pad)
+ if _, err := enc.out.Write(empty); err != nil {
+ panic(err)
+ }
+ enc.pos += pad
+ }
+}
+
+// pad returns the number of bytes of padding, based on current position and additional offset.
+// and alignment.
+func (enc *encoder) padding(offset, algn int) int {
+ abs := enc.pos + offset
+ if abs%algn != 0 {
+ newabs := (abs + algn - 1) & ^(algn - 1)
+ return newabs - abs
+ }
+ return 0
+}
+
+// Calls binary.Write(enc.out, enc.order, v) and panics on write errors.
+func (enc *encoder) binwrite(v interface{}) {
+ if err := binary.Write(enc.out, enc.order, v); err != nil {
+ panic(err)
+ }
+}
+
+// Encode encodes the given values to the underlying reader. All written values
+// are aligned properly as required by the D-Bus spec.
+func (enc *encoder) Encode(vs ...interface{}) (err error) {
+ defer func() {
+ err, _ = recover().(error)
+ }()
+ for _, v := range vs {
+ enc.encode(reflect.ValueOf(v), 0)
+ }
+ return nil
+}
+
+// encode encodes the given value to the writer and panics on error. depth holds
+// the depth of the container nesting.
+func (enc *encoder) encode(v reflect.Value, depth int) {
+ enc.align(alignment(v.Type()))
+ switch v.Kind() {
+ case reflect.Uint8:
+ var b [1]byte
+ b[0] = byte(v.Uint())
+ if _, err := enc.out.Write(b[:]); err != nil {
+ panic(err)
+ }
+ enc.pos++
+ case reflect.Bool:
+ if v.Bool() {
+ enc.encode(reflect.ValueOf(uint32(1)), depth)
+ } else {
+ enc.encode(reflect.ValueOf(uint32(0)), depth)
+ }
+ case reflect.Int16:
+ enc.binwrite(int16(v.Int()))
+ enc.pos += 2
+ case reflect.Uint16:
+ enc.binwrite(uint16(v.Uint()))
+ enc.pos += 2
+ case reflect.Int, reflect.Int32:
+ enc.binwrite(int32(v.Int()))
+ enc.pos += 4
+ case reflect.Uint, reflect.Uint32:
+ enc.binwrite(uint32(v.Uint()))
+ enc.pos += 4
+ case reflect.Int64:
+ enc.binwrite(v.Int())
+ enc.pos += 8
+ case reflect.Uint64:
+ enc.binwrite(v.Uint())
+ enc.pos += 8
+ case reflect.Float64:
+ enc.binwrite(v.Float())
+ enc.pos += 8
+ case reflect.String:
+ enc.encode(reflect.ValueOf(uint32(len(v.String()))), depth)
+ b := make([]byte, v.Len()+1)
+ copy(b, v.String())
+ b[len(b)-1] = 0
+ n, err := enc.out.Write(b)
+ if err != nil {
+ panic(err)
+ }
+ enc.pos += n
+ case reflect.Ptr:
+ enc.encode(v.Elem(), depth)
+ case reflect.Slice, reflect.Array:
+ if depth >= 64 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ // Lookahead offset: 4 bytes for uint32 length (with alignment),
+ // plus alignment for elements.
+ n := enc.padding(0, 4) + 4
+ offset := enc.pos + n + enc.padding(n, alignment(v.Type().Elem()))
+
+ var buf bytes.Buffer
+ bufenc := newEncoderAtOffset(&buf, offset, enc.order)
+
+ for i := 0; i < v.Len(); i++ {
+ bufenc.encode(v.Index(i), depth+1)
+ }
+ enc.encode(reflect.ValueOf(uint32(buf.Len())), depth)
+ length := buf.Len()
+ enc.align(alignment(v.Type().Elem()))
+ if _, err := buf.WriteTo(enc.out); err != nil {
+ panic(err)
+ }
+ enc.pos += length
+ case reflect.Struct:
+ if depth >= 64 && v.Type() != signatureType {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ switch t := v.Type(); t {
+ case signatureType:
+ str := v.Field(0)
+ enc.encode(reflect.ValueOf(byte(str.Len())), depth+1)
+ b := make([]byte, str.Len()+1)
+ copy(b, str.String())
+ b[len(b)-1] = 0
+ n, err := enc.out.Write(b)
+ if err != nil {
+ panic(err)
+ }
+ enc.pos += n
+ case variantType:
+ variant := v.Interface().(Variant)
+ enc.encode(reflect.ValueOf(variant.sig), depth+1)
+ enc.encode(reflect.ValueOf(variant.value), depth+1)
+ default:
+ for i := 0; i < v.Type().NumField(); i++ {
+ field := t.Field(i)
+ if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
+ enc.encode(v.Field(i), depth+1)
+ }
+ }
+ }
+ case reflect.Map:
+ // Maps are arrays of structures, so they actually increase the depth by
+ // 2.
+ if depth >= 63 {
+ panic(FormatError("input exceeds container depth limit"))
+ }
+ if !isKeyType(v.Type().Key()) {
+ panic(InvalidTypeError{v.Type()})
+ }
+ keys := v.MapKeys()
+ // Lookahead offset: 4 bytes for uint32 length (with alignment),
+ // plus 8-byte alignment
+ n := enc.padding(0, 4) + 4
+ offset := enc.pos + n + enc.padding(n, 8)
+
+ var buf bytes.Buffer
+ bufenc := newEncoderAtOffset(&buf, offset, enc.order)
+ for _, k := range keys {
+ bufenc.align(8)
+ bufenc.encode(k, depth+2)
+ bufenc.encode(v.MapIndex(k), depth+2)
+ }
+ enc.encode(reflect.ValueOf(uint32(buf.Len())), depth)
+ length := buf.Len()
+ enc.align(8)
+ if _, err := buf.WriteTo(enc.out); err != nil {
+ panic(err)
+ }
+ enc.pos += length
+ case reflect.Interface:
+ enc.encode(reflect.ValueOf(MakeVariant(v.Interface())), depth)
+ default:
+ panic(InvalidTypeError{v.Type()})
+ }
+}
diff --git a/vendor/github.com/godbus/dbus/v5/export.go b/vendor/github.com/godbus/dbus/v5/export.go
@@ -0,0 +1,441 @@
+package dbus
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "strings"
+)
+
+var (
+ ErrMsgInvalidArg = Error{
+ "org.freedesktop.DBus.Error.InvalidArgs",
+ []interface{}{"Invalid type / number of args"},
+ }
+ ErrMsgNoObject = Error{
+ "org.freedesktop.DBus.Error.NoSuchObject",
+ []interface{}{"No such object"},
+ }
+ ErrMsgUnknownMethod = Error{
+ "org.freedesktop.DBus.Error.UnknownMethod",
+ []interface{}{"Unknown / invalid method"},
+ }
+ ErrMsgUnknownInterface = Error{
+ "org.freedesktop.DBus.Error.UnknownInterface",
+ []interface{}{"Object does not implement the interface"},
+ }
+)
+
+func MakeFailedError(err error) *Error {
+ return &Error{
+ "org.freedesktop.DBus.Error.Failed",
+ []interface{}{err.Error()},
+ }
+}
+
+// Sender is a type which can be used in exported methods to receive the message
+// sender.
+type Sender string
+
+func computeMethodName(name string, mapping map[string]string) string {
+ newname, ok := mapping[name]
+ if ok {
+ name = newname
+ }
+ return name
+}
+
+func getMethods(in interface{}, mapping map[string]string) map[string]reflect.Value {
+ if in == nil {
+ return nil
+ }
+ methods := make(map[string]reflect.Value)
+ val := reflect.ValueOf(in)
+ typ := val.Type()
+ for i := 0; i < typ.NumMethod(); i++ {
+ methtype := typ.Method(i)
+ method := val.Method(i)
+ t := method.Type()
+ // only track valid methods must return *Error as last arg
+ // and must be exported
+ if t.NumOut() == 0 ||
+ t.Out(t.NumOut()-1) != reflect.TypeOf(&ErrMsgInvalidArg) ||
+ methtype.PkgPath != "" {
+ continue
+ }
+ // map names while building table
+ methods[computeMethodName(methtype.Name, mapping)] = method
+ }
+ return methods
+}
+
+func getAllMethods(in interface{}, mapping map[string]string) map[string]reflect.Value {
+ if in == nil {
+ return nil
+ }
+ methods := make(map[string]reflect.Value)
+ val := reflect.ValueOf(in)
+ typ := val.Type()
+ for i := 0; i < typ.NumMethod(); i++ {
+ methtype := typ.Method(i)
+ method := val.Method(i)
+ // map names while building table
+ methods[computeMethodName(methtype.Name, mapping)] = method
+ }
+ return methods
+}
+
+func standardMethodArgumentDecode(m Method, sender string, msg *Message, body []interface{}) ([]interface{}, error) {
+ pointers := make([]interface{}, m.NumArguments())
+ decode := make([]interface{}, 0, len(body))
+
+ for i := 0; i < m.NumArguments(); i++ {
+ tp := reflect.TypeOf(m.ArgumentValue(i))
+ val := reflect.New(tp)
+ pointers[i] = val.Interface()
+ if tp == reflect.TypeOf((*Sender)(nil)).Elem() {
+ val.Elem().SetString(sender)
+ } else if tp == reflect.TypeOf((*Message)(nil)).Elem() {
+ val.Elem().Set(reflect.ValueOf(*msg))
+ } else {
+ decode = append(decode, pointers[i])
+ }
+ }
+
+ if len(decode) != len(body) {
+ return nil, ErrMsgInvalidArg
+ }
+
+ if err := Store(body, decode...); err != nil {
+ return nil, ErrMsgInvalidArg
+ }
+
+ return pointers, nil
+}
+
+func (conn *Conn) decodeArguments(m Method, sender string, msg *Message) ([]interface{}, error) {
+ if decoder, ok := m.(ArgumentDecoder); ok {
+ return decoder.DecodeArguments(conn, sender, msg, msg.Body)
+ }
+ return standardMethodArgumentDecode(m, sender, msg, msg.Body)
+}
+
+// handleCall handles the given method call (i.e. looks if it's one of the
+// pre-implemented ones and searches for a corresponding handler if not).
+func (conn *Conn) handleCall(msg *Message) {
+ name := msg.Headers[FieldMember].value.(string)
+ path := msg.Headers[FieldPath].value.(ObjectPath)
+ ifaceName, _ := msg.Headers[FieldInterface].value.(string)
+ sender, hasSender := msg.Headers[FieldSender].value.(string)
+ serial := msg.serial
+ if ifaceName == "org.freedesktop.DBus.Peer" {
+ switch name {
+ case "Ping":
+ conn.sendReply(sender, serial)
+ case "GetMachineId":
+ conn.sendReply(sender, serial, conn.uuid)
+ default:
+ conn.sendError(ErrMsgUnknownMethod, sender, serial)
+ }
+ return
+ }
+ if len(name) == 0 {
+ conn.sendError(ErrMsgUnknownMethod, sender, serial)
+ }
+
+ object, ok := conn.handler.LookupObject(path)
+ if !ok {
+ conn.sendError(ErrMsgNoObject, sender, serial)
+ return
+ }
+
+ iface, exists := object.LookupInterface(ifaceName)
+ if !exists {
+ conn.sendError(ErrMsgUnknownInterface, sender, serial)
+ return
+ }
+
+ m, exists := iface.LookupMethod(name)
+ if !exists {
+ conn.sendError(ErrMsgUnknownMethod, sender, serial)
+ return
+ }
+ args, err := conn.decodeArguments(m, sender, msg)
+ if err != nil {
+ conn.sendError(err, sender, serial)
+ return
+ }
+
+ ret, err := m.Call(args...)
+ if err != nil {
+ conn.sendError(err, sender, serial)
+ return
+ }
+
+ if msg.Flags&FlagNoReplyExpected == 0 {
+ reply := new(Message)
+ reply.Type = TypeMethodReply
+ reply.Headers = make(map[HeaderField]Variant)
+ if hasSender {
+ reply.Headers[FieldDestination] = msg.Headers[FieldSender]
+ }
+ reply.Headers[FieldReplySerial] = MakeVariant(msg.serial)
+ reply.Body = make([]interface{}, len(ret))
+ for i := 0; i < len(ret); i++ {
+ reply.Body[i] = ret[i]
+ }
+ reply.Headers[FieldSignature] = MakeVariant(SignatureOf(reply.Body...))
+
+ conn.sendMessageAndIfClosed(reply, nil)
+ }
+}
+
+// Emit emits the given signal on the message bus. The name parameter must be
+// formatted as "interface.member", e.g., "org.freedesktop.DBus.NameLost".
+func (conn *Conn) Emit(path ObjectPath, name string, values ...interface{}) error {
+ if !path.IsValid() {
+ return errors.New("dbus: invalid object path")
+ }
+ i := strings.LastIndex(name, ".")
+ if i == -1 {
+ return errors.New("dbus: invalid method name")
+ }
+ iface := name[:i]
+ member := name[i+1:]
+ if !isValidMember(member) {
+ return errors.New("dbus: invalid method name")
+ }
+ if !isValidInterface(iface) {
+ return errors.New("dbus: invalid interface name")
+ }
+ msg := new(Message)
+ msg.Type = TypeSignal
+ msg.Headers = make(map[HeaderField]Variant)
+ msg.Headers[FieldInterface] = MakeVariant(iface)
+ msg.Headers[FieldMember] = MakeVariant(member)
+ msg.Headers[FieldPath] = MakeVariant(path)
+ msg.Body = values
+ if len(values) > 0 {
+ msg.Headers[FieldSignature] = MakeVariant(SignatureOf(values...))
+ }
+
+ var closed bool
+ conn.sendMessageAndIfClosed(msg, func() {
+ closed = true
+ })
+ if closed {
+ return ErrClosed
+ }
+ return nil
+}
+
+// Export registers the given value to be exported as an object on the
+// message bus.
+//
+// If a method call on the given path and interface is received, an exported
+// method with the same name is called with v as the receiver if the
+// parameters match and the last return value is of type *Error. If this
+// *Error is not nil, it is sent back to the caller as an error.
+// Otherwise, a method reply is sent with the other return values as its body.
+//
+// Any parameters with the special type Sender are set to the sender of the
+// dbus message when the method is called. Parameters of this type do not
+// contribute to the dbus signature of the method (i.e. the method is exposed
+// as if the parameters of type Sender were not there).
+//
+// Similarly, any parameters with the type Message are set to the raw message
+// received on the bus. Again, parameters of this type do not contribute to the
+// dbus signature of the method.
+//
+// Every method call is executed in a new goroutine, so the method may be called
+// in multiple goroutines at once.
+//
+// Method calls on the interface org.freedesktop.DBus.Peer will be automatically
+// handled for every object.
+//
+// Passing nil as the first parameter will cause conn to cease handling calls on
+// the given combination of path and interface.
+//
+// Export returns an error if path is not a valid path name.
+func (conn *Conn) Export(v interface{}, path ObjectPath, iface string) error {
+ return conn.ExportWithMap(v, nil, path, iface)
+}
+
+// ExportAll registers all exported methods defined by the given object on
+// the message bus.
+//
+// Unlike Export there is no requirement to have the last parameter as type
+// *Error. If you want to be able to return error then you can append an error
+// type parameter to your method signature. If the error returned is not nil,
+// it is sent back to the caller as an error. Otherwise, a method reply is
+// sent with the other return values as its body.
+func (conn *Conn) ExportAll(v interface{}, path ObjectPath, iface string) error {
+ return conn.export(getAllMethods(v, nil), path, iface, false)
+}
+
+// ExportWithMap works exactly like Export but provides the ability to remap
+// method names (e.g. export a lower-case method).
+//
+// The keys in the map are the real method names (exported on the struct), and
+// the values are the method names to be exported on DBus.
+func (conn *Conn) ExportWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string) error {
+ return conn.export(getMethods(v, mapping), path, iface, false)
+}
+
+// ExportSubtree works exactly like Export but registers the given value for
+// an entire subtree rather under the root path provided.
+//
+// In order to make this useful, one parameter in each of the value's exported
+// methods should be a Message, in which case it will contain the raw message
+// (allowing one to get access to the path that caused the method to be called).
+//
+// Note that more specific export paths take precedence over less specific. For
+// example, a method call using the ObjectPath /foo/bar/baz will call a method
+// exported on /foo/bar before a method exported on /foo.
+func (conn *Conn) ExportSubtree(v interface{}, path ObjectPath, iface string) error {
+ return conn.ExportSubtreeWithMap(v, nil, path, iface)
+}
+
+// ExportSubtreeWithMap works exactly like ExportSubtree but provides the
+// ability to remap method names (e.g. export a lower-case method).
+//
+// The keys in the map are the real method names (exported on the struct), and
+// the values are the method names to be exported on DBus.
+func (conn *Conn) ExportSubtreeWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string) error {
+ return conn.export(getMethods(v, mapping), path, iface, true)
+}
+
+// ExportMethodTable like Export registers the given methods as an object
+// on the message bus. Unlike Export the it uses a method table to define
+// the object instead of a native go object.
+//
+// The method table is a map from method name to function closure
+// representing the method. This allows an object exported on the bus to not
+// necessarily be a native go object. It can be useful for generating exposed
+// methods on the fly.
+//
+// Any non-function objects in the method table are ignored.
+func (conn *Conn) ExportMethodTable(methods map[string]interface{}, path ObjectPath, iface string) error {
+ return conn.exportMethodTable(methods, path, iface, false)
+}
+
+// Like ExportSubtree, but with the same caveats as ExportMethodTable.
+func (conn *Conn) ExportSubtreeMethodTable(methods map[string]interface{}, path ObjectPath, iface string) error {
+ return conn.exportMethodTable(methods, path, iface, true)
+}
+
+func (conn *Conn) exportMethodTable(methods map[string]interface{}, path ObjectPath, iface string, includeSubtree bool) error {
+ var out map[string]reflect.Value
+ if methods != nil {
+ out = make(map[string]reflect.Value)
+ for name, method := range methods {
+ rval := reflect.ValueOf(method)
+ if rval.Kind() != reflect.Func {
+ continue
+ }
+ t := rval.Type()
+ // only track valid methods must return *Error as last arg
+ if t.NumOut() == 0 ||
+ t.Out(t.NumOut()-1) != reflect.TypeOf(&ErrMsgInvalidArg) {
+ continue
+ }
+ out[name] = rval
+ }
+ }
+ return conn.export(out, path, iface, includeSubtree)
+}
+
+func (conn *Conn) unexport(h *defaultHandler, path ObjectPath, iface string) error {
+ if h.PathExists(path) {
+ obj := h.objects[path]
+ obj.DeleteInterface(iface)
+ if len(obj.interfaces) == 0 {
+ h.DeleteObject(path)
+ }
+ }
+ return nil
+}
+
+// export is the worker function for all exports/registrations.
+func (conn *Conn) export(methods map[string]reflect.Value, path ObjectPath, iface string, includeSubtree bool) error {
+ h, ok := conn.handler.(*defaultHandler)
+ if !ok {
+ return fmt.Errorf(
+ `dbus: export only allowed on the default handler. Received: %T"`,
+ conn.handler)
+ }
+
+ if !path.IsValid() {
+ return fmt.Errorf(`dbus: Invalid path name: "%s"`, path)
+ }
+
+ // Remove a previous export if the interface is nil
+ if methods == nil {
+ return conn.unexport(h, path, iface)
+ }
+
+ // If this is the first handler for this path, make a new map to hold all
+ // handlers for this path.
+ if !h.PathExists(path) {
+ h.AddObject(path, newExportedObject())
+ }
+
+ exportedMethods := make(map[string]Method)
+ for name, method := range methods {
+ exportedMethods[name] = exportedMethod{method}
+ }
+
+ // Finally, save this handler
+ obj := h.objects[path]
+ obj.AddInterface(iface, newExportedIntf(exportedMethods, includeSubtree))
+
+ return nil
+}
+
+// ReleaseName calls org.freedesktop.DBus.ReleaseName and awaits a response.
+func (conn *Conn) ReleaseName(name string) (ReleaseNameReply, error) {
+ var r uint32
+ err := conn.busObj.Call("org.freedesktop.DBus.ReleaseName", 0, name).Store(&r)
+ if err != nil {
+ return 0, err
+ }
+ return ReleaseNameReply(r), nil
+}
+
+// RequestName calls org.freedesktop.DBus.RequestName and awaits a response.
+func (conn *Conn) RequestName(name string, flags RequestNameFlags) (RequestNameReply, error) {
+ var r uint32
+ err := conn.busObj.Call("org.freedesktop.DBus.RequestName", 0, name, flags).Store(&r)
+ if err != nil {
+ return 0, err
+ }
+ return RequestNameReply(r), nil
+}
+
+// ReleaseNameReply is the reply to a ReleaseName call.
+type ReleaseNameReply uint32
+
+const (
+ ReleaseNameReplyReleased ReleaseNameReply = 1 + iota
+ ReleaseNameReplyNonExistent
+ ReleaseNameReplyNotOwner
+)
+
+// RequestNameFlags represents the possible flags for a RequestName call.
+type RequestNameFlags uint32
+
+const (
+ NameFlagAllowReplacement RequestNameFlags = 1 << iota
+ NameFlagReplaceExisting
+ NameFlagDoNotQueue
+)
+
+// RequestNameReply is the reply to a RequestName call.
+type RequestNameReply uint32
+
+const (
+ RequestNameReplyPrimaryOwner RequestNameReply = 1 + iota
+ RequestNameReplyInQueue
+ RequestNameReplyExists
+ RequestNameReplyAlreadyOwner
+)
diff --git a/vendor/github.com/godbus/dbus/v5/homedir.go b/vendor/github.com/godbus/dbus/v5/homedir.go
@@ -0,0 +1,28 @@
+package dbus
+
+import (
+ "os"
+ "sync"
+)
+
+var (
+ homeDir string
+ homeDirLock sync.Mutex
+)
+
+func getHomeDir() string {
+ homeDirLock.Lock()
+ defer homeDirLock.Unlock()
+
+ if homeDir != "" {
+ return homeDir
+ }
+
+ homeDir = os.Getenv("HOME")
+ if homeDir != "" {
+ return homeDir
+ }
+
+ homeDir = lookupHomeDir()
+ return homeDir
+}
diff --git a/vendor/github.com/godbus/dbus/v5/homedir_dynamic.go b/vendor/github.com/godbus/dbus/v5/homedir_dynamic.go
@@ -0,0 +1,15 @@
+// +build !static_build
+
+package dbus
+
+import (
+ "os/user"
+)
+
+func lookupHomeDir() string {
+ u, err := user.Current()
+ if err != nil {
+ return "/"
+ }
+ return u.HomeDir
+}
diff --git a/vendor/github.com/godbus/dbus/v5/homedir_static.go b/vendor/github.com/godbus/dbus/v5/homedir_static.go
@@ -0,0 +1,45 @@
+// +build static_build
+
+package dbus
+
+import (
+ "bufio"
+ "os"
+ "strconv"
+ "strings"
+)
+
+func lookupHomeDir() string {
+ myUid := os.Getuid()
+
+ f, err := os.Open("/etc/passwd")
+ if err != nil {
+ return "/"
+ }
+ defer f.Close()
+
+ s := bufio.NewScanner(f)
+
+ for s.Scan() {
+ if err := s.Err(); err != nil {
+ break
+ }
+
+ line := strings.TrimSpace(s.Text())
+ if line == "" {
+ continue
+ }
+
+ parts := strings.Split(line, ":")
+
+ if len(parts) >= 6 {
+ uid, err := strconv.Atoi(parts[2])
+ if err == nil && uid == myUid {
+ return parts[5]
+ }
+ }
+ }
+
+ // Default to / if we can't get a better value
+ return "/"
+}
diff --git a/vendor/github.com/godbus/dbus/v5/match.go b/vendor/github.com/godbus/dbus/v5/match.go
@@ -0,0 +1,89 @@
+package dbus
+
+import (
+ "strconv"
+ "strings"
+)
+
+// MatchOption specifies option for dbus routing match rule. Options can be constructed with WithMatch* helpers.
+// For full list of available options consult
+// https://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing-match-rules
+type MatchOption struct {
+ key string
+ value string
+}
+
+func formatMatchOptions(options []MatchOption) string {
+ items := make([]string, 0, len(options))
+ for _, option := range options {
+ items = append(items, option.key+"='"+option.value+"'")
+ }
+ return strings.Join(items, ",")
+}
+
+// WithMatchOption creates match option with given key and value
+func WithMatchOption(key, value string) MatchOption {
+ return MatchOption{key, value}
+}
+
+// doesn't make sense to export this option because clients can only
+// subscribe to messages with signal type.
+func withMatchType(typ string) MatchOption {
+ return WithMatchOption("type", typ)
+}
+
+// WithMatchSender sets sender match option.
+func WithMatchSender(sender string) MatchOption {
+ return WithMatchOption("sender", sender)
+}
+
+// WithMatchSender sets interface match option.
+func WithMatchInterface(iface string) MatchOption {
+ return WithMatchOption("interface", iface)
+}
+
+// WithMatchMember sets member match option.
+func WithMatchMember(member string) MatchOption {
+ return WithMatchOption("member", member)
+}
+
+// WithMatchObjectPath creates match option that filters events based on given path
+func WithMatchObjectPath(path ObjectPath) MatchOption {
+ return WithMatchOption("path", string(path))
+}
+
+// WithMatchPathNamespace sets path_namespace match option.
+func WithMatchPathNamespace(namespace ObjectPath) MatchOption {
+ return WithMatchOption("path_namespace", string(namespace))
+}
+
+// WithMatchDestination sets destination match option.
+func WithMatchDestination(destination string) MatchOption {
+ return WithMatchOption("destination", destination)
+}
+
+// WithMatchArg sets argN match option, range of N is 0 to 63.
+func WithMatchArg(argIdx int, value string) MatchOption {
+ if argIdx < 0 || argIdx > 63 {
+ panic("range of argument index is 0 to 63")
+ }
+ return WithMatchOption("arg"+strconv.Itoa(argIdx), value)
+}
+
+// WithMatchArgPath sets argN path match option, range of N is 0 to 63.
+func WithMatchArgPath(argIdx int, path string) MatchOption {
+ if argIdx < 0 || argIdx > 63 {
+ panic("range of argument index is 0 to 63")
+ }
+ return WithMatchOption("arg"+strconv.Itoa(argIdx)+"path", path)
+}
+
+// WithMatchArg0Namespace sets arg0namespace match option.
+func WithMatchArg0Namespace(arg0Namespace string) MatchOption {
+ return WithMatchOption("arg0namespace", arg0Namespace)
+}
+
+// WithMatchEavesdrop sets eavesdrop match option.
+func WithMatchEavesdrop(eavesdrop bool) MatchOption {
+ return WithMatchOption("eavesdrop", strconv.FormatBool(eavesdrop))
+}
diff --git a/vendor/github.com/godbus/dbus/v5/message.go b/vendor/github.com/godbus/dbus/v5/message.go
@@ -0,0 +1,353 @@
+package dbus
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "io"
+ "reflect"
+ "strconv"
+)
+
+const protoVersion byte = 1
+
+// Flags represents the possible flags of a D-Bus message.
+type Flags byte
+
+const (
+ // FlagNoReplyExpected signals that the message is not expected to generate
+ // a reply. If this flag is set on outgoing messages, any possible reply
+ // will be discarded.
+ FlagNoReplyExpected Flags = 1 << iota
+ // FlagNoAutoStart signals that the message bus should not automatically
+ // start an application when handling this message.
+ FlagNoAutoStart
+ // FlagAllowInteractiveAuthorization may be set on a method call
+ // message to inform the receiving side that the caller is prepared
+ // to wait for interactive authorization, which might take a
+ // considerable time to complete. For instance, if this flag is set,
+ // it would be appropriate to query the user for passwords or
+ // confirmation via Polkit or a similar framework.
+ FlagAllowInteractiveAuthorization
+)
+
+// Type represents the possible types of a D-Bus message.
+type Type byte
+
+const (
+ TypeMethodCall Type = 1 + iota
+ TypeMethodReply
+ TypeError
+ TypeSignal
+ typeMax
+)
+
+func (t Type) String() string {
+ switch t {
+ case TypeMethodCall:
+ return "method call"
+ case TypeMethodReply:
+ return "reply"
+ case TypeError:
+ return "error"
+ case TypeSignal:
+ return "signal"
+ }
+ return "invalid"
+}
+
+// HeaderField represents the possible byte codes for the headers
+// of a D-Bus message.
+type HeaderField byte
+
+const (
+ FieldPath HeaderField = 1 + iota
+ FieldInterface
+ FieldMember
+ FieldErrorName
+ FieldReplySerial
+ FieldDestination
+ FieldSender
+ FieldSignature
+ FieldUnixFDs
+ fieldMax
+)
+
+// An InvalidMessageError describes the reason why a D-Bus message is regarded as
+// invalid.
+type InvalidMessageError string
+
+func (e InvalidMessageError) Error() string {
+ return "dbus: invalid message: " + string(e)
+}
+
+// fieldType are the types of the various header fields.
+var fieldTypes = [fieldMax]reflect.Type{
+ FieldPath: objectPathType,
+ FieldInterface: stringType,
+ FieldMember: stringType,
+ FieldErrorName: stringType,
+ FieldReplySerial: uint32Type,
+ FieldDestination: stringType,
+ FieldSender: stringType,
+ FieldSignature: signatureType,
+ FieldUnixFDs: uint32Type,
+}
+
+// requiredFields lists the header fields that are required by the different
+// message types.
+var requiredFields = [typeMax][]HeaderField{
+ TypeMethodCall: {FieldPath, FieldMember},
+ TypeMethodReply: {FieldReplySerial},
+ TypeError: {FieldErrorName, FieldReplySerial},
+ TypeSignal: {FieldPath, FieldInterface, FieldMember},
+}
+
+// Message represents a single D-Bus message.
+type Message struct {
+ Type
+ Flags
+ Headers map[HeaderField]Variant
+ Body []interface{}
+
+ serial uint32
+}
+
+type header struct {
+ Field byte
+ Variant
+}
+
+// DecodeMessage tries to decode a single message in the D-Bus wire format
+// from the given reader. The byte order is figured out from the first byte.
+// The possibly returned error can be an error of the underlying reader, an
+// InvalidMessageError or a FormatError.
+func DecodeMessage(rd io.Reader) (msg *Message, err error) {
+ var order binary.ByteOrder
+ var hlength, length uint32
+ var typ, flags, proto byte
+ var headers []header
+
+ b := make([]byte, 1)
+ _, err = rd.Read(b)
+ if err != nil {
+ return
+ }
+ switch b[0] {
+ case 'l':
+ order = binary.LittleEndian
+ case 'B':
+ order = binary.BigEndian
+ default:
+ return nil, InvalidMessageError("invalid byte order")
+ }
+
+ dec := newDecoder(rd, order)
+ dec.pos = 1
+
+ msg = new(Message)
+ vs, err := dec.Decode(Signature{"yyyuu"})
+ if err != nil {
+ return nil, err
+ }
+ if err = Store(vs, &typ, &flags, &proto, &length, &msg.serial); err != nil {
+ return nil, err
+ }
+ msg.Type = Type(typ)
+ msg.Flags = Flags(flags)
+
+ // get the header length separately because we need it later
+ b = make([]byte, 4)
+ _, err = io.ReadFull(rd, b)
+ if err != nil {
+ return nil, err
+ }
+ binary.Read(bytes.NewBuffer(b), order, &hlength)
+ if hlength+length+16 > 1<<27 {
+ return nil, InvalidMessageError("message is too long")
+ }
+ dec = newDecoder(io.MultiReader(bytes.NewBuffer(b), rd), order)
+ dec.pos = 12
+ vs, err = dec.Decode(Signature{"a(yv)"})
+ if err != nil {
+ return nil, err
+ }
+ if err = Store(vs, &headers); err != nil {
+ return nil, err
+ }
+
+ msg.Headers = make(map[HeaderField]Variant)
+ for _, v := range headers {
+ msg.Headers[HeaderField(v.Field)] = v.Variant
+ }
+
+ dec.align(8)
+ body := make([]byte, int(length))
+ if length != 0 {
+ _, err := io.ReadFull(rd, body)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ if err = msg.IsValid(); err != nil {
+ return nil, err
+ }
+ sig, _ := msg.Headers[FieldSignature].value.(Signature)
+ if sig.str != "" {
+ buf := bytes.NewBuffer(body)
+ dec = newDecoder(buf, order)
+ vs, err := dec.Decode(sig)
+ if err != nil {
+ return nil, err
+ }
+ msg.Body = vs
+ }
+
+ return
+}
+
+// EncodeTo encodes and sends a message to the given writer. The byte order must
+// be either binary.LittleEndian or binary.BigEndian. If the message is not
+// valid or an error occurs when writing, an error is returned.
+func (msg *Message) EncodeTo(out io.Writer, order binary.ByteOrder) error {
+ if err := msg.IsValid(); err != nil {
+ return err
+ }
+ var vs [7]interface{}
+ switch order {
+ case binary.LittleEndian:
+ vs[0] = byte('l')
+ case binary.BigEndian:
+ vs[0] = byte('B')
+ default:
+ return errors.New("dbus: invalid byte order")
+ }
+ body := new(bytes.Buffer)
+ enc := newEncoder(body, order)
+ if len(msg.Body) != 0 {
+ enc.Encode(msg.Body...)
+ }
+ vs[1] = msg.Type
+ vs[2] = msg.Flags
+ vs[3] = protoVersion
+ vs[4] = uint32(len(body.Bytes()))
+ vs[5] = msg.serial
+ headers := make([]header, 0, len(msg.Headers))
+ for k, v := range msg.Headers {
+ headers = append(headers, header{byte(k), v})
+ }
+ vs[6] = headers
+ var buf bytes.Buffer
+ enc = newEncoder(&buf, order)
+ enc.Encode(vs[:]...)
+ enc.align(8)
+ body.WriteTo(&buf)
+ if buf.Len() > 1<<27 {
+ return InvalidMessageError("message is too long")
+ }
+ if _, err := buf.WriteTo(out); err != nil {
+ return err
+ }
+ return nil
+}
+
+// IsValid checks whether msg is a valid message and returns an
+// InvalidMessageError if it is not.
+func (msg *Message) IsValid() error {
+ if msg.Flags & ^(FlagNoAutoStart|FlagNoReplyExpected|FlagAllowInteractiveAuthorization) != 0 {
+ return InvalidMessageError("invalid flags")
+ }
+ if msg.Type == 0 || msg.Type >= typeMax {
+ return InvalidMessageError("invalid message type")
+ }
+ for k, v := range msg.Headers {
+ if k == 0 || k >= fieldMax {
+ return InvalidMessageError("invalid header")
+ }
+ if reflect.TypeOf(v.value) != fieldTypes[k] {
+ return InvalidMessageError("invalid type of header field")
+ }
+ }
+ for _, v := range requiredFields[msg.Type] {
+ if _, ok := msg.Headers[v]; !ok {
+ return InvalidMessageError("missing required header")
+ }
+ }
+ if path, ok := msg.Headers[FieldPath]; ok {
+ if !path.value.(ObjectPath).IsValid() {
+ return InvalidMessageError("invalid path name")
+ }
+ }
+ if iface, ok := msg.Headers[FieldInterface]; ok {
+ if !isValidInterface(iface.value.(string)) {
+ return InvalidMessageError("invalid interface name")
+ }
+ }
+ if member, ok := msg.Headers[FieldMember]; ok {
+ if !isValidMember(member.value.(string)) {
+ return InvalidMessageError("invalid member name")
+ }
+ }
+ if errname, ok := msg.Headers[FieldErrorName]; ok {
+ if !isValidInterface(errname.value.(string)) {
+ return InvalidMessageError("invalid error name")
+ }
+ }
+ if len(msg.Body) != 0 {
+ if _, ok := msg.Headers[FieldSignature]; !ok {
+ return InvalidMessageError("missing signature")
+ }
+ }
+ return nil
+}
+
+// Serial returns the message's serial number. The returned value is only valid
+// for messages received by eavesdropping.
+func (msg *Message) Serial() uint32 {
+ return msg.serial
+}
+
+// String returns a string representation of a message similar to the format of
+// dbus-monitor.
+func (msg *Message) String() string {
+ if err := msg.IsValid(); err != nil {
+ return "<invalid>"
+ }
+ s := msg.Type.String()
+ if v, ok := msg.Headers[FieldSender]; ok {
+ s += " from " + v.value.(string)
+ }
+ if v, ok := msg.Headers[FieldDestination]; ok {
+ s += " to " + v.value.(string)
+ }
+ s += " serial " + strconv.FormatUint(uint64(msg.serial), 10)
+ if v, ok := msg.Headers[FieldReplySerial]; ok {
+ s += " reply_serial " + strconv.FormatUint(uint64(v.value.(uint32)), 10)
+ }
+ if v, ok := msg.Headers[FieldUnixFDs]; ok {
+ s += " unixfds " + strconv.FormatUint(uint64(v.value.(uint32)), 10)
+ }
+ if v, ok := msg.Headers[FieldPath]; ok {
+ s += " path " + string(v.value.(ObjectPath))
+ }
+ if v, ok := msg.Headers[FieldInterface]; ok {
+ s += " interface " + v.value.(string)
+ }
+ if v, ok := msg.Headers[FieldErrorName]; ok {
+ s += " error " + v.value.(string)
+ }
+ if v, ok := msg.Headers[FieldMember]; ok {
+ s += " member " + v.value.(string)
+ }
+ if len(msg.Body) != 0 {
+ s += "\n"
+ }
+ for i, v := range msg.Body {
+ s += " " + MakeVariant(v).String()
+ if i != len(msg.Body)-1 {
+ s += "\n"
+ }
+ }
+ return s
+}
diff --git a/vendor/github.com/godbus/dbus/v5/object.go b/vendor/github.com/godbus/dbus/v5/object.go
@@ -0,0 +1,174 @@
+package dbus
+
+import (
+ "context"
+ "errors"
+ "strings"
+)
+
+// BusObject is the interface of a remote object on which methods can be
+// invoked.
+type BusObject interface {
+ Call(method string, flags Flags, args ...interface{}) *Call
+ CallWithContext(ctx context.Context, method string, flags Flags, args ...interface{}) *Call
+ Go(method string, flags Flags, ch chan *Call, args ...interface{}) *Call
+ GoWithContext(ctx context.Context, method string, flags Flags, ch chan *Call, args ...interface{}) *Call
+ AddMatchSignal(iface, member string, options ...MatchOption) *Call
+ RemoveMatchSignal(iface, member string, options ...MatchOption) *Call
+ GetProperty(p string) (Variant, error)
+ StoreProperty(p string, value interface{}) error
+ SetProperty(p string, v interface{}) error
+ Destination() string
+ Path() ObjectPath
+}
+
+// Object represents a remote object on which methods can be invoked.
+type Object struct {
+ conn *Conn
+ dest string
+ path ObjectPath
+}
+
+// Call calls a method with (*Object).Go and waits for its reply.
+func (o *Object) Call(method string, flags Flags, args ...interface{}) *Call {
+ return <-o.createCall(context.Background(), method, flags, make(chan *Call, 1), args...).Done
+}
+
+// CallWithContext acts like Call but takes a context
+func (o *Object) CallWithContext(ctx context.Context, method string, flags Flags, args ...interface{}) *Call {
+ return <-o.createCall(ctx, method, flags, make(chan *Call, 1), args...).Done
+}
+
+// AddMatchSignal subscribes BusObject to signals from specified interface,
+// method (member). Additional filter rules can be added via WithMatch* option constructors.
+// Note: To filter events by object path you have to specify this path via an option.
+//
+// Deprecated: use (*Conn) AddMatchSignal instead.
+func (o *Object) AddMatchSignal(iface, member string, options ...MatchOption) *Call {
+ base := []MatchOption{
+ withMatchType("signal"),
+ WithMatchInterface(iface),
+ WithMatchMember(member),
+ }
+
+ options = append(base, options...)
+ return o.conn.BusObject().Call(
+ "org.freedesktop.DBus.AddMatch",
+ 0,
+ formatMatchOptions(options),
+ )
+}
+
+// RemoveMatchSignal unsubscribes BusObject from signals from specified interface,
+// method (member). Additional filter rules can be added via WithMatch* option constructors
+//
+// Deprecated: use (*Conn) RemoveMatchSignal instead.
+func (o *Object) RemoveMatchSignal(iface, member string, options ...MatchOption) *Call {
+ base := []MatchOption{
+ withMatchType("signal"),
+ WithMatchInterface(iface),
+ WithMatchMember(member),
+ }
+
+ options = append(base, options...)
+ return o.conn.BusObject().Call(
+ "org.freedesktop.DBus.RemoveMatch",
+ 0,
+ formatMatchOptions(options),
+ )
+}
+
+// Go calls a method with the given arguments asynchronously. It returns a
+// Call structure representing this method call. The passed channel will
+// return the same value once the call is done. If ch is nil, a new channel
+// will be allocated. Otherwise, ch has to be buffered or Go will panic.
+//
+// If the flags include FlagNoReplyExpected, ch is ignored and a Call structure
+// is returned with any error in Err and a closed channel in Done containing
+// the returned Call as it's one entry.
+//
+// If the method parameter contains a dot ('.'), the part before the last dot
+// specifies the interface on which the method is called.
+func (o *Object) Go(method string, flags Flags, ch chan *Call, args ...interface{}) *Call {
+ return o.createCall(context.Background(), method, flags, ch, args...)
+}
+
+// GoWithContext acts like Go but takes a context
+func (o *Object) GoWithContext(ctx context.Context, method string, flags Flags, ch chan *Call, args ...interface{}) *Call {
+ return o.createCall(ctx, method, flags, ch, args...)
+}
+
+func (o *Object) createCall(ctx context.Context, method string, flags Flags, ch chan *Call, args ...interface{}) *Call {
+ if ctx == nil {
+ panic("nil context")
+ }
+ iface := ""
+ i := strings.LastIndex(method, ".")
+ if i != -1 {
+ iface = method[:i]
+ }
+ method = method[i+1:]
+ msg := new(Message)
+ msg.Type = TypeMethodCall
+ msg.Flags = flags & (FlagNoAutoStart | FlagNoReplyExpected)
+ msg.Headers = make(map[HeaderField]Variant)
+ msg.Headers[FieldPath] = MakeVariant(o.path)
+ msg.Headers[FieldDestination] = MakeVariant(o.dest)
+ msg.Headers[FieldMember] = MakeVariant(method)
+ if iface != "" {
+ msg.Headers[FieldInterface] = MakeVariant(iface)
+ }
+ msg.Body = args
+ if len(args) > 0 {
+ msg.Headers[FieldSignature] = MakeVariant(SignatureOf(args...))
+ }
+ return o.conn.SendWithContext(ctx, msg, ch)
+}
+
+// GetProperty calls org.freedesktop.DBus.Properties.Get on the given
+// object. The property name must be given in interface.member notation.
+func (o *Object) GetProperty(p string) (Variant, error) {
+ var result Variant
+ err := o.StoreProperty(p, &result)
+ return result, err
+}
+
+// StoreProperty calls org.freedesktop.DBus.Properties.Get on the given
+// object. The property name must be given in interface.member notation.
+// It stores the returned property into the provided value.
+func (o *Object) StoreProperty(p string, value interface{}) error {
+ idx := strings.LastIndex(p, ".")
+ if idx == -1 || idx+1 == len(p) {
+ return errors.New("dbus: invalid property " + p)
+ }
+
+ iface := p[:idx]
+ prop := p[idx+1:]
+
+ return o.Call("org.freedesktop.DBus.Properties.Get", 0, iface, prop).
+ Store(value)
+}
+
+// SetProperty calls org.freedesktop.DBus.Properties.Set on the given
+// object. The property name must be given in interface.member notation.
+func (o *Object) SetProperty(p string, v interface{}) error {
+ idx := strings.LastIndex(p, ".")
+ if idx == -1 || idx+1 == len(p) {
+ return errors.New("dbus: invalid property " + p)
+ }
+
+ iface := p[:idx]
+ prop := p[idx+1:]
+
+ return o.Call("org.freedesktop.DBus.Properties.Set", 0, iface, prop, v).Err
+}
+
+// Destination returns the destination that calls on (o *Object) are sent to.
+func (o *Object) Destination() string {
+ return o.dest
+}
+
+// Path returns the path that calls on (o *Object") are sent to.
+func (o *Object) Path() ObjectPath {
+ return o.path
+}
diff --git a/vendor/github.com/godbus/dbus/v5/sequence.go b/vendor/github.com/godbus/dbus/v5/sequence.go
@@ -0,0 +1,24 @@
+package dbus
+
+// Sequence represents the value of a monotonically increasing counter.
+type Sequence uint64
+
+const (
+ // NoSequence indicates the absence of a sequence value.
+ NoSequence Sequence = 0
+)
+
+// sequenceGenerator represents a monotonically increasing counter.
+type sequenceGenerator struct {
+ nextSequence Sequence
+}
+
+func (generator *sequenceGenerator) next() Sequence {
+ result := generator.nextSequence
+ generator.nextSequence++
+ return result
+}
+
+func newSequenceGenerator() *sequenceGenerator {
+ return &sequenceGenerator{nextSequence: 1}
+}
diff --git a/vendor/github.com/godbus/dbus/v5/sequential_handler.go b/vendor/github.com/godbus/dbus/v5/sequential_handler.go
@@ -0,0 +1,125 @@
+package dbus
+
+import (
+ "sync"
+)
+
+// NewSequentialSignalHandler returns an instance of a new
+// signal handler that guarantees sequential processing of signals. It is a
+// guarantee of this signal handler that signals will be written to
+// channels in the order they are received on the DBus connection.
+func NewSequentialSignalHandler() SignalHandler {
+ return &sequentialSignalHandler{}
+}
+
+type sequentialSignalHandler struct {
+ mu sync.RWMutex
+ closed bool
+ signals []*sequentialSignalChannelData
+}
+
+func (sh *sequentialSignalHandler) DeliverSignal(intf, name string, signal *Signal) {
+ sh.mu.RLock()
+ defer sh.mu.RUnlock()
+ if sh.closed {
+ return
+ }
+ for _, scd := range sh.signals {
+ scd.deliver(signal)
+ }
+}
+
+func (sh *sequentialSignalHandler) Terminate() {
+ sh.mu.Lock()
+ defer sh.mu.Unlock()
+ if sh.closed {
+ return
+ }
+
+ for _, scd := range sh.signals {
+ scd.close()
+ close(scd.ch)
+ }
+ sh.closed = true
+ sh.signals = nil
+}
+
+func (sh *sequentialSignalHandler) AddSignal(ch chan<- *Signal) {
+ sh.mu.Lock()
+ defer sh.mu.Unlock()
+ if sh.closed {
+ return
+ }
+ sh.signals = append(sh.signals, newSequentialSignalChannelData(ch))
+}
+
+func (sh *sequentialSignalHandler) RemoveSignal(ch chan<- *Signal) {
+ sh.mu.Lock()
+ defer sh.mu.Unlock()
+ if sh.closed {
+ return
+ }
+ for i := len(sh.signals) - 1; i >= 0; i-- {
+ if ch == sh.signals[i].ch {
+ sh.signals[i].close()
+ copy(sh.signals[i:], sh.signals[i+1:])
+ sh.signals[len(sh.signals)-1] = nil
+ sh.signals = sh.signals[:len(sh.signals)-1]
+ }
+ }
+}
+
+type sequentialSignalChannelData struct {
+ ch chan<- *Signal
+ in chan *Signal
+ done chan struct{}
+}
+
+func newSequentialSignalChannelData(ch chan<- *Signal) *sequentialSignalChannelData {
+ scd := &sequentialSignalChannelData{
+ ch: ch,
+ in: make(chan *Signal),
+ done: make(chan struct{}),
+ }
+ go scd.bufferSignals()
+ return scd
+}
+
+func (scd *sequentialSignalChannelData) bufferSignals() {
+ defer close(scd.done)
+
+ // Ensure that signals are delivered to scd.ch in the same
+ // order they are received from scd.in.
+ var queue []*Signal
+ for {
+ if len(queue) == 0 {
+ signal, ok := <- scd.in
+ if !ok {
+ return
+ }
+ queue = append(queue, signal)
+ }
+ select {
+ case scd.ch <- queue[0]:
+ copy(queue, queue[1:])
+ queue[len(queue)-1] = nil
+ queue = queue[:len(queue)-1]
+ case signal, ok := <-scd.in:
+ if !ok {
+ return
+ }
+ queue = append(queue, signal)
+ }
+ }
+}
+
+func (scd *sequentialSignalChannelData) deliver(signal *Signal) {
+ scd.in <- signal
+}
+
+func (scd *sequentialSignalChannelData) close() {
+ close(scd.in)
+ // Ensure that bufferSignals() has exited and won't attempt
+ // any future sends on scd.ch
+ <-scd.done
+}
diff --git a/vendor/github.com/godbus/dbus/v5/server_interfaces.go b/vendor/github.com/godbus/dbus/v5/server_interfaces.go
@@ -0,0 +1,107 @@
+package dbus
+
+// Terminator allows a handler to implement a shutdown mechanism that
+// is called when the connection terminates.
+type Terminator interface {
+ Terminate()
+}
+
+// Handler is the representation of a D-Bus Application.
+//
+// The Handler must have a way to lookup objects given
+// an ObjectPath. The returned object must implement the
+// ServerObject interface.
+type Handler interface {
+ LookupObject(path ObjectPath) (ServerObject, bool)
+}
+
+// ServerObject is the representation of an D-Bus Object.
+//
+// Objects are registered at a path for a given Handler.
+// The Objects implement D-Bus interfaces. The semantics
+// of Interface lookup is up to the implementation of
+// the ServerObject. The ServerObject implementation may
+// choose to implement empty string as a valid interface
+// represeting all methods or not per the D-Bus specification.
+type ServerObject interface {
+ LookupInterface(name string) (Interface, bool)
+}
+
+// An Interface is the representation of a D-Bus Interface.
+//
+// Interfaces are a grouping of methods implemented by the Objects.
+// Interfaces are responsible for routing method calls.
+type Interface interface {
+ LookupMethod(name string) (Method, bool)
+}
+
+// A Method represents the exposed methods on D-Bus.
+type Method interface {
+ // Call requires that all arguments are decoded before being passed to it.
+ Call(args ...interface{}) ([]interface{}, error)
+ NumArguments() int
+ NumReturns() int
+ // ArgumentValue returns a representative value for the argument at position
+ // it should be of the proper type. reflect.Zero would be a good mechanism
+ // to use for this Value.
+ ArgumentValue(position int) interface{}
+ // ReturnValue returns a representative value for the return at position
+ // it should be of the proper type. reflect.Zero would be a good mechanism
+ // to use for this Value.
+ ReturnValue(position int) interface{}
+}
+
+// An Argument Decoder can decode arguments using the non-standard mechanism
+//
+// If a method implements this interface then the non-standard
+// decoder will be used.
+//
+// Method arguments must be decoded from the message.
+// The mechanism for doing this will vary based on the
+// implementation of the method. A normal approach is provided
+// as part of this library, but may be replaced with
+// any other decoding scheme.
+type ArgumentDecoder interface {
+ // To decode the arguments of a method the sender and message are
+ // provided incase the semantics of the implementer provides access
+ // to these as part of the method invocation.
+ DecodeArguments(conn *Conn, sender string, msg *Message, args []interface{}) ([]interface{}, error)
+}
+
+// A SignalHandler is responsible for delivering a signal.
+//
+// Signal delivery may be changed from the default channel
+// based approach by Handlers implementing the SignalHandler
+// interface.
+type SignalHandler interface {
+ DeliverSignal(iface, name string, signal *Signal)
+}
+
+// SignalRegistrar manages signal delivery channels.
+//
+// This is an optional set of methods for `SignalHandler`.
+type SignalRegistrar interface {
+ AddSignal(ch chan<- *Signal)
+ RemoveSignal(ch chan<- *Signal)
+}
+
+// A DBusError is used to convert a generic object to a D-Bus error.
+//
+// Any custom error mechanism may implement this interface to provide
+// a custom encoding of the error on D-Bus. By default if a normal
+// error is returned, it will be encoded as the generic
+// "org.freedesktop.DBus.Error.Failed" error. By implementing this
+// interface as well a custom encoding may be provided.
+type DBusError interface {
+ DBusError() (string, []interface{})
+}
+
+// SerialGenerator is responsible for serials generation.
+//
+// Different approaches for the serial generation can be used,
+// maintaining a map guarded with a mutex (the standard way) or
+// simply increment an atomic counter.
+type SerialGenerator interface {
+ GetSerial() uint32
+ RetireSerial(serial uint32)
+}
diff --git a/vendor/github.com/godbus/dbus/v5/sig.go b/vendor/github.com/godbus/dbus/v5/sig.go
@@ -0,0 +1,259 @@
+package dbus
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+)
+
+var sigToType = map[byte]reflect.Type{
+ 'y': byteType,
+ 'b': boolType,
+ 'n': int16Type,
+ 'q': uint16Type,
+ 'i': int32Type,
+ 'u': uint32Type,
+ 'x': int64Type,
+ 't': uint64Type,
+ 'd': float64Type,
+ 's': stringType,
+ 'g': signatureType,
+ 'o': objectPathType,
+ 'v': variantType,
+ 'h': unixFDIndexType,
+}
+
+// Signature represents a correct type signature as specified by the D-Bus
+// specification. The zero value represents the empty signature, "".
+type Signature struct {
+ str string
+}
+
+// SignatureOf returns the concatenation of all the signatures of the given
+// values. It panics if one of them is not representable in D-Bus.
+func SignatureOf(vs ...interface{}) Signature {
+ var s string
+ for _, v := range vs {
+ s += getSignature(reflect.TypeOf(v))
+ }
+ return Signature{s}
+}
+
+// SignatureOfType returns the signature of the given type. It panics if the
+// type is not representable in D-Bus.
+func SignatureOfType(t reflect.Type) Signature {
+ return Signature{getSignature(t)}
+}
+
+// getSignature returns the signature of the given type and panics on unknown types.
+func getSignature(t reflect.Type) string {
+ // handle simple types first
+ switch t.Kind() {
+ case reflect.Uint8:
+ return "y"
+ case reflect.Bool:
+ return "b"
+ case reflect.Int16:
+ return "n"
+ case reflect.Uint16:
+ return "q"
+ case reflect.Int, reflect.Int32:
+ if t == unixFDType {
+ return "h"
+ }
+ return "i"
+ case reflect.Uint, reflect.Uint32:
+ if t == unixFDIndexType {
+ return "h"
+ }
+ return "u"
+ case reflect.Int64:
+ return "x"
+ case reflect.Uint64:
+ return "t"
+ case reflect.Float64:
+ return "d"
+ case reflect.Ptr:
+ return getSignature(t.Elem())
+ case reflect.String:
+ if t == objectPathType {
+ return "o"
+ }
+ return "s"
+ case reflect.Struct:
+ if t == variantType {
+ return "v"
+ } else if t == signatureType {
+ return "g"
+ }
+ var s string
+ for i := 0; i < t.NumField(); i++ {
+ field := t.Field(i)
+ if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
+ s += getSignature(t.Field(i).Type)
+ }
+ }
+ return "(" + s + ")"
+ case reflect.Array, reflect.Slice:
+ return "a" + getSignature(t.Elem())
+ case reflect.Map:
+ if !isKeyType(t.Key()) {
+ panic(InvalidTypeError{t})
+ }
+ return "a{" + getSignature(t.Key()) + getSignature(t.Elem()) + "}"
+ case reflect.Interface:
+ return "v"
+ }
+ panic(InvalidTypeError{t})
+}
+
+// ParseSignature returns the signature represented by this string, or a
+// SignatureError if the string is not a valid signature.
+func ParseSignature(s string) (sig Signature, err error) {
+ if len(s) == 0 {
+ return
+ }
+ if len(s) > 255 {
+ return Signature{""}, SignatureError{s, "too long"}
+ }
+ sig.str = s
+ for err == nil && len(s) != 0 {
+ err, s = validSingle(s, 0)
+ }
+ if err != nil {
+ sig = Signature{""}
+ }
+
+ return
+}
+
+// ParseSignatureMust behaves like ParseSignature, except that it panics if s
+// is not valid.
+func ParseSignatureMust(s string) Signature {
+ sig, err := ParseSignature(s)
+ if err != nil {
+ panic(err)
+ }
+ return sig
+}
+
+// Empty returns whether the signature is the empty signature.
+func (s Signature) Empty() bool {
+ return s.str == ""
+}
+
+// Single returns whether the signature represents a single, complete type.
+func (s Signature) Single() bool {
+ err, r := validSingle(s.str, 0)
+ return err != nil && r == ""
+}
+
+// String returns the signature's string representation.
+func (s Signature) String() string {
+ return s.str
+}
+
+// A SignatureError indicates that a signature passed to a function or received
+// on a connection is not a valid signature.
+type SignatureError struct {
+ Sig string
+ Reason string
+}
+
+func (e SignatureError) Error() string {
+ return fmt.Sprintf("dbus: invalid signature: %q (%s)", e.Sig, e.Reason)
+}
+
+// Try to read a single type from this string. If it was successful, err is nil
+// and rem is the remaining unparsed part. Otherwise, err is a non-nil
+// SignatureError and rem is "". depth is the current recursion depth which may
+// not be greater than 64 and should be given as 0 on the first call.
+func validSingle(s string, depth int) (err error, rem string) {
+ if s == "" {
+ return SignatureError{Sig: s, Reason: "empty signature"}, ""
+ }
+ if depth > 64 {
+ return SignatureError{Sig: s, Reason: "container nesting too deep"}, ""
+ }
+ switch s[0] {
+ case 'y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 'd', 's', 'g', 'o', 'v', 'h':
+ return nil, s[1:]
+ case 'a':
+ if len(s) > 1 && s[1] == '{' {
+ i := findMatching(s[1:], '{', '}')
+ if i == -1 {
+ return SignatureError{Sig: s, Reason: "unmatched '{'"}, ""
+ }
+ i++
+ rem = s[i+1:]
+ s = s[2:i]
+ if err, _ = validSingle(s[:1], depth+1); err != nil {
+ return err, ""
+ }
+ err, nr := validSingle(s[1:], depth+1)
+ if err != nil {
+ return err, ""
+ }
+ if nr != "" {
+ return SignatureError{Sig: s, Reason: "too many types in dict"}, ""
+ }
+ return nil, rem
+ }
+ return validSingle(s[1:], depth+1)
+ case '(':
+ i := findMatching(s, '(', ')')
+ if i == -1 {
+ return SignatureError{Sig: s, Reason: "unmatched ')'"}, ""
+ }
+ rem = s[i+1:]
+ s = s[1:i]
+ for err == nil && s != "" {
+ err, s = validSingle(s, depth+1)
+ }
+ if err != nil {
+ rem = ""
+ }
+ return
+ }
+ return SignatureError{Sig: s, Reason: "invalid type character"}, ""
+}
+
+func findMatching(s string, left, right rune) int {
+ n := 0
+ for i, v := range s {
+ if v == left {
+ n++
+ } else if v == right {
+ n--
+ }
+ if n == 0 {
+ return i
+ }
+ }
+ return -1
+}
+
+// typeFor returns the type of the given signature. It ignores any left over
+// characters and panics if s doesn't start with a valid type signature.
+func typeFor(s string) (t reflect.Type) {
+ err, _ := validSingle(s, 0)
+ if err != nil {
+ panic(err)
+ }
+
+ if t, ok := sigToType[s[0]]; ok {
+ return t
+ }
+ switch s[0] {
+ case 'a':
+ if s[1] == '{' {
+ i := strings.LastIndex(s, "}")
+ t = reflect.MapOf(sigToType[s[2]], typeFor(s[3:i]))
+ } else {
+ t = reflect.SliceOf(typeFor(s[1:]))
+ }
+ case '(':
+ t = interfacesType
+ }
+ return
+}
diff --git a/vendor/github.com/godbus/dbus/v5/transport_darwin.go b/vendor/github.com/godbus/dbus/v5/transport_darwin.go
@@ -0,0 +1,6 @@
+package dbus
+
+func (t *unixTransport) SendNullByte() error {
+ _, err := t.Write([]byte{0})
+ return err
+}
diff --git a/vendor/github.com/godbus/dbus/v5/transport_generic.go b/vendor/github.com/godbus/dbus/v5/transport_generic.go
@@ -0,0 +1,50 @@
+package dbus
+
+import (
+ "encoding/binary"
+ "errors"
+ "io"
+ "unsafe"
+)
+
+var nativeEndian binary.ByteOrder
+
+func detectEndianness() binary.ByteOrder {
+ var x uint32 = 0x01020304
+ if *(*byte)(unsafe.Pointer(&x)) == 0x01 {
+ return binary.BigEndian
+ }
+ return binary.LittleEndian
+}
+
+func init() {
+ nativeEndian = detectEndianness()
+}
+
+type genericTransport struct {
+ io.ReadWriteCloser
+}
+
+func (t genericTransport) SendNullByte() error {
+ _, err := t.Write([]byte{0})
+ return err
+}
+
+func (t genericTransport) SupportsUnixFDs() bool {
+ return false
+}
+
+func (t genericTransport) EnableUnixFDs() {}
+
+func (t genericTransport) ReadMessage() (*Message, error) {
+ return DecodeMessage(t)
+}
+
+func (t genericTransport) SendMessage(msg *Message) error {
+ for _, v := range msg.Body {
+ if _, ok := v.(UnixFD); ok {
+ return errors.New("dbus: unix fd passing not enabled")
+ }
+ }
+ return msg.EncodeTo(t, nativeEndian)
+}
diff --git a/vendor/github.com/godbus/dbus/v5/transport_nonce_tcp.go b/vendor/github.com/godbus/dbus/v5/transport_nonce_tcp.go
@@ -0,0 +1,39 @@
+//+build !windows
+
+package dbus
+
+import (
+ "errors"
+ "io/ioutil"
+ "net"
+)
+
+func init() {
+ transports["nonce-tcp"] = newNonceTcpTransport
+}
+
+func newNonceTcpTransport(keys string) (transport, error) {
+ host := getKey(keys, "host")
+ port := getKey(keys, "port")
+ noncefile := getKey(keys, "noncefile")
+ if host == "" || port == "" || noncefile == "" {
+ return nil, errors.New("dbus: unsupported address (must set host, port and noncefile)")
+ }
+ protocol, err := tcpFamily(keys)
+ if err != nil {
+ return nil, err
+ }
+ socket, err := net.Dial(protocol, net.JoinHostPort(host, port))
+ if err != nil {
+ return nil, err
+ }
+ b, err := ioutil.ReadFile(noncefile)
+ if err != nil {
+ return nil, err
+ }
+ _, err = socket.Write(b)
+ if err != nil {
+ return nil, err
+ }
+ return NewConn(socket)
+}
diff --git a/vendor/github.com/godbus/dbus/v5/transport_tcp.go b/vendor/github.com/godbus/dbus/v5/transport_tcp.go
@@ -0,0 +1,41 @@
+package dbus
+
+import (
+ "errors"
+ "net"
+)
+
+func init() {
+ transports["tcp"] = newTcpTransport
+}
+
+func tcpFamily(keys string) (string, error) {
+ switch getKey(keys, "family") {
+ case "":
+ return "tcp", nil
+ case "ipv4":
+ return "tcp4", nil
+ case "ipv6":
+ return "tcp6", nil
+ default:
+ return "", errors.New("dbus: invalid tcp family (must be ipv4 or ipv6)")
+ }
+}
+
+func newTcpTransport(keys string) (transport, error) {
+ host := getKey(keys, "host")
+ port := getKey(keys, "port")
+ if host == "" || port == "" {
+ return nil, errors.New("dbus: unsupported address (must set host and port)")
+ }
+
+ protocol, err := tcpFamily(keys)
+ if err != nil {
+ return nil, err
+ }
+ socket, err := net.Dial(protocol, net.JoinHostPort(host, port))
+ if err != nil {
+ return nil, err
+ }
+ return NewConn(socket)
+}
diff --git a/vendor/github.com/godbus/dbus/v5/transport_unix.go b/vendor/github.com/godbus/dbus/v5/transport_unix.go
@@ -0,0 +1,214 @@
+//+build !windows,!solaris
+
+package dbus
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "io"
+ "net"
+ "syscall"
+)
+
+type oobReader struct {
+ conn *net.UnixConn
+ oob []byte
+ buf [4096]byte
+}
+
+func (o *oobReader) Read(b []byte) (n int, err error) {
+ n, oobn, flags, _, err := o.conn.ReadMsgUnix(b, o.buf[:])
+ if err != nil {
+ return n, err
+ }
+ if flags&syscall.MSG_CTRUNC != 0 {
+ return n, errors.New("dbus: control data truncated (too many fds received)")
+ }
+ o.oob = append(o.oob, o.buf[:oobn]...)
+ return n, nil
+}
+
+type unixTransport struct {
+ *net.UnixConn
+ rdr *oobReader
+ hasUnixFDs bool
+}
+
+func newUnixTransport(keys string) (transport, error) {
+ var err error
+
+ t := new(unixTransport)
+ abstract := getKey(keys, "abstract")
+ path := getKey(keys, "path")
+ switch {
+ case abstract == "" && path == "":
+ return nil, errors.New("dbus: invalid address (neither path nor abstract set)")
+ case abstract != "" && path == "":
+ t.UnixConn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: "@" + abstract, Net: "unix"})
+ if err != nil {
+ return nil, err
+ }
+ return t, nil
+ case abstract == "" && path != "":
+ t.UnixConn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: path, Net: "unix"})
+ if err != nil {
+ return nil, err
+ }
+ return t, nil
+ default:
+ return nil, errors.New("dbus: invalid address (both path and abstract set)")
+ }
+}
+
+func init() {
+ transports["unix"] = newUnixTransport
+}
+
+func (t *unixTransport) EnableUnixFDs() {
+ t.hasUnixFDs = true
+}
+
+func (t *unixTransport) ReadMessage() (*Message, error) {
+ var (
+ blen, hlen uint32
+ csheader [16]byte
+ headers []header
+ order binary.ByteOrder
+ unixfds uint32
+ )
+ // To be sure that all bytes of out-of-band data are read, we use a special
+ // reader that uses ReadUnix on the underlying connection instead of Read
+ // and gathers the out-of-band data in a buffer.
+ if t.rdr == nil {
+ t.rdr = &oobReader{conn: t.UnixConn}
+ } else {
+ t.rdr.oob = nil
+ }
+
+ // read the first 16 bytes (the part of the header that has a constant size),
+ // from which we can figure out the length of the rest of the message
+ if _, err := io.ReadFull(t.rdr, csheader[:]); err != nil {
+ return nil, err
+ }
+ switch csheader[0] {
+ case 'l':
+ order = binary.LittleEndian
+ case 'B':
+ order = binary.BigEndian
+ default:
+ return nil, InvalidMessageError("invalid byte order")
+ }
+ // csheader[4:8] -> length of message body, csheader[12:16] -> length of
+ // header fields (without alignment)
+ binary.Read(bytes.NewBuffer(csheader[4:8]), order, &blen)
+ binary.Read(bytes.NewBuffer(csheader[12:]), order, &hlen)
+ if hlen%8 != 0 {
+ hlen += 8 - (hlen % 8)
+ }
+
+ // decode headers and look for unix fds
+ headerdata := make([]byte, hlen+4)
+ copy(headerdata, csheader[12:])
+ if _, err := io.ReadFull(t.rdr, headerdata[4:]); err != nil {
+ return nil, err
+ }
+ dec := newDecoder(bytes.NewBuffer(headerdata), order)
+ dec.pos = 12
+ vs, err := dec.Decode(Signature{"a(yv)"})
+ if err != nil {
+ return nil, err
+ }
+ Store(vs, &headers)
+ for _, v := range headers {
+ if v.Field == byte(FieldUnixFDs) {
+ unixfds, _ = v.Variant.value.(uint32)
+ }
+ }
+ all := make([]byte, 16+hlen+blen)
+ copy(all, csheader[:])
+ copy(all[16:], headerdata[4:])
+ if _, err := io.ReadFull(t.rdr, all[16+hlen:]); err != nil {
+ return nil, err
+ }
+ if unixfds != 0 {
+ if !t.hasUnixFDs {
+ return nil, errors.New("dbus: got unix fds on unsupported transport")
+ }
+ // read the fds from the OOB data
+ scms, err := syscall.ParseSocketControlMessage(t.rdr.oob)
+ if err != nil {
+ return nil, err
+ }
+ if len(scms) != 1 {
+ return nil, errors.New("dbus: received more than one socket control message")
+ }
+ fds, err := syscall.ParseUnixRights(&scms[0])
+ if err != nil {
+ return nil, err
+ }
+ msg, err := DecodeMessage(bytes.NewBuffer(all))
+ if err != nil {
+ return nil, err
+ }
+ // substitute the values in the message body (which are indices for the
+ // array receiver via OOB) with the actual values
+ for i, v := range msg.Body {
+ switch v.(type) {
+ case UnixFDIndex:
+ j := v.(UnixFDIndex)
+ if uint32(j) >= unixfds {
+ return nil, InvalidMessageError("invalid index for unix fd")
+ }
+ msg.Body[i] = UnixFD(fds[j])
+ case []UnixFDIndex:
+ idxArray := v.([]UnixFDIndex)
+ fdArray := make([]UnixFD, len(idxArray))
+ for k, j := range idxArray {
+ if uint32(j) >= unixfds {
+ return nil, InvalidMessageError("invalid index for unix fd")
+ }
+ fdArray[k] = UnixFD(fds[j])
+ }
+ msg.Body[i] = fdArray
+ }
+ }
+ return msg, nil
+ }
+ return DecodeMessage(bytes.NewBuffer(all))
+}
+
+func (t *unixTransport) SendMessage(msg *Message) error {
+ fds := make([]int, 0)
+ for i, v := range msg.Body {
+ if fd, ok := v.(UnixFD); ok {
+ msg.Body[i] = UnixFDIndex(len(fds))
+ fds = append(fds, int(fd))
+ }
+ }
+ if len(fds) != 0 {
+ if !t.hasUnixFDs {
+ return errors.New("dbus: unix fd passing not enabled")
+ }
+ msg.Headers[FieldUnixFDs] = MakeVariant(uint32(len(fds)))
+ oob := syscall.UnixRights(fds...)
+ buf := new(bytes.Buffer)
+ msg.EncodeTo(buf, nativeEndian)
+ n, oobn, err := t.UnixConn.WriteMsgUnix(buf.Bytes(), oob, nil)
+ if err != nil {
+ return err
+ }
+ if n != buf.Len() || oobn != len(oob) {
+ return io.ErrShortWrite
+ }
+ } else {
+ if err := msg.EncodeTo(t, nativeEndian); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (t *unixTransport) SupportsUnixFDs() bool {
+ return true
+}
diff --git a/vendor/github.com/godbus/dbus/v5/transport_unixcred_dragonfly.go b/vendor/github.com/godbus/dbus/v5/transport_unixcred_dragonfly.go
@@ -0,0 +1,95 @@
+// The UnixCredentials system call is currently only implemented on Linux
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// https://golang.org/s/go1.4-syscall
+// http://code.google.com/p/go/source/browse/unix/sockcmsg_linux.go?repo=sys
+
+// Local implementation of the UnixCredentials system call for DragonFly BSD
+
+package dbus
+
+/*
+#include <sys/ucred.h>
+*/
+import "C"
+
+import (
+ "io"
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+// http://golang.org/src/pkg/syscall/ztypes_linux_amd64.go
+// http://golang.org/src/pkg/syscall/ztypes_dragonfly_amd64.go
+type Ucred struct {
+ Pid int32
+ Uid uint32
+ Gid uint32
+}
+
+// http://golang.org/src/pkg/syscall/types_linux.go
+// http://golang.org/src/pkg/syscall/types_dragonfly.go
+// https://github.com/DragonFlyBSD/DragonFlyBSD/blob/master/sys/sys/ucred.h
+const (
+ SizeofUcred = C.sizeof_struct_ucred
+)
+
+// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
+func cmsgAlignOf(salen int) int {
+ // From http://golang.org/src/pkg/syscall/sockcmsg_unix.go
+ //salign := sizeofPtr
+ // NOTE: It seems like 64-bit Darwin and DragonFly BSD kernels
+ // still require 32-bit aligned access to network subsystem.
+ //if darwin64Bit || dragonfly64Bit {
+ // salign = 4
+ //}
+ salign := 4
+ return (salen + salign - 1) & ^(salign - 1)
+}
+
+// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
+func cmsgData(h *syscall.Cmsghdr) unsafe.Pointer {
+ return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(syscall.SizeofCmsghdr)))
+}
+
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// UnixCredentials encodes credentials into a socket control message
+// for sending to another process. This can be used for
+// authentication.
+func UnixCredentials(ucred *Ucred) []byte {
+ b := make([]byte, syscall.CmsgSpace(SizeofUcred))
+ h := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
+ h.Level = syscall.SOL_SOCKET
+ h.Type = syscall.SCM_CREDS
+ h.SetLen(syscall.CmsgLen(SizeofUcred))
+ *((*Ucred)(cmsgData(h))) = *ucred
+ return b
+}
+
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// ParseUnixCredentials decodes a socket control message that contains
+// credentials in a Ucred structure. To receive such a message, the
+// SO_PASSCRED option must be enabled on the socket.
+func ParseUnixCredentials(m *syscall.SocketControlMessage) (*Ucred, error) {
+ if m.Header.Level != syscall.SOL_SOCKET {
+ return nil, syscall.EINVAL
+ }
+ if m.Header.Type != syscall.SCM_CREDS {
+ return nil, syscall.EINVAL
+ }
+ ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0]))
+ return &ucred, nil
+}
+
+func (t *unixTransport) SendNullByte() error {
+ ucred := &Ucred{Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid())}
+ b := UnixCredentials(ucred)
+ _, oobn, err := t.UnixConn.WriteMsgUnix([]byte{0}, b, nil)
+ if err != nil {
+ return err
+ }
+ if oobn != len(b) {
+ return io.ErrShortWrite
+ }
+ return nil
+}
diff --git a/vendor/github.com/godbus/dbus/v5/transport_unixcred_freebsd.go b/vendor/github.com/godbus/dbus/v5/transport_unixcred_freebsd.go
@@ -0,0 +1,92 @@
+// The UnixCredentials system call is currently only implemented on Linux
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// https://golang.org/s/go1.4-syscall
+// http://code.google.com/p/go/source/browse/unix/sockcmsg_linux.go?repo=sys
+
+// Local implementation of the UnixCredentials system call for FreeBSD
+
+package dbus
+
+/*
+const int sizeofPtr = sizeof(void*);
+#define _WANT_UCRED
+#include <sys/types.h>
+#include <sys/ucred.h>
+*/
+import "C"
+
+import (
+ "io"
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+// http://golang.org/src/pkg/syscall/ztypes_linux_amd64.go
+// https://golang.org/src/syscall/ztypes_freebsd_amd64.go
+type Ucred struct {
+ Pid int32
+ Uid uint32
+ Gid uint32
+}
+
+// http://golang.org/src/pkg/syscall/types_linux.go
+// https://golang.org/src/syscall/types_freebsd.go
+// https://github.com/freebsd/freebsd/blob/master/sys/sys/ucred.h
+const (
+ SizeofUcred = C.sizeof_struct_ucred
+)
+
+// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
+func cmsgAlignOf(salen int) int {
+ salign := C.sizeofPtr
+
+ return (salen + salign - 1) & ^(salign - 1)
+}
+
+// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
+func cmsgData(h *syscall.Cmsghdr) unsafe.Pointer {
+ return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(syscall.SizeofCmsghdr)))
+}
+
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// UnixCredentials encodes credentials into a socket control message
+// for sending to another process. This can be used for
+// authentication.
+func UnixCredentials(ucred *Ucred) []byte {
+ b := make([]byte, syscall.CmsgSpace(SizeofUcred))
+ h := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
+ h.Level = syscall.SOL_SOCKET
+ h.Type = syscall.SCM_CREDS
+ h.SetLen(syscall.CmsgLen(SizeofUcred))
+ *((*Ucred)(cmsgData(h))) = *ucred
+ return b
+}
+
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// ParseUnixCredentials decodes a socket control message that contains
+// credentials in a Ucred structure. To receive such a message, the
+// SO_PASSCRED option must be enabled on the socket.
+func ParseUnixCredentials(m *syscall.SocketControlMessage) (*Ucred, error) {
+ if m.Header.Level != syscall.SOL_SOCKET {
+ return nil, syscall.EINVAL
+ }
+ if m.Header.Type != syscall.SCM_CREDS {
+ return nil, syscall.EINVAL
+ }
+ ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0]))
+ return &ucred, nil
+}
+
+func (t *unixTransport) SendNullByte() error {
+ ucred := &Ucred{Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid())}
+ b := UnixCredentials(ucred)
+ _, oobn, err := t.UnixConn.WriteMsgUnix([]byte{0}, b, nil)
+ if err != nil {
+ return err
+ }
+ if oobn != len(b) {
+ return io.ErrShortWrite
+ }
+ return nil
+}
diff --git a/vendor/github.com/godbus/dbus/v5/transport_unixcred_linux.go b/vendor/github.com/godbus/dbus/v5/transport_unixcred_linux.go
@@ -0,0 +1,25 @@
+// The UnixCredentials system call is currently only implemented on Linux
+// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
+// https://golang.org/s/go1.4-syscall
+// http://code.google.com/p/go/source/browse/unix/sockcmsg_linux.go?repo=sys
+
+package dbus
+
+import (
+ "io"
+ "os"
+ "syscall"
+)
+
+func (t *unixTransport) SendNullByte() error {
+ ucred := &syscall.Ucred{Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid())}
+ b := syscall.UnixCredentials(ucred)
+ _, oobn, err := t.UnixConn.WriteMsgUnix([]byte{0}, b, nil)
+ if err != nil {
+ return err
+ }
+ if oobn != len(b) {
+ return io.ErrShortWrite
+ }
+ return nil
+}
diff --git a/vendor/github.com/godbus/dbus/v5/transport_unixcred_openbsd.go b/vendor/github.com/godbus/dbus/v5/transport_unixcred_openbsd.go
@@ -0,0 +1,14 @@
+package dbus
+
+import "io"
+
+func (t *unixTransport) SendNullByte() error {
+ n, _, err := t.UnixConn.WriteMsgUnix([]byte{0}, nil, nil)
+ if err != nil {
+ return err
+ }
+ if n != 1 {
+ return io.ErrShortWrite
+ }
+ return nil
+}
diff --git a/vendor/github.com/godbus/dbus/v5/variant.go b/vendor/github.com/godbus/dbus/v5/variant.go
@@ -0,0 +1,150 @@
+package dbus
+
+import (
+ "bytes"
+ "fmt"
+ "reflect"
+ "sort"
+ "strconv"
+)
+
+// Variant represents the D-Bus variant type.
+type Variant struct {
+ sig Signature
+ value interface{}
+}
+
+// MakeVariant converts the given value to a Variant. It panics if v cannot be
+// represented as a D-Bus type.
+func MakeVariant(v interface{}) Variant {
+ return MakeVariantWithSignature(v, SignatureOf(v))
+}
+
+// MakeVariantWithSignature converts the given value to a Variant.
+func MakeVariantWithSignature(v interface{}, s Signature) Variant {
+ return Variant{s, v}
+}
+
+// ParseVariant parses the given string as a variant as described at
+// https://developer.gnome.org/glib/stable/gvariant-text.html. If sig is not
+// empty, it is taken to be the expected signature for the variant.
+func ParseVariant(s string, sig Signature) (Variant, error) {
+ tokens := varLex(s)
+ p := &varParser{tokens: tokens}
+ n, err := varMakeNode(p)
+ if err != nil {
+ return Variant{}, err
+ }
+ if sig.str == "" {
+ sig, err = varInfer(n)
+ if err != nil {
+ return Variant{}, err
+ }
+ }
+ v, err := n.Value(sig)
+ if err != nil {
+ return Variant{}, err
+ }
+ return MakeVariant(v), nil
+}
+
+// format returns a formatted version of v and whether this string can be parsed
+// unambigously.
+func (v Variant) format() (string, bool) {
+ switch v.sig.str[0] {
+ case 'b', 'i':
+ return fmt.Sprint(v.value), true
+ case 'n', 'q', 'u', 'x', 't', 'd', 'h':
+ return fmt.Sprint(v.value), false
+ case 's':
+ return strconv.Quote(v.value.(string)), true
+ case 'o':
+ return strconv.Quote(string(v.value.(ObjectPath))), false
+ case 'g':
+ return strconv.Quote(v.value.(Signature).str), false
+ case 'v':
+ s, unamb := v.value.(Variant).format()
+ if !unamb {
+ return "<@" + v.value.(Variant).sig.str + " " + s + ">", true
+ }
+ return "<" + s + ">", true
+ case 'y':
+ return fmt.Sprintf("%#x", v.value.(byte)), false
+ }
+ rv := reflect.ValueOf(v.value)
+ switch rv.Kind() {
+ case reflect.Slice:
+ if rv.Len() == 0 {
+ return "[]", false
+ }
+ unamb := true
+ buf := bytes.NewBuffer([]byte("["))
+ for i := 0; i < rv.Len(); i++ {
+ // TODO: slooow
+ s, b := MakeVariant(rv.Index(i).Interface()).format()
+ unamb = unamb && b
+ buf.WriteString(s)
+ if i != rv.Len()-1 {
+ buf.WriteString(", ")
+ }
+ }
+ buf.WriteByte(']')
+ return buf.String(), unamb
+ case reflect.Map:
+ if rv.Len() == 0 {
+ return "{}", false
+ }
+ unamb := true
+ var buf bytes.Buffer
+ kvs := make([]string, rv.Len())
+ for i, k := range rv.MapKeys() {
+ s, b := MakeVariant(k.Interface()).format()
+ unamb = unamb && b
+ buf.Reset()
+ buf.WriteString(s)
+ buf.WriteString(": ")
+ s, b = MakeVariant(rv.MapIndex(k).Interface()).format()
+ unamb = unamb && b
+ buf.WriteString(s)
+ kvs[i] = buf.String()
+ }
+ buf.Reset()
+ buf.WriteByte('{')
+ sort.Strings(kvs)
+ for i, kv := range kvs {
+ if i > 0 {
+ buf.WriteString(", ")
+ }
+ buf.WriteString(kv)
+ }
+ buf.WriteByte('}')
+ return buf.String(), unamb
+ }
+ return `"INVALID"`, true
+}
+
+// Signature returns the D-Bus signature of the underlying value of v.
+func (v Variant) Signature() Signature {
+ return v.sig
+}
+
+// String returns the string representation of the underlying value of v as
+// described at https://developer.gnome.org/glib/stable/gvariant-text.html.
+func (v Variant) String() string {
+ s, unamb := v.format()
+ if !unamb {
+ return "@" + v.sig.str + " " + s
+ }
+ return s
+}
+
+// Value returns the underlying value of v.
+func (v Variant) Value() interface{} {
+ return v.value
+}
+
+// Store converts the variant into a native go type using the same
+// mechanism as the "Store" function.
+func (v Variant) Store(value interface{}) error {
+ return storeInterfaces(v.value, value)
+}
diff --git a/vendor/github.com/godbus/dbus/v5/variant_lexer.go b/vendor/github.com/godbus/dbus/v5/variant_lexer.go
@@ -0,0 +1,284 @@
+package dbus
+
+import (
+ "fmt"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+// Heavily inspired by the lexer from text/template.
+
+type varToken struct {
+ typ varTokenType
+ val string
+}
+
+type varTokenType byte
+
+const (
+ tokEOF varTokenType = iota
+ tokError
+ tokNumber
+ tokString
+ tokBool
+ tokArrayStart
+ tokArrayEnd
+ tokDictStart
+ tokDictEnd
+ tokVariantStart
+ tokVariantEnd
+ tokComma
+ tokColon
+ tokType
+ tokByteString
+)
+
+type varLexer struct {
+ input string
+ start int
+ pos int
+ width int
+ tokens []varToken
+}
+
+type lexState func(*varLexer) lexState
+
+func varLex(s string) []varToken {
+ l := &varLexer{input: s}
+ l.run()
+ return l.tokens
+}
+
+func (l *varLexer) accept(valid string) bool {
+ if strings.ContainsRune(valid, l.next()) {
+ return true
+ }
+ l.backup()
+ return false
+}
+
+func (l *varLexer) backup() {
+ l.pos -= l.width
+}
+
+func (l *varLexer) emit(t varTokenType) {
+ l.tokens = append(l.tokens, varToken{t, l.input[l.start:l.pos]})
+ l.start = l.pos
+}
+
+func (l *varLexer) errorf(format string, v ...interface{}) lexState {
+ l.tokens = append(l.tokens, varToken{
+ tokError,
+ fmt.Sprintf(format, v...),
+ })
+ return nil
+}
+
+func (l *varLexer) ignore() {
+ l.start = l.pos
+}
+
+func (l *varLexer) next() rune {
+ var r rune
+
+ if l.pos >= len(l.input) {
+ l.width = 0
+ return -1
+ }
+ r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
+ l.pos += l.width
+ return r
+}
+
+func (l *varLexer) run() {
+ for state := varLexNormal; state != nil; {
+ state = state(l)
+ }
+}
+
+func (l *varLexer) peek() rune {
+ r := l.next()
+ l.backup()
+ return r
+}
+
+func varLexNormal(l *varLexer) lexState {
+ for {
+ r := l.next()
+ switch {
+ case r == -1:
+ l.emit(tokEOF)
+ return nil
+ case r == '[':
+ l.emit(tokArrayStart)
+ case r == ']':
+ l.emit(tokArrayEnd)
+ case r == '{':
+ l.emit(tokDictStart)
+ case r == '}':
+ l.emit(tokDictEnd)
+ case r == '<':
+ l.emit(tokVariantStart)
+ case r == '>':
+ l.emit(tokVariantEnd)
+ case r == ':':
+ l.emit(tokColon)
+ case r == ',':
+ l.emit(tokComma)
+ case r == '\'' || r == '"':
+ l.backup()
+ return varLexString
+ case r == '@':
+ l.backup()
+ return varLexType
+ case unicode.IsSpace(r):
+ l.ignore()
+ case unicode.IsNumber(r) || r == '+' || r == '-':
+ l.backup()
+ return varLexNumber
+ case r == 'b':
+ pos := l.start
+ if n := l.peek(); n == '"' || n == '\'' {
+ return varLexByteString
+ }
+ // not a byte string; try to parse it as a type or bool below
+ l.pos = pos + 1
+ l.width = 1
+ fallthrough
+ default:
+ // either a bool or a type. Try bools first.
+ l.backup()
+ if l.pos+4 <= len(l.input) {
+ if l.input[l.pos:l.pos+4] == "true" {
+ l.pos += 4
+ l.emit(tokBool)
+ continue
+ }
+ }
+ if l.pos+5 <= len(l.input) {
+ if l.input[l.pos:l.pos+5] == "false" {
+ l.pos += 5
+ l.emit(tokBool)
+ continue
+ }
+ }
+ // must be a type.
+ return varLexType
+ }
+ }
+}
+
+var varTypeMap = map[string]string{
+ "boolean": "b",
+ "byte": "y",
+ "int16": "n",
+ "uint16": "q",
+ "int32": "i",
+ "uint32": "u",
+ "int64": "x",
+ "uint64": "t",
+ "double": "f",
+ "string": "s",
+ "objectpath": "o",
+ "signature": "g",
+}
+
+func varLexByteString(l *varLexer) lexState {
+ q := l.next()
+Loop:
+ for {
+ switch l.next() {
+ case '\\':
+ if r := l.next(); r != -1 {
+ break
+ }
+ fallthrough
+ case -1:
+ return l.errorf("unterminated bytestring")
+ case q:
+ break Loop
+ }
+ }
+ l.emit(tokByteString)
+ return varLexNormal
+}
+
+func varLexNumber(l *varLexer) lexState {
+ l.accept("+-")
+ digits := "0123456789"
+ if l.accept("0") {
+ if l.accept("x") {
+ digits = "0123456789abcdefABCDEF"
+ } else {
+ digits = "01234567"
+ }
+ }
+ for strings.ContainsRune(digits, l.next()) {
+ }
+ l.backup()
+ if l.accept(".") {
+ for strings.ContainsRune(digits, l.next()) {
+ }
+ l.backup()
+ }
+ if l.accept("eE") {
+ l.accept("+-")
+ for strings.ContainsRune("0123456789", l.next()) {
+ }
+ l.backup()
+ }
+ if r := l.peek(); unicode.IsLetter(r) {
+ l.next()
+ return l.errorf("bad number syntax: %q", l.input[l.start:l.pos])
+ }
+ l.emit(tokNumber)
+ return varLexNormal
+}
+
+func varLexString(l *varLexer) lexState {
+ q := l.next()
+Loop:
+ for {
+ switch l.next() {
+ case '\\':
+ if r := l.next(); r != -1 {
+ break
+ }
+ fallthrough
+ case -1:
+ return l.errorf("unterminated string")
+ case q:
+ break Loop
+ }
+ }
+ l.emit(tokString)
+ return varLexNormal
+}
+
+func varLexType(l *varLexer) lexState {
+ at := l.accept("@")
+ for {
+ r := l.next()
+ if r == -1 {
+ break
+ }
+ if unicode.IsSpace(r) {
+ l.backup()
+ break
+ }
+ }
+ if at {
+ if _, err := ParseSignature(l.input[l.start+1 : l.pos]); err != nil {
+ return l.errorf("%s", err)
+ }
+ } else {
+ if _, ok := varTypeMap[l.input[l.start:l.pos]]; ok {
+ l.emit(tokType)
+ return varLexNormal
+ }
+ return l.errorf("unrecognized type %q", l.input[l.start:l.pos])
+ }
+ l.emit(tokType)
+ return varLexNormal
+}
diff --git a/vendor/github.com/godbus/dbus/v5/variant_parser.go b/vendor/github.com/godbus/dbus/v5/variant_parser.go
@@ -0,0 +1,817 @@
+package dbus
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "reflect"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+)
+
+type varParser struct {
+ tokens []varToken
+ i int
+}
+
+func (p *varParser) backup() {
+ p.i--
+}
+
+func (p *varParser) next() varToken {
+ if p.i < len(p.tokens) {
+ t := p.tokens[p.i]
+ p.i++
+ return t
+ }
+ return varToken{typ: tokEOF}
+}
+
+type varNode interface {
+ Infer() (Signature, error)
+ String() string
+ Sigs() sigSet
+ Value(Signature) (interface{}, error)
+}
+
+func varMakeNode(p *varParser) (varNode, error) {
+ var sig Signature
+
+ for {
+ t := p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ case tokNumber:
+ return varMakeNumNode(t, sig)
+ case tokString:
+ return varMakeStringNode(t, sig)
+ case tokBool:
+ if sig.str != "" && sig.str != "b" {
+ return nil, varTypeError{t.val, sig}
+ }
+ b, err := strconv.ParseBool(t.val)
+ if err != nil {
+ return nil, err
+ }
+ return boolNode(b), nil
+ case tokArrayStart:
+ return varMakeArrayNode(p, sig)
+ case tokVariantStart:
+ return varMakeVariantNode(p, sig)
+ case tokDictStart:
+ return varMakeDictNode(p, sig)
+ case tokType:
+ if sig.str != "" {
+ return nil, errors.New("unexpected type annotation")
+ }
+ if t.val[0] == '@' {
+ sig.str = t.val[1:]
+ } else {
+ sig.str = varTypeMap[t.val]
+ }
+ case tokByteString:
+ if sig.str != "" && sig.str != "ay" {
+ return nil, varTypeError{t.val, sig}
+ }
+ b, err := varParseByteString(t.val)
+ if err != nil {
+ return nil, err
+ }
+ return byteStringNode(b), nil
+ default:
+ return nil, fmt.Errorf("unexpected %q", t.val)
+ }
+ }
+}
+
+type varTypeError struct {
+ val string
+ sig Signature
+}
+
+func (e varTypeError) Error() string {
+ return fmt.Sprintf("dbus: can't parse %q as type %q", e.val, e.sig.str)
+}
+
+type sigSet map[Signature]bool
+
+func (s sigSet) Empty() bool {
+ return len(s) == 0
+}
+
+func (s sigSet) Intersect(s2 sigSet) sigSet {
+ r := make(sigSet)
+ for k := range s {
+ if s2[k] {
+ r[k] = true
+ }
+ }
+ return r
+}
+
+func (s sigSet) Single() (Signature, bool) {
+ if len(s) == 1 {
+ for k := range s {
+ return k, true
+ }
+ }
+ return Signature{}, false
+}
+
+func (s sigSet) ToArray() sigSet {
+ r := make(sigSet, len(s))
+ for k := range s {
+ r[Signature{"a" + k.str}] = true
+ }
+ return r
+}
+
+type numNode struct {
+ sig Signature
+ str string
+ val interface{}
+}
+
+var numSigSet = sigSet{
+ Signature{"y"}: true,
+ Signature{"n"}: true,
+ Signature{"q"}: true,
+ Signature{"i"}: true,
+ Signature{"u"}: true,
+ Signature{"x"}: true,
+ Signature{"t"}: true,
+ Signature{"d"}: true,
+}
+
+func (n numNode) Infer() (Signature, error) {
+ if strings.ContainsAny(n.str, ".e") {
+ return Signature{"d"}, nil
+ }
+ return Signature{"i"}, nil
+}
+
+func (n numNode) String() string {
+ return n.str
+}
+
+func (n numNode) Sigs() sigSet {
+ if n.sig.str != "" {
+ return sigSet{n.sig: true}
+ }
+ if strings.ContainsAny(n.str, ".e") {
+ return sigSet{Signature{"d"}: true}
+ }
+ return numSigSet
+}
+
+func (n numNode) Value(sig Signature) (interface{}, error) {
+ if n.sig.str != "" && n.sig != sig {
+ return nil, varTypeError{n.str, sig}
+ }
+ if n.val != nil {
+ return n.val, nil
+ }
+ return varNumAs(n.str, sig)
+}
+
+func varMakeNumNode(tok varToken, sig Signature) (varNode, error) {
+ if sig.str == "" {
+ return numNode{str: tok.val}, nil
+ }
+ num, err := varNumAs(tok.val, sig)
+ if err != nil {
+ return nil, err
+ }
+ return numNode{sig: sig, val: num}, nil
+}
+
+func varNumAs(s string, sig Signature) (interface{}, error) {
+ isUnsigned := false
+ size := 32
+ switch sig.str {
+ case "n":
+ size = 16
+ case "i":
+ case "x":
+ size = 64
+ case "y":
+ size = 8
+ isUnsigned = true
+ case "q":
+ size = 16
+ isUnsigned = true
+ case "u":
+ isUnsigned = true
+ case "t":
+ size = 64
+ isUnsigned = true
+ case "d":
+ d, err := strconv.ParseFloat(s, 64)
+ if err != nil {
+ return nil, err
+ }
+ return d, nil
+ default:
+ return nil, varTypeError{s, sig}
+ }
+ base := 10
+ if strings.HasPrefix(s, "0x") {
+ base = 16
+ s = s[2:]
+ }
+ if strings.HasPrefix(s, "0") && len(s) != 1 {
+ base = 8
+ s = s[1:]
+ }
+ if isUnsigned {
+ i, err := strconv.ParseUint(s, base, size)
+ if err != nil {
+ return nil, err
+ }
+ var v interface{} = i
+ switch sig.str {
+ case "y":
+ v = byte(i)
+ case "q":
+ v = uint16(i)
+ case "u":
+ v = uint32(i)
+ }
+ return v, nil
+ }
+ i, err := strconv.ParseInt(s, base, size)
+ if err != nil {
+ return nil, err
+ }
+ var v interface{} = i
+ switch sig.str {
+ case "n":
+ v = int16(i)
+ case "i":
+ v = int32(i)
+ }
+ return v, nil
+}
+
+type stringNode struct {
+ sig Signature
+ str string // parsed
+ val interface{} // has correct type
+}
+
+var stringSigSet = sigSet{
+ Signature{"s"}: true,
+ Signature{"g"}: true,
+ Signature{"o"}: true,
+}
+
+func (n stringNode) Infer() (Signature, error) {
+ return Signature{"s"}, nil
+}
+
+func (n stringNode) String() string {
+ return n.str
+}
+
+func (n stringNode) Sigs() sigSet {
+ if n.sig.str != "" {
+ return sigSet{n.sig: true}
+ }
+ return stringSigSet
+}
+
+func (n stringNode) Value(sig Signature) (interface{}, error) {
+ if n.sig.str != "" && n.sig != sig {
+ return nil, varTypeError{n.str, sig}
+ }
+ if n.val != nil {
+ return n.val, nil
+ }
+ switch {
+ case sig.str == "g":
+ return Signature{n.str}, nil
+ case sig.str == "o":
+ return ObjectPath(n.str), nil
+ case sig.str == "s":
+ return n.str, nil
+ default:
+ return nil, varTypeError{n.str, sig}
+ }
+}
+
+func varMakeStringNode(tok varToken, sig Signature) (varNode, error) {
+ if sig.str != "" && sig.str != "s" && sig.str != "g" && sig.str != "o" {
+ return nil, fmt.Errorf("invalid type %q for string", sig.str)
+ }
+ s, err := varParseString(tok.val)
+ if err != nil {
+ return nil, err
+ }
+ n := stringNode{str: s}
+ if sig.str == "" {
+ return stringNode{str: s}, nil
+ }
+ n.sig = sig
+ switch sig.str {
+ case "o":
+ n.val = ObjectPath(s)
+ case "g":
+ n.val = Signature{s}
+ case "s":
+ n.val = s
+ }
+ return n, nil
+}
+
+func varParseString(s string) (string, error) {
+ // quotes are guaranteed to be there
+ s = s[1 : len(s)-1]
+ buf := new(bytes.Buffer)
+ for len(s) != 0 {
+ r, size := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && size == 1 {
+ return "", errors.New("invalid UTF-8")
+ }
+ s = s[size:]
+ if r != '\\' {
+ buf.WriteRune(r)
+ continue
+ }
+ r, size = utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && size == 1 {
+ return "", errors.New("invalid UTF-8")
+ }
+ s = s[size:]
+ switch r {
+ case 'a':
+ buf.WriteRune(0x7)
+ case 'b':
+ buf.WriteRune(0x8)
+ case 'f':
+ buf.WriteRune(0xc)
+ case 'n':
+ buf.WriteRune('\n')
+ case 'r':
+ buf.WriteRune('\r')
+ case 't':
+ buf.WriteRune('\t')
+ case '\n':
+ case 'u':
+ if len(s) < 4 {
+ return "", errors.New("short unicode escape")
+ }
+ r, err := strconv.ParseUint(s[:4], 16, 32)
+ if err != nil {
+ return "", err
+ }
+ buf.WriteRune(rune(r))
+ s = s[4:]
+ case 'U':
+ if len(s) < 8 {
+ return "", errors.New("short unicode escape")
+ }
+ r, err := strconv.ParseUint(s[:8], 16, 32)
+ if err != nil {
+ return "", err
+ }
+ buf.WriteRune(rune(r))
+ s = s[8:]
+ default:
+ buf.WriteRune(r)
+ }
+ }
+ return buf.String(), nil
+}
+
+var boolSigSet = sigSet{Signature{"b"}: true}
+
+type boolNode bool
+
+func (boolNode) Infer() (Signature, error) {
+ return Signature{"b"}, nil
+}
+
+func (b boolNode) String() string {
+ if b {
+ return "true"
+ }
+ return "false"
+}
+
+func (boolNode) Sigs() sigSet {
+ return boolSigSet
+}
+
+func (b boolNode) Value(sig Signature) (interface{}, error) {
+ if sig.str != "b" {
+ return nil, varTypeError{b.String(), sig}
+ }
+ return bool(b), nil
+}
+
+type arrayNode struct {
+ set sigSet
+ children []varNode
+ val interface{}
+}
+
+func (n arrayNode) Infer() (Signature, error) {
+ for _, v := range n.children {
+ csig, err := varInfer(v)
+ if err != nil {
+ continue
+ }
+ return Signature{"a" + csig.str}, nil
+ }
+ return Signature{}, fmt.Errorf("can't infer type for %q", n.String())
+}
+
+func (n arrayNode) String() string {
+ s := "["
+ for i, v := range n.children {
+ s += v.String()
+ if i != len(n.children)-1 {
+ s += ", "
+ }
+ }
+ return s + "]"
+}
+
+func (n arrayNode) Sigs() sigSet {
+ return n.set
+}
+
+func (n arrayNode) Value(sig Signature) (interface{}, error) {
+ if n.set.Empty() {
+ // no type information whatsoever, so this must be an empty slice
+ return reflect.MakeSlice(typeFor(sig.str), 0, 0).Interface(), nil
+ }
+ if !n.set[sig] {
+ return nil, varTypeError{n.String(), sig}
+ }
+ s := reflect.MakeSlice(typeFor(sig.str), len(n.children), len(n.children))
+ for i, v := range n.children {
+ rv, err := v.Value(Signature{sig.str[1:]})
+ if err != nil {
+ return nil, err
+ }
+ s.Index(i).Set(reflect.ValueOf(rv))
+ }
+ return s.Interface(), nil
+}
+
+func varMakeArrayNode(p *varParser, sig Signature) (varNode, error) {
+ var n arrayNode
+ if sig.str != "" {
+ n.set = sigSet{sig: true}
+ }
+ if t := p.next(); t.typ == tokArrayEnd {
+ return n, nil
+ } else {
+ p.backup()
+ }
+Loop:
+ for {
+ t := p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ }
+ p.backup()
+ cn, err := varMakeNode(p)
+ if err != nil {
+ return nil, err
+ }
+ if cset := cn.Sigs(); !cset.Empty() {
+ if n.set.Empty() {
+ n.set = cset.ToArray()
+ } else {
+ nset := cset.ToArray().Intersect(n.set)
+ if nset.Empty() {
+ return nil, fmt.Errorf("can't parse %q with given type information", cn.String())
+ }
+ n.set = nset
+ }
+ }
+ n.children = append(n.children, cn)
+ switch t := p.next(); t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ case tokArrayEnd:
+ break Loop
+ case tokComma:
+ continue
+ default:
+ return nil, fmt.Errorf("unexpected %q", t.val)
+ }
+ }
+ return n, nil
+}
+
+type variantNode struct {
+ n varNode
+}
+
+var variantSet = sigSet{
+ Signature{"v"}: true,
+}
+
+func (variantNode) Infer() (Signature, error) {
+ return Signature{"v"}, nil
+}
+
+func (n variantNode) String() string {
+ return "<" + n.n.String() + ">"
+}
+
+func (variantNode) Sigs() sigSet {
+ return variantSet
+}
+
+func (n variantNode) Value(sig Signature) (interface{}, error) {
+ if sig.str != "v" {
+ return nil, varTypeError{n.String(), sig}
+ }
+ sig, err := varInfer(n.n)
+ if err != nil {
+ return nil, err
+ }
+ v, err := n.n.Value(sig)
+ if err != nil {
+ return nil, err
+ }
+ return MakeVariant(v), nil
+}
+
+func varMakeVariantNode(p *varParser, sig Signature) (varNode, error) {
+ n, err := varMakeNode(p)
+ if err != nil {
+ return nil, err
+ }
+ if t := p.next(); t.typ != tokVariantEnd {
+ return nil, fmt.Errorf("unexpected %q", t.val)
+ }
+ vn := variantNode{n}
+ if sig.str != "" && sig.str != "v" {
+ return nil, varTypeError{vn.String(), sig}
+ }
+ return variantNode{n}, nil
+}
+
+type dictEntry struct {
+ key, val varNode
+}
+
+type dictNode struct {
+ kset, vset sigSet
+ children []dictEntry
+ val interface{}
+}
+
+func (n dictNode) Infer() (Signature, error) {
+ for _, v := range n.children {
+ ksig, err := varInfer(v.key)
+ if err != nil {
+ continue
+ }
+ vsig, err := varInfer(v.val)
+ if err != nil {
+ continue
+ }
+ return Signature{"a{" + ksig.str + vsig.str + "}"}, nil
+ }
+ return Signature{}, fmt.Errorf("can't infer type for %q", n.String())
+}
+
+func (n dictNode) String() string {
+ s := "{"
+ for i, v := range n.children {
+ s += v.key.String() + ": " + v.val.String()
+ if i != len(n.children)-1 {
+ s += ", "
+ }
+ }
+ return s + "}"
+}
+
+func (n dictNode) Sigs() sigSet {
+ r := sigSet{}
+ for k := range n.kset {
+ for v := range n.vset {
+ sig := "a{" + k.str + v.str + "}"
+ r[Signature{sig}] = true
+ }
+ }
+ return r
+}
+
+func (n dictNode) Value(sig Signature) (interface{}, error) {
+ set := n.Sigs()
+ if set.Empty() {
+ // no type information -> empty dict
+ return reflect.MakeMap(typeFor(sig.str)).Interface(), nil
+ }
+ if !set[sig] {
+ return nil, varTypeError{n.String(), sig}
+ }
+ m := reflect.MakeMap(typeFor(sig.str))
+ ksig := Signature{sig.str[2:3]}
+ vsig := Signature{sig.str[3 : len(sig.str)-1]}
+ for _, v := range n.children {
+ kv, err := v.key.Value(ksig)
+ if err != nil {
+ return nil, err
+ }
+ vv, err := v.val.Value(vsig)
+ if err != nil {
+ return nil, err
+ }
+ m.SetMapIndex(reflect.ValueOf(kv), reflect.ValueOf(vv))
+ }
+ return m.Interface(), nil
+}
+
+func varMakeDictNode(p *varParser, sig Signature) (varNode, error) {
+ var n dictNode
+
+ if sig.str != "" {
+ if len(sig.str) < 5 {
+ return nil, fmt.Errorf("invalid signature %q for dict type", sig)
+ }
+ ksig := Signature{string(sig.str[2])}
+ vsig := Signature{sig.str[3 : len(sig.str)-1]}
+ n.kset = sigSet{ksig: true}
+ n.vset = sigSet{vsig: true}
+ }
+ if t := p.next(); t.typ == tokDictEnd {
+ return n, nil
+ } else {
+ p.backup()
+ }
+Loop:
+ for {
+ t := p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ }
+ p.backup()
+ kn, err := varMakeNode(p)
+ if err != nil {
+ return nil, err
+ }
+ if kset := kn.Sigs(); !kset.Empty() {
+ if n.kset.Empty() {
+ n.kset = kset
+ } else {
+ n.kset = kset.Intersect(n.kset)
+ if n.kset.Empty() {
+ return nil, fmt.Errorf("can't parse %q with given type information", kn.String())
+ }
+ }
+ }
+ t = p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ case tokColon:
+ default:
+ return nil, fmt.Errorf("unexpected %q", t.val)
+ }
+ t = p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ }
+ p.backup()
+ vn, err := varMakeNode(p)
+ if err != nil {
+ return nil, err
+ }
+ if vset := vn.Sigs(); !vset.Empty() {
+ if n.vset.Empty() {
+ n.vset = vset
+ } else {
+ n.vset = n.vset.Intersect(vset)
+ if n.vset.Empty() {
+ return nil, fmt.Errorf("can't parse %q with given type information", vn.String())
+ }
+ }
+ }
+ n.children = append(n.children, dictEntry{kn, vn})
+ t = p.next()
+ switch t.typ {
+ case tokEOF:
+ return nil, io.ErrUnexpectedEOF
+ case tokError:
+ return nil, errors.New(t.val)
+ case tokDictEnd:
+ break Loop
+ case tokComma:
+ continue
+ default:
+ return nil, fmt.Errorf("unexpected %q", t.val)
+ }
+ }
+ return n, nil
+}
+
+type byteStringNode []byte
+
+var byteStringSet = sigSet{
+ Signature{"ay"}: true,
+}
+
+func (byteStringNode) Infer() (Signature, error) {
+ return Signature{"ay"}, nil
+}
+
+func (b byteStringNode) String() string {
+ return string(b)
+}
+
+func (b byteStringNode) Sigs() sigSet {
+ return byteStringSet
+}
+
+func (b byteStringNode) Value(sig Signature) (interface{}, error) {
+ if sig.str != "ay" {
+ return nil, varTypeError{b.String(), sig}
+ }
+ return []byte(b), nil
+}
+
+func varParseByteString(s string) ([]byte, error) {
+ // quotes and b at start are guaranteed to be there
+ b := make([]byte, 0, 1)
+ s = s[2 : len(s)-1]
+ for len(s) != 0 {
+ c := s[0]
+ s = s[1:]
+ if c != '\\' {
+ b = append(b, c)
+ continue
+ }
+ c = s[0]
+ s = s[1:]
+ switch c {
+ case 'a':
+ b = append(b, 0x7)
+ case 'b':
+ b = append(b, 0x8)
+ case 'f':
+ b = append(b, 0xc)
+ case 'n':
+ b = append(b, '\n')
+ case 'r':
+ b = append(b, '\r')
+ case 't':
+ b = append(b, '\t')
+ case 'x':
+ if len(s) < 2 {
+ return nil, errors.New("short escape")
+ }
+ n, err := strconv.ParseUint(s[:2], 16, 8)
+ if err != nil {
+ return nil, err
+ }
+ b = append(b, byte(n))
+ s = s[2:]
+ case '0':
+ if len(s) < 3 {
+ return nil, errors.New("short escape")
+ }
+ n, err := strconv.ParseUint(s[:3], 8, 8)
+ if err != nil {
+ return nil, err
+ }
+ b = append(b, byte(n))
+ s = s[3:]
+ default:
+ b = append(b, c)
+ }
+ }
+ return append(b, 0), nil
+}
+
+func varInfer(n varNode) (Signature, error) {
+ if sig, ok := n.Sigs().Single(); ok {
+ return sig, nil
+ }
+ return n.Infer()
+}
diff --git a/vendor/github.com/gogo/protobuf/AUTHORS b/vendor/github.com/gogo/protobuf/AUTHORS
@@ -0,0 +1,15 @@
+# This is the official list of GoGo authors for copyright purposes.
+# This file is distinct from the CONTRIBUTORS file, which
+# lists people. For example, employees are listed in CONTRIBUTORS,
+# but not in AUTHORS, because the employer holds the copyright.
+
+# Names should be added to this file as one of
+# Organization's name
+# Individual's name <submission email address>
+# Individual's name <submission email address> <email2> <emailN>
+
+# Please keep the list sorted.
+
+Sendgrid, Inc
+Vastech SA (PTY) LTD
+Walter Schulze <awalterschulze@gmail.com>
diff --git a/vendor/github.com/gogo/protobuf/CONTRIBUTORS b/vendor/github.com/gogo/protobuf/CONTRIBUTORS
@@ -0,0 +1,23 @@
+Anton Povarov <anton.povarov@gmail.com>
+Brian Goff <cpuguy83@gmail.com>
+Clayton Coleman <ccoleman@redhat.com>
+Denis Smirnov <denis.smirnov.91@gmail.com>
+DongYun Kang <ceram1000@gmail.com>
+Dwayne Schultz <dschultz@pivotal.io>
+Georg Apitz <gapitz@pivotal.io>
+Gustav Paul <gustav.paul@gmail.com>
+Johan Brandhorst <johan.brandhorst@gmail.com>
+John Shahid <jvshahid@gmail.com>
+John Tuley <john@tuley.org>
+Laurent <laurent@adyoulike.com>
+Patrick Lee <patrick@dropbox.com>
+Peter Edge <peter.edge@gmail.com>
+Roger Johansson <rogeralsing@gmail.com>
+Sam Nguyen <sam.nguyen@sendgrid.com>
+Sergio Arbeo <serabe@gmail.com>
+Stephen J Day <stephen.day@docker.com>
+Tamir Duberstein <tamird@gmail.com>
+Todd Eisenberger <teisenberger@dropbox.com>
+Tormod Erevik Lea <tormodlea@gmail.com>
+Vyacheslav Kim <kane@sendgrid.com>
+Walter Schulze <awalterschulze@gmail.com>
diff --git a/vendor/github.com/gogo/protobuf/LICENSE b/vendor/github.com/gogo/protobuf/LICENSE
@@ -0,0 +1,35 @@
+Copyright (c) 2013, The GoGo Authors. All rights reserved.
+
+Protocol Buffers for Go with Gadgets
+
+Go support for Protocol Buffers - Google's data interchange format
+
+Copyright 2010 The Go Authors. All rights reserved.
+https://github.com/golang/protobuf
+
+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/gogo/protobuf/gogoproto/Makefile b/vendor/github.com/gogo/protobuf/gogoproto/Makefile
@@ -0,0 +1,37 @@
+# Protocol Buffers for Go with Gadgets
+#
+# Copyright (c) 2013, The GoGo Authors. All rights reserved.
+# http://github.com/gogo/protobuf
+#
+# 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.
+#
+# 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.
+
+regenerate:
+ go install github.com/gogo/protobuf/protoc-gen-gogo
+ protoc --gogo_out=Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor:../../../../ --proto_path=../../../../:../protobuf/:. *.proto
+
+restore:
+ cp gogo.pb.golden gogo.pb.go
+
+preserve:
+ cp gogo.pb.go gogo.pb.golden
diff --git a/vendor/github.com/gogo/protobuf/gogoproto/doc.go b/vendor/github.com/gogo/protobuf/gogoproto/doc.go
@@ -0,0 +1,169 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+/*
+Package gogoproto provides extensions for protocol buffers to achieve:
+
+ - fast marshalling and unmarshalling.
+ - peace of mind by optionally generating test and benchmark code.
+ - more canonical Go structures.
+ - less typing by optionally generating extra helper code.
+ - goprotobuf compatibility
+
+More Canonical Go Structures
+
+A lot of time working with a goprotobuf struct will lead you to a place where you create another struct that is easier to work with and then have a function to copy the values between the two structs.
+You might also find that basic structs that started their life as part of an API need to be sent over the wire. With gob, you could just send it. With goprotobuf, you need to make a parallel struct.
+Gogoprotobuf tries to fix these problems with the nullable, embed, customtype and customname field extensions.
+
+ - nullable, if false, a field is generated without a pointer (see warning below).
+ - embed, if true, the field is generated as an embedded field.
+ - customtype, It works with the Marshal and Unmarshal methods, to allow you to have your own types in your struct, but marshal to bytes. For example, custom.Uuid or custom.Fixed128
+ - customname (beta), Changes the generated fieldname. This is especially useful when generated methods conflict with fieldnames.
+ - casttype (beta), Changes the generated fieldtype. All generated code assumes that this type is castable to the protocol buffer field type. It does not work for structs or enums.
+ - castkey (beta), Changes the generated fieldtype for a map key. All generated code assumes that this type is castable to the protocol buffer field type. Only supported on maps.
+ - castvalue (beta), Changes the generated fieldtype for a map value. All generated code assumes that this type is castable to the protocol buffer field type. Only supported on maps.
+
+Warning about nullable: According to the Protocol Buffer specification, you should be able to tell whether a field is set or unset. With the option nullable=false this feature is lost, since your non-nullable fields will always be set. It can be seen as a layer on top of Protocol Buffers, where before and after marshalling all non-nullable fields are set and they cannot be unset.
+
+Let us look at:
+
+ github.com/gogo/protobuf/test/example/example.proto
+
+for a quicker overview.
+
+The following message:
+
+ package test;
+
+ import "github.com/gogo/protobuf/gogoproto/gogo.proto";
+
+ message A {
+ optional string Description = 1 [(gogoproto.nullable) = false];
+ optional int64 Number = 2 [(gogoproto.nullable) = false];
+ optional bytes Id = 3 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uuid", (gogoproto.nullable) = false];
+ }
+
+Will generate a go struct which looks a lot like this:
+
+ type A struct {
+ Description string
+ Number int64
+ Id github_com_gogo_protobuf_test_custom.Uuid
+ }
+
+You will see there are no pointers, since all fields are non-nullable.
+You will also see a custom type which marshals to a string.
+Be warned it is your responsibility to test your custom types thoroughly.
+You should think of every possible empty and nil case for your marshaling, unmarshaling and size methods.
+
+Next we will embed the message A in message B.
+
+ message B {
+ optional A A = 1 [(gogoproto.nullable) = false, (gogoproto.embed) = true];
+ repeated bytes G = 2 [(gogoproto.customtype) = "github.com/gogo/protobuf/test/custom.Uint128", (gogoproto.nullable) = false];
+ }
+
+See below that A is embedded in B.
+
+ type B struct {
+ A
+ G []github_com_gogo_protobuf_test_custom.Uint128
+ }
+
+Also see the repeated custom type.
+
+ type Uint128 [2]uint64
+
+Next we will create a custom name for one of our fields.
+
+ message C {
+ optional int64 size = 1 [(gogoproto.customname) = "MySize"];
+ }
+
+See below that the field's name is MySize and not Size.
+
+ type C struct {
+ MySize *int64
+ }
+
+The is useful when having a protocol buffer message with a field name which conflicts with a generated method.
+As an example, having a field name size and using the sizer plugin to generate a Size method will cause a go compiler error.
+Using customname you can fix this error without changing the field name.
+This is typically useful when working with a protocol buffer that was designed before these methods and/or the go language were avialable.
+
+Gogoprotobuf also has some more subtle changes, these could be changed back:
+
+ - the generated package name for imports do not have the extra /filename.pb,
+ but are actually the imports specified in the .proto file.
+
+Gogoprotobuf also has lost some features which should be brought back with time:
+
+ - Marshalling and unmarshalling with reflect and without the unsafe package,
+ this requires work in pointer_reflect.go
+
+Why does nullable break protocol buffer specifications:
+
+The protocol buffer specification states, somewhere, that you should be able to tell whether a
+field is set or unset. With the option nullable=false this feature is lost,
+since your non-nullable fields will always be set. It can be seen as a layer on top of
+protocol buffers, where before and after marshalling all non-nullable fields are set
+and they cannot be unset.
+
+Goprotobuf Compatibility:
+
+Gogoprotobuf is compatible with Goprotobuf, because it is compatible with protocol buffers.
+Gogoprotobuf generates the same code as goprotobuf if no extensions are used.
+The enumprefix, getters and stringer extensions can be used to remove some of the unnecessary code generated by goprotobuf:
+
+ - gogoproto_import, if false, the generated code imports github.com/golang/protobuf/proto instead of github.com/gogo/protobuf/proto.
+ - goproto_enum_prefix, if false, generates the enum constant names without the messagetype prefix
+ - goproto_enum_stringer (experimental), if false, the enum is generated without the default string method, this is useful for rather using enum_stringer, or allowing you to write your own string method.
+ - goproto_getters, if false, the message is generated without get methods, this is useful when you would rather want to use face
+ - goproto_stringer, if false, the message is generated without the default string method, this is useful for rather using stringer, or allowing you to write your own string method.
+ - goproto_extensions_map (beta), if false, the extensions field is generated as type []byte instead of type map[int32]proto.Extension
+ - goproto_unrecognized (beta), if false, XXX_unrecognized field is not generated. This is useful in conjunction with gogoproto.nullable=false, to generate structures completely devoid of pointers and reduce GC pressure at the cost of losing information about unrecognized fields.
+ - goproto_registration (beta), if true, the generated files will register all messages and types against both gogo/protobuf and golang/protobuf. This is necessary when using third-party packages which read registrations from golang/protobuf (such as the grpc-gateway).
+
+Less Typing and Peace of Mind is explained in their specific plugin folders godoc:
+
+ - github.com/gogo/protobuf/plugin/<extension_name>
+
+If you do not use any of these extension the code that is generated
+will be the same as if goprotobuf has generated it.
+
+The most complete way to see examples is to look at
+
+ github.com/gogo/protobuf/test/thetest.proto
+
+Gogoprototest is a seperate project,
+because we want to keep gogoprotobuf independent of goprotobuf,
+but we still want to test it thoroughly.
+
+*/
+package gogoproto
diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go
@@ -0,0 +1,874 @@
+// Code generated by protoc-gen-gogo. DO NOT EDIT.
+// source: gogo.proto
+
+package gogoproto
+
+import (
+ fmt "fmt"
+ proto "github.com/gogo/protobuf/proto"
+ descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
+ math "math"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
+
+var E_GoprotoEnumPrefix = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 62001,
+ Name: "gogoproto.goproto_enum_prefix",
+ Tag: "varint,62001,opt,name=goproto_enum_prefix",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoEnumStringer = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 62021,
+ Name: "gogoproto.goproto_enum_stringer",
+ Tag: "varint,62021,opt,name=goproto_enum_stringer",
+ Filename: "gogo.proto",
+}
+
+var E_EnumStringer = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 62022,
+ Name: "gogoproto.enum_stringer",
+ Tag: "varint,62022,opt,name=enum_stringer",
+ Filename: "gogo.proto",
+}
+
+var E_EnumCustomname = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 62023,
+ Name: "gogoproto.enum_customname",
+ Tag: "bytes,62023,opt,name=enum_customname",
+ Filename: "gogo.proto",
+}
+
+var E_Enumdecl = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 62024,
+ Name: "gogoproto.enumdecl",
+ Tag: "varint,62024,opt,name=enumdecl",
+ Filename: "gogo.proto",
+}
+
+var E_EnumvalueCustomname = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.EnumValueOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 66001,
+ Name: "gogoproto.enumvalue_customname",
+ Tag: "bytes,66001,opt,name=enumvalue_customname",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoGettersAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63001,
+ Name: "gogoproto.goproto_getters_all",
+ Tag: "varint,63001,opt,name=goproto_getters_all",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoEnumPrefixAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63002,
+ Name: "gogoproto.goproto_enum_prefix_all",
+ Tag: "varint,63002,opt,name=goproto_enum_prefix_all",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoStringerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63003,
+ Name: "gogoproto.goproto_stringer_all",
+ Tag: "varint,63003,opt,name=goproto_stringer_all",
+ Filename: "gogo.proto",
+}
+
+var E_VerboseEqualAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63004,
+ Name: "gogoproto.verbose_equal_all",
+ Tag: "varint,63004,opt,name=verbose_equal_all",
+ Filename: "gogo.proto",
+}
+
+var E_FaceAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63005,
+ Name: "gogoproto.face_all",
+ Tag: "varint,63005,opt,name=face_all",
+ Filename: "gogo.proto",
+}
+
+var E_GostringAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63006,
+ Name: "gogoproto.gostring_all",
+ Tag: "varint,63006,opt,name=gostring_all",
+ Filename: "gogo.proto",
+}
+
+var E_PopulateAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63007,
+ Name: "gogoproto.populate_all",
+ Tag: "varint,63007,opt,name=populate_all",
+ Filename: "gogo.proto",
+}
+
+var E_StringerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63008,
+ Name: "gogoproto.stringer_all",
+ Tag: "varint,63008,opt,name=stringer_all",
+ Filename: "gogo.proto",
+}
+
+var E_OnlyoneAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63009,
+ Name: "gogoproto.onlyone_all",
+ Tag: "varint,63009,opt,name=onlyone_all",
+ Filename: "gogo.proto",
+}
+
+var E_EqualAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63013,
+ Name: "gogoproto.equal_all",
+ Tag: "varint,63013,opt,name=equal_all",
+ Filename: "gogo.proto",
+}
+
+var E_DescriptionAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63014,
+ Name: "gogoproto.description_all",
+ Tag: "varint,63014,opt,name=description_all",
+ Filename: "gogo.proto",
+}
+
+var E_TestgenAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63015,
+ Name: "gogoproto.testgen_all",
+ Tag: "varint,63015,opt,name=testgen_all",
+ Filename: "gogo.proto",
+}
+
+var E_BenchgenAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63016,
+ Name: "gogoproto.benchgen_all",
+ Tag: "varint,63016,opt,name=benchgen_all",
+ Filename: "gogo.proto",
+}
+
+var E_MarshalerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63017,
+ Name: "gogoproto.marshaler_all",
+ Tag: "varint,63017,opt,name=marshaler_all",
+ Filename: "gogo.proto",
+}
+
+var E_UnmarshalerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63018,
+ Name: "gogoproto.unmarshaler_all",
+ Tag: "varint,63018,opt,name=unmarshaler_all",
+ Filename: "gogo.proto",
+}
+
+var E_StableMarshalerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63019,
+ Name: "gogoproto.stable_marshaler_all",
+ Tag: "varint,63019,opt,name=stable_marshaler_all",
+ Filename: "gogo.proto",
+}
+
+var E_SizerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63020,
+ Name: "gogoproto.sizer_all",
+ Tag: "varint,63020,opt,name=sizer_all",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoEnumStringerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63021,
+ Name: "gogoproto.goproto_enum_stringer_all",
+ Tag: "varint,63021,opt,name=goproto_enum_stringer_all",
+ Filename: "gogo.proto",
+}
+
+var E_EnumStringerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63022,
+ Name: "gogoproto.enum_stringer_all",
+ Tag: "varint,63022,opt,name=enum_stringer_all",
+ Filename: "gogo.proto",
+}
+
+var E_UnsafeMarshalerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63023,
+ Name: "gogoproto.unsafe_marshaler_all",
+ Tag: "varint,63023,opt,name=unsafe_marshaler_all",
+ Filename: "gogo.proto",
+}
+
+var E_UnsafeUnmarshalerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63024,
+ Name: "gogoproto.unsafe_unmarshaler_all",
+ Tag: "varint,63024,opt,name=unsafe_unmarshaler_all",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoExtensionsMapAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63025,
+ Name: "gogoproto.goproto_extensions_map_all",
+ Tag: "varint,63025,opt,name=goproto_extensions_map_all",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoUnrecognizedAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63026,
+ Name: "gogoproto.goproto_unrecognized_all",
+ Tag: "varint,63026,opt,name=goproto_unrecognized_all",
+ Filename: "gogo.proto",
+}
+
+var E_GogoprotoImport = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63027,
+ Name: "gogoproto.gogoproto_import",
+ Tag: "varint,63027,opt,name=gogoproto_import",
+ Filename: "gogo.proto",
+}
+
+var E_ProtosizerAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63028,
+ Name: "gogoproto.protosizer_all",
+ Tag: "varint,63028,opt,name=protosizer_all",
+ Filename: "gogo.proto",
+}
+
+var E_CompareAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63029,
+ Name: "gogoproto.compare_all",
+ Tag: "varint,63029,opt,name=compare_all",
+ Filename: "gogo.proto",
+}
+
+var E_TypedeclAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63030,
+ Name: "gogoproto.typedecl_all",
+ Tag: "varint,63030,opt,name=typedecl_all",
+ Filename: "gogo.proto",
+}
+
+var E_EnumdeclAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63031,
+ Name: "gogoproto.enumdecl_all",
+ Tag: "varint,63031,opt,name=enumdecl_all",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoRegistration = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63032,
+ Name: "gogoproto.goproto_registration",
+ Tag: "varint,63032,opt,name=goproto_registration",
+ Filename: "gogo.proto",
+}
+
+var E_MessagenameAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63033,
+ Name: "gogoproto.messagename_all",
+ Tag: "varint,63033,opt,name=messagename_all",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoSizecacheAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63034,
+ Name: "gogoproto.goproto_sizecache_all",
+ Tag: "varint,63034,opt,name=goproto_sizecache_all",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoUnkeyedAll = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FileOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 63035,
+ Name: "gogoproto.goproto_unkeyed_all",
+ Tag: "varint,63035,opt,name=goproto_unkeyed_all",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoGetters = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64001,
+ Name: "gogoproto.goproto_getters",
+ Tag: "varint,64001,opt,name=goproto_getters",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoStringer = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64003,
+ Name: "gogoproto.goproto_stringer",
+ Tag: "varint,64003,opt,name=goproto_stringer",
+ Filename: "gogo.proto",
+}
+
+var E_VerboseEqual = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64004,
+ Name: "gogoproto.verbose_equal",
+ Tag: "varint,64004,opt,name=verbose_equal",
+ Filename: "gogo.proto",
+}
+
+var E_Face = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64005,
+ Name: "gogoproto.face",
+ Tag: "varint,64005,opt,name=face",
+ Filename: "gogo.proto",
+}
+
+var E_Gostring = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64006,
+ Name: "gogoproto.gostring",
+ Tag: "varint,64006,opt,name=gostring",
+ Filename: "gogo.proto",
+}
+
+var E_Populate = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64007,
+ Name: "gogoproto.populate",
+ Tag: "varint,64007,opt,name=populate",
+ Filename: "gogo.proto",
+}
+
+var E_Stringer = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 67008,
+ Name: "gogoproto.stringer",
+ Tag: "varint,67008,opt,name=stringer",
+ Filename: "gogo.proto",
+}
+
+var E_Onlyone = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64009,
+ Name: "gogoproto.onlyone",
+ Tag: "varint,64009,opt,name=onlyone",
+ Filename: "gogo.proto",
+}
+
+var E_Equal = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64013,
+ Name: "gogoproto.equal",
+ Tag: "varint,64013,opt,name=equal",
+ Filename: "gogo.proto",
+}
+
+var E_Description = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64014,
+ Name: "gogoproto.description",
+ Tag: "varint,64014,opt,name=description",
+ Filename: "gogo.proto",
+}
+
+var E_Testgen = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64015,
+ Name: "gogoproto.testgen",
+ Tag: "varint,64015,opt,name=testgen",
+ Filename: "gogo.proto",
+}
+
+var E_Benchgen = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64016,
+ Name: "gogoproto.benchgen",
+ Tag: "varint,64016,opt,name=benchgen",
+ Filename: "gogo.proto",
+}
+
+var E_Marshaler = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64017,
+ Name: "gogoproto.marshaler",
+ Tag: "varint,64017,opt,name=marshaler",
+ Filename: "gogo.proto",
+}
+
+var E_Unmarshaler = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64018,
+ Name: "gogoproto.unmarshaler",
+ Tag: "varint,64018,opt,name=unmarshaler",
+ Filename: "gogo.proto",
+}
+
+var E_StableMarshaler = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64019,
+ Name: "gogoproto.stable_marshaler",
+ Tag: "varint,64019,opt,name=stable_marshaler",
+ Filename: "gogo.proto",
+}
+
+var E_Sizer = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64020,
+ Name: "gogoproto.sizer",
+ Tag: "varint,64020,opt,name=sizer",
+ Filename: "gogo.proto",
+}
+
+var E_UnsafeMarshaler = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64023,
+ Name: "gogoproto.unsafe_marshaler",
+ Tag: "varint,64023,opt,name=unsafe_marshaler",
+ Filename: "gogo.proto",
+}
+
+var E_UnsafeUnmarshaler = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64024,
+ Name: "gogoproto.unsafe_unmarshaler",
+ Tag: "varint,64024,opt,name=unsafe_unmarshaler",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoExtensionsMap = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64025,
+ Name: "gogoproto.goproto_extensions_map",
+ Tag: "varint,64025,opt,name=goproto_extensions_map",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoUnrecognized = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64026,
+ Name: "gogoproto.goproto_unrecognized",
+ Tag: "varint,64026,opt,name=goproto_unrecognized",
+ Filename: "gogo.proto",
+}
+
+var E_Protosizer = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64028,
+ Name: "gogoproto.protosizer",
+ Tag: "varint,64028,opt,name=protosizer",
+ Filename: "gogo.proto",
+}
+
+var E_Compare = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64029,
+ Name: "gogoproto.compare",
+ Tag: "varint,64029,opt,name=compare",
+ Filename: "gogo.proto",
+}
+
+var E_Typedecl = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64030,
+ Name: "gogoproto.typedecl",
+ Tag: "varint,64030,opt,name=typedecl",
+ Filename: "gogo.proto",
+}
+
+var E_Messagename = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64033,
+ Name: "gogoproto.messagename",
+ Tag: "varint,64033,opt,name=messagename",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoSizecache = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64034,
+ Name: "gogoproto.goproto_sizecache",
+ Tag: "varint,64034,opt,name=goproto_sizecache",
+ Filename: "gogo.proto",
+}
+
+var E_GoprotoUnkeyed = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.MessageOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 64035,
+ Name: "gogoproto.goproto_unkeyed",
+ Tag: "varint,64035,opt,name=goproto_unkeyed",
+ Filename: "gogo.proto",
+}
+
+var E_Nullable = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 65001,
+ Name: "gogoproto.nullable",
+ Tag: "varint,65001,opt,name=nullable",
+ Filename: "gogo.proto",
+}
+
+var E_Embed = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 65002,
+ Name: "gogoproto.embed",
+ Tag: "varint,65002,opt,name=embed",
+ Filename: "gogo.proto",
+}
+
+var E_Customtype = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65003,
+ Name: "gogoproto.customtype",
+ Tag: "bytes,65003,opt,name=customtype",
+ Filename: "gogo.proto",
+}
+
+var E_Customname = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65004,
+ Name: "gogoproto.customname",
+ Tag: "bytes,65004,opt,name=customname",
+ Filename: "gogo.proto",
+}
+
+var E_Jsontag = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65005,
+ Name: "gogoproto.jsontag",
+ Tag: "bytes,65005,opt,name=jsontag",
+ Filename: "gogo.proto",
+}
+
+var E_Moretags = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65006,
+ Name: "gogoproto.moretags",
+ Tag: "bytes,65006,opt,name=moretags",
+ Filename: "gogo.proto",
+}
+
+var E_Casttype = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65007,
+ Name: "gogoproto.casttype",
+ Tag: "bytes,65007,opt,name=casttype",
+ Filename: "gogo.proto",
+}
+
+var E_Castkey = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65008,
+ Name: "gogoproto.castkey",
+ Tag: "bytes,65008,opt,name=castkey",
+ Filename: "gogo.proto",
+}
+
+var E_Castvalue = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 65009,
+ Name: "gogoproto.castvalue",
+ Tag: "bytes,65009,opt,name=castvalue",
+ Filename: "gogo.proto",
+}
+
+var E_Stdtime = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 65010,
+ Name: "gogoproto.stdtime",
+ Tag: "varint,65010,opt,name=stdtime",
+ Filename: "gogo.proto",
+}
+
+var E_Stdduration = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 65011,
+ Name: "gogoproto.stdduration",
+ Tag: "varint,65011,opt,name=stdduration",
+ Filename: "gogo.proto",
+}
+
+var E_Wktpointer = &proto.ExtensionDesc{
+ ExtendedType: (*descriptor.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 65012,
+ Name: "gogoproto.wktpointer",
+ Tag: "varint,65012,opt,name=wktpointer",
+ Filename: "gogo.proto",
+}
+
+func init() {
+ proto.RegisterExtension(E_GoprotoEnumPrefix)
+ proto.RegisterExtension(E_GoprotoEnumStringer)
+ proto.RegisterExtension(E_EnumStringer)
+ proto.RegisterExtension(E_EnumCustomname)
+ proto.RegisterExtension(E_Enumdecl)
+ proto.RegisterExtension(E_EnumvalueCustomname)
+ proto.RegisterExtension(E_GoprotoGettersAll)
+ proto.RegisterExtension(E_GoprotoEnumPrefixAll)
+ proto.RegisterExtension(E_GoprotoStringerAll)
+ proto.RegisterExtension(E_VerboseEqualAll)
+ proto.RegisterExtension(E_FaceAll)
+ proto.RegisterExtension(E_GostringAll)
+ proto.RegisterExtension(E_PopulateAll)
+ proto.RegisterExtension(E_StringerAll)
+ proto.RegisterExtension(E_OnlyoneAll)
+ proto.RegisterExtension(E_EqualAll)
+ proto.RegisterExtension(E_DescriptionAll)
+ proto.RegisterExtension(E_TestgenAll)
+ proto.RegisterExtension(E_BenchgenAll)
+ proto.RegisterExtension(E_MarshalerAll)
+ proto.RegisterExtension(E_UnmarshalerAll)
+ proto.RegisterExtension(E_StableMarshalerAll)
+ proto.RegisterExtension(E_SizerAll)
+ proto.RegisterExtension(E_GoprotoEnumStringerAll)
+ proto.RegisterExtension(E_EnumStringerAll)
+ proto.RegisterExtension(E_UnsafeMarshalerAll)
+ proto.RegisterExtension(E_UnsafeUnmarshalerAll)
+ proto.RegisterExtension(E_GoprotoExtensionsMapAll)
+ proto.RegisterExtension(E_GoprotoUnrecognizedAll)
+ proto.RegisterExtension(E_GogoprotoImport)
+ proto.RegisterExtension(E_ProtosizerAll)
+ proto.RegisterExtension(E_CompareAll)
+ proto.RegisterExtension(E_TypedeclAll)
+ proto.RegisterExtension(E_EnumdeclAll)
+ proto.RegisterExtension(E_GoprotoRegistration)
+ proto.RegisterExtension(E_MessagenameAll)
+ proto.RegisterExtension(E_GoprotoSizecacheAll)
+ proto.RegisterExtension(E_GoprotoUnkeyedAll)
+ proto.RegisterExtension(E_GoprotoGetters)
+ proto.RegisterExtension(E_GoprotoStringer)
+ proto.RegisterExtension(E_VerboseEqual)
+ proto.RegisterExtension(E_Face)
+ proto.RegisterExtension(E_Gostring)
+ proto.RegisterExtension(E_Populate)
+ proto.RegisterExtension(E_Stringer)
+ proto.RegisterExtension(E_Onlyone)
+ proto.RegisterExtension(E_Equal)
+ proto.RegisterExtension(E_Description)
+ proto.RegisterExtension(E_Testgen)
+ proto.RegisterExtension(E_Benchgen)
+ proto.RegisterExtension(E_Marshaler)
+ proto.RegisterExtension(E_Unmarshaler)
+ proto.RegisterExtension(E_StableMarshaler)
+ proto.RegisterExtension(E_Sizer)
+ proto.RegisterExtension(E_UnsafeMarshaler)
+ proto.RegisterExtension(E_UnsafeUnmarshaler)
+ proto.RegisterExtension(E_GoprotoExtensionsMap)
+ proto.RegisterExtension(E_GoprotoUnrecognized)
+ proto.RegisterExtension(E_Protosizer)
+ proto.RegisterExtension(E_Compare)
+ proto.RegisterExtension(E_Typedecl)
+ proto.RegisterExtension(E_Messagename)
+ proto.RegisterExtension(E_GoprotoSizecache)
+ proto.RegisterExtension(E_GoprotoUnkeyed)
+ proto.RegisterExtension(E_Nullable)
+ proto.RegisterExtension(E_Embed)
+ proto.RegisterExtension(E_Customtype)
+ proto.RegisterExtension(E_Customname)
+ proto.RegisterExtension(E_Jsontag)
+ proto.RegisterExtension(E_Moretags)
+ proto.RegisterExtension(E_Casttype)
+ proto.RegisterExtension(E_Castkey)
+ proto.RegisterExtension(E_Castvalue)
+ proto.RegisterExtension(E_Stdtime)
+ proto.RegisterExtension(E_Stdduration)
+ proto.RegisterExtension(E_Wktpointer)
+}
+
+func init() { proto.RegisterFile("gogo.proto", fileDescriptor_592445b5231bc2b9) }
+
+var fileDescriptor_592445b5231bc2b9 = []byte{
+ // 1328 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x98, 0x49, 0x6f, 0x1c, 0x45,
+ 0x14, 0x80, 0x85, 0x48, 0x64, 0x4f, 0x79, 0x8b, 0xc7, 0xc6, 0x84, 0x08, 0x44, 0xe0, 0xc4, 0xc9,
+ 0x3e, 0x45, 0x28, 0x65, 0x45, 0x96, 0x63, 0x39, 0x56, 0x10, 0x0e, 0xc6, 0x89, 0xc3, 0x76, 0x18,
+ 0xf5, 0xf4, 0x94, 0xdb, 0x8d, 0xbb, 0xbb, 0x9a, 0xee, 0xea, 0x10, 0xe7, 0x86, 0xc2, 0x22, 0x84,
+ 0xd8, 0x91, 0x20, 0x21, 0x09, 0x04, 0xc4, 0xbe, 0x86, 0x7d, 0xb9, 0x70, 0x61, 0xb9, 0xf2, 0x1f,
+ 0xb8, 0x00, 0x66, 0xf7, 0xcd, 0x17, 0xf4, 0xba, 0xdf, 0xeb, 0xa9, 0x69, 0x8f, 0x54, 0x35, 0xb7,
+ 0xf6, 0xb8, 0xbe, 0x6f, 0xaa, 0xdf, 0xeb, 0x7a, 0xef, 0x4d, 0x33, 0xe6, 0x49, 0x4f, 0x4e, 0xc6,
+ 0x89, 0x54, 0xb2, 0x5e, 0x83, 0xeb, 0xfc, 0x72, 0xdf, 0x7e, 0x4f, 0x4a, 0x2f, 0x10, 0x53, 0xf9,
+ 0x5f, 0xcd, 0x6c, 0x75, 0xaa, 0x25, 0x52, 0x37, 0xf1, 0x63, 0x25, 0x93, 0x62, 0x31, 0x3f, 0xc6,
+ 0xc6, 0x70, 0x71, 0x43, 0x44, 0x59, 0xd8, 0x88, 0x13, 0xb1, 0xea, 0x9f, 0xae, 0x5f, 0x3f, 0x59,
+ 0x90, 0x93, 0x44, 0x4e, 0xce, 0x47, 0x59, 0x78, 0x47, 0xac, 0x7c, 0x19, 0xa5, 0x7b, 0xaf, 0xfc,
+ 0x72, 0xf5, 0xfe, 0xab, 0x6e, 0xe9, 0x5f, 0x1e, 0x45, 0x14, 0xfe, 0xb7, 0x94, 0x83, 0x7c, 0x99,
+ 0x5d, 0xd3, 0xe1, 0x4b, 0x55, 0xe2, 0x47, 0x9e, 0x48, 0x0c, 0xc6, 0xef, 0xd1, 0x38, 0xa6, 0x19,
+ 0x8f, 0x23, 0xca, 0xe7, 0xd8, 0x50, 0x2f, 0xae, 0x1f, 0xd0, 0x35, 0x28, 0x74, 0xc9, 0x02, 0x1b,
+ 0xc9, 0x25, 0x6e, 0x96, 0x2a, 0x19, 0x46, 0x4e, 0x28, 0x0c, 0x9a, 0x1f, 0x73, 0x4d, 0x6d, 0x79,
+ 0x18, 0xb0, 0xb9, 0x92, 0xe2, 0x9c, 0xf5, 0xc3, 0x27, 0x2d, 0xe1, 0x06, 0x06, 0xc3, 0x4f, 0xb8,
+ 0x91, 0x72, 0x3d, 0x3f, 0xc9, 0xc6, 0xe1, 0xfa, 0x94, 0x13, 0x64, 0x42, 0xdf, 0xc9, 0x4d, 0x5d,
+ 0x3d, 0x27, 0x61, 0x19, 0xc9, 0x7e, 0x3e, 0xbb, 0x2b, 0xdf, 0xce, 0x58, 0x29, 0xd0, 0xf6, 0xa4,
+ 0x65, 0xd1, 0x13, 0x4a, 0x89, 0x24, 0x6d, 0x38, 0x41, 0xb7, 0xed, 0x1d, 0xf1, 0x83, 0xd2, 0x78,
+ 0x6e, 0xb3, 0x33, 0x8b, 0x0b, 0x05, 0x39, 0x1b, 0x04, 0x7c, 0x85, 0x5d, 0xdb, 0xe5, 0xa9, 0xb0,
+ 0x70, 0x9e, 0x47, 0xe7, 0xf8, 0x8e, 0x27, 0x03, 0xb4, 0x4b, 0x8c, 0x3e, 0x2f, 0x73, 0x69, 0xe1,
+ 0x7c, 0x19, 0x9d, 0x75, 0x64, 0x29, 0xa5, 0x60, 0xbc, 0x8d, 0x8d, 0x9e, 0x12, 0x49, 0x53, 0xa6,
+ 0xa2, 0x21, 0x1e, 0xc8, 0x9c, 0xc0, 0x42, 0x77, 0x01, 0x75, 0x23, 0x08, 0xce, 0x03, 0x07, 0xae,
+ 0x83, 0xac, 0x7f, 0xd5, 0x71, 0x85, 0x85, 0xe2, 0x22, 0x2a, 0xfa, 0x60, 0x3d, 0xa0, 0xb3, 0x6c,
+ 0xd0, 0x93, 0xc5, 0x2d, 0x59, 0xe0, 0x97, 0x10, 0x1f, 0x20, 0x06, 0x15, 0xb1, 0x8c, 0xb3, 0xc0,
+ 0x51, 0x36, 0x3b, 0x78, 0x85, 0x14, 0xc4, 0xa0, 0xa2, 0x87, 0xb0, 0xbe, 0x4a, 0x8a, 0x54, 0x8b,
+ 0xe7, 0x0c, 0x1b, 0x90, 0x51, 0xb0, 0x21, 0x23, 0x9b, 0x4d, 0x5c, 0x46, 0x03, 0x43, 0x04, 0x04,
+ 0xd3, 0xac, 0x66, 0x9b, 0x88, 0x37, 0x36, 0xe9, 0x78, 0x50, 0x06, 0x16, 0xd8, 0x08, 0x15, 0x28,
+ 0x5f, 0x46, 0x16, 0x8a, 0x37, 0x51, 0x31, 0xac, 0x61, 0x78, 0x1b, 0x4a, 0xa4, 0xca, 0x13, 0x36,
+ 0x92, 0xb7, 0xe8, 0x36, 0x10, 0xc1, 0x50, 0x36, 0x45, 0xe4, 0xae, 0xd9, 0x19, 0xde, 0xa6, 0x50,
+ 0x12, 0x03, 0x8a, 0x39, 0x36, 0x14, 0x3a, 0x49, 0xba, 0xe6, 0x04, 0x56, 0xe9, 0x78, 0x07, 0x1d,
+ 0x83, 0x25, 0x84, 0x11, 0xc9, 0xa2, 0x5e, 0x34, 0xef, 0x52, 0x44, 0x34, 0x0c, 0x8f, 0x5e, 0xaa,
+ 0x9c, 0x66, 0x20, 0x1a, 0xbd, 0xd8, 0xde, 0xa3, 0xa3, 0x57, 0xb0, 0x8b, 0xba, 0x71, 0x9a, 0xd5,
+ 0x52, 0xff, 0x8c, 0x95, 0xe6, 0x7d, 0xca, 0x74, 0x0e, 0x00, 0x7c, 0x0f, 0xbb, 0xae, 0x6b, 0x9b,
+ 0xb0, 0x90, 0x7d, 0x80, 0xb2, 0x89, 0x2e, 0xad, 0x02, 0x4b, 0x42, 0xaf, 0xca, 0x0f, 0xa9, 0x24,
+ 0x88, 0x8a, 0x6b, 0x89, 0x8d, 0x67, 0x51, 0xea, 0xac, 0xf6, 0x16, 0xb5, 0x8f, 0x28, 0x6a, 0x05,
+ 0xdb, 0x11, 0xb5, 0x13, 0x6c, 0x02, 0x8d, 0xbd, 0xe5, 0xf5, 0x63, 0x2a, 0xac, 0x05, 0xbd, 0xd2,
+ 0x99, 0xdd, 0xfb, 0xd8, 0xbe, 0x32, 0x9c, 0xa7, 0x95, 0x88, 0x52, 0x60, 0x1a, 0xa1, 0x13, 0x5b,
+ 0x98, 0xaf, 0xa0, 0x99, 0x2a, 0xfe, 0x7c, 0x29, 0x58, 0x74, 0x62, 0x90, 0xdf, 0xcd, 0xf6, 0x92,
+ 0x3c, 0x8b, 0x12, 0xe1, 0x4a, 0x2f, 0xf2, 0xcf, 0x88, 0x96, 0x85, 0xfa, 0x93, 0x4a, 0xaa, 0x56,
+ 0x34, 0x1c, 0xcc, 0x47, 0xd9, 0x9e, 0x72, 0x56, 0x69, 0xf8, 0x61, 0x2c, 0x13, 0x65, 0x30, 0x7e,
+ 0x4a, 0x99, 0x2a, 0xb9, 0xa3, 0x39, 0xc6, 0xe7, 0xd9, 0x70, 0xfe, 0xa7, 0xed, 0x23, 0xf9, 0x19,
+ 0x8a, 0x86, 0xda, 0x14, 0x16, 0x0e, 0x57, 0x86, 0xb1, 0x93, 0xd8, 0xd4, 0xbf, 0xcf, 0xa9, 0x70,
+ 0x20, 0x82, 0x85, 0x43, 0x6d, 0xc4, 0x02, 0xba, 0xbd, 0x85, 0xe1, 0x0b, 0x2a, 0x1c, 0xc4, 0xa0,
+ 0x82, 0x06, 0x06, 0x0b, 0xc5, 0x97, 0xa4, 0x20, 0x06, 0x14, 0x77, 0xb6, 0x1b, 0x6d, 0x22, 0x3c,
+ 0x3f, 0x55, 0x89, 0x03, 0xab, 0x0d, 0xaa, 0xaf, 0x36, 0x3b, 0x87, 0xb0, 0x65, 0x0d, 0x85, 0x4a,
+ 0x14, 0x8a, 0x34, 0x75, 0x3c, 0x01, 0x13, 0x87, 0xc5, 0xc6, 0xbe, 0xa6, 0x4a, 0xa4, 0x61, 0xb0,
+ 0x37, 0x6d, 0x42, 0x84, 0xb0, 0xbb, 0x8e, 0xbb, 0x66, 0xa3, 0xfb, 0xa6, 0xb2, 0xb9, 0xe3, 0xc4,
+ 0x82, 0x53, 0x9b, 0x7f, 0xb2, 0x68, 0x5d, 0x6c, 0x58, 0x3d, 0x9d, 0xdf, 0x56, 0xe6, 0x9f, 0x95,
+ 0x82, 0x2c, 0x6a, 0xc8, 0x48, 0x65, 0x9e, 0xaa, 0xdf, 0xb8, 0xc3, 0xb5, 0x58, 0xdc, 0x17, 0xe9,
+ 0x1e, 0xda, 0xc2, 0xfb, 0xed, 0x1c, 0xa7, 0xf8, 0xed, 0xf0, 0x90, 0x77, 0x0e, 0x3d, 0x66, 0xd9,
+ 0xd9, 0xad, 0xf2, 0x39, 0xef, 0x98, 0x79, 0xf8, 0x11, 0x36, 0xd4, 0x31, 0xf0, 0x98, 0x55, 0x0f,
+ 0xa3, 0x6a, 0x50, 0x9f, 0x77, 0xf8, 0x01, 0xb6, 0x0b, 0x86, 0x17, 0x33, 0xfe, 0x08, 0xe2, 0xf9,
+ 0x72, 0x7e, 0x88, 0xf5, 0xd3, 0xd0, 0x62, 0x46, 0x1f, 0x45, 0xb4, 0x44, 0x00, 0xa7, 0x81, 0xc5,
+ 0x8c, 0x3f, 0x46, 0x38, 0x21, 0x80, 0xdb, 0x87, 0xf0, 0xbb, 0x27, 0x76, 0x61, 0xd3, 0xa1, 0xd8,
+ 0x4d, 0xb3, 0x3e, 0x9c, 0x54, 0xcc, 0xf4, 0xe3, 0xf8, 0xe5, 0x44, 0xf0, 0x5b, 0xd9, 0x6e, 0xcb,
+ 0x80, 0x3f, 0x89, 0x68, 0xb1, 0x9e, 0xcf, 0xb1, 0x01, 0x6d, 0x3a, 0x31, 0xe3, 0x4f, 0x21, 0xae,
+ 0x53, 0xb0, 0x75, 0x9c, 0x4e, 0xcc, 0x82, 0xa7, 0x69, 0xeb, 0x48, 0x40, 0xd8, 0x68, 0x30, 0x31,
+ 0xd3, 0xcf, 0x50, 0xd4, 0x09, 0xe1, 0x33, 0xac, 0x56, 0x36, 0x1b, 0x33, 0xff, 0x2c, 0xf2, 0x6d,
+ 0x06, 0x22, 0xa0, 0x35, 0x3b, 0xb3, 0xe2, 0x39, 0x8a, 0x80, 0x46, 0xc1, 0x31, 0xaa, 0x0e, 0x30,
+ 0x66, 0xd3, 0xf3, 0x74, 0x8c, 0x2a, 0xf3, 0x0b, 0x64, 0x33, 0xaf, 0xf9, 0x66, 0xc5, 0x0b, 0x94,
+ 0xcd, 0x7c, 0x3d, 0x6c, 0xa3, 0x3a, 0x11, 0x98, 0x1d, 0x2f, 0xd2, 0x36, 0x2a, 0x03, 0x01, 0x5f,
+ 0x62, 0xf5, 0x9d, 0xd3, 0x80, 0xd9, 0xf7, 0x12, 0xfa, 0x46, 0x77, 0x0c, 0x03, 0xfc, 0x2e, 0x36,
+ 0xd1, 0x7d, 0x12, 0x30, 0x5b, 0xcf, 0x6d, 0x55, 0x7e, 0xbb, 0xe9, 0x83, 0x00, 0x3f, 0xd1, 0x6e,
+ 0x29, 0xfa, 0x14, 0x60, 0xd6, 0x9e, 0xdf, 0xea, 0x2c, 0xdc, 0xfa, 0x10, 0xc0, 0x67, 0x19, 0x6b,
+ 0x37, 0x60, 0xb3, 0xeb, 0x02, 0xba, 0x34, 0x08, 0x8e, 0x06, 0xf6, 0x5f, 0x33, 0x7f, 0x91, 0x8e,
+ 0x06, 0x12, 0x70, 0x34, 0xa8, 0xf5, 0x9a, 0xe9, 0x4b, 0x74, 0x34, 0x08, 0x81, 0x27, 0x5b, 0xeb,
+ 0x6e, 0x66, 0xc3, 0x65, 0x7a, 0xb2, 0x35, 0x8a, 0x1f, 0x63, 0xa3, 0x3b, 0x1a, 0xa2, 0x59, 0xf5,
+ 0x1a, 0xaa, 0xf6, 0x54, 0xfb, 0xa1, 0xde, 0xbc, 0xb0, 0x19, 0x9a, 0x6d, 0xaf, 0x57, 0x9a, 0x17,
+ 0xf6, 0x42, 0x3e, 0xcd, 0xfa, 0xa3, 0x2c, 0x08, 0xe0, 0xf0, 0xd4, 0x6f, 0xe8, 0xd2, 0x4d, 0x45,
+ 0xd0, 0x22, 0xc5, 0xaf, 0xdb, 0x18, 0x1d, 0x02, 0xf8, 0x01, 0xb6, 0x5b, 0x84, 0x4d, 0xd1, 0x32,
+ 0x91, 0xbf, 0x6d, 0x53, 0xc1, 0x84, 0xd5, 0x7c, 0x86, 0xb1, 0xe2, 0xd5, 0x08, 0x84, 0xd9, 0xc4,
+ 0xfe, 0xbe, 0x5d, 0xbc, 0xa5, 0xd1, 0x90, 0xb6, 0x20, 0x4f, 0x8a, 0x41, 0xb0, 0xd9, 0x29, 0xc8,
+ 0x33, 0x72, 0x90, 0xf5, 0xdd, 0x9f, 0xca, 0x48, 0x39, 0x9e, 0x89, 0xfe, 0x03, 0x69, 0x5a, 0x0f,
+ 0x01, 0x0b, 0x65, 0x22, 0x94, 0xe3, 0xa5, 0x26, 0xf6, 0x4f, 0x64, 0x4b, 0x00, 0x60, 0xd7, 0x49,
+ 0x95, 0xcd, 0x7d, 0xff, 0x45, 0x30, 0x01, 0xb0, 0x69, 0xb8, 0x5e, 0x17, 0x1b, 0x26, 0xf6, 0x6f,
+ 0xda, 0x34, 0xae, 0xe7, 0x87, 0x58, 0x0d, 0x2e, 0xf3, 0xb7, 0x4a, 0x26, 0xf8, 0x1f, 0x84, 0xdb,
+ 0x04, 0x7c, 0x73, 0xaa, 0x5a, 0xca, 0x37, 0x07, 0xfb, 0x5f, 0xcc, 0x34, 0xad, 0xe7, 0xb3, 0x6c,
+ 0x20, 0x55, 0xad, 0x56, 0x86, 0xf3, 0xa9, 0x01, 0xff, 0x6f, 0xbb, 0x7c, 0x65, 0x51, 0x32, 0x90,
+ 0xed, 0x07, 0xd7, 0x55, 0x2c, 0xfd, 0x48, 0x89, 0xc4, 0x64, 0xd8, 0x42, 0x83, 0x86, 0x1c, 0x9e,
+ 0x67, 0x63, 0xae, 0x0c, 0xab, 0xdc, 0x61, 0xb6, 0x20, 0x17, 0xe4, 0x52, 0x5e, 0x67, 0xee, 0xbd,
+ 0xd9, 0xf3, 0xd5, 0x5a, 0xd6, 0x9c, 0x74, 0x65, 0x38, 0x05, 0xbf, 0x3c, 0xda, 0x2f, 0x54, 0xcb,
+ 0xdf, 0x21, 0xff, 0x07, 0x00, 0x00, 0xff, 0xff, 0x9c, 0xaf, 0x70, 0x4e, 0x83, 0x15, 0x00, 0x00,
+}
diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.golden b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.golden
@@ -0,0 +1,45 @@
+// Code generated by protoc-gen-go.
+// source: gogo.proto
+// DO NOT EDIT!
+
+package gogoproto
+
+import proto "github.com/gogo/protobuf/proto"
+import json "encoding/json"
+import math "math"
+import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
+
+// Reference proto, json, and math imports to suppress error if they are not otherwise used.
+var _ = proto.Marshal
+var _ = &json.SyntaxError{}
+var _ = math.Inf
+
+var E_Nullable = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 51235,
+ Name: "gogoproto.nullable",
+ Tag: "varint,51235,opt,name=nullable",
+}
+
+var E_Embed = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 51236,
+ Name: "gogoproto.embed",
+ Tag: "varint,51236,opt,name=embed",
+}
+
+var E_Customtype = &proto.ExtensionDesc{
+ ExtendedType: (*google_protobuf.FieldOptions)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 51237,
+ Name: "gogoproto.customtype",
+ Tag: "bytes,51237,opt,name=customtype",
+}
+
+func init() {
+ proto.RegisterExtension(E_Nullable)
+ proto.RegisterExtension(E_Embed)
+ proto.RegisterExtension(E_Customtype)
+}
diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto b/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto
@@ -0,0 +1,144 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+syntax = "proto2";
+package gogoproto;
+
+import "google/protobuf/descriptor.proto";
+
+option java_package = "com.google.protobuf";
+option java_outer_classname = "GoGoProtos";
+option go_package = "github.com/gogo/protobuf/gogoproto";
+
+extend google.protobuf.EnumOptions {
+ optional bool goproto_enum_prefix = 62001;
+ optional bool goproto_enum_stringer = 62021;
+ optional bool enum_stringer = 62022;
+ optional string enum_customname = 62023;
+ optional bool enumdecl = 62024;
+}
+
+extend google.protobuf.EnumValueOptions {
+ optional string enumvalue_customname = 66001;
+}
+
+extend google.protobuf.FileOptions {
+ optional bool goproto_getters_all = 63001;
+ optional bool goproto_enum_prefix_all = 63002;
+ optional bool goproto_stringer_all = 63003;
+ optional bool verbose_equal_all = 63004;
+ optional bool face_all = 63005;
+ optional bool gostring_all = 63006;
+ optional bool populate_all = 63007;
+ optional bool stringer_all = 63008;
+ optional bool onlyone_all = 63009;
+
+ optional bool equal_all = 63013;
+ optional bool description_all = 63014;
+ optional bool testgen_all = 63015;
+ optional bool benchgen_all = 63016;
+ optional bool marshaler_all = 63017;
+ optional bool unmarshaler_all = 63018;
+ optional bool stable_marshaler_all = 63019;
+
+ optional bool sizer_all = 63020;
+
+ optional bool goproto_enum_stringer_all = 63021;
+ optional bool enum_stringer_all = 63022;
+
+ optional bool unsafe_marshaler_all = 63023;
+ optional bool unsafe_unmarshaler_all = 63024;
+
+ optional bool goproto_extensions_map_all = 63025;
+ optional bool goproto_unrecognized_all = 63026;
+ optional bool gogoproto_import = 63027;
+ optional bool protosizer_all = 63028;
+ optional bool compare_all = 63029;
+ optional bool typedecl_all = 63030;
+ optional bool enumdecl_all = 63031;
+
+ optional bool goproto_registration = 63032;
+ optional bool messagename_all = 63033;
+
+ optional bool goproto_sizecache_all = 63034;
+ optional bool goproto_unkeyed_all = 63035;
+}
+
+extend google.protobuf.MessageOptions {
+ optional bool goproto_getters = 64001;
+ optional bool goproto_stringer = 64003;
+ optional bool verbose_equal = 64004;
+ optional bool face = 64005;
+ optional bool gostring = 64006;
+ optional bool populate = 64007;
+ optional bool stringer = 67008;
+ optional bool onlyone = 64009;
+
+ optional bool equal = 64013;
+ optional bool description = 64014;
+ optional bool testgen = 64015;
+ optional bool benchgen = 64016;
+ optional bool marshaler = 64017;
+ optional bool unmarshaler = 64018;
+ optional bool stable_marshaler = 64019;
+
+ optional bool sizer = 64020;
+
+ optional bool unsafe_marshaler = 64023;
+ optional bool unsafe_unmarshaler = 64024;
+
+ optional bool goproto_extensions_map = 64025;
+ optional bool goproto_unrecognized = 64026;
+
+ optional bool protosizer = 64028;
+ optional bool compare = 64029;
+
+ optional bool typedecl = 64030;
+
+ optional bool messagename = 64033;
+
+ optional bool goproto_sizecache = 64034;
+ optional bool goproto_unkeyed = 64035;
+}
+
+extend google.protobuf.FieldOptions {
+ optional bool nullable = 65001;
+ optional bool embed = 65002;
+ optional string customtype = 65003;
+ optional string customname = 65004;
+ optional string jsontag = 65005;
+ optional string moretags = 65006;
+ optional string casttype = 65007;
+ optional string castkey = 65008;
+ optional string castvalue = 65009;
+
+ optional bool stdtime = 65010;
+ optional bool stdduration = 65011;
+ optional bool wktpointer = 65012;
+
+}
diff --git a/vendor/github.com/gogo/protobuf/gogoproto/helper.go b/vendor/github.com/gogo/protobuf/gogoproto/helper.go
@@ -0,0 +1,415 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package gogoproto
+
+import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
+import proto "github.com/gogo/protobuf/proto"
+
+func IsEmbed(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Embed, false)
+}
+
+func IsNullable(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Nullable, true)
+}
+
+func IsStdTime(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Stdtime, false)
+}
+
+func IsStdDuration(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Stdduration, false)
+}
+
+func IsStdDouble(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Wktpointer, false) && *field.TypeName == ".google.protobuf.DoubleValue"
+}
+
+func IsStdFloat(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Wktpointer, false) && *field.TypeName == ".google.protobuf.FloatValue"
+}
+
+func IsStdInt64(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Wktpointer, false) && *field.TypeName == ".google.protobuf.Int64Value"
+}
+
+func IsStdUInt64(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Wktpointer, false) && *field.TypeName == ".google.protobuf.UInt64Value"
+}
+
+func IsStdInt32(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Wktpointer, false) && *field.TypeName == ".google.protobuf.Int32Value"
+}
+
+func IsStdUInt32(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Wktpointer, false) && *field.TypeName == ".google.protobuf.UInt32Value"
+}
+
+func IsStdBool(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Wktpointer, false) && *field.TypeName == ".google.protobuf.BoolValue"
+}
+
+func IsStdString(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Wktpointer, false) && *field.TypeName == ".google.protobuf.StringValue"
+}
+
+func IsStdBytes(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Wktpointer, false) && *field.TypeName == ".google.protobuf.BytesValue"
+}
+
+func IsStdType(field *google_protobuf.FieldDescriptorProto) bool {
+ return (IsStdTime(field) || IsStdDuration(field) ||
+ IsStdDouble(field) || IsStdFloat(field) ||
+ IsStdInt64(field) || IsStdUInt64(field) ||
+ IsStdInt32(field) || IsStdUInt32(field) ||
+ IsStdBool(field) ||
+ IsStdString(field) || IsStdBytes(field))
+}
+
+func IsWktPtr(field *google_protobuf.FieldDescriptorProto) bool {
+ return proto.GetBoolExtension(field.Options, E_Wktpointer, false)
+}
+
+func NeedsNilCheck(proto3 bool, field *google_protobuf.FieldDescriptorProto) bool {
+ nullable := IsNullable(field)
+ if field.IsMessage() || IsCustomType(field) {
+ return nullable
+ }
+ if proto3 {
+ return false
+ }
+ return nullable || *field.Type == google_protobuf.FieldDescriptorProto_TYPE_BYTES
+}
+
+func IsCustomType(field *google_protobuf.FieldDescriptorProto) bool {
+ typ := GetCustomType(field)
+ if len(typ) > 0 {
+ return true
+ }
+ return false
+}
+
+func IsCastType(field *google_protobuf.FieldDescriptorProto) bool {
+ typ := GetCastType(field)
+ if len(typ) > 0 {
+ return true
+ }
+ return false
+}
+
+func IsCastKey(field *google_protobuf.FieldDescriptorProto) bool {
+ typ := GetCastKey(field)
+ if len(typ) > 0 {
+ return true
+ }
+ return false
+}
+
+func IsCastValue(field *google_protobuf.FieldDescriptorProto) bool {
+ typ := GetCastValue(field)
+ if len(typ) > 0 {
+ return true
+ }
+ return false
+}
+
+func HasEnumDecl(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool {
+ return proto.GetBoolExtension(enum.Options, E_Enumdecl, proto.GetBoolExtension(file.Options, E_EnumdeclAll, true))
+}
+
+func HasTypeDecl(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Typedecl, proto.GetBoolExtension(file.Options, E_TypedeclAll, true))
+}
+
+func GetCustomType(field *google_protobuf.FieldDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Customtype)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetCastType(field *google_protobuf.FieldDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Casttype)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetCastKey(field *google_protobuf.FieldDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Castkey)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetCastValue(field *google_protobuf.FieldDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Castvalue)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func IsCustomName(field *google_protobuf.FieldDescriptorProto) bool {
+ name := GetCustomName(field)
+ if len(name) > 0 {
+ return true
+ }
+ return false
+}
+
+func IsEnumCustomName(field *google_protobuf.EnumDescriptorProto) bool {
+ name := GetEnumCustomName(field)
+ if len(name) > 0 {
+ return true
+ }
+ return false
+}
+
+func IsEnumValueCustomName(field *google_protobuf.EnumValueDescriptorProto) bool {
+ name := GetEnumValueCustomName(field)
+ if len(name) > 0 {
+ return true
+ }
+ return false
+}
+
+func GetCustomName(field *google_protobuf.FieldDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Customname)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetEnumCustomName(field *google_protobuf.EnumDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_EnumCustomname)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetEnumValueCustomName(field *google_protobuf.EnumValueDescriptorProto) string {
+ if field == nil {
+ return ""
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_EnumvalueCustomname)
+ if err == nil && v.(*string) != nil {
+ return *(v.(*string))
+ }
+ }
+ return ""
+}
+
+func GetJsonTag(field *google_protobuf.FieldDescriptorProto) *string {
+ if field == nil {
+ return nil
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Jsontag)
+ if err == nil && v.(*string) != nil {
+ return (v.(*string))
+ }
+ }
+ return nil
+}
+
+func GetMoreTags(field *google_protobuf.FieldDescriptorProto) *string {
+ if field == nil {
+ return nil
+ }
+ if field.Options != nil {
+ v, err := proto.GetExtension(field.Options, E_Moretags)
+ if err == nil && v.(*string) != nil {
+ return (v.(*string))
+ }
+ }
+ return nil
+}
+
+type EnableFunc func(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool
+
+func EnabledGoEnumPrefix(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool {
+ return proto.GetBoolExtension(enum.Options, E_GoprotoEnumPrefix, proto.GetBoolExtension(file.Options, E_GoprotoEnumPrefixAll, true))
+}
+
+func EnabledGoStringer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_GoprotoStringer, proto.GetBoolExtension(file.Options, E_GoprotoStringerAll, true))
+}
+
+func HasGoGetters(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_GoprotoGetters, proto.GetBoolExtension(file.Options, E_GoprotoGettersAll, true))
+}
+
+func IsUnion(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Onlyone, proto.GetBoolExtension(file.Options, E_OnlyoneAll, false))
+}
+
+func HasGoString(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Gostring, proto.GetBoolExtension(file.Options, E_GostringAll, false))
+}
+
+func HasEqual(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Equal, proto.GetBoolExtension(file.Options, E_EqualAll, false))
+}
+
+func HasVerboseEqual(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_VerboseEqual, proto.GetBoolExtension(file.Options, E_VerboseEqualAll, false))
+}
+
+func IsStringer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Stringer, proto.GetBoolExtension(file.Options, E_StringerAll, false))
+}
+
+func IsFace(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Face, proto.GetBoolExtension(file.Options, E_FaceAll, false))
+}
+
+func HasDescription(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Description, proto.GetBoolExtension(file.Options, E_DescriptionAll, false))
+}
+
+func HasPopulate(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Populate, proto.GetBoolExtension(file.Options, E_PopulateAll, false))
+}
+
+func HasTestGen(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Testgen, proto.GetBoolExtension(file.Options, E_TestgenAll, false))
+}
+
+func HasBenchGen(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Benchgen, proto.GetBoolExtension(file.Options, E_BenchgenAll, false))
+}
+
+func IsMarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Marshaler, proto.GetBoolExtension(file.Options, E_MarshalerAll, false))
+}
+
+func IsUnmarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Unmarshaler, proto.GetBoolExtension(file.Options, E_UnmarshalerAll, false))
+}
+
+func IsStableMarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_StableMarshaler, proto.GetBoolExtension(file.Options, E_StableMarshalerAll, false))
+}
+
+func IsSizer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Sizer, proto.GetBoolExtension(file.Options, E_SizerAll, false))
+}
+
+func IsProtoSizer(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Protosizer, proto.GetBoolExtension(file.Options, E_ProtosizerAll, false))
+}
+
+func IsGoEnumStringer(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool {
+ return proto.GetBoolExtension(enum.Options, E_GoprotoEnumStringer, proto.GetBoolExtension(file.Options, E_GoprotoEnumStringerAll, true))
+}
+
+func IsEnumStringer(file *google_protobuf.FileDescriptorProto, enum *google_protobuf.EnumDescriptorProto) bool {
+ return proto.GetBoolExtension(enum.Options, E_EnumStringer, proto.GetBoolExtension(file.Options, E_EnumStringerAll, false))
+}
+
+func IsUnsafeMarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_UnsafeMarshaler, proto.GetBoolExtension(file.Options, E_UnsafeMarshalerAll, false))
+}
+
+func IsUnsafeUnmarshaler(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_UnsafeUnmarshaler, proto.GetBoolExtension(file.Options, E_UnsafeUnmarshalerAll, false))
+}
+
+func HasExtensionsMap(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_GoprotoExtensionsMap, proto.GetBoolExtension(file.Options, E_GoprotoExtensionsMapAll, true))
+}
+
+func HasUnrecognized(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_GoprotoUnrecognized, proto.GetBoolExtension(file.Options, E_GoprotoUnrecognizedAll, true))
+}
+
+func IsProto3(file *google_protobuf.FileDescriptorProto) bool {
+ return file.GetSyntax() == "proto3"
+}
+
+func ImportsGoGoProto(file *google_protobuf.FileDescriptorProto) bool {
+ return proto.GetBoolExtension(file.Options, E_GogoprotoImport, true)
+}
+
+func HasCompare(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Compare, proto.GetBoolExtension(file.Options, E_CompareAll, false))
+}
+
+func RegistersGolangProto(file *google_protobuf.FileDescriptorProto) bool {
+ return proto.GetBoolExtension(file.Options, E_GoprotoRegistration, false)
+}
+
+func HasMessageName(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_Messagename, proto.GetBoolExtension(file.Options, E_MessagenameAll, false))
+}
+
+func HasSizecache(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_GoprotoSizecache, proto.GetBoolExtension(file.Options, E_GoprotoSizecacheAll, true))
+}
+
+func HasUnkeyed(file *google_protobuf.FileDescriptorProto, message *google_protobuf.DescriptorProto) bool {
+ return proto.GetBoolExtension(message.Options, E_GoprotoUnkeyed, proto.GetBoolExtension(file.Options, E_GoprotoUnkeyedAll, true))
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/Makefile b/vendor/github.com/gogo/protobuf/proto/Makefile
@@ -0,0 +1,43 @@
+# Go support for Protocol Buffers - Google's data interchange format
+#
+# Copyright 2010 The Go Authors. All rights reserved.
+# https://github.com/golang/protobuf
+#
+# 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.
+
+install:
+ go install
+
+test: install generate-test-pbs
+ go test
+
+
+generate-test-pbs:
+ make install
+ make -C test_proto
+ make -C proto3_proto
+ make
diff --git a/vendor/github.com/gogo/protobuf/proto/clone.go b/vendor/github.com/gogo/protobuf/proto/clone.go
@@ -0,0 +1,258 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2011 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// Protocol buffer deep copy and merge.
+// TODO: RawMessage.
+
+package proto
+
+import (
+ "fmt"
+ "log"
+ "reflect"
+ "strings"
+)
+
+// Clone returns a deep copy of a protocol buffer.
+func Clone(src Message) Message {
+ in := reflect.ValueOf(src)
+ if in.IsNil() {
+ return src
+ }
+ out := reflect.New(in.Type().Elem())
+ dst := out.Interface().(Message)
+ Merge(dst, src)
+ return dst
+}
+
+// Merger is the interface representing objects that can merge messages of the same type.
+type Merger interface {
+ // Merge merges src into this message.
+ // Required and optional fields that are set in src will be set to that value in dst.
+ // Elements of repeated fields will be appended.
+ //
+ // Merge may panic if called with a different argument type than the receiver.
+ Merge(src Message)
+}
+
+// generatedMerger is the custom merge method that generated protos will have.
+// We must add this method since a generate Merge method will conflict with
+// many existing protos that have a Merge data field already defined.
+type generatedMerger interface {
+ XXX_Merge(src Message)
+}
+
+// Merge merges src into dst.
+// Required and optional fields that are set in src will be set to that value in dst.
+// Elements of repeated fields will be appended.
+// Merge panics if src and dst are not the same type, or if dst is nil.
+func Merge(dst, src Message) {
+ if m, ok := dst.(Merger); ok {
+ m.Merge(src)
+ return
+ }
+
+ in := reflect.ValueOf(src)
+ out := reflect.ValueOf(dst)
+ if out.IsNil() {
+ panic("proto: nil destination")
+ }
+ if in.Type() != out.Type() {
+ panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src))
+ }
+ if in.IsNil() {
+ return // Merge from nil src is a noop
+ }
+ if m, ok := dst.(generatedMerger); ok {
+ m.XXX_Merge(src)
+ return
+ }
+ mergeStruct(out.Elem(), in.Elem())
+}
+
+func mergeStruct(out, in reflect.Value) {
+ sprop := GetProperties(in.Type())
+ for i := 0; i < in.NumField(); i++ {
+ f := in.Type().Field(i)
+ if strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+ mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
+ }
+
+ if emIn, ok := in.Addr().Interface().(extensionsBytes); ok {
+ emOut := out.Addr().Interface().(extensionsBytes)
+ bIn := emIn.GetExtensions()
+ bOut := emOut.GetExtensions()
+ *bOut = append(*bOut, *bIn...)
+ } else if emIn, err := extendable(in.Addr().Interface()); err == nil {
+ emOut, _ := extendable(out.Addr().Interface())
+ mIn, muIn := emIn.extensionsRead()
+ if mIn != nil {
+ mOut := emOut.extensionsWrite()
+ muIn.Lock()
+ mergeExtension(mOut, mIn)
+ muIn.Unlock()
+ }
+ }
+
+ uf := in.FieldByName("XXX_unrecognized")
+ if !uf.IsValid() {
+ return
+ }
+ uin := uf.Bytes()
+ if len(uin) > 0 {
+ out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
+ }
+}
+
+// mergeAny performs a merge between two values of the same type.
+// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
+// prop is set if this is a struct field (it may be nil).
+func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
+ if in.Type() == protoMessageType {
+ if !in.IsNil() {
+ if out.IsNil() {
+ out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
+ } else {
+ Merge(out.Interface().(Message), in.Interface().(Message))
+ }
+ }
+ return
+ }
+ switch in.Kind() {
+ case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
+ reflect.String, reflect.Uint32, reflect.Uint64:
+ if !viaPtr && isProto3Zero(in) {
+ return
+ }
+ out.Set(in)
+ case reflect.Interface:
+ // Probably a oneof field; copy non-nil values.
+ if in.IsNil() {
+ return
+ }
+ // Allocate destination if it is not set, or set to a different type.
+ // Otherwise we will merge as normal.
+ if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
+ out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
+ }
+ mergeAny(out.Elem(), in.Elem(), false, nil)
+ case reflect.Map:
+ if in.Len() == 0 {
+ return
+ }
+ if out.IsNil() {
+ out.Set(reflect.MakeMap(in.Type()))
+ }
+ // For maps with value types of *T or []byte we need to deep copy each value.
+ elemKind := in.Type().Elem().Kind()
+ for _, key := range in.MapKeys() {
+ var val reflect.Value
+ switch elemKind {
+ case reflect.Ptr:
+ val = reflect.New(in.Type().Elem().Elem())
+ mergeAny(val, in.MapIndex(key), false, nil)
+ case reflect.Slice:
+ val = in.MapIndex(key)
+ val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
+ default:
+ val = in.MapIndex(key)
+ }
+ out.SetMapIndex(key, val)
+ }
+ case reflect.Ptr:
+ if in.IsNil() {
+ return
+ }
+ if out.IsNil() {
+ out.Set(reflect.New(in.Elem().Type()))
+ }
+ mergeAny(out.Elem(), in.Elem(), true, nil)
+ case reflect.Slice:
+ if in.IsNil() {
+ return
+ }
+ if in.Type().Elem().Kind() == reflect.Uint8 {
+ // []byte is a scalar bytes field, not a repeated field.
+
+ // Edge case: if this is in a proto3 message, a zero length
+ // bytes field is considered the zero value, and should not
+ // be merged.
+ if prop != nil && prop.proto3 && in.Len() == 0 {
+ return
+ }
+
+ // Make a deep copy.
+ // Append to []byte{} instead of []byte(nil) so that we never end up
+ // with a nil result.
+ out.SetBytes(append([]byte{}, in.Bytes()...))
+ return
+ }
+ n := in.Len()
+ if out.IsNil() {
+ out.Set(reflect.MakeSlice(in.Type(), 0, n))
+ }
+ switch in.Type().Elem().Kind() {
+ case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
+ reflect.String, reflect.Uint32, reflect.Uint64:
+ out.Set(reflect.AppendSlice(out, in))
+ default:
+ for i := 0; i < n; i++ {
+ x := reflect.Indirect(reflect.New(in.Type().Elem()))
+ mergeAny(x, in.Index(i), false, nil)
+ out.Set(reflect.Append(out, x))
+ }
+ }
+ case reflect.Struct:
+ mergeStruct(out, in)
+ default:
+ // unknown type, so not a protocol buffer
+ log.Printf("proto: don't know how to copy %v", in)
+ }
+}
+
+func mergeExtension(out, in map[int32]Extension) {
+ for extNum, eIn := range in {
+ eOut := Extension{desc: eIn.desc}
+ if eIn.value != nil {
+ v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
+ mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
+ eOut.value = v.Interface()
+ }
+ if eIn.enc != nil {
+ eOut.enc = make([]byte, len(eIn.enc))
+ copy(eOut.enc, eIn.enc)
+ }
+
+ out[extNum] = eOut
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/custom_gogo.go b/vendor/github.com/gogo/protobuf/proto/custom_gogo.go
@@ -0,0 +1,39 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2018, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import "reflect"
+
+type custom interface {
+ Marshal() ([]byte, error)
+ Unmarshal(data []byte) error
+ Size() int
+}
+
+var customType = reflect.TypeOf((*custom)(nil)).Elem()
diff --git a/vendor/github.com/gogo/protobuf/proto/decode.go b/vendor/github.com/gogo/protobuf/proto/decode.go
@@ -0,0 +1,427 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Routines for decoding protocol buffer data to construct in-memory representations.
+ */
+
+import (
+ "errors"
+ "fmt"
+ "io"
+)
+
+// errOverflow is returned when an integer is too large to be represented.
+var errOverflow = errors.New("proto: integer overflow")
+
+// ErrInternalBadWireType is returned by generated code when an incorrect
+// wire type is encountered. It does not get returned to user code.
+var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
+
+// DecodeVarint reads a varint-encoded integer from the slice.
+// It returns the integer and the number of bytes consumed, or
+// zero if there is not enough.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func DecodeVarint(buf []byte) (x uint64, n int) {
+ for shift := uint(0); shift < 64; shift += 7 {
+ if n >= len(buf) {
+ return 0, 0
+ }
+ b := uint64(buf[n])
+ n++
+ x |= (b & 0x7F) << shift
+ if (b & 0x80) == 0 {
+ return x, n
+ }
+ }
+
+ // The number is too large to represent in a 64-bit value.
+ return 0, 0
+}
+
+func (p *Buffer) decodeVarintSlow() (x uint64, err error) {
+ i := p.index
+ l := len(p.buf)
+
+ for shift := uint(0); shift < 64; shift += 7 {
+ if i >= l {
+ err = io.ErrUnexpectedEOF
+ return
+ }
+ b := p.buf[i]
+ i++
+ x |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ p.index = i
+ return
+ }
+ }
+
+ // The number is too large to represent in a 64-bit value.
+ err = errOverflow
+ return
+}
+
+// DecodeVarint reads a varint-encoded integer from the Buffer.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func (p *Buffer) DecodeVarint() (x uint64, err error) {
+ i := p.index
+ buf := p.buf
+
+ if i >= len(buf) {
+ return 0, io.ErrUnexpectedEOF
+ } else if buf[i] < 0x80 {
+ p.index++
+ return uint64(buf[i]), nil
+ } else if len(buf)-i < 10 {
+ return p.decodeVarintSlow()
+ }
+
+ var b uint64
+ // we already checked the first byte
+ x = uint64(buf[i]) - 0x80
+ i++
+
+ b = uint64(buf[i])
+ i++
+ x += b << 7
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 7
+
+ b = uint64(buf[i])
+ i++
+ x += b << 14
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 14
+
+ b = uint64(buf[i])
+ i++
+ x += b << 21
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 21
+
+ b = uint64(buf[i])
+ i++
+ x += b << 28
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 28
+
+ b = uint64(buf[i])
+ i++
+ x += b << 35
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 35
+
+ b = uint64(buf[i])
+ i++
+ x += b << 42
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 42
+
+ b = uint64(buf[i])
+ i++
+ x += b << 49
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 49
+
+ b = uint64(buf[i])
+ i++
+ x += b << 56
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 56
+
+ b = uint64(buf[i])
+ i++
+ x += b << 63
+ if b&0x80 == 0 {
+ goto done
+ }
+
+ return 0, errOverflow
+
+done:
+ p.index = i
+ return x, nil
+}
+
+// DecodeFixed64 reads a 64-bit integer from the Buffer.
+// This is the format for the
+// fixed64, sfixed64, and double protocol buffer types.
+func (p *Buffer) DecodeFixed64() (x uint64, err error) {
+ // x, err already 0
+ i := p.index + 8
+ if i < 0 || i > len(p.buf) {
+ err = io.ErrUnexpectedEOF
+ return
+ }
+ p.index = i
+
+ x = uint64(p.buf[i-8])
+ x |= uint64(p.buf[i-7]) << 8
+ x |= uint64(p.buf[i-6]) << 16
+ x |= uint64(p.buf[i-5]) << 24
+ x |= uint64(p.buf[i-4]) << 32
+ x |= uint64(p.buf[i-3]) << 40
+ x |= uint64(p.buf[i-2]) << 48
+ x |= uint64(p.buf[i-1]) << 56
+ return
+}
+
+// DecodeFixed32 reads a 32-bit integer from the Buffer.
+// This is the format for the
+// fixed32, sfixed32, and float protocol buffer types.
+func (p *Buffer) DecodeFixed32() (x uint64, err error) {
+ // x, err already 0
+ i := p.index + 4
+ if i < 0 || i > len(p.buf) {
+ err = io.ErrUnexpectedEOF
+ return
+ }
+ p.index = i
+
+ x = uint64(p.buf[i-4])
+ x |= uint64(p.buf[i-3]) << 8
+ x |= uint64(p.buf[i-2]) << 16
+ x |= uint64(p.buf[i-1]) << 24
+ return
+}
+
+// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
+// from the Buffer.
+// This is the format used for the sint64 protocol buffer type.
+func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
+ x, err = p.DecodeVarint()
+ if err != nil {
+ return
+ }
+ x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
+ return
+}
+
+// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
+// from the Buffer.
+// This is the format used for the sint32 protocol buffer type.
+func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
+ x, err = p.DecodeVarint()
+ if err != nil {
+ return
+ }
+ x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
+ return
+}
+
+// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
+// This is the format used for the bytes protocol buffer
+// type and for embedded messages.
+func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
+ n, err := p.DecodeVarint()
+ if err != nil {
+ return nil, err
+ }
+
+ nb := int(n)
+ if nb < 0 {
+ return nil, fmt.Errorf("proto: bad byte length %d", nb)
+ }
+ end := p.index + nb
+ if end < p.index || end > len(p.buf) {
+ return nil, io.ErrUnexpectedEOF
+ }
+
+ if !alloc {
+ // todo: check if can get more uses of alloc=false
+ buf = p.buf[p.index:end]
+ p.index += nb
+ return
+ }
+
+ buf = make([]byte, nb)
+ copy(buf, p.buf[p.index:])
+ p.index += nb
+ return
+}
+
+// DecodeStringBytes reads an encoded string from the Buffer.
+// This is the format used for the proto2 string type.
+func (p *Buffer) DecodeStringBytes() (s string, err error) {
+ buf, err := p.DecodeRawBytes(false)
+ if err != nil {
+ return
+ }
+ return string(buf), nil
+}
+
+// Unmarshaler is the interface representing objects that can
+// unmarshal themselves. The argument points to data that may be
+// overwritten, so implementations should not keep references to the
+// buffer.
+// Unmarshal implementations should not clear the receiver.
+// Any unmarshaled data should be merged into the receiver.
+// Callers of Unmarshal that do not want to retain existing data
+// should Reset the receiver before calling Unmarshal.
+type Unmarshaler interface {
+ Unmarshal([]byte) error
+}
+
+// newUnmarshaler is the interface representing objects that can
+// unmarshal themselves. The semantics are identical to Unmarshaler.
+//
+// This exists to support protoc-gen-go generated messages.
+// The proto package will stop type-asserting to this interface in the future.
+//
+// DO NOT DEPEND ON THIS.
+type newUnmarshaler interface {
+ XXX_Unmarshal([]byte) error
+}
+
+// Unmarshal parses the protocol buffer representation in buf and places the
+// decoded result in pb. If the struct underlying pb does not match
+// the data in buf, the results can be unpredictable.
+//
+// Unmarshal resets pb before starting to unmarshal, so any
+// existing data in pb is always removed. Use UnmarshalMerge
+// to preserve and append to existing data.
+func Unmarshal(buf []byte, pb Message) error {
+ pb.Reset()
+ if u, ok := pb.(newUnmarshaler); ok {
+ return u.XXX_Unmarshal(buf)
+ }
+ if u, ok := pb.(Unmarshaler); ok {
+ return u.Unmarshal(buf)
+ }
+ return NewBuffer(buf).Unmarshal(pb)
+}
+
+// UnmarshalMerge parses the protocol buffer representation in buf and
+// writes the decoded result to pb. If the struct underlying pb does not match
+// the data in buf, the results can be unpredictable.
+//
+// UnmarshalMerge merges into existing data in pb.
+// Most code should use Unmarshal instead.
+func UnmarshalMerge(buf []byte, pb Message) error {
+ if u, ok := pb.(newUnmarshaler); ok {
+ return u.XXX_Unmarshal(buf)
+ }
+ if u, ok := pb.(Unmarshaler); ok {
+ // NOTE: The history of proto have unfortunately been inconsistent
+ // whether Unmarshaler should or should not implicitly clear itself.
+ // Some implementations do, most do not.
+ // Thus, calling this here may or may not do what people want.
+ //
+ // See https://github.com/golang/protobuf/issues/424
+ return u.Unmarshal(buf)
+ }
+ return NewBuffer(buf).Unmarshal(pb)
+}
+
+// DecodeMessage reads a count-delimited message from the Buffer.
+func (p *Buffer) DecodeMessage(pb Message) error {
+ enc, err := p.DecodeRawBytes(false)
+ if err != nil {
+ return err
+ }
+ return NewBuffer(enc).Unmarshal(pb)
+}
+
+// DecodeGroup reads a tag-delimited group from the Buffer.
+// StartGroup tag is already consumed. This function consumes
+// EndGroup tag.
+func (p *Buffer) DecodeGroup(pb Message) error {
+ b := p.buf[p.index:]
+ x, y := findEndGroup(b)
+ if x < 0 {
+ return io.ErrUnexpectedEOF
+ }
+ err := Unmarshal(b[:x], pb)
+ p.index += y
+ return err
+}
+
+// Unmarshal parses the protocol buffer representation in the
+// Buffer and places the decoded result in pb. If the struct
+// underlying pb does not match the data in the buffer, the results can be
+// unpredictable.
+//
+// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal.
+func (p *Buffer) Unmarshal(pb Message) error {
+ // If the object can unmarshal itself, let it.
+ if u, ok := pb.(newUnmarshaler); ok {
+ err := u.XXX_Unmarshal(p.buf[p.index:])
+ p.index = len(p.buf)
+ return err
+ }
+ if u, ok := pb.(Unmarshaler); ok {
+ // NOTE: The history of proto have unfortunately been inconsistent
+ // whether Unmarshaler should or should not implicitly clear itself.
+ // Some implementations do, most do not.
+ // Thus, calling this here may or may not do what people want.
+ //
+ // See https://github.com/golang/protobuf/issues/424
+ err := u.Unmarshal(p.buf[p.index:])
+ p.index = len(p.buf)
+ return err
+ }
+
+ // Slow workaround for messages that aren't Unmarshalers.
+ // This includes some hand-coded .pb.go files and
+ // bootstrap protos.
+ // TODO: fix all of those and then add Unmarshal to
+ // the Message interface. Then:
+ // The cast above and code below can be deleted.
+ // The old unmarshaler can be deleted.
+ // Clients can call Unmarshal directly (can already do that, actually).
+ var info InternalMessageInfo
+ err := info.Unmarshal(pb, p.buf[p.index:])
+ p.index = len(p.buf)
+ return err
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/deprecated.go b/vendor/github.com/gogo/protobuf/proto/deprecated.go
@@ -0,0 +1,63 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2018 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+import "errors"
+
+// Deprecated: do not use.
+type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 }
+
+// Deprecated: do not use.
+func GetStats() Stats { return Stats{} }
+
+// Deprecated: do not use.
+func MarshalMessageSet(interface{}) ([]byte, error) {
+ return nil, errors.New("proto: not implemented")
+}
+
+// Deprecated: do not use.
+func UnmarshalMessageSet([]byte, interface{}) error {
+ return errors.New("proto: not implemented")
+}
+
+// Deprecated: do not use.
+func MarshalMessageSetJSON(interface{}) ([]byte, error) {
+ return nil, errors.New("proto: not implemented")
+}
+
+// Deprecated: do not use.
+func UnmarshalMessageSetJSON([]byte, interface{}) error {
+ return errors.New("proto: not implemented")
+}
+
+// Deprecated: do not use.
+func RegisterMessageSetType(Message, int32, string) {}
diff --git a/vendor/github.com/gogo/protobuf/proto/discard.go b/vendor/github.com/gogo/protobuf/proto/discard.go
@@ -0,0 +1,350 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2017 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+ "sync"
+ "sync/atomic"
+)
+
+type generatedDiscarder interface {
+ XXX_DiscardUnknown()
+}
+
+// DiscardUnknown recursively discards all unknown fields from this message
+// and all embedded messages.
+//
+// When unmarshaling a message with unrecognized fields, the tags and values
+// of such fields are preserved in the Message. This allows a later call to
+// marshal to be able to produce a message that continues to have those
+// unrecognized fields. To avoid this, DiscardUnknown is used to
+// explicitly clear the unknown fields after unmarshaling.
+//
+// For proto2 messages, the unknown fields of message extensions are only
+// discarded from messages that have been accessed via GetExtension.
+func DiscardUnknown(m Message) {
+ if m, ok := m.(generatedDiscarder); ok {
+ m.XXX_DiscardUnknown()
+ return
+ }
+ // TODO: Dynamically populate a InternalMessageInfo for legacy messages,
+ // but the master branch has no implementation for InternalMessageInfo,
+ // so it would be more work to replicate that approach.
+ discardLegacy(m)
+}
+
+// DiscardUnknown recursively discards all unknown fields.
+func (a *InternalMessageInfo) DiscardUnknown(m Message) {
+ di := atomicLoadDiscardInfo(&a.discard)
+ if di == nil {
+ di = getDiscardInfo(reflect.TypeOf(m).Elem())
+ atomicStoreDiscardInfo(&a.discard, di)
+ }
+ di.discard(toPointer(&m))
+}
+
+type discardInfo struct {
+ typ reflect.Type
+
+ initialized int32 // 0: only typ is valid, 1: everything is valid
+ lock sync.Mutex
+
+ fields []discardFieldInfo
+ unrecognized field
+}
+
+type discardFieldInfo struct {
+ field field // Offset of field, guaranteed to be valid
+ discard func(src pointer)
+}
+
+var (
+ discardInfoMap = map[reflect.Type]*discardInfo{}
+ discardInfoLock sync.Mutex
+)
+
+func getDiscardInfo(t reflect.Type) *discardInfo {
+ discardInfoLock.Lock()
+ defer discardInfoLock.Unlock()
+ di := discardInfoMap[t]
+ if di == nil {
+ di = &discardInfo{typ: t}
+ discardInfoMap[t] = di
+ }
+ return di
+}
+
+func (di *discardInfo) discard(src pointer) {
+ if src.isNil() {
+ return // Nothing to do.
+ }
+
+ if atomic.LoadInt32(&di.initialized) == 0 {
+ di.computeDiscardInfo()
+ }
+
+ for _, fi := range di.fields {
+ sfp := src.offset(fi.field)
+ fi.discard(sfp)
+ }
+
+ // For proto2 messages, only discard unknown fields in message extensions
+ // that have been accessed via GetExtension.
+ if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil {
+ // Ignore lock since DiscardUnknown is not concurrency safe.
+ emm, _ := em.extensionsRead()
+ for _, mx := range emm {
+ if m, ok := mx.value.(Message); ok {
+ DiscardUnknown(m)
+ }
+ }
+ }
+
+ if di.unrecognized.IsValid() {
+ *src.offset(di.unrecognized).toBytes() = nil
+ }
+}
+
+func (di *discardInfo) computeDiscardInfo() {
+ di.lock.Lock()
+ defer di.lock.Unlock()
+ if di.initialized != 0 {
+ return
+ }
+ t := di.typ
+ n := t.NumField()
+
+ for i := 0; i < n; i++ {
+ f := t.Field(i)
+ if strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+
+ dfi := discardFieldInfo{field: toField(&f)}
+ tf := f.Type
+
+ // Unwrap tf to get its most basic type.
+ var isPointer, isSlice bool
+ if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
+ isSlice = true
+ tf = tf.Elem()
+ }
+ if tf.Kind() == reflect.Ptr {
+ isPointer = true
+ tf = tf.Elem()
+ }
+ if isPointer && isSlice && tf.Kind() != reflect.Struct {
+ panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name))
+ }
+
+ switch tf.Kind() {
+ case reflect.Struct:
+ switch {
+ case !isPointer:
+ panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name))
+ case isSlice: // E.g., []*pb.T
+ discardInfo := getDiscardInfo(tf)
+ dfi.discard = func(src pointer) {
+ sps := src.getPointerSlice()
+ for _, sp := range sps {
+ if !sp.isNil() {
+ discardInfo.discard(sp)
+ }
+ }
+ }
+ default: // E.g., *pb.T
+ discardInfo := getDiscardInfo(tf)
+ dfi.discard = func(src pointer) {
+ sp := src.getPointer()
+ if !sp.isNil() {
+ discardInfo.discard(sp)
+ }
+ }
+ }
+ case reflect.Map:
+ switch {
+ case isPointer || isSlice:
+ panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name))
+ default: // E.g., map[K]V
+ if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T)
+ dfi.discard = func(src pointer) {
+ sm := src.asPointerTo(tf).Elem()
+ if sm.Len() == 0 {
+ return
+ }
+ for _, key := range sm.MapKeys() {
+ val := sm.MapIndex(key)
+ DiscardUnknown(val.Interface().(Message))
+ }
+ }
+ } else {
+ dfi.discard = func(pointer) {} // Noop
+ }
+ }
+ case reflect.Interface:
+ // Must be oneof field.
+ switch {
+ case isPointer || isSlice:
+ panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name))
+ default: // E.g., interface{}
+ // TODO: Make this faster?
+ dfi.discard = func(src pointer) {
+ su := src.asPointerTo(tf).Elem()
+ if !su.IsNil() {
+ sv := su.Elem().Elem().Field(0)
+ if sv.Kind() == reflect.Ptr && sv.IsNil() {
+ return
+ }
+ switch sv.Type().Kind() {
+ case reflect.Ptr: // Proto struct (e.g., *T)
+ DiscardUnknown(sv.Interface().(Message))
+ }
+ }
+ }
+ }
+ default:
+ continue
+ }
+ di.fields = append(di.fields, dfi)
+ }
+
+ di.unrecognized = invalidField
+ if f, ok := t.FieldByName("XXX_unrecognized"); ok {
+ if f.Type != reflect.TypeOf([]byte{}) {
+ panic("expected XXX_unrecognized to be of type []byte")
+ }
+ di.unrecognized = toField(&f)
+ }
+
+ atomic.StoreInt32(&di.initialized, 1)
+}
+
+func discardLegacy(m Message) {
+ v := reflect.ValueOf(m)
+ if v.Kind() != reflect.Ptr || v.IsNil() {
+ return
+ }
+ v = v.Elem()
+ if v.Kind() != reflect.Struct {
+ return
+ }
+ t := v.Type()
+
+ for i := 0; i < v.NumField(); i++ {
+ f := t.Field(i)
+ if strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+ vf := v.Field(i)
+ tf := f.Type
+
+ // Unwrap tf to get its most basic type.
+ var isPointer, isSlice bool
+ if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
+ isSlice = true
+ tf = tf.Elem()
+ }
+ if tf.Kind() == reflect.Ptr {
+ isPointer = true
+ tf = tf.Elem()
+ }
+ if isPointer && isSlice && tf.Kind() != reflect.Struct {
+ panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))
+ }
+
+ switch tf.Kind() {
+ case reflect.Struct:
+ switch {
+ case !isPointer:
+ panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))
+ case isSlice: // E.g., []*pb.T
+ for j := 0; j < vf.Len(); j++ {
+ discardLegacy(vf.Index(j).Interface().(Message))
+ }
+ default: // E.g., *pb.T
+ discardLegacy(vf.Interface().(Message))
+ }
+ case reflect.Map:
+ switch {
+ case isPointer || isSlice:
+ panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))
+ default: // E.g., map[K]V
+ tv := vf.Type().Elem()
+ if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)
+ for _, key := range vf.MapKeys() {
+ val := vf.MapIndex(key)
+ discardLegacy(val.Interface().(Message))
+ }
+ }
+ }
+ case reflect.Interface:
+ // Must be oneof field.
+ switch {
+ case isPointer || isSlice:
+ panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))
+ default: // E.g., test_proto.isCommunique_Union interface
+ if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {
+ vf = vf.Elem() // E.g., *test_proto.Communique_Msg
+ if !vf.IsNil() {
+ vf = vf.Elem() // E.g., test_proto.Communique_Msg
+ vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value
+ if vf.Kind() == reflect.Ptr {
+ discardLegacy(vf.Interface().(Message))
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() {
+ if vf.Type() != reflect.TypeOf([]byte{}) {
+ panic("expected XXX_unrecognized to be of type []byte")
+ }
+ vf.Set(reflect.ValueOf([]byte(nil)))
+ }
+
+ // For proto2 messages, only discard unknown fields in message extensions
+ // that have been accessed via GetExtension.
+ if em, err := extendable(m); err == nil {
+ // Ignore lock since discardLegacy is not concurrency safe.
+ emm, _ := em.extensionsRead()
+ for _, mx := range emm {
+ if m, ok := mx.value.(Message); ok {
+ discardLegacy(m)
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/duration.go b/vendor/github.com/gogo/protobuf/proto/duration.go
@@ -0,0 +1,100 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+// This file implements conversions between google.protobuf.Duration
+// and time.Duration.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+)
+
+const (
+ // Range of a Duration in seconds, as specified in
+ // google/protobuf/duration.proto. This is about 10,000 years in seconds.
+ maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
+ minSeconds = -maxSeconds
+)
+
+// validateDuration determines whether the Duration is valid according to the
+// definition in google/protobuf/duration.proto. A valid Duration
+// may still be too large to fit into a time.Duration (the range of Duration
+// is about 10,000 years, and the range of time.Duration is about 290).
+func validateDuration(d *duration) error {
+ if d == nil {
+ return errors.New("duration: nil Duration")
+ }
+ if d.Seconds < minSeconds || d.Seconds > maxSeconds {
+ return fmt.Errorf("duration: %#v: seconds out of range", d)
+ }
+ if d.Nanos <= -1e9 || d.Nanos >= 1e9 {
+ return fmt.Errorf("duration: %#v: nanos out of range", d)
+ }
+ // Seconds and Nanos must have the same sign, unless d.Nanos is zero.
+ if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) {
+ return fmt.Errorf("duration: %#v: seconds and nanos have different signs", d)
+ }
+ return nil
+}
+
+// DurationFromProto converts a Duration to a time.Duration. DurationFromProto
+// returns an error if the Duration is invalid or is too large to be
+// represented in a time.Duration.
+func durationFromProto(p *duration) (time.Duration, error) {
+ if err := validateDuration(p); err != nil {
+ return 0, err
+ }
+ d := time.Duration(p.Seconds) * time.Second
+ if int64(d/time.Second) != p.Seconds {
+ return 0, fmt.Errorf("duration: %#v is out of range for time.Duration", p)
+ }
+ if p.Nanos != 0 {
+ d += time.Duration(p.Nanos)
+ if (d < 0) != (p.Nanos < 0) {
+ return 0, fmt.Errorf("duration: %#v is out of range for time.Duration", p)
+ }
+ }
+ return d, nil
+}
+
+// DurationProto converts a time.Duration to a Duration.
+func durationProto(d time.Duration) *duration {
+ nanos := d.Nanoseconds()
+ secs := nanos / 1e9
+ nanos -= secs * 1e9
+ return &duration{
+ Seconds: secs,
+ Nanos: int32(nanos),
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/duration_gogo.go b/vendor/github.com/gogo/protobuf/proto/duration_gogo.go
@@ -0,0 +1,49 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2016, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import (
+ "reflect"
+ "time"
+)
+
+var durationType = reflect.TypeOf((*time.Duration)(nil)).Elem()
+
+type duration struct {
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
+}
+
+func (m *duration) Reset() { *m = duration{} }
+func (*duration) ProtoMessage() {}
+func (*duration) String() string { return "duration<string>" }
+
+func init() {
+ RegisterType((*duration)(nil), "gogo.protobuf.proto.duration")
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/encode.go b/vendor/github.com/gogo/protobuf/proto/encode.go
@@ -0,0 +1,205 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Routines for encoding data into the wire format for protocol buffers.
+ */
+
+import (
+ "errors"
+ "reflect"
+)
+
+var (
+ // errRepeatedHasNil is the error returned if Marshal is called with
+ // a struct with a repeated field containing a nil element.
+ errRepeatedHasNil = errors.New("proto: repeated field has nil element")
+
+ // errOneofHasNil is the error returned if Marshal is called with
+ // a struct with a oneof field containing a nil element.
+ errOneofHasNil = errors.New("proto: oneof field has nil value")
+
+ // ErrNil is the error returned if Marshal is called with nil.
+ ErrNil = errors.New("proto: Marshal called with nil")
+
+ // ErrTooLarge is the error returned if Marshal is called with a
+ // message that encodes to >2GB.
+ ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
+)
+
+// The fundamental encoders that put bytes on the wire.
+// Those that take integer types all accept uint64 and are
+// therefore of type valueEncoder.
+
+const maxVarintBytes = 10 // maximum length of a varint
+
+// EncodeVarint returns the varint encoding of x.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+// Not used by the package itself, but helpful to clients
+// wishing to use the same encoding.
+func EncodeVarint(x uint64) []byte {
+ var buf [maxVarintBytes]byte
+ var n int
+ for n = 0; x > 127; n++ {
+ buf[n] = 0x80 | uint8(x&0x7F)
+ x >>= 7
+ }
+ buf[n] = uint8(x)
+ n++
+ return buf[0:n]
+}
+
+// EncodeVarint writes a varint-encoded integer to the Buffer.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func (p *Buffer) EncodeVarint(x uint64) error {
+ for x >= 1<<7 {
+ p.buf = append(p.buf, uint8(x&0x7f|0x80))
+ x >>= 7
+ }
+ p.buf = append(p.buf, uint8(x))
+ return nil
+}
+
+// SizeVarint returns the varint encoding size of an integer.
+func SizeVarint(x uint64) int {
+ switch {
+ case x < 1<<7:
+ return 1
+ case x < 1<<14:
+ return 2
+ case x < 1<<21:
+ return 3
+ case x < 1<<28:
+ return 4
+ case x < 1<<35:
+ return 5
+ case x < 1<<42:
+ return 6
+ case x < 1<<49:
+ return 7
+ case x < 1<<56:
+ return 8
+ case x < 1<<63:
+ return 9
+ }
+ return 10
+}
+
+// EncodeFixed64 writes a 64-bit integer to the Buffer.
+// This is the format for the
+// fixed64, sfixed64, and double protocol buffer types.
+func (p *Buffer) EncodeFixed64(x uint64) error {
+ p.buf = append(p.buf,
+ uint8(x),
+ uint8(x>>8),
+ uint8(x>>16),
+ uint8(x>>24),
+ uint8(x>>32),
+ uint8(x>>40),
+ uint8(x>>48),
+ uint8(x>>56))
+ return nil
+}
+
+// EncodeFixed32 writes a 32-bit integer to the Buffer.
+// This is the format for the
+// fixed32, sfixed32, and float protocol buffer types.
+func (p *Buffer) EncodeFixed32(x uint64) error {
+ p.buf = append(p.buf,
+ uint8(x),
+ uint8(x>>8),
+ uint8(x>>16),
+ uint8(x>>24))
+ return nil
+}
+
+// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
+// to the Buffer.
+// This is the format used for the sint64 protocol buffer type.
+func (p *Buffer) EncodeZigzag64(x uint64) error {
+ // use signed number to get arithmetic right shift.
+ return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+}
+
+// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
+// to the Buffer.
+// This is the format used for the sint32 protocol buffer type.
+func (p *Buffer) EncodeZigzag32(x uint64) error {
+ // use signed number to get arithmetic right shift.
+ return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
+}
+
+// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
+// This is the format used for the bytes protocol buffer
+// type and for embedded messages.
+func (p *Buffer) EncodeRawBytes(b []byte) error {
+ p.EncodeVarint(uint64(len(b)))
+ p.buf = append(p.buf, b...)
+ return nil
+}
+
+// EncodeStringBytes writes an encoded string to the Buffer.
+// This is the format used for the proto2 string type.
+func (p *Buffer) EncodeStringBytes(s string) error {
+ p.EncodeVarint(uint64(len(s)))
+ p.buf = append(p.buf, s...)
+ return nil
+}
+
+// Marshaler is the interface representing objects that can marshal themselves.
+type Marshaler interface {
+ Marshal() ([]byte, error)
+}
+
+// EncodeMessage writes the protocol buffer to the Buffer,
+// prefixed by a varint-encoded length.
+func (p *Buffer) EncodeMessage(pb Message) error {
+ siz := Size(pb)
+ sizVar := SizeVarint(uint64(siz))
+ p.grow(siz + sizVar)
+ p.EncodeVarint(uint64(siz))
+ return p.Marshal(pb)
+}
+
+// All protocol buffer fields are nillable, but be careful.
+func isNil(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+ return v.IsNil()
+ }
+ return false
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/encode_gogo.go b/vendor/github.com/gogo/protobuf/proto/encode_gogo.go
@@ -0,0 +1,33 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+func NewRequiredNotSetError(field string) *RequiredNotSetError {
+ return &RequiredNotSetError{field}
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/equal.go b/vendor/github.com/gogo/protobuf/proto/equal.go
@@ -0,0 +1,300 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2011 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// Protocol buffer comparison.
+
+package proto
+
+import (
+ "bytes"
+ "log"
+ "reflect"
+ "strings"
+)
+
+/*
+Equal returns true iff protocol buffers a and b are equal.
+The arguments must both be pointers to protocol buffer structs.
+
+Equality is defined in this way:
+ - Two messages are equal iff they are the same type,
+ corresponding fields are equal, unknown field sets
+ are equal, and extensions sets are equal.
+ - Two set scalar fields are equal iff their values are equal.
+ If the fields are of a floating-point type, remember that
+ NaN != x for all x, including NaN. If the message is defined
+ in a proto3 .proto file, fields are not "set"; specifically,
+ zero length proto3 "bytes" fields are equal (nil == {}).
+ - Two repeated fields are equal iff their lengths are the same,
+ and their corresponding elements are equal. Note a "bytes" field,
+ although represented by []byte, is not a repeated field and the
+ rule for the scalar fields described above applies.
+ - Two unset fields are equal.
+ - Two unknown field sets are equal if their current
+ encoded state is equal.
+ - Two extension sets are equal iff they have corresponding
+ elements that are pairwise equal.
+ - Two map fields are equal iff their lengths are the same,
+ and they contain the same set of elements. Zero-length map
+ fields are equal.
+ - Every other combination of things are not equal.
+
+The return value is undefined if a and b are not protocol buffers.
+*/
+func Equal(a, b Message) bool {
+ if a == nil || b == nil {
+ return a == b
+ }
+ v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
+ if v1.Type() != v2.Type() {
+ return false
+ }
+ if v1.Kind() == reflect.Ptr {
+ if v1.IsNil() {
+ return v2.IsNil()
+ }
+ if v2.IsNil() {
+ return false
+ }
+ v1, v2 = v1.Elem(), v2.Elem()
+ }
+ if v1.Kind() != reflect.Struct {
+ return false
+ }
+ return equalStruct(v1, v2)
+}
+
+// v1 and v2 are known to have the same type.
+func equalStruct(v1, v2 reflect.Value) bool {
+ sprop := GetProperties(v1.Type())
+ for i := 0; i < v1.NumField(); i++ {
+ f := v1.Type().Field(i)
+ if strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+ f1, f2 := v1.Field(i), v2.Field(i)
+ if f.Type.Kind() == reflect.Ptr {
+ if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
+ // both unset
+ continue
+ } else if n1 != n2 {
+ // set/unset mismatch
+ return false
+ }
+ f1, f2 = f1.Elem(), f2.Elem()
+ }
+ if !equalAny(f1, f2, sprop.Prop[i]) {
+ return false
+ }
+ }
+
+ if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() {
+ em2 := v2.FieldByName("XXX_InternalExtensions")
+ if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) {
+ return false
+ }
+ }
+
+ if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
+ em2 := v2.FieldByName("XXX_extensions")
+ if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
+ return false
+ }
+ }
+
+ uf := v1.FieldByName("XXX_unrecognized")
+ if !uf.IsValid() {
+ return true
+ }
+
+ u1 := uf.Bytes()
+ u2 := v2.FieldByName("XXX_unrecognized").Bytes()
+ return bytes.Equal(u1, u2)
+}
+
+// v1 and v2 are known to have the same type.
+// prop may be nil.
+func equalAny(v1, v2 reflect.Value, prop *Properties) bool {
+ if v1.Type() == protoMessageType {
+ m1, _ := v1.Interface().(Message)
+ m2, _ := v2.Interface().(Message)
+ return Equal(m1, m2)
+ }
+ switch v1.Kind() {
+ case reflect.Bool:
+ return v1.Bool() == v2.Bool()
+ case reflect.Float32, reflect.Float64:
+ return v1.Float() == v2.Float()
+ case reflect.Int32, reflect.Int64:
+ return v1.Int() == v2.Int()
+ case reflect.Interface:
+ // Probably a oneof field; compare the inner values.
+ n1, n2 := v1.IsNil(), v2.IsNil()
+ if n1 || n2 {
+ return n1 == n2
+ }
+ e1, e2 := v1.Elem(), v2.Elem()
+ if e1.Type() != e2.Type() {
+ return false
+ }
+ return equalAny(e1, e2, nil)
+ case reflect.Map:
+ if v1.Len() != v2.Len() {
+ return false
+ }
+ for _, key := range v1.MapKeys() {
+ val2 := v2.MapIndex(key)
+ if !val2.IsValid() {
+ // This key was not found in the second map.
+ return false
+ }
+ if !equalAny(v1.MapIndex(key), val2, nil) {
+ return false
+ }
+ }
+ return true
+ case reflect.Ptr:
+ // Maps may have nil values in them, so check for nil.
+ if v1.IsNil() && v2.IsNil() {
+ return true
+ }
+ if v1.IsNil() != v2.IsNil() {
+ return false
+ }
+ return equalAny(v1.Elem(), v2.Elem(), prop)
+ case reflect.Slice:
+ if v1.Type().Elem().Kind() == reflect.Uint8 {
+ // short circuit: []byte
+
+ // Edge case: if this is in a proto3 message, a zero length
+ // bytes field is considered the zero value.
+ if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 {
+ return true
+ }
+ if v1.IsNil() != v2.IsNil() {
+ return false
+ }
+ return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
+ }
+
+ if v1.Len() != v2.Len() {
+ return false
+ }
+ for i := 0; i < v1.Len(); i++ {
+ if !equalAny(v1.Index(i), v2.Index(i), prop) {
+ return false
+ }
+ }
+ return true
+ case reflect.String:
+ return v1.Interface().(string) == v2.Interface().(string)
+ case reflect.Struct:
+ return equalStruct(v1, v2)
+ case reflect.Uint32, reflect.Uint64:
+ return v1.Uint() == v2.Uint()
+ }
+
+ // unknown type, so not a protocol buffer
+ log.Printf("proto: don't know how to compare %v", v1)
+ return false
+}
+
+// base is the struct type that the extensions are based on.
+// x1 and x2 are InternalExtensions.
+func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool {
+ em1, _ := x1.extensionsRead()
+ em2, _ := x2.extensionsRead()
+ return equalExtMap(base, em1, em2)
+}
+
+func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool {
+ if len(em1) != len(em2) {
+ return false
+ }
+
+ for extNum, e1 := range em1 {
+ e2, ok := em2[extNum]
+ if !ok {
+ return false
+ }
+
+ m1, m2 := e1.value, e2.value
+
+ if m1 == nil && m2 == nil {
+ // Both have only encoded form.
+ if bytes.Equal(e1.enc, e2.enc) {
+ continue
+ }
+ // The bytes are different, but the extensions might still be
+ // equal. We need to decode them to compare.
+ }
+
+ if m1 != nil && m2 != nil {
+ // Both are unencoded.
+ if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
+ return false
+ }
+ continue
+ }
+
+ // At least one is encoded. To do a semantically correct comparison
+ // we need to unmarshal them first.
+ var desc *ExtensionDesc
+ if m := extensionMaps[base]; m != nil {
+ desc = m[extNum]
+ }
+ if desc == nil {
+ // If both have only encoded form and the bytes are the same,
+ // it is handled above. We get here when the bytes are different.
+ // We don't know how to decode it, so just compare them as byte
+ // slices.
+ log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
+ return false
+ }
+ var err error
+ if m1 == nil {
+ m1, err = decodeExtension(e1.enc, desc)
+ }
+ if m2 == nil && err == nil {
+ m2, err = decodeExtension(e2.enc, desc)
+ }
+ if err != nil {
+ // The encoded form is invalid.
+ log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
+ return false
+ }
+ if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
+ return false
+ }
+ }
+
+ return true
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/extensions.go b/vendor/github.com/gogo/protobuf/proto/extensions.go
@@ -0,0 +1,605 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Types and routines for supporting protocol buffer extensions.
+ */
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "reflect"
+ "strconv"
+ "sync"
+)
+
+// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
+var ErrMissingExtension = errors.New("proto: missing extension")
+
+// ExtensionRange represents a range of message extensions for a protocol buffer.
+// Used in code generated by the protocol compiler.
+type ExtensionRange struct {
+ Start, End int32 // both inclusive
+}
+
+// extendableProto is an interface implemented by any protocol buffer generated by the current
+// proto compiler that may be extended.
+type extendableProto interface {
+ Message
+ ExtensionRangeArray() []ExtensionRange
+ extensionsWrite() map[int32]Extension
+ extensionsRead() (map[int32]Extension, sync.Locker)
+}
+
+// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous
+// version of the proto compiler that may be extended.
+type extendableProtoV1 interface {
+ Message
+ ExtensionRangeArray() []ExtensionRange
+ ExtensionMap() map[int32]Extension
+}
+
+// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto.
+type extensionAdapter struct {
+ extendableProtoV1
+}
+
+func (e extensionAdapter) extensionsWrite() map[int32]Extension {
+ return e.ExtensionMap()
+}
+
+func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) {
+ return e.ExtensionMap(), notLocker{}
+}
+
+// notLocker is a sync.Locker whose Lock and Unlock methods are nops.
+type notLocker struct{}
+
+func (n notLocker) Lock() {}
+func (n notLocker) Unlock() {}
+
+// extendable returns the extendableProto interface for the given generated proto message.
+// If the proto message has the old extension format, it returns a wrapper that implements
+// the extendableProto interface.
+func extendable(p interface{}) (extendableProto, error) {
+ switch p := p.(type) {
+ case extendableProto:
+ if isNilPtr(p) {
+ return nil, fmt.Errorf("proto: nil %T is not extendable", p)
+ }
+ return p, nil
+ case extendableProtoV1:
+ if isNilPtr(p) {
+ return nil, fmt.Errorf("proto: nil %T is not extendable", p)
+ }
+ return extensionAdapter{p}, nil
+ case extensionsBytes:
+ return slowExtensionAdapter{p}, nil
+ }
+ // Don't allocate a specific error containing %T:
+ // this is the hot path for Clone and MarshalText.
+ return nil, errNotExtendable
+}
+
+var errNotExtendable = errors.New("proto: not an extendable proto.Message")
+
+func isNilPtr(x interface{}) bool {
+ v := reflect.ValueOf(x)
+ return v.Kind() == reflect.Ptr && v.IsNil()
+}
+
+// XXX_InternalExtensions is an internal representation of proto extensions.
+//
+// Each generated message struct type embeds an anonymous XXX_InternalExtensions field,
+// thus gaining the unexported 'extensions' method, which can be called only from the proto package.
+//
+// The methods of XXX_InternalExtensions are not concurrency safe in general,
+// but calls to logically read-only methods such as has and get may be executed concurrently.
+type XXX_InternalExtensions struct {
+ // The struct must be indirect so that if a user inadvertently copies a
+ // generated message and its embedded XXX_InternalExtensions, they
+ // avoid the mayhem of a copied mutex.
+ //
+ // The mutex serializes all logically read-only operations to p.extensionMap.
+ // It is up to the client to ensure that write operations to p.extensionMap are
+ // mutually exclusive with other accesses.
+ p *struct {
+ mu sync.Mutex
+ extensionMap map[int32]Extension
+ }
+}
+
+// extensionsWrite returns the extension map, creating it on first use.
+func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension {
+ if e.p == nil {
+ e.p = new(struct {
+ mu sync.Mutex
+ extensionMap map[int32]Extension
+ })
+ e.p.extensionMap = make(map[int32]Extension)
+ }
+ return e.p.extensionMap
+}
+
+// extensionsRead returns the extensions map for read-only use. It may be nil.
+// The caller must hold the returned mutex's lock when accessing Elements within the map.
+func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) {
+ if e.p == nil {
+ return nil, nil
+ }
+ return e.p.extensionMap, &e.p.mu
+}
+
+// ExtensionDesc represents an extension specification.
+// Used in generated code from the protocol compiler.
+type ExtensionDesc struct {
+ ExtendedType Message // nil pointer to the type that is being extended
+ ExtensionType interface{} // nil pointer to the extension type
+ Field int32 // field number
+ Name string // fully-qualified name of extension, for text formatting
+ Tag string // protobuf tag style
+ Filename string // name of the file in which the extension is defined
+}
+
+func (ed *ExtensionDesc) repeated() bool {
+ t := reflect.TypeOf(ed.ExtensionType)
+ return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
+}
+
+// Extension represents an extension in a message.
+type Extension struct {
+ // When an extension is stored in a message using SetExtension
+ // only desc and value are set. When the message is marshaled
+ // enc will be set to the encoded form of the message.
+ //
+ // When a message is unmarshaled and contains extensions, each
+ // extension will have only enc set. When such an extension is
+ // accessed using GetExtension (or GetExtensions) desc and value
+ // will be set.
+ desc *ExtensionDesc
+ value interface{}
+ enc []byte
+}
+
+// SetRawExtension is for testing only.
+func SetRawExtension(base Message, id int32, b []byte) {
+ if ebase, ok := base.(extensionsBytes); ok {
+ clearExtension(base, id)
+ ext := ebase.GetExtensions()
+ *ext = append(*ext, b...)
+ return
+ }
+ epb, err := extendable(base)
+ if err != nil {
+ return
+ }
+ extmap := epb.extensionsWrite()
+ extmap[id] = Extension{enc: b}
+}
+
+// isExtensionField returns true iff the given field number is in an extension range.
+func isExtensionField(pb extendableProto, field int32) bool {
+ for _, er := range pb.ExtensionRangeArray() {
+ if er.Start <= field && field <= er.End {
+ return true
+ }
+ }
+ return false
+}
+
+// checkExtensionTypes checks that the given extension is valid for pb.
+func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
+ var pbi interface{} = pb
+ // Check the extended type.
+ if ea, ok := pbi.(extensionAdapter); ok {
+ pbi = ea.extendableProtoV1
+ }
+ if ea, ok := pbi.(slowExtensionAdapter); ok {
+ pbi = ea.extensionsBytes
+ }
+ if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b {
+ return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a)
+ }
+ // Check the range.
+ if !isExtensionField(pb, extension.Field) {
+ return errors.New("proto: bad extension number; not in declared ranges")
+ }
+ return nil
+}
+
+// extPropKey is sufficient to uniquely identify an extension.
+type extPropKey struct {
+ base reflect.Type
+ field int32
+}
+
+var extProp = struct {
+ sync.RWMutex
+ m map[extPropKey]*Properties
+}{
+ m: make(map[extPropKey]*Properties),
+}
+
+func extensionProperties(ed *ExtensionDesc) *Properties {
+ key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
+
+ extProp.RLock()
+ if prop, ok := extProp.m[key]; ok {
+ extProp.RUnlock()
+ return prop
+ }
+ extProp.RUnlock()
+
+ extProp.Lock()
+ defer extProp.Unlock()
+ // Check again.
+ if prop, ok := extProp.m[key]; ok {
+ return prop
+ }
+
+ prop := new(Properties)
+ prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
+ extProp.m[key] = prop
+ return prop
+}
+
+// HasExtension returns whether the given extension is present in pb.
+func HasExtension(pb Message, extension *ExtensionDesc) bool {
+ if epb, doki := pb.(extensionsBytes); doki {
+ ext := epb.GetExtensions()
+ buf := *ext
+ o := 0
+ for o < len(buf) {
+ tag, n := DecodeVarint(buf[o:])
+ fieldNum := int32(tag >> 3)
+ if int32(fieldNum) == extension.Field {
+ return true
+ }
+ wireType := int(tag & 0x7)
+ o += n
+ l, err := size(buf[o:], wireType)
+ if err != nil {
+ return false
+ }
+ o += l
+ }
+ return false
+ }
+ // TODO: Check types, field numbers, etc.?
+ epb, err := extendable(pb)
+ if err != nil {
+ return false
+ }
+ extmap, mu := epb.extensionsRead()
+ if extmap == nil {
+ return false
+ }
+ mu.Lock()
+ _, ok := extmap[extension.Field]
+ mu.Unlock()
+ return ok
+}
+
+// ClearExtension removes the given extension from pb.
+func ClearExtension(pb Message, extension *ExtensionDesc) {
+ clearExtension(pb, extension.Field)
+}
+
+func clearExtension(pb Message, fieldNum int32) {
+ if epb, ok := pb.(extensionsBytes); ok {
+ offset := 0
+ for offset != -1 {
+ offset = deleteExtension(epb, fieldNum, offset)
+ }
+ return
+ }
+ epb, err := extendable(pb)
+ if err != nil {
+ return
+ }
+ // TODO: Check types, field numbers, etc.?
+ extmap := epb.extensionsWrite()
+ delete(extmap, fieldNum)
+}
+
+// GetExtension retrieves a proto2 extended field from pb.
+//
+// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil),
+// then GetExtension parses the encoded field and returns a Go value of the specified type.
+// If the field is not present, then the default value is returned (if one is specified),
+// otherwise ErrMissingExtension is reported.
+//
+// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil),
+// then GetExtension returns the raw encoded bytes of the field extension.
+func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) {
+ if epb, doki := pb.(extensionsBytes); doki {
+ ext := epb.GetExtensions()
+ return decodeExtensionFromBytes(extension, *ext)
+ }
+
+ epb, err := extendable(pb)
+ if err != nil {
+ return nil, err
+ }
+
+ if extension.ExtendedType != nil {
+ // can only check type if this is a complete descriptor
+ if cerr := checkExtensionTypes(epb, extension); cerr != nil {
+ return nil, cerr
+ }
+ }
+
+ emap, mu := epb.extensionsRead()
+ if emap == nil {
+ return defaultExtensionValue(extension)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ e, ok := emap[extension.Field]
+ if !ok {
+ // defaultExtensionValue returns the default value or
+ // ErrMissingExtension if there is no default.
+ return defaultExtensionValue(extension)
+ }
+
+ if e.value != nil {
+ // Already decoded. Check the descriptor, though.
+ if e.desc != extension {
+ // This shouldn't happen. If it does, it means that
+ // GetExtension was called twice with two different
+ // descriptors with the same field number.
+ return nil, errors.New("proto: descriptor conflict")
+ }
+ return e.value, nil
+ }
+
+ if extension.ExtensionType == nil {
+ // incomplete descriptor
+ return e.enc, nil
+ }
+
+ v, err := decodeExtension(e.enc, extension)
+ if err != nil {
+ return nil, err
+ }
+
+ // Remember the decoded version and drop the encoded version.
+ // That way it is safe to mutate what we return.
+ e.value = v
+ e.desc = extension
+ e.enc = nil
+ emap[extension.Field] = e
+ return e.value, nil
+}
+
+// defaultExtensionValue returns the default value for extension.
+// If no default for an extension is defined ErrMissingExtension is returned.
+func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) {
+ if extension.ExtensionType == nil {
+ // incomplete descriptor, so no default
+ return nil, ErrMissingExtension
+ }
+
+ t := reflect.TypeOf(extension.ExtensionType)
+ props := extensionProperties(extension)
+
+ sf, _, err := fieldDefault(t, props)
+ if err != nil {
+ return nil, err
+ }
+
+ if sf == nil || sf.value == nil {
+ // There is no default value.
+ return nil, ErrMissingExtension
+ }
+
+ if t.Kind() != reflect.Ptr {
+ // We do not need to return a Ptr, we can directly return sf.value.
+ return sf.value, nil
+ }
+
+ // We need to return an interface{} that is a pointer to sf.value.
+ value := reflect.New(t).Elem()
+ value.Set(reflect.New(value.Type().Elem()))
+ if sf.kind == reflect.Int32 {
+ // We may have an int32 or an enum, but the underlying data is int32.
+ // Since we can't set an int32 into a non int32 reflect.value directly
+ // set it as a int32.
+ value.Elem().SetInt(int64(sf.value.(int32)))
+ } else {
+ value.Elem().Set(reflect.ValueOf(sf.value))
+ }
+ return value.Interface(), nil
+}
+
+// decodeExtension decodes an extension encoded in b.
+func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
+ t := reflect.TypeOf(extension.ExtensionType)
+ unmarshal := typeUnmarshaler(t, extension.Tag)
+
+ // t is a pointer to a struct, pointer to basic type or a slice.
+ // Allocate space to store the pointer/slice.
+ value := reflect.New(t).Elem()
+
+ var err error
+ for {
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ wire := int(x) & 7
+
+ b, err = unmarshal(b, valToPointer(value.Addr()), wire)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(b) == 0 {
+ break
+ }
+ }
+ return value.Interface(), nil
+}
+
+// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
+// The returned slice has the same length as es; missing extensions will appear as nil elements.
+func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
+ epb, err := extendable(pb)
+ if err != nil {
+ return nil, err
+ }
+ extensions = make([]interface{}, len(es))
+ for i, e := range es {
+ extensions[i], err = GetExtension(epb, e)
+ if err == ErrMissingExtension {
+ err = nil
+ }
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
+// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
+// just the Field field, which defines the extension's field number.
+func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
+ epb, err := extendable(pb)
+ if err != nil {
+ return nil, err
+ }
+ registeredExtensions := RegisteredExtensions(pb)
+
+ emap, mu := epb.extensionsRead()
+ if emap == nil {
+ return nil, nil
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ extensions := make([]*ExtensionDesc, 0, len(emap))
+ for extid, e := range emap {
+ desc := e.desc
+ if desc == nil {
+ desc = registeredExtensions[extid]
+ if desc == nil {
+ desc = &ExtensionDesc{Field: extid}
+ }
+ }
+
+ extensions = append(extensions, desc)
+ }
+ return extensions, nil
+}
+
+// SetExtension sets the specified extension of pb to the specified value.
+func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
+ if epb, ok := pb.(extensionsBytes); ok {
+ ClearExtension(pb, extension)
+ newb, err := encodeExtension(extension, value)
+ if err != nil {
+ return err
+ }
+ bb := epb.GetExtensions()
+ *bb = append(*bb, newb...)
+ return nil
+ }
+ epb, err := extendable(pb)
+ if err != nil {
+ return err
+ }
+ if err := checkExtensionTypes(epb, extension); err != nil {
+ return err
+ }
+ typ := reflect.TypeOf(extension.ExtensionType)
+ if typ != reflect.TypeOf(value) {
+ return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", value, extension.ExtensionType)
+ }
+ // nil extension values need to be caught early, because the
+ // encoder can't distinguish an ErrNil due to a nil extension
+ // from an ErrNil due to a missing field. Extensions are
+ // always optional, so the encoder would just swallow the error
+ // and drop all the extensions from the encoded message.
+ if reflect.ValueOf(value).IsNil() {
+ return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
+ }
+
+ extmap := epb.extensionsWrite()
+ extmap[extension.Field] = Extension{desc: extension, value: value}
+ return nil
+}
+
+// ClearAllExtensions clears all extensions from pb.
+func ClearAllExtensions(pb Message) {
+ if epb, doki := pb.(extensionsBytes); doki {
+ ext := epb.GetExtensions()
+ *ext = []byte{}
+ return
+ }
+ epb, err := extendable(pb)
+ if err != nil {
+ return
+ }
+ m := epb.extensionsWrite()
+ for k := range m {
+ delete(m, k)
+ }
+}
+
+// A global registry of extensions.
+// The generated code will register the generated descriptors by calling RegisterExtension.
+
+var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
+
+// RegisterExtension is called from the generated code.
+func RegisterExtension(desc *ExtensionDesc) {
+ st := reflect.TypeOf(desc.ExtendedType).Elem()
+ m := extensionMaps[st]
+ if m == nil {
+ m = make(map[int32]*ExtensionDesc)
+ extensionMaps[st] = m
+ }
+ if _, ok := m[desc.Field]; ok {
+ panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
+ }
+ m[desc.Field] = desc
+}
+
+// RegisteredExtensions returns a map of the registered extensions of a
+// protocol buffer struct, indexed by the extension number.
+// The argument pb should be a nil pointer to the struct type.
+func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
+ return extensionMaps[reflect.TypeOf(pb).Elem()]
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go b/vendor/github.com/gogo/protobuf/proto/extensions_gogo.go
@@ -0,0 +1,389 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+)
+
+type extensionsBytes interface {
+ Message
+ ExtensionRangeArray() []ExtensionRange
+ GetExtensions() *[]byte
+}
+
+type slowExtensionAdapter struct {
+ extensionsBytes
+}
+
+func (s slowExtensionAdapter) extensionsWrite() map[int32]Extension {
+ panic("Please report a bug to github.com/gogo/protobuf if you see this message: Writing extensions is not supported for extensions stored in a byte slice field.")
+}
+
+func (s slowExtensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) {
+ b := s.GetExtensions()
+ m, err := BytesToExtensionsMap(*b)
+ if err != nil {
+ panic(err)
+ }
+ return m, notLocker{}
+}
+
+func GetBoolExtension(pb Message, extension *ExtensionDesc, ifnotset bool) bool {
+ if reflect.ValueOf(pb).IsNil() {
+ return ifnotset
+ }
+ value, err := GetExtension(pb, extension)
+ if err != nil {
+ return ifnotset
+ }
+ if value == nil {
+ return ifnotset
+ }
+ if value.(*bool) == nil {
+ return ifnotset
+ }
+ return *(value.(*bool))
+}
+
+func (this *Extension) Equal(that *Extension) bool {
+ if err := this.Encode(); err != nil {
+ return false
+ }
+ if err := that.Encode(); err != nil {
+ return false
+ }
+ return bytes.Equal(this.enc, that.enc)
+}
+
+func (this *Extension) Compare(that *Extension) int {
+ if err := this.Encode(); err != nil {
+ return 1
+ }
+ if err := that.Encode(); err != nil {
+ return -1
+ }
+ return bytes.Compare(this.enc, that.enc)
+}
+
+func SizeOfInternalExtension(m extendableProto) (n int) {
+ info := getMarshalInfo(reflect.TypeOf(m))
+ return info.sizeV1Extensions(m.extensionsWrite())
+}
+
+type sortableMapElem struct {
+ field int32
+ ext Extension
+}
+
+func newSortableExtensionsFromMap(m map[int32]Extension) sortableExtensions {
+ s := make(sortableExtensions, 0, len(m))
+ for k, v := range m {
+ s = append(s, &sortableMapElem{field: k, ext: v})
+ }
+ return s
+}
+
+type sortableExtensions []*sortableMapElem
+
+func (this sortableExtensions) Len() int { return len(this) }
+
+func (this sortableExtensions) Swap(i, j int) { this[i], this[j] = this[j], this[i] }
+
+func (this sortableExtensions) Less(i, j int) bool { return this[i].field < this[j].field }
+
+func (this sortableExtensions) String() string {
+ sort.Sort(this)
+ ss := make([]string, len(this))
+ for i := range this {
+ ss[i] = fmt.Sprintf("%d: %v", this[i].field, this[i].ext)
+ }
+ return "map[" + strings.Join(ss, ",") + "]"
+}
+
+func StringFromInternalExtension(m extendableProto) string {
+ return StringFromExtensionsMap(m.extensionsWrite())
+}
+
+func StringFromExtensionsMap(m map[int32]Extension) string {
+ return newSortableExtensionsFromMap(m).String()
+}
+
+func StringFromExtensionsBytes(ext []byte) string {
+ m, err := BytesToExtensionsMap(ext)
+ if err != nil {
+ panic(err)
+ }
+ return StringFromExtensionsMap(m)
+}
+
+func EncodeInternalExtension(m extendableProto, data []byte) (n int, err error) {
+ return EncodeExtensionMap(m.extensionsWrite(), data)
+}
+
+func EncodeInternalExtensionBackwards(m extendableProto, data []byte) (n int, err error) {
+ return EncodeExtensionMapBackwards(m.extensionsWrite(), data)
+}
+
+func EncodeExtensionMap(m map[int32]Extension, data []byte) (n int, err error) {
+ o := 0
+ for _, e := range m {
+ if err := e.Encode(); err != nil {
+ return 0, err
+ }
+ n := copy(data[o:], e.enc)
+ if n != len(e.enc) {
+ return 0, io.ErrShortBuffer
+ }
+ o += n
+ }
+ return o, nil
+}
+
+func EncodeExtensionMapBackwards(m map[int32]Extension, data []byte) (n int, err error) {
+ o := 0
+ end := len(data)
+ for _, e := range m {
+ if err := e.Encode(); err != nil {
+ return 0, err
+ }
+ n := copy(data[end-len(e.enc):], e.enc)
+ if n != len(e.enc) {
+ return 0, io.ErrShortBuffer
+ }
+ end -= n
+ o += n
+ }
+ return o, nil
+}
+
+func GetRawExtension(m map[int32]Extension, id int32) ([]byte, error) {
+ e := m[id]
+ if err := e.Encode(); err != nil {
+ return nil, err
+ }
+ return e.enc, nil
+}
+
+func size(buf []byte, wire int) (int, error) {
+ switch wire {
+ case WireVarint:
+ _, n := DecodeVarint(buf)
+ return n, nil
+ case WireFixed64:
+ return 8, nil
+ case WireBytes:
+ v, n := DecodeVarint(buf)
+ return int(v) + n, nil
+ case WireFixed32:
+ return 4, nil
+ case WireStartGroup:
+ offset := 0
+ for {
+ u, n := DecodeVarint(buf[offset:])
+ fwire := int(u & 0x7)
+ offset += n
+ if fwire == WireEndGroup {
+ return offset, nil
+ }
+ s, err := size(buf[offset:], wire)
+ if err != nil {
+ return 0, err
+ }
+ offset += s
+ }
+ }
+ return 0, fmt.Errorf("proto: can't get size for unknown wire type %d", wire)
+}
+
+func BytesToExtensionsMap(buf []byte) (map[int32]Extension, error) {
+ m := make(map[int32]Extension)
+ i := 0
+ for i < len(buf) {
+ tag, n := DecodeVarint(buf[i:])
+ if n <= 0 {
+ return nil, fmt.Errorf("unable to decode varint")
+ }
+ fieldNum := int32(tag >> 3)
+ wireType := int(tag & 0x7)
+ l, err := size(buf[i+n:], wireType)
+ if err != nil {
+ return nil, err
+ }
+ end := i + int(l) + n
+ m[int32(fieldNum)] = Extension{enc: buf[i:end]}
+ i = end
+ }
+ return m, nil
+}
+
+func NewExtension(e []byte) Extension {
+ ee := Extension{enc: make([]byte, len(e))}
+ copy(ee.enc, e)
+ return ee
+}
+
+func AppendExtension(e Message, tag int32, buf []byte) {
+ if ee, eok := e.(extensionsBytes); eok {
+ ext := ee.GetExtensions()
+ *ext = append(*ext, buf...)
+ return
+ }
+ if ee, eok := e.(extendableProto); eok {
+ m := ee.extensionsWrite()
+ ext := m[int32(tag)] // may be missing
+ ext.enc = append(ext.enc, buf...)
+ m[int32(tag)] = ext
+ }
+}
+
+func encodeExtension(extension *ExtensionDesc, value interface{}) ([]byte, error) {
+ u := getMarshalInfo(reflect.TypeOf(extension.ExtendedType))
+ ei := u.getExtElemInfo(extension)
+ v := value
+ p := toAddrPointer(&v, ei.isptr)
+ siz := ei.sizer(p, SizeVarint(ei.wiretag))
+ buf := make([]byte, 0, siz)
+ return ei.marshaler(buf, p, ei.wiretag, false)
+}
+
+func decodeExtensionFromBytes(extension *ExtensionDesc, buf []byte) (interface{}, error) {
+ o := 0
+ for o < len(buf) {
+ tag, n := DecodeVarint((buf)[o:])
+ fieldNum := int32(tag >> 3)
+ wireType := int(tag & 0x7)
+ if o+n > len(buf) {
+ return nil, fmt.Errorf("unable to decode extension")
+ }
+ l, err := size((buf)[o+n:], wireType)
+ if err != nil {
+ return nil, err
+ }
+ if int32(fieldNum) == extension.Field {
+ if o+n+l > len(buf) {
+ return nil, fmt.Errorf("unable to decode extension")
+ }
+ v, err := decodeExtension((buf)[o:o+n+l], extension)
+ if err != nil {
+ return nil, err
+ }
+ return v, nil
+ }
+ o += n + l
+ }
+ return defaultExtensionValue(extension)
+}
+
+func (this *Extension) Encode() error {
+ if this.enc == nil {
+ var err error
+ this.enc, err = encodeExtension(this.desc, this.value)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (this Extension) GoString() string {
+ if err := this.Encode(); err != nil {
+ return fmt.Sprintf("error encoding extension: %v", err)
+ }
+ return fmt.Sprintf("proto.NewExtension(%#v)", this.enc)
+}
+
+func SetUnsafeExtension(pb Message, fieldNum int32, value interface{}) error {
+ typ := reflect.TypeOf(pb).Elem()
+ ext, ok := extensionMaps[typ]
+ if !ok {
+ return fmt.Errorf("proto: bad extended type; %s is not extendable", typ.String())
+ }
+ desc, ok := ext[fieldNum]
+ if !ok {
+ return errors.New("proto: bad extension number; not in declared ranges")
+ }
+ return SetExtension(pb, desc, value)
+}
+
+func GetUnsafeExtension(pb Message, fieldNum int32) (interface{}, error) {
+ typ := reflect.TypeOf(pb).Elem()
+ ext, ok := extensionMaps[typ]
+ if !ok {
+ return nil, fmt.Errorf("proto: bad extended type; %s is not extendable", typ.String())
+ }
+ desc, ok := ext[fieldNum]
+ if !ok {
+ return nil, fmt.Errorf("unregistered field number %d", fieldNum)
+ }
+ return GetExtension(pb, desc)
+}
+
+func NewUnsafeXXX_InternalExtensions(m map[int32]Extension) XXX_InternalExtensions {
+ x := &XXX_InternalExtensions{
+ p: new(struct {
+ mu sync.Mutex
+ extensionMap map[int32]Extension
+ }),
+ }
+ x.p.extensionMap = m
+ return *x
+}
+
+func GetUnsafeExtensionsMap(extendable Message) map[int32]Extension {
+ pb := extendable.(extendableProto)
+ return pb.extensionsWrite()
+}
+
+func deleteExtension(pb extensionsBytes, theFieldNum int32, offset int) int {
+ ext := pb.GetExtensions()
+ for offset < len(*ext) {
+ tag, n1 := DecodeVarint((*ext)[offset:])
+ fieldNum := int32(tag >> 3)
+ wireType := int(tag & 0x7)
+ n2, err := size((*ext)[offset+n1:], wireType)
+ if err != nil {
+ panic(err)
+ }
+ newOffset := offset + n1 + n2
+ if fieldNum == theFieldNum {
+ *ext = append((*ext)[:offset], (*ext)[newOffset:]...)
+ return offset
+ }
+ offset = newOffset
+ }
+ return -1
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/lib.go b/vendor/github.com/gogo/protobuf/proto/lib.go
@@ -0,0 +1,973 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+/*
+Package proto converts data structures to and from the wire format of
+protocol buffers. It works in concert with the Go source code generated
+for .proto files by the protocol compiler.
+
+A summary of the properties of the protocol buffer interface
+for a protocol buffer variable v:
+
+ - Names are turned from camel_case to CamelCase for export.
+ - There are no methods on v to set fields; just treat
+ them as structure fields.
+ - There are getters that return a field's value if set,
+ and return the field's default value if unset.
+ The getters work even if the receiver is a nil message.
+ - The zero value for a struct is its correct initialization state.
+ All desired fields must be set before marshaling.
+ - A Reset() method will restore a protobuf struct to its zero state.
+ - Non-repeated fields are pointers to the values; nil means unset.
+ That is, optional or required field int32 f becomes F *int32.
+ - Repeated fields are slices.
+ - Helper functions are available to aid the setting of fields.
+ msg.Foo = proto.String("hello") // set field
+ - Constants are defined to hold the default values of all fields that
+ have them. They have the form Default_StructName_FieldName.
+ Because the getter methods handle defaulted values,
+ direct use of these constants should be rare.
+ - Enums are given type names and maps from names to values.
+ Enum values are prefixed by the enclosing message's name, or by the
+ enum's type name if it is a top-level enum. Enum types have a String
+ method, and a Enum method to assist in message construction.
+ - Nested messages, groups and enums have type names prefixed with the name of
+ the surrounding message type.
+ - Extensions are given descriptor names that start with E_,
+ followed by an underscore-delimited list of the nested messages
+ that contain it (if any) followed by the CamelCased name of the
+ extension field itself. HasExtension, ClearExtension, GetExtension
+ and SetExtension are functions for manipulating extensions.
+ - Oneof field sets are given a single field in their message,
+ with distinguished wrapper types for each possible field value.
+ - Marshal and Unmarshal are functions to encode and decode the wire format.
+
+When the .proto file specifies `syntax="proto3"`, there are some differences:
+
+ - Non-repeated fields of non-message type are values instead of pointers.
+ - Enum types do not get an Enum method.
+
+The simplest way to describe this is to see an example.
+Given file test.proto, containing
+
+ package example;
+
+ enum FOO { X = 17; }
+
+ message Test {
+ required string label = 1;
+ optional int32 type = 2 [default=77];
+ repeated int64 reps = 3;
+ optional group OptionalGroup = 4 {
+ required string RequiredField = 5;
+ }
+ oneof union {
+ int32 number = 6;
+ string name = 7;
+ }
+ }
+
+The resulting file, test.pb.go, is:
+
+ package example
+
+ import proto "github.com/gogo/protobuf/proto"
+ import math "math"
+
+ type FOO int32
+ const (
+ FOO_X FOO = 17
+ )
+ var FOO_name = map[int32]string{
+ 17: "X",
+ }
+ var FOO_value = map[string]int32{
+ "X": 17,
+ }
+
+ func (x FOO) Enum() *FOO {
+ p := new(FOO)
+ *p = x
+ return p
+ }
+ func (x FOO) String() string {
+ return proto.EnumName(FOO_name, int32(x))
+ }
+ func (x *FOO) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FOO_value, data)
+ if err != nil {
+ return err
+ }
+ *x = FOO(value)
+ return nil
+ }
+
+ type Test struct {
+ Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
+ Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
+ Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
+ Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
+ // Types that are valid to be assigned to Union:
+ // *Test_Number
+ // *Test_Name
+ Union isTest_Union `protobuf_oneof:"union"`
+ XXX_unrecognized []byte `json:"-"`
+ }
+ func (m *Test) Reset() { *m = Test{} }
+ func (m *Test) String() string { return proto.CompactTextString(m) }
+ func (*Test) ProtoMessage() {}
+
+ type isTest_Union interface {
+ isTest_Union()
+ }
+
+ type Test_Number struct {
+ Number int32 `protobuf:"varint,6,opt,name=number"`
+ }
+ type Test_Name struct {
+ Name string `protobuf:"bytes,7,opt,name=name"`
+ }
+
+ func (*Test_Number) isTest_Union() {}
+ func (*Test_Name) isTest_Union() {}
+
+ func (m *Test) GetUnion() isTest_Union {
+ if m != nil {
+ return m.Union
+ }
+ return nil
+ }
+ const Default_Test_Type int32 = 77
+
+ func (m *Test) GetLabel() string {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return ""
+ }
+
+ func (m *Test) GetType() int32 {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return Default_Test_Type
+ }
+
+ func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
+ if m != nil {
+ return m.Optionalgroup
+ }
+ return nil
+ }
+
+ type Test_OptionalGroup struct {
+ RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
+ }
+ func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
+ func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
+
+ func (m *Test_OptionalGroup) GetRequiredField() string {
+ if m != nil && m.RequiredField != nil {
+ return *m.RequiredField
+ }
+ return ""
+ }
+
+ func (m *Test) GetNumber() int32 {
+ if x, ok := m.GetUnion().(*Test_Number); ok {
+ return x.Number
+ }
+ return 0
+ }
+
+ func (m *Test) GetName() string {
+ if x, ok := m.GetUnion().(*Test_Name); ok {
+ return x.Name
+ }
+ return ""
+ }
+
+ func init() {
+ proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
+ }
+
+To create and play with a Test object:
+
+ package main
+
+ import (
+ "log"
+
+ "github.com/gogo/protobuf/proto"
+ pb "./example.pb"
+ )
+
+ func main() {
+ test := &pb.Test{
+ Label: proto.String("hello"),
+ Type: proto.Int32(17),
+ Reps: []int64{1, 2, 3},
+ Optionalgroup: &pb.Test_OptionalGroup{
+ RequiredField: proto.String("good bye"),
+ },
+ Union: &pb.Test_Name{"fred"},
+ }
+ data, err := proto.Marshal(test)
+ if err != nil {
+ log.Fatal("marshaling error: ", err)
+ }
+ newTest := &pb.Test{}
+ err = proto.Unmarshal(data, newTest)
+ if err != nil {
+ log.Fatal("unmarshaling error: ", err)
+ }
+ // Now test and newTest contain the same data.
+ if test.GetLabel() != newTest.GetLabel() {
+ log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
+ }
+ // Use a type switch to determine which oneof was set.
+ switch u := test.Union.(type) {
+ case *pb.Test_Number: // u.Number contains the number.
+ case *pb.Test_Name: // u.Name contains the string.
+ }
+ // etc.
+ }
+*/
+package proto
+
+import (
+ "encoding/json"
+ "fmt"
+ "log"
+ "reflect"
+ "sort"
+ "strconv"
+ "sync"
+)
+
+// RequiredNotSetError is an error type returned by either Marshal or Unmarshal.
+// Marshal reports this when a required field is not initialized.
+// Unmarshal reports this when a required field is missing from the wire data.
+type RequiredNotSetError struct{ field string }
+
+func (e *RequiredNotSetError) Error() string {
+ if e.field == "" {
+ return fmt.Sprintf("proto: required field not set")
+ }
+ return fmt.Sprintf("proto: required field %q not set", e.field)
+}
+func (e *RequiredNotSetError) RequiredNotSet() bool {
+ return true
+}
+
+type invalidUTF8Error struct{ field string }
+
+func (e *invalidUTF8Error) Error() string {
+ if e.field == "" {
+ return "proto: invalid UTF-8 detected"
+ }
+ return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field)
+}
+func (e *invalidUTF8Error) InvalidUTF8() bool {
+ return true
+}
+
+// errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8.
+// This error should not be exposed to the external API as such errors should
+// be recreated with the field information.
+var errInvalidUTF8 = &invalidUTF8Error{}
+
+// isNonFatal reports whether the error is either a RequiredNotSet error
+// or a InvalidUTF8 error.
+func isNonFatal(err error) bool {
+ if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() {
+ return true
+ }
+ if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() {
+ return true
+ }
+ return false
+}
+
+type nonFatal struct{ E error }
+
+// Merge merges err into nf and reports whether it was successful.
+// Otherwise it returns false for any fatal non-nil errors.
+func (nf *nonFatal) Merge(err error) (ok bool) {
+ if err == nil {
+ return true // not an error
+ }
+ if !isNonFatal(err) {
+ return false // fatal error
+ }
+ if nf.E == nil {
+ nf.E = err // store first instance of non-fatal error
+ }
+ return true
+}
+
+// Message is implemented by generated protocol buffer messages.
+type Message interface {
+ Reset()
+ String() string
+ ProtoMessage()
+}
+
+// A Buffer is a buffer manager for marshaling and unmarshaling
+// protocol buffers. It may be reused between invocations to
+// reduce memory usage. It is not necessary to use a Buffer;
+// the global functions Marshal and Unmarshal create a
+// temporary Buffer and are fine for most applications.
+type Buffer struct {
+ buf []byte // encode/decode byte stream
+ index int // read point
+
+ deterministic bool
+}
+
+// NewBuffer allocates a new Buffer and initializes its internal data to
+// the contents of the argument slice.
+func NewBuffer(e []byte) *Buffer {
+ return &Buffer{buf: e}
+}
+
+// Reset resets the Buffer, ready for marshaling a new protocol buffer.
+func (p *Buffer) Reset() {
+ p.buf = p.buf[0:0] // for reading/writing
+ p.index = 0 // for reading
+}
+
+// SetBuf replaces the internal buffer with the slice,
+// ready for unmarshaling the contents of the slice.
+func (p *Buffer) SetBuf(s []byte) {
+ p.buf = s
+ p.index = 0
+}
+
+// Bytes returns the contents of the Buffer.
+func (p *Buffer) Bytes() []byte { return p.buf }
+
+// SetDeterministic sets whether to use deterministic serialization.
+//
+// Deterministic serialization guarantees that for a given binary, equal
+// messages will always be serialized to the same bytes. This implies:
+//
+// - Repeated serialization of a message will return the same bytes.
+// - Different processes of the same binary (which may be executing on
+// different machines) will serialize equal messages to the same bytes.
+//
+// Note that the deterministic serialization is NOT canonical across
+// languages. It is not guaranteed to remain stable over time. It is unstable
+// across different builds with schema changes due to unknown fields.
+// Users who need canonical serialization (e.g., persistent storage in a
+// canonical form, fingerprinting, etc.) should define their own
+// canonicalization specification and implement their own serializer rather
+// than relying on this API.
+//
+// If deterministic serialization is requested, map entries will be sorted
+// by keys in lexographical order. This is an implementation detail and
+// subject to change.
+func (p *Buffer) SetDeterministic(deterministic bool) {
+ p.deterministic = deterministic
+}
+
+/*
+ * Helper routines for simplifying the creation of optional fields of basic type.
+ */
+
+// Bool is a helper routine that allocates a new bool value
+// to store v and returns a pointer to it.
+func Bool(v bool) *bool {
+ return &v
+}
+
+// Int32 is a helper routine that allocates a new int32 value
+// to store v and returns a pointer to it.
+func Int32(v int32) *int32 {
+ return &v
+}
+
+// Int is a helper routine that allocates a new int32 value
+// to store v and returns a pointer to it, but unlike Int32
+// its argument value is an int.
+func Int(v int) *int32 {
+ p := new(int32)
+ *p = int32(v)
+ return p
+}
+
+// Int64 is a helper routine that allocates a new int64 value
+// to store v and returns a pointer to it.
+func Int64(v int64) *int64 {
+ return &v
+}
+
+// Float32 is a helper routine that allocates a new float32 value
+// to store v and returns a pointer to it.
+func Float32(v float32) *float32 {
+ return &v
+}
+
+// Float64 is a helper routine that allocates a new float64 value
+// to store v and returns a pointer to it.
+func Float64(v float64) *float64 {
+ return &v
+}
+
+// Uint32 is a helper routine that allocates a new uint32 value
+// to store v and returns a pointer to it.
+func Uint32(v uint32) *uint32 {
+ return &v
+}
+
+// Uint64 is a helper routine that allocates a new uint64 value
+// to store v and returns a pointer to it.
+func Uint64(v uint64) *uint64 {
+ return &v
+}
+
+// String is a helper routine that allocates a new string value
+// to store v and returns a pointer to it.
+func String(v string) *string {
+ return &v
+}
+
+// EnumName is a helper function to simplify printing protocol buffer enums
+// by name. Given an enum map and a value, it returns a useful string.
+func EnumName(m map[int32]string, v int32) string {
+ s, ok := m[v]
+ if ok {
+ return s
+ }
+ return strconv.Itoa(int(v))
+}
+
+// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
+// from their JSON-encoded representation. Given a map from the enum's symbolic
+// names to its int values, and a byte buffer containing the JSON-encoded
+// value, it returns an int32 that can be cast to the enum type by the caller.
+//
+// The function can deal with both JSON representations, numeric and symbolic.
+func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
+ if data[0] == '"' {
+ // New style: enums are strings.
+ var repr string
+ if err := json.Unmarshal(data, &repr); err != nil {
+ return -1, err
+ }
+ val, ok := m[repr]
+ if !ok {
+ return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
+ }
+ return val, nil
+ }
+ // Old style: enums are ints.
+ var val int32
+ if err := json.Unmarshal(data, &val); err != nil {
+ return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
+ }
+ return val, nil
+}
+
+// DebugPrint dumps the encoded data in b in a debugging format with a header
+// including the string s. Used in testing but made available for general debugging.
+func (p *Buffer) DebugPrint(s string, b []byte) {
+ var u uint64
+
+ obuf := p.buf
+ sindex := p.index
+ p.buf = b
+ p.index = 0
+ depth := 0
+
+ fmt.Printf("\n--- %s ---\n", s)
+
+out:
+ for {
+ for i := 0; i < depth; i++ {
+ fmt.Print(" ")
+ }
+
+ index := p.index
+ if index == len(p.buf) {
+ break
+ }
+
+ op, err := p.DecodeVarint()
+ if err != nil {
+ fmt.Printf("%3d: fetching op err %v\n", index, err)
+ break out
+ }
+ tag := op >> 3
+ wire := op & 7
+
+ switch wire {
+ default:
+ fmt.Printf("%3d: t=%3d unknown wire=%d\n",
+ index, tag, wire)
+ break out
+
+ case WireBytes:
+ var r []byte
+
+ r, err = p.DecodeRawBytes(false)
+ if err != nil {
+ break out
+ }
+ fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
+ if len(r) <= 6 {
+ for i := 0; i < len(r); i++ {
+ fmt.Printf(" %.2x", r[i])
+ }
+ } else {
+ for i := 0; i < 3; i++ {
+ fmt.Printf(" %.2x", r[i])
+ }
+ fmt.Printf(" ..")
+ for i := len(r) - 3; i < len(r); i++ {
+ fmt.Printf(" %.2x", r[i])
+ }
+ }
+ fmt.Printf("\n")
+
+ case WireFixed32:
+ u, err = p.DecodeFixed32()
+ if err != nil {
+ fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
+ break out
+ }
+ fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
+
+ case WireFixed64:
+ u, err = p.DecodeFixed64()
+ if err != nil {
+ fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
+ break out
+ }
+ fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
+
+ case WireVarint:
+ u, err = p.DecodeVarint()
+ if err != nil {
+ fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
+ break out
+ }
+ fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
+
+ case WireStartGroup:
+ fmt.Printf("%3d: t=%3d start\n", index, tag)
+ depth++
+
+ case WireEndGroup:
+ depth--
+ fmt.Printf("%3d: t=%3d end\n", index, tag)
+ }
+ }
+
+ if depth != 0 {
+ fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
+ }
+ fmt.Printf("\n")
+
+ p.buf = obuf
+ p.index = sindex
+}
+
+// SetDefaults sets unset protocol buffer fields to their default values.
+// It only modifies fields that are both unset and have defined defaults.
+// It recursively sets default values in any non-nil sub-messages.
+func SetDefaults(pb Message) {
+ setDefaults(reflect.ValueOf(pb), true, false)
+}
+
+// v is a struct.
+func setDefaults(v reflect.Value, recur, zeros bool) {
+ if v.Kind() == reflect.Ptr {
+ v = v.Elem()
+ }
+
+ defaultMu.RLock()
+ dm, ok := defaults[v.Type()]
+ defaultMu.RUnlock()
+ if !ok {
+ dm = buildDefaultMessage(v.Type())
+ defaultMu.Lock()
+ defaults[v.Type()] = dm
+ defaultMu.Unlock()
+ }
+
+ for _, sf := range dm.scalars {
+ f := v.Field(sf.index)
+ if !f.IsNil() {
+ // field already set
+ continue
+ }
+ dv := sf.value
+ if dv == nil && !zeros {
+ // no explicit default, and don't want to set zeros
+ continue
+ }
+ fptr := f.Addr().Interface() // **T
+ // TODO: Consider batching the allocations we do here.
+ switch sf.kind {
+ case reflect.Bool:
+ b := new(bool)
+ if dv != nil {
+ *b = dv.(bool)
+ }
+ *(fptr.(**bool)) = b
+ case reflect.Float32:
+ f := new(float32)
+ if dv != nil {
+ *f = dv.(float32)
+ }
+ *(fptr.(**float32)) = f
+ case reflect.Float64:
+ f := new(float64)
+ if dv != nil {
+ *f = dv.(float64)
+ }
+ *(fptr.(**float64)) = f
+ case reflect.Int32:
+ // might be an enum
+ if ft := f.Type(); ft != int32PtrType {
+ // enum
+ f.Set(reflect.New(ft.Elem()))
+ if dv != nil {
+ f.Elem().SetInt(int64(dv.(int32)))
+ }
+ } else {
+ // int32 field
+ i := new(int32)
+ if dv != nil {
+ *i = dv.(int32)
+ }
+ *(fptr.(**int32)) = i
+ }
+ case reflect.Int64:
+ i := new(int64)
+ if dv != nil {
+ *i = dv.(int64)
+ }
+ *(fptr.(**int64)) = i
+ case reflect.String:
+ s := new(string)
+ if dv != nil {
+ *s = dv.(string)
+ }
+ *(fptr.(**string)) = s
+ case reflect.Uint8:
+ // exceptional case: []byte
+ var b []byte
+ if dv != nil {
+ db := dv.([]byte)
+ b = make([]byte, len(db))
+ copy(b, db)
+ } else {
+ b = []byte{}
+ }
+ *(fptr.(*[]byte)) = b
+ case reflect.Uint32:
+ u := new(uint32)
+ if dv != nil {
+ *u = dv.(uint32)
+ }
+ *(fptr.(**uint32)) = u
+ case reflect.Uint64:
+ u := new(uint64)
+ if dv != nil {
+ *u = dv.(uint64)
+ }
+ *(fptr.(**uint64)) = u
+ default:
+ log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
+ }
+ }
+
+ for _, ni := range dm.nested {
+ f := v.Field(ni)
+ // f is *T or T or []*T or []T
+ switch f.Kind() {
+ case reflect.Struct:
+ setDefaults(f, recur, zeros)
+
+ case reflect.Ptr:
+ if f.IsNil() {
+ continue
+ }
+ setDefaults(f, recur, zeros)
+
+ case reflect.Slice:
+ for i := 0; i < f.Len(); i++ {
+ e := f.Index(i)
+ if e.Kind() == reflect.Ptr && e.IsNil() {
+ continue
+ }
+ setDefaults(e, recur, zeros)
+ }
+
+ case reflect.Map:
+ for _, k := range f.MapKeys() {
+ e := f.MapIndex(k)
+ if e.IsNil() {
+ continue
+ }
+ setDefaults(e, recur, zeros)
+ }
+ }
+ }
+}
+
+var (
+ // defaults maps a protocol buffer struct type to a slice of the fields,
+ // with its scalar fields set to their proto-declared non-zero default values.
+ defaultMu sync.RWMutex
+ defaults = make(map[reflect.Type]defaultMessage)
+
+ int32PtrType = reflect.TypeOf((*int32)(nil))
+)
+
+// defaultMessage represents information about the default values of a message.
+type defaultMessage struct {
+ scalars []scalarField
+ nested []int // struct field index of nested messages
+}
+
+type scalarField struct {
+ index int // struct field index
+ kind reflect.Kind // element type (the T in *T or []T)
+ value interface{} // the proto-declared default value, or nil
+}
+
+// t is a struct type.
+func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
+ sprop := GetProperties(t)
+ for _, prop := range sprop.Prop {
+ fi, ok := sprop.decoderTags.get(prop.Tag)
+ if !ok {
+ // XXX_unrecognized
+ continue
+ }
+ ft := t.Field(fi).Type
+
+ sf, nested, err := fieldDefault(ft, prop)
+ switch {
+ case err != nil:
+ log.Print(err)
+ case nested:
+ dm.nested = append(dm.nested, fi)
+ case sf != nil:
+ sf.index = fi
+ dm.scalars = append(dm.scalars, *sf)
+ }
+ }
+
+ return dm
+}
+
+// fieldDefault returns the scalarField for field type ft.
+// sf will be nil if the field can not have a default.
+// nestedMessage will be true if this is a nested message.
+// Note that sf.index is not set on return.
+func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
+ var canHaveDefault bool
+ switch ft.Kind() {
+ case reflect.Struct:
+ nestedMessage = true // non-nullable
+
+ case reflect.Ptr:
+ if ft.Elem().Kind() == reflect.Struct {
+ nestedMessage = true
+ } else {
+ canHaveDefault = true // proto2 scalar field
+ }
+
+ case reflect.Slice:
+ switch ft.Elem().Kind() {
+ case reflect.Ptr, reflect.Struct:
+ nestedMessage = true // repeated message
+ case reflect.Uint8:
+ canHaveDefault = true // bytes field
+ }
+
+ case reflect.Map:
+ if ft.Elem().Kind() == reflect.Ptr {
+ nestedMessage = true // map with message values
+ }
+ }
+
+ if !canHaveDefault {
+ if nestedMessage {
+ return nil, true, nil
+ }
+ return nil, false, nil
+ }
+
+ // We now know that ft is a pointer or slice.
+ sf = &scalarField{kind: ft.Elem().Kind()}
+
+ // scalar fields without defaults
+ if !prop.HasDefault {
+ return sf, false, nil
+ }
+
+ // a scalar field: either *T or []byte
+ switch ft.Elem().Kind() {
+ case reflect.Bool:
+ x, err := strconv.ParseBool(prop.Default)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ case reflect.Float32:
+ x, err := strconv.ParseFloat(prop.Default, 32)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
+ }
+ sf.value = float32(x)
+ case reflect.Float64:
+ x, err := strconv.ParseFloat(prop.Default, 64)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ case reflect.Int32:
+ x, err := strconv.ParseInt(prop.Default, 10, 32)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
+ }
+ sf.value = int32(x)
+ case reflect.Int64:
+ x, err := strconv.ParseInt(prop.Default, 10, 64)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ case reflect.String:
+ sf.value = prop.Default
+ case reflect.Uint8:
+ // []byte (not *uint8)
+ sf.value = []byte(prop.Default)
+ case reflect.Uint32:
+ x, err := strconv.ParseUint(prop.Default, 10, 32)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
+ }
+ sf.value = uint32(x)
+ case reflect.Uint64:
+ x, err := strconv.ParseUint(prop.Default, 10, 64)
+ if err != nil {
+ return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
+ }
+ sf.value = x
+ default:
+ return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
+ }
+
+ return sf, false, nil
+}
+
+// mapKeys returns a sort.Interface to be used for sorting the map keys.
+// Map fields may have key types of non-float scalars, strings and enums.
+func mapKeys(vs []reflect.Value) sort.Interface {
+ s := mapKeySorter{vs: vs}
+
+ // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.
+ if len(vs) == 0 {
+ return s
+ }
+ switch vs[0].Kind() {
+ case reflect.Int32, reflect.Int64:
+ s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
+ case reflect.Uint32, reflect.Uint64:
+ s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
+ case reflect.Bool:
+ s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true
+ case reflect.String:
+ s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }
+ default:
+ panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))
+ }
+
+ return s
+}
+
+type mapKeySorter struct {
+ vs []reflect.Value
+ less func(a, b reflect.Value) bool
+}
+
+func (s mapKeySorter) Len() int { return len(s.vs) }
+func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
+func (s mapKeySorter) Less(i, j int) bool {
+ return s.less(s.vs[i], s.vs[j])
+}
+
+// isProto3Zero reports whether v is a zero proto3 value.
+func isProto3Zero(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Bool:
+ return !v.Bool()
+ case reflect.Int32, reflect.Int64:
+ return v.Int() == 0
+ case reflect.Uint32, reflect.Uint64:
+ return v.Uint() == 0
+ case reflect.Float32, reflect.Float64:
+ return v.Float() == 0
+ case reflect.String:
+ return v.String() == ""
+ }
+ return false
+}
+
+const (
+ // ProtoPackageIsVersion3 is referenced from generated protocol buffer files
+ // to assert that that code is compatible with this version of the proto package.
+ GoGoProtoPackageIsVersion3 = true
+
+ // ProtoPackageIsVersion2 is referenced from generated protocol buffer files
+ // to assert that that code is compatible with this version of the proto package.
+ GoGoProtoPackageIsVersion2 = true
+
+ // ProtoPackageIsVersion1 is referenced from generated protocol buffer files
+ // to assert that that code is compatible with this version of the proto package.
+ GoGoProtoPackageIsVersion1 = true
+)
+
+// InternalMessageInfo is a type used internally by generated .pb.go files.
+// This type is not intended to be used by non-generated code.
+// This type is not subject to any compatibility guarantee.
+type InternalMessageInfo struct {
+ marshal *marshalInfo
+ unmarshal *unmarshalInfo
+ merge *mergeInfo
+ discard *discardInfo
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/lib_gogo.go b/vendor/github.com/gogo/protobuf/proto/lib_gogo.go
@@ -0,0 +1,50 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import (
+ "encoding/json"
+ "strconv"
+)
+
+type Sizer interface {
+ Size() int
+}
+
+type ProtoSizer interface {
+ ProtoSize() int
+}
+
+func MarshalJSONEnum(m map[int32]string, value int32) ([]byte, error) {
+ s, ok := m[value]
+ if !ok {
+ s = strconv.Itoa(int(value))
+ }
+ return json.Marshal(s)
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/message_set.go b/vendor/github.com/gogo/protobuf/proto/message_set.go
@@ -0,0 +1,181 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Support for message sets.
+ */
+
+import (
+ "errors"
+)
+
+// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
+// A message type ID is required for storing a protocol buffer in a message set.
+var errNoMessageTypeID = errors.New("proto does not have a message type ID")
+
+// The first two types (_MessageSet_Item and messageSet)
+// model what the protocol compiler produces for the following protocol message:
+// message MessageSet {
+// repeated group Item = 1 {
+// required int32 type_id = 2;
+// required string message = 3;
+// };
+// }
+// That is the MessageSet wire format. We can't use a proto to generate these
+// because that would introduce a circular dependency between it and this package.
+
+type _MessageSet_Item struct {
+ TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
+ Message []byte `protobuf:"bytes,3,req,name=message"`
+}
+
+type messageSet struct {
+ Item []*_MessageSet_Item `protobuf:"group,1,rep"`
+ XXX_unrecognized []byte
+ // TODO: caching?
+}
+
+// Make sure messageSet is a Message.
+var _ Message = (*messageSet)(nil)
+
+// messageTypeIder is an interface satisfied by a protocol buffer type
+// that may be stored in a MessageSet.
+type messageTypeIder interface {
+ MessageTypeId() int32
+}
+
+func (ms *messageSet) find(pb Message) *_MessageSet_Item {
+ mti, ok := pb.(messageTypeIder)
+ if !ok {
+ return nil
+ }
+ id := mti.MessageTypeId()
+ for _, item := range ms.Item {
+ if *item.TypeId == id {
+ return item
+ }
+ }
+ return nil
+}
+
+func (ms *messageSet) Has(pb Message) bool {
+ return ms.find(pb) != nil
+}
+
+func (ms *messageSet) Unmarshal(pb Message) error {
+ if item := ms.find(pb); item != nil {
+ return Unmarshal(item.Message, pb)
+ }
+ if _, ok := pb.(messageTypeIder); !ok {
+ return errNoMessageTypeID
+ }
+ return nil // TODO: return error instead?
+}
+
+func (ms *messageSet) Marshal(pb Message) error {
+ msg, err := Marshal(pb)
+ if err != nil {
+ return err
+ }
+ if item := ms.find(pb); item != nil {
+ // reuse existing item
+ item.Message = msg
+ return nil
+ }
+
+ mti, ok := pb.(messageTypeIder)
+ if !ok {
+ return errNoMessageTypeID
+ }
+
+ mtid := mti.MessageTypeId()
+ ms.Item = append(ms.Item, &_MessageSet_Item{
+ TypeId: &mtid,
+ Message: msg,
+ })
+ return nil
+}
+
+func (ms *messageSet) Reset() { *ms = messageSet{} }
+func (ms *messageSet) String() string { return CompactTextString(ms) }
+func (*messageSet) ProtoMessage() {}
+
+// Support for the message_set_wire_format message option.
+
+func skipVarint(buf []byte) []byte {
+ i := 0
+ for ; buf[i]&0x80 != 0; i++ {
+ }
+ return buf[i+1:]
+}
+
+// unmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
+// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
+func unmarshalMessageSet(buf []byte, exts interface{}) error {
+ var m map[int32]Extension
+ switch exts := exts.(type) {
+ case *XXX_InternalExtensions:
+ m = exts.extensionsWrite()
+ case map[int32]Extension:
+ m = exts
+ default:
+ return errors.New("proto: not an extension map")
+ }
+
+ ms := new(messageSet)
+ if err := Unmarshal(buf, ms); err != nil {
+ return err
+ }
+ for _, item := range ms.Item {
+ id := *item.TypeId
+ msg := item.Message
+
+ // Restore wire type and field number varint, plus length varint.
+ // Be careful to preserve duplicate items.
+ b := EncodeVarint(uint64(id)<<3 | WireBytes)
+ if ext, ok := m[id]; ok {
+ // Existing data; rip off the tag and length varint
+ // so we join the new data correctly.
+ // We can assume that ext.enc is set because we are unmarshaling.
+ o := ext.enc[len(b):] // skip wire type and field number
+ _, n := DecodeVarint(o) // calculate length of length varint
+ o = o[n:] // skip length varint
+ msg = append(o, msg...) // join old data and new data
+ }
+ b = append(b, EncodeVarint(uint64(len(msg)))...)
+ b = append(b, msg...)
+
+ m[id] = Extension{enc: b}
+ }
+ return nil
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go b/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go
@@ -0,0 +1,357 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2012 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// +build purego appengine js
+
+// This file contains an implementation of proto field accesses using package reflect.
+// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
+// be used on App Engine.
+
+package proto
+
+import (
+ "reflect"
+ "sync"
+)
+
+const unsafeAllowed = false
+
+// A field identifies a field in a struct, accessible from a pointer.
+// In this implementation, a field is identified by the sequence of field indices
+// passed to reflect's FieldByIndex.
+type field []int
+
+// toField returns a field equivalent to the given reflect field.
+func toField(f *reflect.StructField) field {
+ return f.Index
+}
+
+// invalidField is an invalid field identifier.
+var invalidField = field(nil)
+
+// zeroField is a noop when calling pointer.offset.
+var zeroField = field([]int{})
+
+// IsValid reports whether the field identifier is valid.
+func (f field) IsValid() bool { return f != nil }
+
+// The pointer type is for the table-driven decoder.
+// The implementation here uses a reflect.Value of pointer type to
+// create a generic pointer. In pointer_unsafe.go we use unsafe
+// instead of reflect to implement the same (but faster) interface.
+type pointer struct {
+ v reflect.Value
+}
+
+// toPointer converts an interface of pointer type to a pointer
+// that points to the same target.
+func toPointer(i *Message) pointer {
+ return pointer{v: reflect.ValueOf(*i)}
+}
+
+// toAddrPointer converts an interface to a pointer that points to
+// the interface data.
+func toAddrPointer(i *interface{}, isptr bool) pointer {
+ v := reflect.ValueOf(*i)
+ u := reflect.New(v.Type())
+ u.Elem().Set(v)
+ return pointer{v: u}
+}
+
+// valToPointer converts v to a pointer. v must be of pointer type.
+func valToPointer(v reflect.Value) pointer {
+ return pointer{v: v}
+}
+
+// offset converts from a pointer to a structure to a pointer to
+// one of its fields.
+func (p pointer) offset(f field) pointer {
+ return pointer{v: p.v.Elem().FieldByIndex(f).Addr()}
+}
+
+func (p pointer) isNil() bool {
+ return p.v.IsNil()
+}
+
+// grow updates the slice s in place to make it one element longer.
+// s must be addressable.
+// Returns the (addressable) new element.
+func grow(s reflect.Value) reflect.Value {
+ n, m := s.Len(), s.Cap()
+ if n < m {
+ s.SetLen(n + 1)
+ } else {
+ s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem())))
+ }
+ return s.Index(n)
+}
+
+func (p pointer) toInt64() *int64 {
+ return p.v.Interface().(*int64)
+}
+func (p pointer) toInt64Ptr() **int64 {
+ return p.v.Interface().(**int64)
+}
+func (p pointer) toInt64Slice() *[]int64 {
+ return p.v.Interface().(*[]int64)
+}
+
+var int32ptr = reflect.TypeOf((*int32)(nil))
+
+func (p pointer) toInt32() *int32 {
+ return p.v.Convert(int32ptr).Interface().(*int32)
+}
+
+// The toInt32Ptr/Slice methods don't work because of enums.
+// Instead, we must use set/get methods for the int32ptr/slice case.
+/*
+ func (p pointer) toInt32Ptr() **int32 {
+ return p.v.Interface().(**int32)
+}
+ func (p pointer) toInt32Slice() *[]int32 {
+ return p.v.Interface().(*[]int32)
+}
+*/
+func (p pointer) getInt32Ptr() *int32 {
+ if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
+ // raw int32 type
+ return p.v.Elem().Interface().(*int32)
+ }
+ // an enum
+ return p.v.Elem().Convert(int32PtrType).Interface().(*int32)
+}
+func (p pointer) setInt32Ptr(v int32) {
+ // Allocate value in a *int32. Possibly convert that to a *enum.
+ // Then assign it to a **int32 or **enum.
+ // Note: we can convert *int32 to *enum, but we can't convert
+ // **int32 to **enum!
+ p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem()))
+}
+
+// getInt32Slice copies []int32 from p as a new slice.
+// This behavior differs from the implementation in pointer_unsafe.go.
+func (p pointer) getInt32Slice() []int32 {
+ if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
+ // raw int32 type
+ return p.v.Elem().Interface().([]int32)
+ }
+ // an enum
+ // Allocate a []int32, then assign []enum's values into it.
+ // Note: we can't convert []enum to []int32.
+ slice := p.v.Elem()
+ s := make([]int32, slice.Len())
+ for i := 0; i < slice.Len(); i++ {
+ s[i] = int32(slice.Index(i).Int())
+ }
+ return s
+}
+
+// setInt32Slice copies []int32 into p as a new slice.
+// This behavior differs from the implementation in pointer_unsafe.go.
+func (p pointer) setInt32Slice(v []int32) {
+ if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
+ // raw int32 type
+ p.v.Elem().Set(reflect.ValueOf(v))
+ return
+ }
+ // an enum
+ // Allocate a []enum, then assign []int32's values into it.
+ // Note: we can't convert []enum to []int32.
+ slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v))
+ for i, x := range v {
+ slice.Index(i).SetInt(int64(x))
+ }
+ p.v.Elem().Set(slice)
+}
+func (p pointer) appendInt32Slice(v int32) {
+ grow(p.v.Elem()).SetInt(int64(v))
+}
+
+func (p pointer) toUint64() *uint64 {
+ return p.v.Interface().(*uint64)
+}
+func (p pointer) toUint64Ptr() **uint64 {
+ return p.v.Interface().(**uint64)
+}
+func (p pointer) toUint64Slice() *[]uint64 {
+ return p.v.Interface().(*[]uint64)
+}
+func (p pointer) toUint32() *uint32 {
+ return p.v.Interface().(*uint32)
+}
+func (p pointer) toUint32Ptr() **uint32 {
+ return p.v.Interface().(**uint32)
+}
+func (p pointer) toUint32Slice() *[]uint32 {
+ return p.v.Interface().(*[]uint32)
+}
+func (p pointer) toBool() *bool {
+ return p.v.Interface().(*bool)
+}
+func (p pointer) toBoolPtr() **bool {
+ return p.v.Interface().(**bool)
+}
+func (p pointer) toBoolSlice() *[]bool {
+ return p.v.Interface().(*[]bool)
+}
+func (p pointer) toFloat64() *float64 {
+ return p.v.Interface().(*float64)
+}
+func (p pointer) toFloat64Ptr() **float64 {
+ return p.v.Interface().(**float64)
+}
+func (p pointer) toFloat64Slice() *[]float64 {
+ return p.v.Interface().(*[]float64)
+}
+func (p pointer) toFloat32() *float32 {
+ return p.v.Interface().(*float32)
+}
+func (p pointer) toFloat32Ptr() **float32 {
+ return p.v.Interface().(**float32)
+}
+func (p pointer) toFloat32Slice() *[]float32 {
+ return p.v.Interface().(*[]float32)
+}
+func (p pointer) toString() *string {
+ return p.v.Interface().(*string)
+}
+func (p pointer) toStringPtr() **string {
+ return p.v.Interface().(**string)
+}
+func (p pointer) toStringSlice() *[]string {
+ return p.v.Interface().(*[]string)
+}
+func (p pointer) toBytes() *[]byte {
+ return p.v.Interface().(*[]byte)
+}
+func (p pointer) toBytesSlice() *[][]byte {
+ return p.v.Interface().(*[][]byte)
+}
+func (p pointer) toExtensions() *XXX_InternalExtensions {
+ return p.v.Interface().(*XXX_InternalExtensions)
+}
+func (p pointer) toOldExtensions() *map[int32]Extension {
+ return p.v.Interface().(*map[int32]Extension)
+}
+func (p pointer) getPointer() pointer {
+ return pointer{v: p.v.Elem()}
+}
+func (p pointer) setPointer(q pointer) {
+ p.v.Elem().Set(q.v)
+}
+func (p pointer) appendPointer(q pointer) {
+ grow(p.v.Elem()).Set(q.v)
+}
+
+// getPointerSlice copies []*T from p as a new []pointer.
+// This behavior differs from the implementation in pointer_unsafe.go.
+func (p pointer) getPointerSlice() []pointer {
+ if p.v.IsNil() {
+ return nil
+ }
+ n := p.v.Elem().Len()
+ s := make([]pointer, n)
+ for i := 0; i < n; i++ {
+ s[i] = pointer{v: p.v.Elem().Index(i)}
+ }
+ return s
+}
+
+// setPointerSlice copies []pointer into p as a new []*T.
+// This behavior differs from the implementation in pointer_unsafe.go.
+func (p pointer) setPointerSlice(v []pointer) {
+ if v == nil {
+ p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem())
+ return
+ }
+ s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v))
+ for _, p := range v {
+ s = reflect.Append(s, p.v)
+ }
+ p.v.Elem().Set(s)
+}
+
+// getInterfacePointer returns a pointer that points to the
+// interface data of the interface pointed by p.
+func (p pointer) getInterfacePointer() pointer {
+ if p.v.Elem().IsNil() {
+ return pointer{v: p.v.Elem()}
+ }
+ return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct
+}
+
+func (p pointer) asPointerTo(t reflect.Type) reflect.Value {
+ // TODO: check that p.v.Type().Elem() == t?
+ return p.v
+}
+
+func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo {
+ atomicLock.Lock()
+ defer atomicLock.Unlock()
+ return *p
+}
+func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) {
+ atomicLock.Lock()
+ defer atomicLock.Unlock()
+ *p = v
+}
+func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo {
+ atomicLock.Lock()
+ defer atomicLock.Unlock()
+ return *p
+}
+func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) {
+ atomicLock.Lock()
+ defer atomicLock.Unlock()
+ *p = v
+}
+func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo {
+ atomicLock.Lock()
+ defer atomicLock.Unlock()
+ return *p
+}
+func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) {
+ atomicLock.Lock()
+ defer atomicLock.Unlock()
+ *p = v
+}
+func atomicLoadDiscardInfo(p **discardInfo) *discardInfo {
+ atomicLock.Lock()
+ defer atomicLock.Unlock()
+ return *p
+}
+func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) {
+ atomicLock.Lock()
+ defer atomicLock.Unlock()
+ *p = v
+}
+
+var atomicLock sync.Mutex
diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go b/vendor/github.com/gogo/protobuf/proto/pointer_reflect_gogo.go
@@ -0,0 +1,59 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2018, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+// +build purego appengine js
+
+// This file contains an implementation of proto field accesses using package reflect.
+// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
+// be used on App Engine.
+
+package proto
+
+import (
+ "reflect"
+)
+
+// TODO: untested, so probably incorrect.
+
+func (p pointer) getRef() pointer {
+ return pointer{v: p.v.Addr()}
+}
+
+func (p pointer) appendRef(v pointer, typ reflect.Type) {
+ slice := p.getSlice(typ)
+ elem := v.asPointerTo(typ).Elem()
+ newSlice := reflect.Append(slice, elem)
+ slice.Set(newSlice)
+}
+
+func (p pointer) getSlice(typ reflect.Type) reflect.Value {
+ sliceTyp := reflect.SliceOf(typ)
+ slice := p.asPointerTo(sliceTyp)
+ slice = slice.Elem()
+ return slice
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go
@@ -0,0 +1,308 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2012 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// +build !purego,!appengine,!js
+
+// This file contains the implementation of the proto field accesses using package unsafe.
+
+package proto
+
+import (
+ "reflect"
+ "sync/atomic"
+ "unsafe"
+)
+
+const unsafeAllowed = true
+
+// A field identifies a field in a struct, accessible from a pointer.
+// In this implementation, a field is identified by its byte offset from the start of the struct.
+type field uintptr
+
+// toField returns a field equivalent to the given reflect field.
+func toField(f *reflect.StructField) field {
+ return field(f.Offset)
+}
+
+// invalidField is an invalid field identifier.
+const invalidField = ^field(0)
+
+// zeroField is a noop when calling pointer.offset.
+const zeroField = field(0)
+
+// IsValid reports whether the field identifier is valid.
+func (f field) IsValid() bool {
+ return f != invalidField
+}
+
+// The pointer type below is for the new table-driven encoder/decoder.
+// The implementation here uses unsafe.Pointer to create a generic pointer.
+// In pointer_reflect.go we use reflect instead of unsafe to implement
+// the same (but slower) interface.
+type pointer struct {
+ p unsafe.Pointer
+}
+
+// size of pointer
+var ptrSize = unsafe.Sizeof(uintptr(0))
+
+// toPointer converts an interface of pointer type to a pointer
+// that points to the same target.
+func toPointer(i *Message) pointer {
+ // Super-tricky - read pointer out of data word of interface value.
+ // Saves ~25ns over the equivalent:
+ // return valToPointer(reflect.ValueOf(*i))
+ return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
+}
+
+// toAddrPointer converts an interface to a pointer that points to
+// the interface data.
+func toAddrPointer(i *interface{}, isptr bool) pointer {
+ // Super-tricky - read or get the address of data word of interface value.
+ if isptr {
+ // The interface is of pointer type, thus it is a direct interface.
+ // The data word is the pointer data itself. We take its address.
+ return pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)}
+ }
+ // The interface is not of pointer type. The data word is the pointer
+ // to the data.
+ return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
+}
+
+// valToPointer converts v to a pointer. v must be of pointer type.
+func valToPointer(v reflect.Value) pointer {
+ return pointer{p: unsafe.Pointer(v.Pointer())}
+}
+
+// offset converts from a pointer to a structure to a pointer to
+// one of its fields.
+func (p pointer) offset(f field) pointer {
+ // For safety, we should panic if !f.IsValid, however calling panic causes
+ // this to no longer be inlineable, which is a serious performance cost.
+ /*
+ if !f.IsValid() {
+ panic("invalid field")
+ }
+ */
+ return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))}
+}
+
+func (p pointer) isNil() bool {
+ return p.p == nil
+}
+
+func (p pointer) toInt64() *int64 {
+ return (*int64)(p.p)
+}
+func (p pointer) toInt64Ptr() **int64 {
+ return (**int64)(p.p)
+}
+func (p pointer) toInt64Slice() *[]int64 {
+ return (*[]int64)(p.p)
+}
+func (p pointer) toInt32() *int32 {
+ return (*int32)(p.p)
+}
+
+// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist.
+/*
+ func (p pointer) toInt32Ptr() **int32 {
+ return (**int32)(p.p)
+ }
+ func (p pointer) toInt32Slice() *[]int32 {
+ return (*[]int32)(p.p)
+ }
+*/
+func (p pointer) getInt32Ptr() *int32 {
+ return *(**int32)(p.p)
+}
+func (p pointer) setInt32Ptr(v int32) {
+ *(**int32)(p.p) = &v
+}
+
+// getInt32Slice loads a []int32 from p.
+// The value returned is aliased with the original slice.
+// This behavior differs from the implementation in pointer_reflect.go.
+func (p pointer) getInt32Slice() []int32 {
+ return *(*[]int32)(p.p)
+}
+
+// setInt32Slice stores a []int32 to p.
+// The value set is aliased with the input slice.
+// This behavior differs from the implementation in pointer_reflect.go.
+func (p pointer) setInt32Slice(v []int32) {
+ *(*[]int32)(p.p) = v
+}
+
+// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead?
+func (p pointer) appendInt32Slice(v int32) {
+ s := (*[]int32)(p.p)
+ *s = append(*s, v)
+}
+
+func (p pointer) toUint64() *uint64 {
+ return (*uint64)(p.p)
+}
+func (p pointer) toUint64Ptr() **uint64 {
+ return (**uint64)(p.p)
+}
+func (p pointer) toUint64Slice() *[]uint64 {
+ return (*[]uint64)(p.p)
+}
+func (p pointer) toUint32() *uint32 {
+ return (*uint32)(p.p)
+}
+func (p pointer) toUint32Ptr() **uint32 {
+ return (**uint32)(p.p)
+}
+func (p pointer) toUint32Slice() *[]uint32 {
+ return (*[]uint32)(p.p)
+}
+func (p pointer) toBool() *bool {
+ return (*bool)(p.p)
+}
+func (p pointer) toBoolPtr() **bool {
+ return (**bool)(p.p)
+}
+func (p pointer) toBoolSlice() *[]bool {
+ return (*[]bool)(p.p)
+}
+func (p pointer) toFloat64() *float64 {
+ return (*float64)(p.p)
+}
+func (p pointer) toFloat64Ptr() **float64 {
+ return (**float64)(p.p)
+}
+func (p pointer) toFloat64Slice() *[]float64 {
+ return (*[]float64)(p.p)
+}
+func (p pointer) toFloat32() *float32 {
+ return (*float32)(p.p)
+}
+func (p pointer) toFloat32Ptr() **float32 {
+ return (**float32)(p.p)
+}
+func (p pointer) toFloat32Slice() *[]float32 {
+ return (*[]float32)(p.p)
+}
+func (p pointer) toString() *string {
+ return (*string)(p.p)
+}
+func (p pointer) toStringPtr() **string {
+ return (**string)(p.p)
+}
+func (p pointer) toStringSlice() *[]string {
+ return (*[]string)(p.p)
+}
+func (p pointer) toBytes() *[]byte {
+ return (*[]byte)(p.p)
+}
+func (p pointer) toBytesSlice() *[][]byte {
+ return (*[][]byte)(p.p)
+}
+func (p pointer) toExtensions() *XXX_InternalExtensions {
+ return (*XXX_InternalExtensions)(p.p)
+}
+func (p pointer) toOldExtensions() *map[int32]Extension {
+ return (*map[int32]Extension)(p.p)
+}
+
+// getPointerSlice loads []*T from p as a []pointer.
+// The value returned is aliased with the original slice.
+// This behavior differs from the implementation in pointer_reflect.go.
+func (p pointer) getPointerSlice() []pointer {
+ // Super-tricky - p should point to a []*T where T is a
+ // message type. We load it as []pointer.
+ return *(*[]pointer)(p.p)
+}
+
+// setPointerSlice stores []pointer into p as a []*T.
+// The value set is aliased with the input slice.
+// This behavior differs from the implementation in pointer_reflect.go.
+func (p pointer) setPointerSlice(v []pointer) {
+ // Super-tricky - p should point to a []*T where T is a
+ // message type. We store it as []pointer.
+ *(*[]pointer)(p.p) = v
+}
+
+// getPointer loads the pointer at p and returns it.
+func (p pointer) getPointer() pointer {
+ return pointer{p: *(*unsafe.Pointer)(p.p)}
+}
+
+// setPointer stores the pointer q at p.
+func (p pointer) setPointer(q pointer) {
+ *(*unsafe.Pointer)(p.p) = q.p
+}
+
+// append q to the slice pointed to by p.
+func (p pointer) appendPointer(q pointer) {
+ s := (*[]unsafe.Pointer)(p.p)
+ *s = append(*s, q.p)
+}
+
+// getInterfacePointer returns a pointer that points to the
+// interface data of the interface pointed by p.
+func (p pointer) getInterfacePointer() pointer {
+ // Super-tricky - read pointer out of data word of interface value.
+ return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]}
+}
+
+// asPointerTo returns a reflect.Value that is a pointer to an
+// object of type t stored at p.
+func (p pointer) asPointerTo(t reflect.Type) reflect.Value {
+ return reflect.NewAt(t, p.p)
+}
+
+func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo {
+ return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
+}
+func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) {
+ atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
+}
+func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo {
+ return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
+}
+func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) {
+ atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
+}
+func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo {
+ return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
+}
+func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) {
+ atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
+}
+func atomicLoadDiscardInfo(p **discardInfo) *discardInfo {
+ return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
+}
+func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) {
+ atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go b/vendor/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go
@@ -0,0 +1,56 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2018, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+// +build !purego,!appengine,!js
+
+// This file contains the implementation of the proto field accesses using package unsafe.
+
+package proto
+
+import (
+ "reflect"
+ "unsafe"
+)
+
+func (p pointer) getRef() pointer {
+ return pointer{p: (unsafe.Pointer)(&p.p)}
+}
+
+func (p pointer) appendRef(v pointer, typ reflect.Type) {
+ slice := p.getSlice(typ)
+ elem := v.asPointerTo(typ).Elem()
+ newSlice := reflect.Append(slice, elem)
+ slice.Set(newSlice)
+}
+
+func (p pointer) getSlice(typ reflect.Type) reflect.Value {
+ sliceTyp := reflect.SliceOf(typ)
+ slice := p.asPointerTo(sliceTyp)
+ slice = slice.Elem()
+ return slice
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/properties.go b/vendor/github.com/gogo/protobuf/proto/properties.go
@@ -0,0 +1,610 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+/*
+ * Routines for encoding data into the wire format for protocol buffers.
+ */
+
+import (
+ "fmt"
+ "log"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+)
+
+const debug bool = false
+
+// Constants that identify the encoding of a value on the wire.
+const (
+ WireVarint = 0
+ WireFixed64 = 1
+ WireBytes = 2
+ WireStartGroup = 3
+ WireEndGroup = 4
+ WireFixed32 = 5
+)
+
+// tagMap is an optimization over map[int]int for typical protocol buffer
+// use-cases. Encoded protocol buffers are often in tag order with small tag
+// numbers.
+type tagMap struct {
+ fastTags []int
+ slowTags map[int]int
+}
+
+// tagMapFastLimit is the upper bound on the tag number that will be stored in
+// the tagMap slice rather than its map.
+const tagMapFastLimit = 1024
+
+func (p *tagMap) get(t int) (int, bool) {
+ if t > 0 && t < tagMapFastLimit {
+ if t >= len(p.fastTags) {
+ return 0, false
+ }
+ fi := p.fastTags[t]
+ return fi, fi >= 0
+ }
+ fi, ok := p.slowTags[t]
+ return fi, ok
+}
+
+func (p *tagMap) put(t int, fi int) {
+ if t > 0 && t < tagMapFastLimit {
+ for len(p.fastTags) < t+1 {
+ p.fastTags = append(p.fastTags, -1)
+ }
+ p.fastTags[t] = fi
+ return
+ }
+ if p.slowTags == nil {
+ p.slowTags = make(map[int]int)
+ }
+ p.slowTags[t] = fi
+}
+
+// StructProperties represents properties for all the fields of a struct.
+// decoderTags and decoderOrigNames should only be used by the decoder.
+type StructProperties struct {
+ Prop []*Properties // properties for each field
+ reqCount int // required count
+ decoderTags tagMap // map from proto tag to struct field number
+ decoderOrigNames map[string]int // map from original name to struct field number
+ order []int // list of struct field numbers in tag order
+
+ // OneofTypes contains information about the oneof fields in this message.
+ // It is keyed by the original name of a field.
+ OneofTypes map[string]*OneofProperties
+}
+
+// OneofProperties represents information about a specific field in a oneof.
+type OneofProperties struct {
+ Type reflect.Type // pointer to generated struct type for this oneof field
+ Field int // struct field number of the containing oneof in the message
+ Prop *Properties
+}
+
+// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
+// See encode.go, (*Buffer).enc_struct.
+
+func (sp *StructProperties) Len() int { return len(sp.order) }
+func (sp *StructProperties) Less(i, j int) bool {
+ return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
+}
+func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
+
+// Properties represents the protocol-specific behavior of a single struct field.
+type Properties struct {
+ Name string // name of the field, for error messages
+ OrigName string // original name before protocol compiler (always set)
+ JSONName string // name to use for JSON; determined by protoc
+ Wire string
+ WireType int
+ Tag int
+ Required bool
+ Optional bool
+ Repeated bool
+ Packed bool // relevant for repeated primitives only
+ Enum string // set for enum types only
+ proto3 bool // whether this is known to be a proto3 field
+ oneof bool // whether this is a oneof field
+
+ Default string // default value
+ HasDefault bool // whether an explicit default was provided
+ CustomType string
+ CastType string
+ StdTime bool
+ StdDuration bool
+ WktPointer bool
+
+ stype reflect.Type // set for struct types only
+ ctype reflect.Type // set for custom types only
+ sprop *StructProperties // set for struct types only
+
+ mtype reflect.Type // set for map types only
+ MapKeyProp *Properties // set for map types only
+ MapValProp *Properties // set for map types only
+}
+
+// String formats the properties in the protobuf struct field tag style.
+func (p *Properties) String() string {
+ s := p.Wire
+ s += ","
+ s += strconv.Itoa(p.Tag)
+ if p.Required {
+ s += ",req"
+ }
+ if p.Optional {
+ s += ",opt"
+ }
+ if p.Repeated {
+ s += ",rep"
+ }
+ if p.Packed {
+ s += ",packed"
+ }
+ s += ",name=" + p.OrigName
+ if p.JSONName != p.OrigName {
+ s += ",json=" + p.JSONName
+ }
+ if p.proto3 {
+ s += ",proto3"
+ }
+ if p.oneof {
+ s += ",oneof"
+ }
+ if len(p.Enum) > 0 {
+ s += ",enum=" + p.Enum
+ }
+ if p.HasDefault {
+ s += ",def=" + p.Default
+ }
+ return s
+}
+
+// Parse populates p by parsing a string in the protobuf struct field tag style.
+func (p *Properties) Parse(s string) {
+ // "bytes,49,opt,name=foo,def=hello!"
+ fields := strings.Split(s, ",") // breaks def=, but handled below.
+ if len(fields) < 2 {
+ log.Printf("proto: tag has too few fields: %q", s)
+ return
+ }
+
+ p.Wire = fields[0]
+ switch p.Wire {
+ case "varint":
+ p.WireType = WireVarint
+ case "fixed32":
+ p.WireType = WireFixed32
+ case "fixed64":
+ p.WireType = WireFixed64
+ case "zigzag32":
+ p.WireType = WireVarint
+ case "zigzag64":
+ p.WireType = WireVarint
+ case "bytes", "group":
+ p.WireType = WireBytes
+ // no numeric converter for non-numeric types
+ default:
+ log.Printf("proto: tag has unknown wire type: %q", s)
+ return
+ }
+
+ var err error
+ p.Tag, err = strconv.Atoi(fields[1])
+ if err != nil {
+ return
+ }
+
+outer:
+ for i := 2; i < len(fields); i++ {
+ f := fields[i]
+ switch {
+ case f == "req":
+ p.Required = true
+ case f == "opt":
+ p.Optional = true
+ case f == "rep":
+ p.Repeated = true
+ case f == "packed":
+ p.Packed = true
+ case strings.HasPrefix(f, "name="):
+ p.OrigName = f[5:]
+ case strings.HasPrefix(f, "json="):
+ p.JSONName = f[5:]
+ case strings.HasPrefix(f, "enum="):
+ p.Enum = f[5:]
+ case f == "proto3":
+ p.proto3 = true
+ case f == "oneof":
+ p.oneof = true
+ case strings.HasPrefix(f, "def="):
+ p.HasDefault = true
+ p.Default = f[4:] // rest of string
+ if i+1 < len(fields) {
+ // Commas aren't escaped, and def is always last.
+ p.Default += "," + strings.Join(fields[i+1:], ",")
+ break outer
+ }
+ case strings.HasPrefix(f, "embedded="):
+ p.OrigName = strings.Split(f, "=")[1]
+ case strings.HasPrefix(f, "customtype="):
+ p.CustomType = strings.Split(f, "=")[1]
+ case strings.HasPrefix(f, "casttype="):
+ p.CastType = strings.Split(f, "=")[1]
+ case f == "stdtime":
+ p.StdTime = true
+ case f == "stdduration":
+ p.StdDuration = true
+ case f == "wktptr":
+ p.WktPointer = true
+ }
+ }
+}
+
+var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
+
+// setFieldProps initializes the field properties for submessages and maps.
+func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
+ isMap := typ.Kind() == reflect.Map
+ if len(p.CustomType) > 0 && !isMap {
+ p.ctype = typ
+ p.setTag(lockGetProp)
+ return
+ }
+ if p.StdTime && !isMap {
+ p.setTag(lockGetProp)
+ return
+ }
+ if p.StdDuration && !isMap {
+ p.setTag(lockGetProp)
+ return
+ }
+ if p.WktPointer && !isMap {
+ p.setTag(lockGetProp)
+ return
+ }
+ switch t1 := typ; t1.Kind() {
+ case reflect.Struct:
+ p.stype = typ
+ case reflect.Ptr:
+ if t1.Elem().Kind() == reflect.Struct {
+ p.stype = t1.Elem()
+ }
+ case reflect.Slice:
+ switch t2 := t1.Elem(); t2.Kind() {
+ case reflect.Ptr:
+ switch t3 := t2.Elem(); t3.Kind() {
+ case reflect.Struct:
+ p.stype = t3
+ }
+ case reflect.Struct:
+ p.stype = t2
+ }
+
+ case reflect.Map:
+
+ p.mtype = t1
+ p.MapKeyProp = &Properties{}
+ p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
+ p.MapValProp = &Properties{}
+ vtype := p.mtype.Elem()
+ if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
+ // The value type is not a message (*T) or bytes ([]byte),
+ // so we need encoders for the pointer to this type.
+ vtype = reflect.PtrTo(vtype)
+ }
+
+ p.MapValProp.CustomType = p.CustomType
+ p.MapValProp.StdDuration = p.StdDuration
+ p.MapValProp.StdTime = p.StdTime
+ p.MapValProp.WktPointer = p.WktPointer
+ p.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
+ }
+ p.setTag(lockGetProp)
+}
+
+func (p *Properties) setTag(lockGetProp bool) {
+ if p.stype != nil {
+ if lockGetProp {
+ p.sprop = GetProperties(p.stype)
+ } else {
+ p.sprop = getPropertiesLocked(p.stype)
+ }
+ }
+}
+
+var (
+ marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
+)
+
+// Init populates the properties from a protocol buffer struct tag.
+func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
+ p.init(typ, name, tag, f, true)
+}
+
+func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
+ // "bytes,49,opt,def=hello!"
+ p.Name = name
+ p.OrigName = name
+ if tag == "" {
+ return
+ }
+ p.Parse(tag)
+ p.setFieldProps(typ, f, lockGetProp)
+}
+
+var (
+ propertiesMu sync.RWMutex
+ propertiesMap = make(map[reflect.Type]*StructProperties)
+)
+
+// GetProperties returns the list of properties for the type represented by t.
+// t must represent a generated struct type of a protocol message.
+func GetProperties(t reflect.Type) *StructProperties {
+ if t.Kind() != reflect.Struct {
+ panic("proto: type must have kind struct")
+ }
+
+ // Most calls to GetProperties in a long-running program will be
+ // retrieving details for types we have seen before.
+ propertiesMu.RLock()
+ sprop, ok := propertiesMap[t]
+ propertiesMu.RUnlock()
+ if ok {
+ return sprop
+ }
+
+ propertiesMu.Lock()
+ sprop = getPropertiesLocked(t)
+ propertiesMu.Unlock()
+ return sprop
+}
+
+type (
+ oneofFuncsIface interface {
+ XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
+ }
+ oneofWrappersIface interface {
+ XXX_OneofWrappers() []interface{}
+ }
+)
+
+// getPropertiesLocked requires that propertiesMu is held.
+func getPropertiesLocked(t reflect.Type) *StructProperties {
+ if prop, ok := propertiesMap[t]; ok {
+ return prop
+ }
+
+ prop := new(StructProperties)
+ // in case of recursive protos, fill this in now.
+ propertiesMap[t] = prop
+
+ // build properties
+ prop.Prop = make([]*Properties, t.NumField())
+ prop.order = make([]int, t.NumField())
+
+ isOneofMessage := false
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ p := new(Properties)
+ name := f.Name
+ p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
+
+ oneof := f.Tag.Get("protobuf_oneof") // special case
+ if oneof != "" {
+ isOneofMessage = true
+ // Oneof fields don't use the traditional protobuf tag.
+ p.OrigName = oneof
+ }
+ prop.Prop[i] = p
+ prop.order[i] = i
+ if debug {
+ print(i, " ", f.Name, " ", t.String(), " ")
+ if p.Tag > 0 {
+ print(p.String())
+ }
+ print("\n")
+ }
+ }
+
+ // Re-order prop.order.
+ sort.Sort(prop)
+
+ if isOneofMessage {
+ var oots []interface{}
+ switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
+ case oneofFuncsIface:
+ _, _, _, oots = m.XXX_OneofFuncs()
+ case oneofWrappersIface:
+ oots = m.XXX_OneofWrappers()
+ }
+ if len(oots) > 0 {
+ // Interpret oneof metadata.
+ prop.OneofTypes = make(map[string]*OneofProperties)
+ for _, oot := range oots {
+ oop := &OneofProperties{
+ Type: reflect.ValueOf(oot).Type(), // *T
+ Prop: new(Properties),
+ }
+ sft := oop.Type.Elem().Field(0)
+ oop.Prop.Name = sft.Name
+ oop.Prop.Parse(sft.Tag.Get("protobuf"))
+ // There will be exactly one interface field that
+ // this new value is assignable to.
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ if f.Type.Kind() != reflect.Interface {
+ continue
+ }
+ if !oop.Type.AssignableTo(f.Type) {
+ continue
+ }
+ oop.Field = i
+ break
+ }
+ prop.OneofTypes[oop.Prop.OrigName] = oop
+ }
+ }
+ }
+
+ // build required counts
+ // build tags
+ reqCount := 0
+ prop.decoderOrigNames = make(map[string]int)
+ for i, p := range prop.Prop {
+ if strings.HasPrefix(p.Name, "XXX_") {
+ // Internal fields should not appear in tags/origNames maps.
+ // They are handled specially when encoding and decoding.
+ continue
+ }
+ if p.Required {
+ reqCount++
+ }
+ prop.decoderTags.put(p.Tag, i)
+ prop.decoderOrigNames[p.OrigName] = i
+ }
+ prop.reqCount = reqCount
+
+ return prop
+}
+
+// A global registry of enum types.
+// The generated code will register the generated maps by calling RegisterEnum.
+
+var enumValueMaps = make(map[string]map[string]int32)
+var enumStringMaps = make(map[string]map[int32]string)
+
+// RegisterEnum is called from the generated code to install the enum descriptor
+// maps into the global table to aid parsing text format protocol buffers.
+func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
+ if _, ok := enumValueMaps[typeName]; ok {
+ panic("proto: duplicate enum registered: " + typeName)
+ }
+ enumValueMaps[typeName] = valueMap
+ if _, ok := enumStringMaps[typeName]; ok {
+ panic("proto: duplicate enum registered: " + typeName)
+ }
+ enumStringMaps[typeName] = unusedNameMap
+}
+
+// EnumValueMap returns the mapping from names to integers of the
+// enum type enumType, or a nil if not found.
+func EnumValueMap(enumType string) map[string]int32 {
+ return enumValueMaps[enumType]
+}
+
+// A registry of all linked message types.
+// The string is a fully-qualified proto name ("pkg.Message").
+var (
+ protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers
+ protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types
+ revProtoTypes = make(map[reflect.Type]string)
+)
+
+// RegisterType is called from generated code and maps from the fully qualified
+// proto name to the type (pointer to struct) of the protocol buffer.
+func RegisterType(x Message, name string) {
+ if _, ok := protoTypedNils[name]; ok {
+ // TODO: Some day, make this a panic.
+ log.Printf("proto: duplicate proto type registered: %s", name)
+ return
+ }
+ t := reflect.TypeOf(x)
+ if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 {
+ // Generated code always calls RegisterType with nil x.
+ // This check is just for extra safety.
+ protoTypedNils[name] = x
+ } else {
+ protoTypedNils[name] = reflect.Zero(t).Interface().(Message)
+ }
+ revProtoTypes[t] = name
+}
+
+// RegisterMapType is called from generated code and maps from the fully qualified
+// proto name to the native map type of the proto map definition.
+func RegisterMapType(x interface{}, name string) {
+ if reflect.TypeOf(x).Kind() != reflect.Map {
+ panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name))
+ }
+ if _, ok := protoMapTypes[name]; ok {
+ log.Printf("proto: duplicate proto type registered: %s", name)
+ return
+ }
+ t := reflect.TypeOf(x)
+ protoMapTypes[name] = t
+ revProtoTypes[t] = name
+}
+
+// MessageName returns the fully-qualified proto name for the given message type.
+func MessageName(x Message) string {
+ type xname interface {
+ XXX_MessageName() string
+ }
+ if m, ok := x.(xname); ok {
+ return m.XXX_MessageName()
+ }
+ return revProtoTypes[reflect.TypeOf(x)]
+}
+
+// MessageType returns the message type (pointer to struct) for a named message.
+// The type is not guaranteed to implement proto.Message if the name refers to a
+// map entry.
+func MessageType(name string) reflect.Type {
+ if t, ok := protoTypedNils[name]; ok {
+ return reflect.TypeOf(t)
+ }
+ return protoMapTypes[name]
+}
+
+// A registry of all linked proto files.
+var (
+ protoFiles = make(map[string][]byte) // file name => fileDescriptor
+)
+
+// RegisterFile is called from generated code and maps from the
+// full file name of a .proto file to its compressed FileDescriptorProto.
+func RegisterFile(filename string, fileDescriptor []byte) {
+ protoFiles[filename] = fileDescriptor
+}
+
+// FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
+func FileDescriptor(filename string) []byte { return protoFiles[filename] }
diff --git a/vendor/github.com/gogo/protobuf/proto/properties_gogo.go b/vendor/github.com/gogo/protobuf/proto/properties_gogo.go
@@ -0,0 +1,36 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2018, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import (
+ "reflect"
+)
+
+var sizerType = reflect.TypeOf((*Sizer)(nil)).Elem()
+var protosizerType = reflect.TypeOf((*ProtoSizer)(nil)).Elem()
diff --git a/vendor/github.com/gogo/protobuf/proto/skip_gogo.go b/vendor/github.com/gogo/protobuf/proto/skip_gogo.go
@@ -0,0 +1,119 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import (
+ "fmt"
+ "io"
+)
+
+func Skip(data []byte) (n int, err error) {
+ l := len(data)
+ index := 0
+ for index < l {
+ var wire uint64
+ for shift := uint(0); ; shift += 7 {
+ if index >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[index]
+ index++
+ wire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ wireType := int(wire & 0x7)
+ switch wireType {
+ case 0:
+ for {
+ if index >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ index++
+ if data[index-1] < 0x80 {
+ break
+ }
+ }
+ return index, nil
+ case 1:
+ index += 8
+ return index, nil
+ case 2:
+ var length int
+ for shift := uint(0); ; shift += 7 {
+ if index >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[index]
+ index++
+ length |= (int(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ index += length
+ return index, nil
+ case 3:
+ for {
+ var innerWire uint64
+ var start int = index
+ for shift := uint(0); ; shift += 7 {
+ if index >= l {
+ return 0, io.ErrUnexpectedEOF
+ }
+ b := data[index]
+ index++
+ innerWire |= (uint64(b) & 0x7F) << shift
+ if b < 0x80 {
+ break
+ }
+ }
+ innerWireType := int(innerWire & 0x7)
+ if innerWireType == 4 {
+ break
+ }
+ next, err := Skip(data[start:])
+ if err != nil {
+ return 0, err
+ }
+ index = start + next
+ }
+ return index, nil
+ case 4:
+ return index, nil
+ case 5:
+ index += 4
+ return index, nil
+ default:
+ return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
+ }
+ }
+ panic("unreachable")
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/table_marshal.go b/vendor/github.com/gogo/protobuf/proto/table_marshal.go
@@ -0,0 +1,3009 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "unicode/utf8"
+)
+
+// a sizer takes a pointer to a field and the size of its tag, computes the size of
+// the encoded data.
+type sizer func(pointer, int) int
+
+// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format),
+// marshals the field to the end of the slice, returns the slice and error (if any).
+type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error)
+
+// marshalInfo is the information used for marshaling a message.
+type marshalInfo struct {
+ typ reflect.Type
+ fields []*marshalFieldInfo
+ unrecognized field // offset of XXX_unrecognized
+ extensions field // offset of XXX_InternalExtensions
+ v1extensions field // offset of XXX_extensions
+ sizecache field // offset of XXX_sizecache
+ initialized int32 // 0 -- only typ is set, 1 -- fully initialized
+ messageset bool // uses message set wire format
+ hasmarshaler bool // has custom marshaler
+ sync.RWMutex // protect extElems map, also for initialization
+ extElems map[int32]*marshalElemInfo // info of extension elements
+
+ hassizer bool // has custom sizer
+ hasprotosizer bool // has custom protosizer
+
+ bytesExtensions field // offset of XXX_extensions where the field type is []byte
+}
+
+// marshalFieldInfo is the information used for marshaling a field of a message.
+type marshalFieldInfo struct {
+ field field
+ wiretag uint64 // tag in wire format
+ tagsize int // size of tag in wire format
+ sizer sizer
+ marshaler marshaler
+ isPointer bool
+ required bool // field is required
+ name string // name of the field, for error reporting
+ oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements
+}
+
+// marshalElemInfo is the information used for marshaling an extension or oneof element.
+type marshalElemInfo struct {
+ wiretag uint64 // tag in wire format
+ tagsize int // size of tag in wire format
+ sizer sizer
+ marshaler marshaler
+ isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only)
+}
+
+var (
+ marshalInfoMap = map[reflect.Type]*marshalInfo{}
+ marshalInfoLock sync.Mutex
+
+ uint8SliceType = reflect.TypeOf(([]uint8)(nil)).Kind()
+)
+
+// getMarshalInfo returns the information to marshal a given type of message.
+// The info it returns may not necessarily initialized.
+// t is the type of the message (NOT the pointer to it).
+func getMarshalInfo(t reflect.Type) *marshalInfo {
+ marshalInfoLock.Lock()
+ u, ok := marshalInfoMap[t]
+ if !ok {
+ u = &marshalInfo{typ: t}
+ marshalInfoMap[t] = u
+ }
+ marshalInfoLock.Unlock()
+ return u
+}
+
+// Size is the entry point from generated code,
+// and should be ONLY called by generated code.
+// It computes the size of encoded data of msg.
+// a is a pointer to a place to store cached marshal info.
+func (a *InternalMessageInfo) Size(msg Message) int {
+ u := getMessageMarshalInfo(msg, a)
+ ptr := toPointer(&msg)
+ if ptr.isNil() {
+ // We get here if msg is a typed nil ((*SomeMessage)(nil)),
+ // so it satisfies the interface, and msg == nil wouldn't
+ // catch it. We don't want crash in this case.
+ return 0
+ }
+ return u.size(ptr)
+}
+
+// Marshal is the entry point from generated code,
+// and should be ONLY called by generated code.
+// It marshals msg to the end of b.
+// a is a pointer to a place to store cached marshal info.
+func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) {
+ u := getMessageMarshalInfo(msg, a)
+ ptr := toPointer(&msg)
+ if ptr.isNil() {
+ // We get here if msg is a typed nil ((*SomeMessage)(nil)),
+ // so it satisfies the interface, and msg == nil wouldn't
+ // catch it. We don't want crash in this case.
+ return b, ErrNil
+ }
+ return u.marshal(b, ptr, deterministic)
+}
+
+func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo {
+ // u := a.marshal, but atomically.
+ // We use an atomic here to ensure memory consistency.
+ u := atomicLoadMarshalInfo(&a.marshal)
+ if u == nil {
+ // Get marshal information from type of message.
+ t := reflect.ValueOf(msg).Type()
+ if t.Kind() != reflect.Ptr {
+ panic(fmt.Sprintf("cannot handle non-pointer message type %v", t))
+ }
+ u = getMarshalInfo(t.Elem())
+ // Store it in the cache for later users.
+ // a.marshal = u, but atomically.
+ atomicStoreMarshalInfo(&a.marshal, u)
+ }
+ return u
+}
+
+// size is the main function to compute the size of the encoded data of a message.
+// ptr is the pointer to the message.
+func (u *marshalInfo) size(ptr pointer) int {
+ if atomic.LoadInt32(&u.initialized) == 0 {
+ u.computeMarshalInfo()
+ }
+
+ // If the message can marshal itself, let it do it, for compatibility.
+ // NOTE: This is not efficient.
+ if u.hasmarshaler {
+ // Uses the message's Size method if available
+ if u.hassizer {
+ s := ptr.asPointerTo(u.typ).Interface().(Sizer)
+ return s.Size()
+ }
+ // Uses the message's ProtoSize method if available
+ if u.hasprotosizer {
+ s := ptr.asPointerTo(u.typ).Interface().(ProtoSizer)
+ return s.ProtoSize()
+ }
+
+ m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
+ b, _ := m.Marshal()
+ return len(b)
+ }
+
+ n := 0
+ for _, f := range u.fields {
+ if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
+ // nil pointer always marshals to nothing
+ continue
+ }
+ n += f.sizer(ptr.offset(f.field), f.tagsize)
+ }
+ if u.extensions.IsValid() {
+ e := ptr.offset(u.extensions).toExtensions()
+ if u.messageset {
+ n += u.sizeMessageSet(e)
+ } else {
+ n += u.sizeExtensions(e)
+ }
+ }
+ if u.v1extensions.IsValid() {
+ m := *ptr.offset(u.v1extensions).toOldExtensions()
+ n += u.sizeV1Extensions(m)
+ }
+ if u.bytesExtensions.IsValid() {
+ s := *ptr.offset(u.bytesExtensions).toBytes()
+ n += len(s)
+ }
+ if u.unrecognized.IsValid() {
+ s := *ptr.offset(u.unrecognized).toBytes()
+ n += len(s)
+ }
+
+ // cache the result for use in marshal
+ if u.sizecache.IsValid() {
+ atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n))
+ }
+ return n
+}
+
+// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated),
+// fall back to compute the size.
+func (u *marshalInfo) cachedsize(ptr pointer) int {
+ if u.sizecache.IsValid() {
+ return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32()))
+ }
+ return u.size(ptr)
+}
+
+// marshal is the main function to marshal a message. It takes a byte slice and appends
+// the encoded data to the end of the slice, returns the slice and error (if any).
+// ptr is the pointer to the message.
+// If deterministic is true, map is marshaled in deterministic order.
+func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) {
+ if atomic.LoadInt32(&u.initialized) == 0 {
+ u.computeMarshalInfo()
+ }
+
+ // If the message can marshal itself, let it do it, for compatibility.
+ // NOTE: This is not efficient.
+ if u.hasmarshaler {
+ m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
+ b1, err := m.Marshal()
+ b = append(b, b1...)
+ return b, err
+ }
+
+ var err, errLater error
+ // The old marshaler encodes extensions at beginning.
+ if u.extensions.IsValid() {
+ e := ptr.offset(u.extensions).toExtensions()
+ if u.messageset {
+ b, err = u.appendMessageSet(b, e, deterministic)
+ } else {
+ b, err = u.appendExtensions(b, e, deterministic)
+ }
+ if err != nil {
+ return b, err
+ }
+ }
+ if u.v1extensions.IsValid() {
+ m := *ptr.offset(u.v1extensions).toOldExtensions()
+ b, err = u.appendV1Extensions(b, m, deterministic)
+ if err != nil {
+ return b, err
+ }
+ }
+ if u.bytesExtensions.IsValid() {
+ s := *ptr.offset(u.bytesExtensions).toBytes()
+ b = append(b, s...)
+ }
+ for _, f := range u.fields {
+ if f.required {
+ if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
+ // Required field is not set.
+ // We record the error but keep going, to give a complete marshaling.
+ if errLater == nil {
+ errLater = &RequiredNotSetError{f.name}
+ }
+ continue
+ }
+ }
+ if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
+ // nil pointer always marshals to nothing
+ continue
+ }
+ b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic)
+ if err != nil {
+ if err1, ok := err.(*RequiredNotSetError); ok {
+ // Required field in submessage is not set.
+ // We record the error but keep going, to give a complete marshaling.
+ if errLater == nil {
+ errLater = &RequiredNotSetError{f.name + "." + err1.field}
+ }
+ continue
+ }
+ if err == errRepeatedHasNil {
+ err = errors.New("proto: repeated field " + f.name + " has nil element")
+ }
+ if err == errInvalidUTF8 {
+ if errLater == nil {
+ fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
+ errLater = &invalidUTF8Error{fullName}
+ }
+ continue
+ }
+ return b, err
+ }
+ }
+ if u.unrecognized.IsValid() {
+ s := *ptr.offset(u.unrecognized).toBytes()
+ b = append(b, s...)
+ }
+ return b, errLater
+}
+
+// computeMarshalInfo initializes the marshal info.
+func (u *marshalInfo) computeMarshalInfo() {
+ u.Lock()
+ defer u.Unlock()
+ if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock
+ return
+ }
+
+ t := u.typ
+ u.unrecognized = invalidField
+ u.extensions = invalidField
+ u.v1extensions = invalidField
+ u.bytesExtensions = invalidField
+ u.sizecache = invalidField
+ isOneofMessage := false
+
+ if reflect.PtrTo(t).Implements(sizerType) {
+ u.hassizer = true
+ }
+ if reflect.PtrTo(t).Implements(protosizerType) {
+ u.hasprotosizer = true
+ }
+ // If the message can marshal itself, let it do it, for compatibility.
+ // NOTE: This is not efficient.
+ if reflect.PtrTo(t).Implements(marshalerType) {
+ u.hasmarshaler = true
+ atomic.StoreInt32(&u.initialized, 1)
+ return
+ }
+
+ n := t.NumField()
+
+ // deal with XXX fields first
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ if f.Tag.Get("protobuf_oneof") != "" {
+ isOneofMessage = true
+ }
+ if !strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+ switch f.Name {
+ case "XXX_sizecache":
+ u.sizecache = toField(&f)
+ case "XXX_unrecognized":
+ u.unrecognized = toField(&f)
+ case "XXX_InternalExtensions":
+ u.extensions = toField(&f)
+ u.messageset = f.Tag.Get("protobuf_messageset") == "1"
+ case "XXX_extensions":
+ if f.Type.Kind() == reflect.Map {
+ u.v1extensions = toField(&f)
+ } else {
+ u.bytesExtensions = toField(&f)
+ }
+ case "XXX_NoUnkeyedLiteral":
+ // nothing to do
+ default:
+ panic("unknown XXX field: " + f.Name)
+ }
+ n--
+ }
+
+ // get oneof implementers
+ var oneofImplementers []interface{}
+ // gogo: isOneofMessage is needed for embedded oneof messages, without a marshaler and unmarshaler
+ if isOneofMessage {
+ switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
+ case oneofFuncsIface:
+ _, _, _, oneofImplementers = m.XXX_OneofFuncs()
+ case oneofWrappersIface:
+ oneofImplementers = m.XXX_OneofWrappers()
+ }
+ }
+
+ // normal fields
+ fields := make([]marshalFieldInfo, n) // batch allocation
+ u.fields = make([]*marshalFieldInfo, 0, n)
+ for i, j := 0, 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+
+ if strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+ field := &fields[j]
+ j++
+ field.name = f.Name
+ u.fields = append(u.fields, field)
+ if f.Tag.Get("protobuf_oneof") != "" {
+ field.computeOneofFieldInfo(&f, oneofImplementers)
+ continue
+ }
+ if f.Tag.Get("protobuf") == "" {
+ // field has no tag (not in generated message), ignore it
+ u.fields = u.fields[:len(u.fields)-1]
+ j--
+ continue
+ }
+ field.computeMarshalFieldInfo(&f)
+ }
+
+ // fields are marshaled in tag order on the wire.
+ sort.Sort(byTag(u.fields))
+
+ atomic.StoreInt32(&u.initialized, 1)
+}
+
+// helper for sorting fields by tag
+type byTag []*marshalFieldInfo
+
+func (a byTag) Len() int { return len(a) }
+func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
+func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag }
+
+// getExtElemInfo returns the information to marshal an extension element.
+// The info it returns is initialized.
+func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo {
+ // get from cache first
+ u.RLock()
+ e, ok := u.extElems[desc.Field]
+ u.RUnlock()
+ if ok {
+ return e
+ }
+
+ t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct
+ tags := strings.Split(desc.Tag, ",")
+ tag, err := strconv.Atoi(tags[1])
+ if err != nil {
+ panic("tag is not an integer")
+ }
+ wt := wiretype(tags[0])
+ sizr, marshalr := typeMarshaler(t, tags, false, false)
+ e = &marshalElemInfo{
+ wiretag: uint64(tag)<<3 | wt,
+ tagsize: SizeVarint(uint64(tag) << 3),
+ sizer: sizr,
+ marshaler: marshalr,
+ isptr: t.Kind() == reflect.Ptr,
+ }
+
+ // update cache
+ u.Lock()
+ if u.extElems == nil {
+ u.extElems = make(map[int32]*marshalElemInfo)
+ }
+ u.extElems[desc.Field] = e
+ u.Unlock()
+ return e
+}
+
+// computeMarshalFieldInfo fills up the information to marshal a field.
+func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) {
+ // parse protobuf tag of the field.
+ // tag has format of "bytes,49,opt,name=foo,def=hello!"
+ tags := strings.Split(f.Tag.Get("protobuf"), ",")
+ if tags[0] == "" {
+ return
+ }
+ tag, err := strconv.Atoi(tags[1])
+ if err != nil {
+ panic("tag is not an integer")
+ }
+ wt := wiretype(tags[0])
+ if tags[2] == "req" {
+ fi.required = true
+ }
+ fi.setTag(f, tag, wt)
+ fi.setMarshaler(f, tags)
+}
+
+func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) {
+ fi.field = toField(f)
+ fi.wiretag = math.MaxInt32 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire.
+ fi.isPointer = true
+ fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f)
+ fi.oneofElems = make(map[reflect.Type]*marshalElemInfo)
+
+ ityp := f.Type // interface type
+ for _, o := range oneofImplementers {
+ t := reflect.TypeOf(o)
+ if !t.Implements(ityp) {
+ continue
+ }
+ sf := t.Elem().Field(0) // oneof implementer is a struct with a single field
+ tags := strings.Split(sf.Tag.Get("protobuf"), ",")
+ tag, err := strconv.Atoi(tags[1])
+ if err != nil {
+ panic("tag is not an integer")
+ }
+ wt := wiretype(tags[0])
+ sizr, marshalr := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value
+ fi.oneofElems[t.Elem()] = &marshalElemInfo{
+ wiretag: uint64(tag)<<3 | wt,
+ tagsize: SizeVarint(uint64(tag) << 3),
+ sizer: sizr,
+ marshaler: marshalr,
+ }
+ }
+}
+
+// wiretype returns the wire encoding of the type.
+func wiretype(encoding string) uint64 {
+ switch encoding {
+ case "fixed32":
+ return WireFixed32
+ case "fixed64":
+ return WireFixed64
+ case "varint", "zigzag32", "zigzag64":
+ return WireVarint
+ case "bytes":
+ return WireBytes
+ case "group":
+ return WireStartGroup
+ }
+ panic("unknown wire type " + encoding)
+}
+
+// setTag fills up the tag (in wire format) and its size in the info of a field.
+func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) {
+ fi.field = toField(f)
+ fi.wiretag = uint64(tag)<<3 | wt
+ fi.tagsize = SizeVarint(uint64(tag) << 3)
+}
+
+// setMarshaler fills up the sizer and marshaler in the info of a field.
+func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) {
+ switch f.Type.Kind() {
+ case reflect.Map:
+ // map field
+ fi.isPointer = true
+ fi.sizer, fi.marshaler = makeMapMarshaler(f)
+ return
+ case reflect.Ptr, reflect.Slice:
+ fi.isPointer = true
+ }
+ fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false)
+}
+
+// typeMarshaler returns the sizer and marshaler of a given field.
+// t is the type of the field.
+// tags is the generated "protobuf" tag of the field.
+// If nozero is true, zero value is not marshaled to the wire.
+// If oneof is true, it is a oneof field.
+func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) {
+ encoding := tags[0]
+
+ pointer := false
+ slice := false
+ if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
+ slice = true
+ t = t.Elem()
+ }
+ if t.Kind() == reflect.Ptr {
+ pointer = true
+ t = t.Elem()
+ }
+
+ packed := false
+ proto3 := false
+ ctype := false
+ isTime := false
+ isDuration := false
+ isWktPointer := false
+ validateUTF8 := true
+ for i := 2; i < len(tags); i++ {
+ if tags[i] == "packed" {
+ packed = true
+ }
+ if tags[i] == "proto3" {
+ proto3 = true
+ }
+ if strings.HasPrefix(tags[i], "customtype=") {
+ ctype = true
+ }
+ if tags[i] == "stdtime" {
+ isTime = true
+ }
+ if tags[i] == "stdduration" {
+ isDuration = true
+ }
+ if tags[i] == "wktptr" {
+ isWktPointer = true
+ }
+ }
+ validateUTF8 = validateUTF8 && proto3
+ if !proto3 && !pointer && !slice {
+ nozero = false
+ }
+
+ if ctype {
+ if reflect.PtrTo(t).Implements(customType) {
+ if slice {
+ return makeMessageRefSliceMarshaler(getMarshalInfo(t))
+ }
+ if pointer {
+ return makeCustomPtrMarshaler(getMarshalInfo(t))
+ }
+ return makeCustomMarshaler(getMarshalInfo(t))
+ } else {
+ panic(fmt.Sprintf("custom type: type: %v, does not implement the proto.custom interface", t))
+ }
+ }
+
+ if isTime {
+ if pointer {
+ if slice {
+ return makeTimePtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeTimePtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeTimeSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeTimeMarshaler(getMarshalInfo(t))
+ }
+
+ if isDuration {
+ if pointer {
+ if slice {
+ return makeDurationPtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeDurationPtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeDurationSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeDurationMarshaler(getMarshalInfo(t))
+ }
+
+ if isWktPointer {
+ switch t.Kind() {
+ case reflect.Float64:
+ if pointer {
+ if slice {
+ return makeStdDoubleValuePtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdDoubleValuePtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeStdDoubleValueSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdDoubleValueMarshaler(getMarshalInfo(t))
+ case reflect.Float32:
+ if pointer {
+ if slice {
+ return makeStdFloatValuePtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdFloatValuePtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeStdFloatValueSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdFloatValueMarshaler(getMarshalInfo(t))
+ case reflect.Int64:
+ if pointer {
+ if slice {
+ return makeStdInt64ValuePtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdInt64ValuePtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeStdInt64ValueSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdInt64ValueMarshaler(getMarshalInfo(t))
+ case reflect.Uint64:
+ if pointer {
+ if slice {
+ return makeStdUInt64ValuePtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdUInt64ValuePtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeStdUInt64ValueSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdUInt64ValueMarshaler(getMarshalInfo(t))
+ case reflect.Int32:
+ if pointer {
+ if slice {
+ return makeStdInt32ValuePtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdInt32ValuePtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeStdInt32ValueSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdInt32ValueMarshaler(getMarshalInfo(t))
+ case reflect.Uint32:
+ if pointer {
+ if slice {
+ return makeStdUInt32ValuePtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdUInt32ValuePtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeStdUInt32ValueSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdUInt32ValueMarshaler(getMarshalInfo(t))
+ case reflect.Bool:
+ if pointer {
+ if slice {
+ return makeStdBoolValuePtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdBoolValuePtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeStdBoolValueSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdBoolValueMarshaler(getMarshalInfo(t))
+ case reflect.String:
+ if pointer {
+ if slice {
+ return makeStdStringValuePtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdStringValuePtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeStdStringValueSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdStringValueMarshaler(getMarshalInfo(t))
+ case uint8SliceType:
+ if pointer {
+ if slice {
+ return makeStdBytesValuePtrSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdBytesValuePtrMarshaler(getMarshalInfo(t))
+ }
+ if slice {
+ return makeStdBytesValueSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeStdBytesValueMarshaler(getMarshalInfo(t))
+ default:
+ panic(fmt.Sprintf("unknown wktpointer type %#v", t))
+ }
+ }
+
+ switch t.Kind() {
+ case reflect.Bool:
+ if pointer {
+ return sizeBoolPtr, appendBoolPtr
+ }
+ if slice {
+ if packed {
+ return sizeBoolPackedSlice, appendBoolPackedSlice
+ }
+ return sizeBoolSlice, appendBoolSlice
+ }
+ if nozero {
+ return sizeBoolValueNoZero, appendBoolValueNoZero
+ }
+ return sizeBoolValue, appendBoolValue
+ case reflect.Uint32:
+ switch encoding {
+ case "fixed32":
+ if pointer {
+ return sizeFixed32Ptr, appendFixed32Ptr
+ }
+ if slice {
+ if packed {
+ return sizeFixed32PackedSlice, appendFixed32PackedSlice
+ }
+ return sizeFixed32Slice, appendFixed32Slice
+ }
+ if nozero {
+ return sizeFixed32ValueNoZero, appendFixed32ValueNoZero
+ }
+ return sizeFixed32Value, appendFixed32Value
+ case "varint":
+ if pointer {
+ return sizeVarint32Ptr, appendVarint32Ptr
+ }
+ if slice {
+ if packed {
+ return sizeVarint32PackedSlice, appendVarint32PackedSlice
+ }
+ return sizeVarint32Slice, appendVarint32Slice
+ }
+ if nozero {
+ return sizeVarint32ValueNoZero, appendVarint32ValueNoZero
+ }
+ return sizeVarint32Value, appendVarint32Value
+ }
+ case reflect.Int32:
+ switch encoding {
+ case "fixed32":
+ if pointer {
+ return sizeFixedS32Ptr, appendFixedS32Ptr
+ }
+ if slice {
+ if packed {
+ return sizeFixedS32PackedSlice, appendFixedS32PackedSlice
+ }
+ return sizeFixedS32Slice, appendFixedS32Slice
+ }
+ if nozero {
+ return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero
+ }
+ return sizeFixedS32Value, appendFixedS32Value
+ case "varint":
+ if pointer {
+ return sizeVarintS32Ptr, appendVarintS32Ptr
+ }
+ if slice {
+ if packed {
+ return sizeVarintS32PackedSlice, appendVarintS32PackedSlice
+ }
+ return sizeVarintS32Slice, appendVarintS32Slice
+ }
+ if nozero {
+ return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero
+ }
+ return sizeVarintS32Value, appendVarintS32Value
+ case "zigzag32":
+ if pointer {
+ return sizeZigzag32Ptr, appendZigzag32Ptr
+ }
+ if slice {
+ if packed {
+ return sizeZigzag32PackedSlice, appendZigzag32PackedSlice
+ }
+ return sizeZigzag32Slice, appendZigzag32Slice
+ }
+ if nozero {
+ return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero
+ }
+ return sizeZigzag32Value, appendZigzag32Value
+ }
+ case reflect.Uint64:
+ switch encoding {
+ case "fixed64":
+ if pointer {
+ return sizeFixed64Ptr, appendFixed64Ptr
+ }
+ if slice {
+ if packed {
+ return sizeFixed64PackedSlice, appendFixed64PackedSlice
+ }
+ return sizeFixed64Slice, appendFixed64Slice
+ }
+ if nozero {
+ return sizeFixed64ValueNoZero, appendFixed64ValueNoZero
+ }
+ return sizeFixed64Value, appendFixed64Value
+ case "varint":
+ if pointer {
+ return sizeVarint64Ptr, appendVarint64Ptr
+ }
+ if slice {
+ if packed {
+ return sizeVarint64PackedSlice, appendVarint64PackedSlice
+ }
+ return sizeVarint64Slice, appendVarint64Slice
+ }
+ if nozero {
+ return sizeVarint64ValueNoZero, appendVarint64ValueNoZero
+ }
+ return sizeVarint64Value, appendVarint64Value
+ }
+ case reflect.Int64:
+ switch encoding {
+ case "fixed64":
+ if pointer {
+ return sizeFixedS64Ptr, appendFixedS64Ptr
+ }
+ if slice {
+ if packed {
+ return sizeFixedS64PackedSlice, appendFixedS64PackedSlice
+ }
+ return sizeFixedS64Slice, appendFixedS64Slice
+ }
+ if nozero {
+ return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero
+ }
+ return sizeFixedS64Value, appendFixedS64Value
+ case "varint":
+ if pointer {
+ return sizeVarintS64Ptr, appendVarintS64Ptr
+ }
+ if slice {
+ if packed {
+ return sizeVarintS64PackedSlice, appendVarintS64PackedSlice
+ }
+ return sizeVarintS64Slice, appendVarintS64Slice
+ }
+ if nozero {
+ return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero
+ }
+ return sizeVarintS64Value, appendVarintS64Value
+ case "zigzag64":
+ if pointer {
+ return sizeZigzag64Ptr, appendZigzag64Ptr
+ }
+ if slice {
+ if packed {
+ return sizeZigzag64PackedSlice, appendZigzag64PackedSlice
+ }
+ return sizeZigzag64Slice, appendZigzag64Slice
+ }
+ if nozero {
+ return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero
+ }
+ return sizeZigzag64Value, appendZigzag64Value
+ }
+ case reflect.Float32:
+ if pointer {
+ return sizeFloat32Ptr, appendFloat32Ptr
+ }
+ if slice {
+ if packed {
+ return sizeFloat32PackedSlice, appendFloat32PackedSlice
+ }
+ return sizeFloat32Slice, appendFloat32Slice
+ }
+ if nozero {
+ return sizeFloat32ValueNoZero, appendFloat32ValueNoZero
+ }
+ return sizeFloat32Value, appendFloat32Value
+ case reflect.Float64:
+ if pointer {
+ return sizeFloat64Ptr, appendFloat64Ptr
+ }
+ if slice {
+ if packed {
+ return sizeFloat64PackedSlice, appendFloat64PackedSlice
+ }
+ return sizeFloat64Slice, appendFloat64Slice
+ }
+ if nozero {
+ return sizeFloat64ValueNoZero, appendFloat64ValueNoZero
+ }
+ return sizeFloat64Value, appendFloat64Value
+ case reflect.String:
+ if validateUTF8 {
+ if pointer {
+ return sizeStringPtr, appendUTF8StringPtr
+ }
+ if slice {
+ return sizeStringSlice, appendUTF8StringSlice
+ }
+ if nozero {
+ return sizeStringValueNoZero, appendUTF8StringValueNoZero
+ }
+ return sizeStringValue, appendUTF8StringValue
+ }
+ if pointer {
+ return sizeStringPtr, appendStringPtr
+ }
+ if slice {
+ return sizeStringSlice, appendStringSlice
+ }
+ if nozero {
+ return sizeStringValueNoZero, appendStringValueNoZero
+ }
+ return sizeStringValue, appendStringValue
+ case reflect.Slice:
+ if slice {
+ return sizeBytesSlice, appendBytesSlice
+ }
+ if oneof {
+ // Oneof bytes field may also have "proto3" tag.
+ // We want to marshal it as a oneof field. Do this
+ // check before the proto3 check.
+ return sizeBytesOneof, appendBytesOneof
+ }
+ if proto3 {
+ return sizeBytes3, appendBytes3
+ }
+ return sizeBytes, appendBytes
+ case reflect.Struct:
+ switch encoding {
+ case "group":
+ if slice {
+ return makeGroupSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeGroupMarshaler(getMarshalInfo(t))
+ case "bytes":
+ if pointer {
+ if slice {
+ return makeMessageSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeMessageMarshaler(getMarshalInfo(t))
+ } else {
+ if slice {
+ return makeMessageRefSliceMarshaler(getMarshalInfo(t))
+ }
+ return makeMessageRefMarshaler(getMarshalInfo(t))
+ }
+ }
+ }
+ panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding))
+}
+
+// Below are functions to size/marshal a specific type of a field.
+// They are stored in the field's info, and called by function pointers.
+// They have type sizer or marshaler.
+
+func sizeFixed32Value(_ pointer, tagsize int) int {
+ return 4 + tagsize
+}
+func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toUint32()
+ if v == 0 {
+ return 0
+ }
+ return 4 + tagsize
+}
+func sizeFixed32Ptr(ptr pointer, tagsize int) int {
+ p := *ptr.toUint32Ptr()
+ if p == nil {
+ return 0
+ }
+ return 4 + tagsize
+}
+func sizeFixed32Slice(ptr pointer, tagsize int) int {
+ s := *ptr.toUint32Slice()
+ return (4 + tagsize) * len(s)
+}
+func sizeFixed32PackedSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toUint32Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
+}
+func sizeFixedS32Value(_ pointer, tagsize int) int {
+ return 4 + tagsize
+}
+func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toInt32()
+ if v == 0 {
+ return 0
+ }
+ return 4 + tagsize
+}
+func sizeFixedS32Ptr(ptr pointer, tagsize int) int {
+ p := ptr.getInt32Ptr()
+ if p == nil {
+ return 0
+ }
+ return 4 + tagsize
+}
+func sizeFixedS32Slice(ptr pointer, tagsize int) int {
+ s := ptr.getInt32Slice()
+ return (4 + tagsize) * len(s)
+}
+func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int {
+ s := ptr.getInt32Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
+}
+func sizeFloat32Value(_ pointer, tagsize int) int {
+ return 4 + tagsize
+}
+func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int {
+ v := math.Float32bits(*ptr.toFloat32())
+ if v == 0 {
+ return 0
+ }
+ return 4 + tagsize
+}
+func sizeFloat32Ptr(ptr pointer, tagsize int) int {
+ p := *ptr.toFloat32Ptr()
+ if p == nil {
+ return 0
+ }
+ return 4 + tagsize
+}
+func sizeFloat32Slice(ptr pointer, tagsize int) int {
+ s := *ptr.toFloat32Slice()
+ return (4 + tagsize) * len(s)
+}
+func sizeFloat32PackedSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toFloat32Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
+}
+func sizeFixed64Value(_ pointer, tagsize int) int {
+ return 8 + tagsize
+}
+func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toUint64()
+ if v == 0 {
+ return 0
+ }
+ return 8 + tagsize
+}
+func sizeFixed64Ptr(ptr pointer, tagsize int) int {
+ p := *ptr.toUint64Ptr()
+ if p == nil {
+ return 0
+ }
+ return 8 + tagsize
+}
+func sizeFixed64Slice(ptr pointer, tagsize int) int {
+ s := *ptr.toUint64Slice()
+ return (8 + tagsize) * len(s)
+}
+func sizeFixed64PackedSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toUint64Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
+}
+func sizeFixedS64Value(_ pointer, tagsize int) int {
+ return 8 + tagsize
+}
+func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toInt64()
+ if v == 0 {
+ return 0
+ }
+ return 8 + tagsize
+}
+func sizeFixedS64Ptr(ptr pointer, tagsize int) int {
+ p := *ptr.toInt64Ptr()
+ if p == nil {
+ return 0
+ }
+ return 8 + tagsize
+}
+func sizeFixedS64Slice(ptr pointer, tagsize int) int {
+ s := *ptr.toInt64Slice()
+ return (8 + tagsize) * len(s)
+}
+func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toInt64Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
+}
+func sizeFloat64Value(_ pointer, tagsize int) int {
+ return 8 + tagsize
+}
+func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int {
+ v := math.Float64bits(*ptr.toFloat64())
+ if v == 0 {
+ return 0
+ }
+ return 8 + tagsize
+}
+func sizeFloat64Ptr(ptr pointer, tagsize int) int {
+ p := *ptr.toFloat64Ptr()
+ if p == nil {
+ return 0
+ }
+ return 8 + tagsize
+}
+func sizeFloat64Slice(ptr pointer, tagsize int) int {
+ s := *ptr.toFloat64Slice()
+ return (8 + tagsize) * len(s)
+}
+func sizeFloat64PackedSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toFloat64Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
+}
+func sizeVarint32Value(ptr pointer, tagsize int) int {
+ v := *ptr.toUint32()
+ return SizeVarint(uint64(v)) + tagsize
+}
+func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toUint32()
+ if v == 0 {
+ return 0
+ }
+ return SizeVarint(uint64(v)) + tagsize
+}
+func sizeVarint32Ptr(ptr pointer, tagsize int) int {
+ p := *ptr.toUint32Ptr()
+ if p == nil {
+ return 0
+ }
+ return SizeVarint(uint64(*p)) + tagsize
+}
+func sizeVarint32Slice(ptr pointer, tagsize int) int {
+ s := *ptr.toUint32Slice()
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v)) + tagsize
+ }
+ return n
+}
+func sizeVarint32PackedSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toUint32Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v))
+ }
+ return n + SizeVarint(uint64(n)) + tagsize
+}
+func sizeVarintS32Value(ptr pointer, tagsize int) int {
+ v := *ptr.toInt32()
+ return SizeVarint(uint64(v)) + tagsize
+}
+func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toInt32()
+ if v == 0 {
+ return 0
+ }
+ return SizeVarint(uint64(v)) + tagsize
+}
+func sizeVarintS32Ptr(ptr pointer, tagsize int) int {
+ p := ptr.getInt32Ptr()
+ if p == nil {
+ return 0
+ }
+ return SizeVarint(uint64(*p)) + tagsize
+}
+func sizeVarintS32Slice(ptr pointer, tagsize int) int {
+ s := ptr.getInt32Slice()
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v)) + tagsize
+ }
+ return n
+}
+func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int {
+ s := ptr.getInt32Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v))
+ }
+ return n + SizeVarint(uint64(n)) + tagsize
+}
+func sizeVarint64Value(ptr pointer, tagsize int) int {
+ v := *ptr.toUint64()
+ return SizeVarint(v) + tagsize
+}
+func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toUint64()
+ if v == 0 {
+ return 0
+ }
+ return SizeVarint(v) + tagsize
+}
+func sizeVarint64Ptr(ptr pointer, tagsize int) int {
+ p := *ptr.toUint64Ptr()
+ if p == nil {
+ return 0
+ }
+ return SizeVarint(*p) + tagsize
+}
+func sizeVarint64Slice(ptr pointer, tagsize int) int {
+ s := *ptr.toUint64Slice()
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(v) + tagsize
+ }
+ return n
+}
+func sizeVarint64PackedSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toUint64Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(v)
+ }
+ return n + SizeVarint(uint64(n)) + tagsize
+}
+func sizeVarintS64Value(ptr pointer, tagsize int) int {
+ v := *ptr.toInt64()
+ return SizeVarint(uint64(v)) + tagsize
+}
+func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toInt64()
+ if v == 0 {
+ return 0
+ }
+ return SizeVarint(uint64(v)) + tagsize
+}
+func sizeVarintS64Ptr(ptr pointer, tagsize int) int {
+ p := *ptr.toInt64Ptr()
+ if p == nil {
+ return 0
+ }
+ return SizeVarint(uint64(*p)) + tagsize
+}
+func sizeVarintS64Slice(ptr pointer, tagsize int) int {
+ s := *ptr.toInt64Slice()
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v)) + tagsize
+ }
+ return n
+}
+func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toInt64Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v))
+ }
+ return n + SizeVarint(uint64(n)) + tagsize
+}
+func sizeZigzag32Value(ptr pointer, tagsize int) int {
+ v := *ptr.toInt32()
+ return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
+}
+func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toInt32()
+ if v == 0 {
+ return 0
+ }
+ return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
+}
+func sizeZigzag32Ptr(ptr pointer, tagsize int) int {
+ p := ptr.getInt32Ptr()
+ if p == nil {
+ return 0
+ }
+ v := *p
+ return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
+}
+func sizeZigzag32Slice(ptr pointer, tagsize int) int {
+ s := ptr.getInt32Slice()
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
+ }
+ return n
+}
+func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int {
+ s := ptr.getInt32Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
+ }
+ return n + SizeVarint(uint64(n)) + tagsize
+}
+func sizeZigzag64Value(ptr pointer, tagsize int) int {
+ v := *ptr.toInt64()
+ return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
+}
+func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toInt64()
+ if v == 0 {
+ return 0
+ }
+ return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
+}
+func sizeZigzag64Ptr(ptr pointer, tagsize int) int {
+ p := *ptr.toInt64Ptr()
+ if p == nil {
+ return 0
+ }
+ v := *p
+ return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
+}
+func sizeZigzag64Slice(ptr pointer, tagsize int) int {
+ s := *ptr.toInt64Slice()
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
+ }
+ return n
+}
+func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toInt64Slice()
+ if len(s) == 0 {
+ return 0
+ }
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
+ }
+ return n + SizeVarint(uint64(n)) + tagsize
+}
+func sizeBoolValue(_ pointer, tagsize int) int {
+ return 1 + tagsize
+}
+func sizeBoolValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toBool()
+ if !v {
+ return 0
+ }
+ return 1 + tagsize
+}
+func sizeBoolPtr(ptr pointer, tagsize int) int {
+ p := *ptr.toBoolPtr()
+ if p == nil {
+ return 0
+ }
+ return 1 + tagsize
+}
+func sizeBoolSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toBoolSlice()
+ return (1 + tagsize) * len(s)
+}
+func sizeBoolPackedSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toBoolSlice()
+ if len(s) == 0 {
+ return 0
+ }
+ return len(s) + SizeVarint(uint64(len(s))) + tagsize
+}
+func sizeStringValue(ptr pointer, tagsize int) int {
+ v := *ptr.toString()
+ return len(v) + SizeVarint(uint64(len(v))) + tagsize
+}
+func sizeStringValueNoZero(ptr pointer, tagsize int) int {
+ v := *ptr.toString()
+ if v == "" {
+ return 0
+ }
+ return len(v) + SizeVarint(uint64(len(v))) + tagsize
+}
+func sizeStringPtr(ptr pointer, tagsize int) int {
+ p := *ptr.toStringPtr()
+ if p == nil {
+ return 0
+ }
+ v := *p
+ return len(v) + SizeVarint(uint64(len(v))) + tagsize
+}
+func sizeStringSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toStringSlice()
+ n := 0
+ for _, v := range s {
+ n += len(v) + SizeVarint(uint64(len(v))) + tagsize
+ }
+ return n
+}
+func sizeBytes(ptr pointer, tagsize int) int {
+ v := *ptr.toBytes()
+ if v == nil {
+ return 0
+ }
+ return len(v) + SizeVarint(uint64(len(v))) + tagsize
+}
+func sizeBytes3(ptr pointer, tagsize int) int {
+ v := *ptr.toBytes()
+ if len(v) == 0 {
+ return 0
+ }
+ return len(v) + SizeVarint(uint64(len(v))) + tagsize
+}
+func sizeBytesOneof(ptr pointer, tagsize int) int {
+ v := *ptr.toBytes()
+ return len(v) + SizeVarint(uint64(len(v))) + tagsize
+}
+func sizeBytesSlice(ptr pointer, tagsize int) int {
+ s := *ptr.toBytesSlice()
+ n := 0
+ for _, v := range s {
+ n += len(v) + SizeVarint(uint64(len(v))) + tagsize
+ }
+ return n
+}
+
+// appendFixed32 appends an encoded fixed32 to b.
+func appendFixed32(b []byte, v uint32) []byte {
+ b = append(b,
+ byte(v),
+ byte(v>>8),
+ byte(v>>16),
+ byte(v>>24))
+ return b
+}
+
+// appendFixed64 appends an encoded fixed64 to b.
+func appendFixed64(b []byte, v uint64) []byte {
+ b = append(b,
+ byte(v),
+ byte(v>>8),
+ byte(v>>16),
+ byte(v>>24),
+ byte(v>>32),
+ byte(v>>40),
+ byte(v>>48),
+ byte(v>>56))
+ return b
+}
+
+// appendVarint appends an encoded varint to b.
+func appendVarint(b []byte, v uint64) []byte {
+ // TODO: make 1-byte (maybe 2-byte) case inline-able, once we
+ // have non-leaf inliner.
+ switch {
+ case v < 1<<7:
+ b = append(b, byte(v))
+ case v < 1<<14:
+ b = append(b,
+ byte(v&0x7f|0x80),
+ byte(v>>7))
+ case v < 1<<21:
+ b = append(b,
+ byte(v&0x7f|0x80),
+ byte((v>>7)&0x7f|0x80),
+ byte(v>>14))
+ case v < 1<<28:
+ b = append(b,
+ byte(v&0x7f|0x80),
+ byte((v>>7)&0x7f|0x80),
+ byte((v>>14)&0x7f|0x80),
+ byte(v>>21))
+ case v < 1<<35:
+ b = append(b,
+ byte(v&0x7f|0x80),
+ byte((v>>7)&0x7f|0x80),
+ byte((v>>14)&0x7f|0x80),
+ byte((v>>21)&0x7f|0x80),
+ byte(v>>28))
+ case v < 1<<42:
+ b = append(b,
+ byte(v&0x7f|0x80),
+ byte((v>>7)&0x7f|0x80),
+ byte((v>>14)&0x7f|0x80),
+ byte((v>>21)&0x7f|0x80),
+ byte((v>>28)&0x7f|0x80),
+ byte(v>>35))
+ case v < 1<<49:
+ b = append(b,
+ byte(v&0x7f|0x80),
+ byte((v>>7)&0x7f|0x80),
+ byte((v>>14)&0x7f|0x80),
+ byte((v>>21)&0x7f|0x80),
+ byte((v>>28)&0x7f|0x80),
+ byte((v>>35)&0x7f|0x80),
+ byte(v>>42))
+ case v < 1<<56:
+ b = append(b,
+ byte(v&0x7f|0x80),
+ byte((v>>7)&0x7f|0x80),
+ byte((v>>14)&0x7f|0x80),
+ byte((v>>21)&0x7f|0x80),
+ byte((v>>28)&0x7f|0x80),
+ byte((v>>35)&0x7f|0x80),
+ byte((v>>42)&0x7f|0x80),
+ byte(v>>49))
+ case v < 1<<63:
+ b = append(b,
+ byte(v&0x7f|0x80),
+ byte((v>>7)&0x7f|0x80),
+ byte((v>>14)&0x7f|0x80),
+ byte((v>>21)&0x7f|0x80),
+ byte((v>>28)&0x7f|0x80),
+ byte((v>>35)&0x7f|0x80),
+ byte((v>>42)&0x7f|0x80),
+ byte((v>>49)&0x7f|0x80),
+ byte(v>>56))
+ default:
+ b = append(b,
+ byte(v&0x7f|0x80),
+ byte((v>>7)&0x7f|0x80),
+ byte((v>>14)&0x7f|0x80),
+ byte((v>>21)&0x7f|0x80),
+ byte((v>>28)&0x7f|0x80),
+ byte((v>>35)&0x7f|0x80),
+ byte((v>>42)&0x7f|0x80),
+ byte((v>>49)&0x7f|0x80),
+ byte((v>>56)&0x7f|0x80),
+ 1)
+ }
+ return b
+}
+
+func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toUint32()
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, v)
+ return b, nil
+}
+func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toUint32()
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, v)
+ return b, nil
+}
+func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toUint32Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, *p)
+ return b, nil
+}
+func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toUint32Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, v)
+ }
+ return b, nil
+}
+func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toUint32Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ b = appendVarint(b, uint64(4*len(s)))
+ for _, v := range s {
+ b = appendFixed32(b, v)
+ }
+ return b, nil
+}
+func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt32()
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, uint32(v))
+ return b, nil
+}
+func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt32()
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, uint32(v))
+ return b, nil
+}
+func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := ptr.getInt32Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, uint32(*p))
+ return b, nil
+}
+func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := ptr.getInt32Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, uint32(v))
+ }
+ return b, nil
+}
+func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := ptr.getInt32Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ b = appendVarint(b, uint64(4*len(s)))
+ for _, v := range s {
+ b = appendFixed32(b, uint32(v))
+ }
+ return b, nil
+}
+func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := math.Float32bits(*ptr.toFloat32())
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, v)
+ return b, nil
+}
+func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := math.Float32bits(*ptr.toFloat32())
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, v)
+ return b, nil
+}
+func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toFloat32Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, math.Float32bits(*p))
+ return b, nil
+}
+func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toFloat32Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendFixed32(b, math.Float32bits(v))
+ }
+ return b, nil
+}
+func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toFloat32Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ b = appendVarint(b, uint64(4*len(s)))
+ for _, v := range s {
+ b = appendFixed32(b, math.Float32bits(v))
+ }
+ return b, nil
+}
+func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toUint64()
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, v)
+ return b, nil
+}
+func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toUint64()
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, v)
+ return b, nil
+}
+func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toUint64Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, *p)
+ return b, nil
+}
+func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toUint64Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, v)
+ }
+ return b, nil
+}
+func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toUint64Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ b = appendVarint(b, uint64(8*len(s)))
+ for _, v := range s {
+ b = appendFixed64(b, v)
+ }
+ return b, nil
+}
+func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt64()
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, uint64(v))
+ return b, nil
+}
+func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt64()
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, uint64(v))
+ return b, nil
+}
+func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toInt64Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, uint64(*p))
+ return b, nil
+}
+func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toInt64Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, uint64(v))
+ }
+ return b, nil
+}
+func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toInt64Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ b = appendVarint(b, uint64(8*len(s)))
+ for _, v := range s {
+ b = appendFixed64(b, uint64(v))
+ }
+ return b, nil
+}
+func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := math.Float64bits(*ptr.toFloat64())
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, v)
+ return b, nil
+}
+func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := math.Float64bits(*ptr.toFloat64())
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, v)
+ return b, nil
+}
+func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toFloat64Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, math.Float64bits(*p))
+ return b, nil
+}
+func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toFloat64Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendFixed64(b, math.Float64bits(v))
+ }
+ return b, nil
+}
+func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toFloat64Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ b = appendVarint(b, uint64(8*len(s)))
+ for _, v := range s {
+ b = appendFixed64(b, math.Float64bits(v))
+ }
+ return b, nil
+}
+func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toUint32()
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v))
+ return b, nil
+}
+func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toUint32()
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v))
+ return b, nil
+}
+func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toUint32Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(*p))
+ return b, nil
+}
+func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toUint32Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v))
+ }
+ return b, nil
+}
+func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toUint32Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ // compute size
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v))
+ }
+ b = appendVarint(b, uint64(n))
+ for _, v := range s {
+ b = appendVarint(b, uint64(v))
+ }
+ return b, nil
+}
+func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt32()
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v))
+ return b, nil
+}
+func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt32()
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v))
+ return b, nil
+}
+func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := ptr.getInt32Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(*p))
+ return b, nil
+}
+func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := ptr.getInt32Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v))
+ }
+ return b, nil
+}
+func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := ptr.getInt32Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ // compute size
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v))
+ }
+ b = appendVarint(b, uint64(n))
+ for _, v := range s {
+ b = appendVarint(b, uint64(v))
+ }
+ return b, nil
+}
+func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toUint64()
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, v)
+ return b, nil
+}
+func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toUint64()
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, v)
+ return b, nil
+}
+func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toUint64Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, *p)
+ return b, nil
+}
+func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toUint64Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, v)
+ }
+ return b, nil
+}
+func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toUint64Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ // compute size
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(v)
+ }
+ b = appendVarint(b, uint64(n))
+ for _, v := range s {
+ b = appendVarint(b, v)
+ }
+ return b, nil
+}
+func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt64()
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v))
+ return b, nil
+}
+func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt64()
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v))
+ return b, nil
+}
+func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toInt64Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(*p))
+ return b, nil
+}
+func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toInt64Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v))
+ }
+ return b, nil
+}
+func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toInt64Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ // compute size
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v))
+ }
+ b = appendVarint(b, uint64(n))
+ for _, v := range s {
+ b = appendVarint(b, uint64(v))
+ }
+ return b, nil
+}
+func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt32()
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
+ return b, nil
+}
+func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt32()
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
+ return b, nil
+}
+func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := ptr.getInt32Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ v := *p
+ b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
+ return b, nil
+}
+func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := ptr.getInt32Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
+ }
+ return b, nil
+}
+func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := ptr.getInt32Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ // compute size
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
+ }
+ b = appendVarint(b, uint64(n))
+ for _, v := range s {
+ b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
+ }
+ return b, nil
+}
+func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt64()
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
+ return b, nil
+}
+func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toInt64()
+ if v == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
+ return b, nil
+}
+func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toInt64Ptr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ v := *p
+ b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
+ return b, nil
+}
+func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toInt64Slice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
+ }
+ return b, nil
+}
+func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toInt64Slice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ // compute size
+ n := 0
+ for _, v := range s {
+ n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
+ }
+ b = appendVarint(b, uint64(n))
+ for _, v := range s {
+ b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
+ }
+ return b, nil
+}
+func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toBool()
+ b = appendVarint(b, wiretag)
+ if v {
+ b = append(b, 1)
+ } else {
+ b = append(b, 0)
+ }
+ return b, nil
+}
+func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toBool()
+ if !v {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = append(b, 1)
+ return b, nil
+}
+
+func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toBoolPtr()
+ if p == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ if *p {
+ b = append(b, 1)
+ } else {
+ b = append(b, 0)
+ }
+ return b, nil
+}
+func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toBoolSlice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ if v {
+ b = append(b, 1)
+ } else {
+ b = append(b, 0)
+ }
+ }
+ return b, nil
+}
+func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toBoolSlice()
+ if len(s) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag&^7|WireBytes)
+ b = appendVarint(b, uint64(len(s)))
+ for _, v := range s {
+ if v {
+ b = append(b, 1)
+ } else {
+ b = append(b, 0)
+ }
+ }
+ return b, nil
+}
+func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toString()
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ return b, nil
+}
+func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toString()
+ if v == "" {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ return b, nil
+}
+func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ p := *ptr.toStringPtr()
+ if p == nil {
+ return b, nil
+ }
+ v := *p
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ return b, nil
+}
+func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toStringSlice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ }
+ return b, nil
+}
+func appendUTF8StringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ var invalidUTF8 bool
+ v := *ptr.toString()
+ if !utf8.ValidString(v) {
+ invalidUTF8 = true
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ if invalidUTF8 {
+ return b, errInvalidUTF8
+ }
+ return b, nil
+}
+func appendUTF8StringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ var invalidUTF8 bool
+ v := *ptr.toString()
+ if v == "" {
+ return b, nil
+ }
+ if !utf8.ValidString(v) {
+ invalidUTF8 = true
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ if invalidUTF8 {
+ return b, errInvalidUTF8
+ }
+ return b, nil
+}
+func appendUTF8StringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ var invalidUTF8 bool
+ p := *ptr.toStringPtr()
+ if p == nil {
+ return b, nil
+ }
+ v := *p
+ if !utf8.ValidString(v) {
+ invalidUTF8 = true
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ if invalidUTF8 {
+ return b, errInvalidUTF8
+ }
+ return b, nil
+}
+func appendUTF8StringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ var invalidUTF8 bool
+ s := *ptr.toStringSlice()
+ for _, v := range s {
+ if !utf8.ValidString(v) {
+ invalidUTF8 = true
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ }
+ if invalidUTF8 {
+ return b, errInvalidUTF8
+ }
+ return b, nil
+}
+func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toBytes()
+ if v == nil {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ return b, nil
+}
+func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toBytes()
+ if len(v) == 0 {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ return b, nil
+}
+func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ v := *ptr.toBytes()
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ return b, nil
+}
+func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
+ s := *ptr.toBytesSlice()
+ for _, v := range s {
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(v)))
+ b = append(b, v...)
+ }
+ return b, nil
+}
+
+// makeGroupMarshaler returns the sizer and marshaler for a group.
+// u is the marshal info of the underlying message.
+func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ p := ptr.getPointer()
+ if p.isNil() {
+ return 0
+ }
+ return u.size(p) + 2*tagsize
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ p := ptr.getPointer()
+ if p.isNil() {
+ return b, nil
+ }
+ var err error
+ b = appendVarint(b, wiretag) // start group
+ b, err = u.marshal(b, p, deterministic)
+ b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
+ return b, err
+ }
+}
+
+// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice.
+// u is the marshal info of the underlying message.
+func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getPointerSlice()
+ n := 0
+ for _, v := range s {
+ if v.isNil() {
+ continue
+ }
+ n += u.size(v) + 2*tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getPointerSlice()
+ var err error
+ var nerr nonFatal
+ for _, v := range s {
+ if v.isNil() {
+ return b, errRepeatedHasNil
+ }
+ b = appendVarint(b, wiretag) // start group
+ b, err = u.marshal(b, v, deterministic)
+ b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
+ if !nerr.Merge(err) {
+ if err == ErrNil {
+ err = errRepeatedHasNil
+ }
+ return b, err
+ }
+ }
+ return b, nerr.E
+ }
+}
+
+// makeMessageMarshaler returns the sizer and marshaler for a message field.
+// u is the marshal info of the message.
+func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ p := ptr.getPointer()
+ if p.isNil() {
+ return 0
+ }
+ siz := u.size(p)
+ return siz + SizeVarint(uint64(siz)) + tagsize
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ p := ptr.getPointer()
+ if p.isNil() {
+ return b, nil
+ }
+ b = appendVarint(b, wiretag)
+ siz := u.cachedsize(p)
+ b = appendVarint(b, uint64(siz))
+ return u.marshal(b, p, deterministic)
+ }
+}
+
+// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice.
+// u is the marshal info of the message.
+func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getPointerSlice()
+ n := 0
+ for _, v := range s {
+ if v.isNil() {
+ continue
+ }
+ siz := u.size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getPointerSlice()
+ var err error
+ var nerr nonFatal
+ for _, v := range s {
+ if v.isNil() {
+ return b, errRepeatedHasNil
+ }
+ b = appendVarint(b, wiretag)
+ siz := u.cachedsize(v)
+ b = appendVarint(b, uint64(siz))
+ b, err = u.marshal(b, v, deterministic)
+
+ if !nerr.Merge(err) {
+ if err == ErrNil {
+ err = errRepeatedHasNil
+ }
+ return b, err
+ }
+ }
+ return b, nerr.E
+ }
+}
+
+// makeMapMarshaler returns the sizer and marshaler for a map field.
+// f is the pointer to the reflect data structure of the field.
+func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) {
+ // figure out key and value type
+ t := f.Type
+ keyType := t.Key()
+ valType := t.Elem()
+ tags := strings.Split(f.Tag.Get("protobuf"), ",")
+ keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",")
+ valTags := strings.Split(f.Tag.Get("protobuf_val"), ",")
+ stdOptions := false
+ for _, t := range tags {
+ if strings.HasPrefix(t, "customtype=") {
+ valTags = append(valTags, t)
+ }
+ if t == "stdtime" {
+ valTags = append(valTags, t)
+ stdOptions = true
+ }
+ if t == "stdduration" {
+ valTags = append(valTags, t)
+ stdOptions = true
+ }
+ if t == "wktptr" {
+ valTags = append(valTags, t)
+ }
+ }
+ keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map
+ valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map
+ keyWireTag := 1<<3 | wiretype(keyTags[0])
+ valWireTag := 2<<3 | wiretype(valTags[0])
+
+ // We create an interface to get the addresses of the map key and value.
+ // If value is pointer-typed, the interface is a direct interface, the
+ // idata itself is the value. Otherwise, the idata is the pointer to the
+ // value.
+ // Key cannot be pointer-typed.
+ valIsPtr := valType.Kind() == reflect.Ptr
+
+ // If value is a message with nested maps, calling
+ // valSizer in marshal may be quadratic. We should use
+ // cached version in marshal (but not in size).
+ // If value is not message type, we don't have size cache,
+ // but it cannot be nested either. Just use valSizer.
+ valCachedSizer := valSizer
+ if valIsPtr && !stdOptions && valType.Elem().Kind() == reflect.Struct {
+ u := getMarshalInfo(valType.Elem())
+ valCachedSizer = func(ptr pointer, tagsize int) int {
+ // Same as message sizer, but use cache.
+ p := ptr.getPointer()
+ if p.isNil() {
+ return 0
+ }
+ siz := u.cachedsize(p)
+ return siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ }
+ return func(ptr pointer, tagsize int) int {
+ m := ptr.asPointerTo(t).Elem() // the map
+ n := 0
+ for _, k := range m.MapKeys() {
+ ki := k.Interface()
+ vi := m.MapIndex(k).Interface()
+ kaddr := toAddrPointer(&ki, false) // pointer to key
+ vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value
+ siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) {
+ m := ptr.asPointerTo(t).Elem() // the map
+ var err error
+ keys := m.MapKeys()
+ if len(keys) > 1 && deterministic {
+ sort.Sort(mapKeys(keys))
+ }
+
+ var nerr nonFatal
+ for _, k := range keys {
+ ki := k.Interface()
+ vi := m.MapIndex(k).Interface()
+ kaddr := toAddrPointer(&ki, false) // pointer to key
+ vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value
+ b = appendVarint(b, tag)
+ siz := keySizer(kaddr, 1) + valCachedSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
+ b = appendVarint(b, uint64(siz))
+ b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic)
+ if !nerr.Merge(err) {
+ return b, err
+ }
+ b, err = valMarshaler(b, vaddr, valWireTag, deterministic)
+ if err != ErrNil && !nerr.Merge(err) { // allow nil value in map
+ return b, err
+ }
+ }
+ return b, nerr.E
+ }
+}
+
+// makeOneOfMarshaler returns the sizer and marshaler for a oneof field.
+// fi is the marshal info of the field.
+// f is the pointer to the reflect data structure of the field.
+func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) {
+ // Oneof field is an interface. We need to get the actual data type on the fly.
+ t := f.Type
+ return func(ptr pointer, _ int) int {
+ p := ptr.getInterfacePointer()
+ if p.isNil() {
+ return 0
+ }
+ v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
+ telem := v.Type()
+ e := fi.oneofElems[telem]
+ return e.sizer(p, e.tagsize)
+ },
+ func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) {
+ p := ptr.getInterfacePointer()
+ if p.isNil() {
+ return b, nil
+ }
+ v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
+ telem := v.Type()
+ if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() {
+ return b, errOneofHasNil
+ }
+ e := fi.oneofElems[telem]
+ return e.marshaler(b, p, e.wiretag, deterministic)
+ }
+}
+
+// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field.
+func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int {
+ m, mu := ext.extensionsRead()
+ if m == nil {
+ return 0
+ }
+ mu.Lock()
+
+ n := 0
+ for _, e := range m {
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ n += len(e.enc)
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+ ei := u.getExtElemInfo(e.desc)
+ v := e.value
+ p := toAddrPointer(&v, ei.isptr)
+ n += ei.sizer(p, ei.tagsize)
+ }
+ mu.Unlock()
+ return n
+}
+
+// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b.
+func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
+ m, mu := ext.extensionsRead()
+ if m == nil {
+ return b, nil
+ }
+ mu.Lock()
+ defer mu.Unlock()
+
+ var err error
+ var nerr nonFatal
+
+ // Fast-path for common cases: zero or one extensions.
+ // Don't bother sorting the keys.
+ if len(m) <= 1 {
+ for _, e := range m {
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ b = append(b, e.enc...)
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ ei := u.getExtElemInfo(e.desc)
+ v := e.value
+ p := toAddrPointer(&v, ei.isptr)
+ b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
+ if !nerr.Merge(err) {
+ return b, err
+ }
+ }
+ return b, nerr.E
+ }
+
+ // Sort the keys to provide a deterministic encoding.
+ // Not sure this is required, but the old code does it.
+ keys := make([]int, 0, len(m))
+ for k := range m {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+
+ for _, k := range keys {
+ e := m[int32(k)]
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ b = append(b, e.enc...)
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ ei := u.getExtElemInfo(e.desc)
+ v := e.value
+ p := toAddrPointer(&v, ei.isptr)
+ b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
+ if !nerr.Merge(err) {
+ return b, err
+ }
+ }
+ return b, nerr.E
+}
+
+// message set format is:
+// message MessageSet {
+// repeated group Item = 1 {
+// required int32 type_id = 2;
+// required string message = 3;
+// };
+// }
+
+// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field
+// in message set format (above).
+func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int {
+ m, mu := ext.extensionsRead()
+ if m == nil {
+ return 0
+ }
+ mu.Lock()
+
+ n := 0
+ for id, e := range m {
+ n += 2 // start group, end group. tag = 1 (size=1)
+ n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1)
+
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
+ siz := len(msgWithLen)
+ n += siz + 1 // message, tag = 3 (size=1)
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ ei := u.getExtElemInfo(e.desc)
+ v := e.value
+ p := toAddrPointer(&v, ei.isptr)
+ n += ei.sizer(p, 1) // message, tag = 3 (size=1)
+ }
+ mu.Unlock()
+ return n
+}
+
+// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above)
+// to the end of byte slice b.
+func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
+ m, mu := ext.extensionsRead()
+ if m == nil {
+ return b, nil
+ }
+ mu.Lock()
+ defer mu.Unlock()
+
+ var err error
+ var nerr nonFatal
+
+ // Fast-path for common cases: zero or one extensions.
+ // Don't bother sorting the keys.
+ if len(m) <= 1 {
+ for id, e := range m {
+ b = append(b, 1<<3|WireStartGroup)
+ b = append(b, 2<<3|WireVarint)
+ b = appendVarint(b, uint64(id))
+
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
+ b = append(b, 3<<3|WireBytes)
+ b = append(b, msgWithLen...)
+ b = append(b, 1<<3|WireEndGroup)
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ ei := u.getExtElemInfo(e.desc)
+ v := e.value
+ p := toAddrPointer(&v, ei.isptr)
+ b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
+ if !nerr.Merge(err) {
+ return b, err
+ }
+ b = append(b, 1<<3|WireEndGroup)
+ }
+ return b, nerr.E
+ }
+
+ // Sort the keys to provide a deterministic encoding.
+ keys := make([]int, 0, len(m))
+ for k := range m {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+
+ for _, id := range keys {
+ e := m[int32(id)]
+ b = append(b, 1<<3|WireStartGroup)
+ b = append(b, 2<<3|WireVarint)
+ b = appendVarint(b, uint64(id))
+
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
+ b = append(b, 3<<3|WireBytes)
+ b = append(b, msgWithLen...)
+ b = append(b, 1<<3|WireEndGroup)
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ ei := u.getExtElemInfo(e.desc)
+ v := e.value
+ p := toAddrPointer(&v, ei.isptr)
+ b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
+ b = append(b, 1<<3|WireEndGroup)
+ if !nerr.Merge(err) {
+ return b, err
+ }
+ }
+ return b, nerr.E
+}
+
+// sizeV1Extensions computes the size of encoded data for a V1-API extension field.
+func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int {
+ if m == nil {
+ return 0
+ }
+
+ n := 0
+ for _, e := range m {
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ n += len(e.enc)
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ ei := u.getExtElemInfo(e.desc)
+ v := e.value
+ p := toAddrPointer(&v, ei.isptr)
+ n += ei.sizer(p, ei.tagsize)
+ }
+ return n
+}
+
+// appendV1Extensions marshals a V1-API extension field to the end of byte slice b.
+func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) {
+ if m == nil {
+ return b, nil
+ }
+
+ // Sort the keys to provide a deterministic encoding.
+ keys := make([]int, 0, len(m))
+ for k := range m {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+
+ var err error
+ var nerr nonFatal
+ for _, k := range keys {
+ e := m[int32(k)]
+ if e.value == nil || e.desc == nil {
+ // Extension is only in its encoded form.
+ b = append(b, e.enc...)
+ continue
+ }
+
+ // We don't skip extensions that have an encoded form set,
+ // because the extension value may have been mutated after
+ // the last time this function was called.
+
+ ei := u.getExtElemInfo(e.desc)
+ v := e.value
+ p := toAddrPointer(&v, ei.isptr)
+ b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
+ if !nerr.Merge(err) {
+ return b, err
+ }
+ }
+ return b, nerr.E
+}
+
+// newMarshaler is the interface representing objects that can marshal themselves.
+//
+// This exists to support protoc-gen-go generated messages.
+// The proto package will stop type-asserting to this interface in the future.
+//
+// DO NOT DEPEND ON THIS.
+type newMarshaler interface {
+ XXX_Size() int
+ XXX_Marshal(b []byte, deterministic bool) ([]byte, error)
+}
+
+// Size returns the encoded size of a protocol buffer message.
+// This is the main entry point.
+func Size(pb Message) int {
+ if m, ok := pb.(newMarshaler); ok {
+ return m.XXX_Size()
+ }
+ if m, ok := pb.(Marshaler); ok {
+ // If the message can marshal itself, let it do it, for compatibility.
+ // NOTE: This is not efficient.
+ b, _ := m.Marshal()
+ return len(b)
+ }
+ // in case somehow we didn't generate the wrapper
+ if pb == nil {
+ return 0
+ }
+ var info InternalMessageInfo
+ return info.Size(pb)
+}
+
+// Marshal takes a protocol buffer message
+// and encodes it into the wire format, returning the data.
+// This is the main entry point.
+func Marshal(pb Message) ([]byte, error) {
+ if m, ok := pb.(newMarshaler); ok {
+ siz := m.XXX_Size()
+ b := make([]byte, 0, siz)
+ return m.XXX_Marshal(b, false)
+ }
+ if m, ok := pb.(Marshaler); ok {
+ // If the message can marshal itself, let it do it, for compatibility.
+ // NOTE: This is not efficient.
+ return m.Marshal()
+ }
+ // in case somehow we didn't generate the wrapper
+ if pb == nil {
+ return nil, ErrNil
+ }
+ var info InternalMessageInfo
+ siz := info.Size(pb)
+ b := make([]byte, 0, siz)
+ return info.Marshal(b, pb, false)
+}
+
+// Marshal takes a protocol buffer message
+// and encodes it into the wire format, writing the result to the
+// Buffer.
+// This is an alternative entry point. It is not necessary to use
+// a Buffer for most applications.
+func (p *Buffer) Marshal(pb Message) error {
+ var err error
+ if p.deterministic {
+ if _, ok := pb.(Marshaler); ok {
+ return fmt.Errorf("proto: deterministic not supported by the Marshal method of %T", pb)
+ }
+ }
+ if m, ok := pb.(newMarshaler); ok {
+ siz := m.XXX_Size()
+ p.grow(siz) // make sure buf has enough capacity
+ pp := p.buf[len(p.buf) : len(p.buf) : len(p.buf)+siz]
+ pp, err = m.XXX_Marshal(pp, p.deterministic)
+ p.buf = append(p.buf, pp...)
+ return err
+ }
+ if m, ok := pb.(Marshaler); ok {
+ // If the message can marshal itself, let it do it, for compatibility.
+ // NOTE: This is not efficient.
+ var b []byte
+ b, err = m.Marshal()
+ p.buf = append(p.buf, b...)
+ return err
+ }
+ // in case somehow we didn't generate the wrapper
+ if pb == nil {
+ return ErrNil
+ }
+ var info InternalMessageInfo
+ siz := info.Size(pb)
+ p.grow(siz) // make sure buf has enough capacity
+ p.buf, err = info.Marshal(p.buf, pb, p.deterministic)
+ return err
+}
+
+// grow grows the buffer's capacity, if necessary, to guarantee space for
+// another n bytes. After grow(n), at least n bytes can be written to the
+// buffer without another allocation.
+func (p *Buffer) grow(n int) {
+ need := len(p.buf) + n
+ if need <= cap(p.buf) {
+ return
+ }
+ newCap := len(p.buf) * 2
+ if newCap < need {
+ newCap = need
+ }
+ p.buf = append(make([]byte, 0, newCap), p.buf...)
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go b/vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go
@@ -0,0 +1,388 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2018, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import (
+ "reflect"
+ "time"
+)
+
+// makeMessageRefMarshaler differs a bit from makeMessageMarshaler
+// It marshal a message T instead of a *T
+func makeMessageRefMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ siz := u.size(ptr)
+ return siz + SizeVarint(uint64(siz)) + tagsize
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ b = appendVarint(b, wiretag)
+ siz := u.cachedsize(ptr)
+ b = appendVarint(b, uint64(siz))
+ return u.marshal(b, ptr, deterministic)
+ }
+}
+
+// makeMessageRefSliceMarshaler differs quite a lot from makeMessageSliceMarshaler
+// It marshals a slice of messages []T instead of []*T
+func makeMessageRefSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ e := elem.Interface()
+ v := toAddrPointer(&e, false)
+ siz := u.size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ var err, errreq error
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ e := elem.Interface()
+ v := toAddrPointer(&e, false)
+ b = appendVarint(b, wiretag)
+ siz := u.size(v)
+ b = appendVarint(b, uint64(siz))
+ b, err = u.marshal(b, v, deterministic)
+
+ if err != nil {
+ if _, ok := err.(*RequiredNotSetError); ok {
+ // Required field in submessage is not set.
+ // We record the error but keep going, to give a complete marshaling.
+ if errreq == nil {
+ errreq = err
+ }
+ continue
+ }
+ if err == ErrNil {
+ err = errRepeatedHasNil
+ }
+ return b, err
+ }
+ }
+
+ return b, errreq
+ }
+}
+
+func makeCustomPtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ m := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(custom)
+ siz := m.Size()
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ m := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(custom)
+ siz := m.Size()
+ buf, err := m.Marshal()
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeCustomMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ m := ptr.asPointerTo(u.typ).Interface().(custom)
+ siz := m.Size()
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ m := ptr.asPointerTo(u.typ).Interface().(custom)
+ siz := m.Size()
+ buf, err := m.Marshal()
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeTimeMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ t := ptr.asPointerTo(u.typ).Interface().(*time.Time)
+ ts, err := timestampProto(*t)
+ if err != nil {
+ return 0
+ }
+ siz := Size(ts)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ t := ptr.asPointerTo(u.typ).Interface().(*time.Time)
+ ts, err := timestampProto(*t)
+ if err != nil {
+ return nil, err
+ }
+ buf, err := Marshal(ts)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeTimePtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Time)
+ ts, err := timestampProto(*t)
+ if err != nil {
+ return 0
+ }
+ siz := Size(ts)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Time)
+ ts, err := timestampProto(*t)
+ if err != nil {
+ return nil, err
+ }
+ buf, err := Marshal(ts)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeTimeSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(time.Time)
+ ts, err := timestampProto(t)
+ if err != nil {
+ return 0
+ }
+ siz := Size(ts)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(time.Time)
+ ts, err := timestampProto(t)
+ if err != nil {
+ return nil, err
+ }
+ siz := Size(ts)
+ buf, err := Marshal(ts)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeTimePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*time.Time)
+ ts, err := timestampProto(*t)
+ if err != nil {
+ return 0
+ }
+ siz := Size(ts)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*time.Time)
+ ts, err := timestampProto(*t)
+ if err != nil {
+ return nil, err
+ }
+ siz := Size(ts)
+ buf, err := Marshal(ts)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeDurationMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ d := ptr.asPointerTo(u.typ).Interface().(*time.Duration)
+ dur := durationProto(*d)
+ siz := Size(dur)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ d := ptr.asPointerTo(u.typ).Interface().(*time.Duration)
+ dur := durationProto(*d)
+ buf, err := Marshal(dur)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeDurationPtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ d := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Duration)
+ dur := durationProto(*d)
+ siz := Size(dur)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ d := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*time.Duration)
+ dur := durationProto(*d)
+ buf, err := Marshal(dur)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeDurationSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ d := elem.Interface().(time.Duration)
+ dur := durationProto(d)
+ siz := Size(dur)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ d := elem.Interface().(time.Duration)
+ dur := durationProto(d)
+ siz := Size(dur)
+ buf, err := Marshal(dur)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeDurationPtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ d := elem.Interface().(*time.Duration)
+ dur := durationProto(*d)
+ siz := Size(dur)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ d := elem.Interface().(*time.Duration)
+ dur := durationProto(*d)
+ siz := Size(dur)
+ buf, err := Marshal(dur)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/table_merge.go b/vendor/github.com/gogo/protobuf/proto/table_merge.go
@@ -0,0 +1,676 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+ "sync"
+ "sync/atomic"
+)
+
+// Merge merges the src message into dst.
+// This assumes that dst and src of the same type and are non-nil.
+func (a *InternalMessageInfo) Merge(dst, src Message) {
+ mi := atomicLoadMergeInfo(&a.merge)
+ if mi == nil {
+ mi = getMergeInfo(reflect.TypeOf(dst).Elem())
+ atomicStoreMergeInfo(&a.merge, mi)
+ }
+ mi.merge(toPointer(&dst), toPointer(&src))
+}
+
+type mergeInfo struct {
+ typ reflect.Type
+
+ initialized int32 // 0: only typ is valid, 1: everything is valid
+ lock sync.Mutex
+
+ fields []mergeFieldInfo
+ unrecognized field // Offset of XXX_unrecognized
+}
+
+type mergeFieldInfo struct {
+ field field // Offset of field, guaranteed to be valid
+
+ // isPointer reports whether the value in the field is a pointer.
+ // This is true for the following situations:
+ // * Pointer to struct
+ // * Pointer to basic type (proto2 only)
+ // * Slice (first value in slice header is a pointer)
+ // * String (first value in string header is a pointer)
+ isPointer bool
+
+ // basicWidth reports the width of the field assuming that it is directly
+ // embedded in the struct (as is the case for basic types in proto3).
+ // The possible values are:
+ // 0: invalid
+ // 1: bool
+ // 4: int32, uint32, float32
+ // 8: int64, uint64, float64
+ basicWidth int
+
+ // Where dst and src are pointers to the types being merged.
+ merge func(dst, src pointer)
+}
+
+var (
+ mergeInfoMap = map[reflect.Type]*mergeInfo{}
+ mergeInfoLock sync.Mutex
+)
+
+func getMergeInfo(t reflect.Type) *mergeInfo {
+ mergeInfoLock.Lock()
+ defer mergeInfoLock.Unlock()
+ mi := mergeInfoMap[t]
+ if mi == nil {
+ mi = &mergeInfo{typ: t}
+ mergeInfoMap[t] = mi
+ }
+ return mi
+}
+
+// merge merges src into dst assuming they are both of type *mi.typ.
+func (mi *mergeInfo) merge(dst, src pointer) {
+ if dst.isNil() {
+ panic("proto: nil destination")
+ }
+ if src.isNil() {
+ return // Nothing to do.
+ }
+
+ if atomic.LoadInt32(&mi.initialized) == 0 {
+ mi.computeMergeInfo()
+ }
+
+ for _, fi := range mi.fields {
+ sfp := src.offset(fi.field)
+
+ // As an optimization, we can avoid the merge function call cost
+ // if we know for sure that the source will have no effect
+ // by checking if it is the zero value.
+ if unsafeAllowed {
+ if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string
+ continue
+ }
+ if fi.basicWidth > 0 {
+ switch {
+ case fi.basicWidth == 1 && !*sfp.toBool():
+ continue
+ case fi.basicWidth == 4 && *sfp.toUint32() == 0:
+ continue
+ case fi.basicWidth == 8 && *sfp.toUint64() == 0:
+ continue
+ }
+ }
+ }
+
+ dfp := dst.offset(fi.field)
+ fi.merge(dfp, sfp)
+ }
+
+ // TODO: Make this faster?
+ out := dst.asPointerTo(mi.typ).Elem()
+ in := src.asPointerTo(mi.typ).Elem()
+ if emIn, err := extendable(in.Addr().Interface()); err == nil {
+ emOut, _ := extendable(out.Addr().Interface())
+ mIn, muIn := emIn.extensionsRead()
+ if mIn != nil {
+ mOut := emOut.extensionsWrite()
+ muIn.Lock()
+ mergeExtension(mOut, mIn)
+ muIn.Unlock()
+ }
+ }
+
+ if mi.unrecognized.IsValid() {
+ if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 {
+ *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...)
+ }
+ }
+}
+
+func (mi *mergeInfo) computeMergeInfo() {
+ mi.lock.Lock()
+ defer mi.lock.Unlock()
+ if mi.initialized != 0 {
+ return
+ }
+ t := mi.typ
+ n := t.NumField()
+
+ props := GetProperties(t)
+ for i := 0; i < n; i++ {
+ f := t.Field(i)
+ if strings.HasPrefix(f.Name, "XXX_") {
+ continue
+ }
+
+ mfi := mergeFieldInfo{field: toField(&f)}
+ tf := f.Type
+
+ // As an optimization, we can avoid the merge function call cost
+ // if we know for sure that the source will have no effect
+ // by checking if it is the zero value.
+ if unsafeAllowed {
+ switch tf.Kind() {
+ case reflect.Ptr, reflect.Slice, reflect.String:
+ // As a special case, we assume slices and strings are pointers
+ // since we know that the first field in the SliceSlice or
+ // StringHeader is a data pointer.
+ mfi.isPointer = true
+ case reflect.Bool:
+ mfi.basicWidth = 1
+ case reflect.Int32, reflect.Uint32, reflect.Float32:
+ mfi.basicWidth = 4
+ case reflect.Int64, reflect.Uint64, reflect.Float64:
+ mfi.basicWidth = 8
+ }
+ }
+
+ // Unwrap tf to get at its most basic type.
+ var isPointer, isSlice bool
+ if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
+ isSlice = true
+ tf = tf.Elem()
+ }
+ if tf.Kind() == reflect.Ptr {
+ isPointer = true
+ tf = tf.Elem()
+ }
+ if isPointer && isSlice && tf.Kind() != reflect.Struct {
+ panic("both pointer and slice for basic type in " + tf.Name())
+ }
+
+ switch tf.Kind() {
+ case reflect.Int32:
+ switch {
+ case isSlice: // E.g., []int32
+ mfi.merge = func(dst, src pointer) {
+ // NOTE: toInt32Slice is not defined (see pointer_reflect.go).
+ /*
+ sfsp := src.toInt32Slice()
+ if *sfsp != nil {
+ dfsp := dst.toInt32Slice()
+ *dfsp = append(*dfsp, *sfsp...)
+ if *dfsp == nil {
+ *dfsp = []int64{}
+ }
+ }
+ */
+ sfs := src.getInt32Slice()
+ if sfs != nil {
+ dfs := dst.getInt32Slice()
+ dfs = append(dfs, sfs...)
+ if dfs == nil {
+ dfs = []int32{}
+ }
+ dst.setInt32Slice(dfs)
+ }
+ }
+ case isPointer: // E.g., *int32
+ mfi.merge = func(dst, src pointer) {
+ // NOTE: toInt32Ptr is not defined (see pointer_reflect.go).
+ /*
+ sfpp := src.toInt32Ptr()
+ if *sfpp != nil {
+ dfpp := dst.toInt32Ptr()
+ if *dfpp == nil {
+ *dfpp = Int32(**sfpp)
+ } else {
+ **dfpp = **sfpp
+ }
+ }
+ */
+ sfp := src.getInt32Ptr()
+ if sfp != nil {
+ dfp := dst.getInt32Ptr()
+ if dfp == nil {
+ dst.setInt32Ptr(*sfp)
+ } else {
+ *dfp = *sfp
+ }
+ }
+ }
+ default: // E.g., int32
+ mfi.merge = func(dst, src pointer) {
+ if v := *src.toInt32(); v != 0 {
+ *dst.toInt32() = v
+ }
+ }
+ }
+ case reflect.Int64:
+ switch {
+ case isSlice: // E.g., []int64
+ mfi.merge = func(dst, src pointer) {
+ sfsp := src.toInt64Slice()
+ if *sfsp != nil {
+ dfsp := dst.toInt64Slice()
+ *dfsp = append(*dfsp, *sfsp...)
+ if *dfsp == nil {
+ *dfsp = []int64{}
+ }
+ }
+ }
+ case isPointer: // E.g., *int64
+ mfi.merge = func(dst, src pointer) {
+ sfpp := src.toInt64Ptr()
+ if *sfpp != nil {
+ dfpp := dst.toInt64Ptr()
+ if *dfpp == nil {
+ *dfpp = Int64(**sfpp)
+ } else {
+ **dfpp = **sfpp
+ }
+ }
+ }
+ default: // E.g., int64
+ mfi.merge = func(dst, src pointer) {
+ if v := *src.toInt64(); v != 0 {
+ *dst.toInt64() = v
+ }
+ }
+ }
+ case reflect.Uint32:
+ switch {
+ case isSlice: // E.g., []uint32
+ mfi.merge = func(dst, src pointer) {
+ sfsp := src.toUint32Slice()
+ if *sfsp != nil {
+ dfsp := dst.toUint32Slice()
+ *dfsp = append(*dfsp, *sfsp...)
+ if *dfsp == nil {
+ *dfsp = []uint32{}
+ }
+ }
+ }
+ case isPointer: // E.g., *uint32
+ mfi.merge = func(dst, src pointer) {
+ sfpp := src.toUint32Ptr()
+ if *sfpp != nil {
+ dfpp := dst.toUint32Ptr()
+ if *dfpp == nil {
+ *dfpp = Uint32(**sfpp)
+ } else {
+ **dfpp = **sfpp
+ }
+ }
+ }
+ default: // E.g., uint32
+ mfi.merge = func(dst, src pointer) {
+ if v := *src.toUint32(); v != 0 {
+ *dst.toUint32() = v
+ }
+ }
+ }
+ case reflect.Uint64:
+ switch {
+ case isSlice: // E.g., []uint64
+ mfi.merge = func(dst, src pointer) {
+ sfsp := src.toUint64Slice()
+ if *sfsp != nil {
+ dfsp := dst.toUint64Slice()
+ *dfsp = append(*dfsp, *sfsp...)
+ if *dfsp == nil {
+ *dfsp = []uint64{}
+ }
+ }
+ }
+ case isPointer: // E.g., *uint64
+ mfi.merge = func(dst, src pointer) {
+ sfpp := src.toUint64Ptr()
+ if *sfpp != nil {
+ dfpp := dst.toUint64Ptr()
+ if *dfpp == nil {
+ *dfpp = Uint64(**sfpp)
+ } else {
+ **dfpp = **sfpp
+ }
+ }
+ }
+ default: // E.g., uint64
+ mfi.merge = func(dst, src pointer) {
+ if v := *src.toUint64(); v != 0 {
+ *dst.toUint64() = v
+ }
+ }
+ }
+ case reflect.Float32:
+ switch {
+ case isSlice: // E.g., []float32
+ mfi.merge = func(dst, src pointer) {
+ sfsp := src.toFloat32Slice()
+ if *sfsp != nil {
+ dfsp := dst.toFloat32Slice()
+ *dfsp = append(*dfsp, *sfsp...)
+ if *dfsp == nil {
+ *dfsp = []float32{}
+ }
+ }
+ }
+ case isPointer: // E.g., *float32
+ mfi.merge = func(dst, src pointer) {
+ sfpp := src.toFloat32Ptr()
+ if *sfpp != nil {
+ dfpp := dst.toFloat32Ptr()
+ if *dfpp == nil {
+ *dfpp = Float32(**sfpp)
+ } else {
+ **dfpp = **sfpp
+ }
+ }
+ }
+ default: // E.g., float32
+ mfi.merge = func(dst, src pointer) {
+ if v := *src.toFloat32(); v != 0 {
+ *dst.toFloat32() = v
+ }
+ }
+ }
+ case reflect.Float64:
+ switch {
+ case isSlice: // E.g., []float64
+ mfi.merge = func(dst, src pointer) {
+ sfsp := src.toFloat64Slice()
+ if *sfsp != nil {
+ dfsp := dst.toFloat64Slice()
+ *dfsp = append(*dfsp, *sfsp...)
+ if *dfsp == nil {
+ *dfsp = []float64{}
+ }
+ }
+ }
+ case isPointer: // E.g., *float64
+ mfi.merge = func(dst, src pointer) {
+ sfpp := src.toFloat64Ptr()
+ if *sfpp != nil {
+ dfpp := dst.toFloat64Ptr()
+ if *dfpp == nil {
+ *dfpp = Float64(**sfpp)
+ } else {
+ **dfpp = **sfpp
+ }
+ }
+ }
+ default: // E.g., float64
+ mfi.merge = func(dst, src pointer) {
+ if v := *src.toFloat64(); v != 0 {
+ *dst.toFloat64() = v
+ }
+ }
+ }
+ case reflect.Bool:
+ switch {
+ case isSlice: // E.g., []bool
+ mfi.merge = func(dst, src pointer) {
+ sfsp := src.toBoolSlice()
+ if *sfsp != nil {
+ dfsp := dst.toBoolSlice()
+ *dfsp = append(*dfsp, *sfsp...)
+ if *dfsp == nil {
+ *dfsp = []bool{}
+ }
+ }
+ }
+ case isPointer: // E.g., *bool
+ mfi.merge = func(dst, src pointer) {
+ sfpp := src.toBoolPtr()
+ if *sfpp != nil {
+ dfpp := dst.toBoolPtr()
+ if *dfpp == nil {
+ *dfpp = Bool(**sfpp)
+ } else {
+ **dfpp = **sfpp
+ }
+ }
+ }
+ default: // E.g., bool
+ mfi.merge = func(dst, src pointer) {
+ if v := *src.toBool(); v {
+ *dst.toBool() = v
+ }
+ }
+ }
+ case reflect.String:
+ switch {
+ case isSlice: // E.g., []string
+ mfi.merge = func(dst, src pointer) {
+ sfsp := src.toStringSlice()
+ if *sfsp != nil {
+ dfsp := dst.toStringSlice()
+ *dfsp = append(*dfsp, *sfsp...)
+ if *dfsp == nil {
+ *dfsp = []string{}
+ }
+ }
+ }
+ case isPointer: // E.g., *string
+ mfi.merge = func(dst, src pointer) {
+ sfpp := src.toStringPtr()
+ if *sfpp != nil {
+ dfpp := dst.toStringPtr()
+ if *dfpp == nil {
+ *dfpp = String(**sfpp)
+ } else {
+ **dfpp = **sfpp
+ }
+ }
+ }
+ default: // E.g., string
+ mfi.merge = func(dst, src pointer) {
+ if v := *src.toString(); v != "" {
+ *dst.toString() = v
+ }
+ }
+ }
+ case reflect.Slice:
+ isProto3 := props.Prop[i].proto3
+ switch {
+ case isPointer:
+ panic("bad pointer in byte slice case in " + tf.Name())
+ case tf.Elem().Kind() != reflect.Uint8:
+ panic("bad element kind in byte slice case in " + tf.Name())
+ case isSlice: // E.g., [][]byte
+ mfi.merge = func(dst, src pointer) {
+ sbsp := src.toBytesSlice()
+ if *sbsp != nil {
+ dbsp := dst.toBytesSlice()
+ for _, sb := range *sbsp {
+ if sb == nil {
+ *dbsp = append(*dbsp, nil)
+ } else {
+ *dbsp = append(*dbsp, append([]byte{}, sb...))
+ }
+ }
+ if *dbsp == nil {
+ *dbsp = [][]byte{}
+ }
+ }
+ }
+ default: // E.g., []byte
+ mfi.merge = func(dst, src pointer) {
+ sbp := src.toBytes()
+ if *sbp != nil {
+ dbp := dst.toBytes()
+ if !isProto3 || len(*sbp) > 0 {
+ *dbp = append([]byte{}, *sbp...)
+ }
+ }
+ }
+ }
+ case reflect.Struct:
+ switch {
+ case isSlice && !isPointer: // E.g. []pb.T
+ mergeInfo := getMergeInfo(tf)
+ zero := reflect.Zero(tf)
+ mfi.merge = func(dst, src pointer) {
+ // TODO: Make this faster?
+ dstsp := dst.asPointerTo(f.Type)
+ dsts := dstsp.Elem()
+ srcs := src.asPointerTo(f.Type).Elem()
+ for i := 0; i < srcs.Len(); i++ {
+ dsts = reflect.Append(dsts, zero)
+ srcElement := srcs.Index(i).Addr()
+ dstElement := dsts.Index(dsts.Len() - 1).Addr()
+ mergeInfo.merge(valToPointer(dstElement), valToPointer(srcElement))
+ }
+ if dsts.IsNil() {
+ dsts = reflect.MakeSlice(f.Type, 0, 0)
+ }
+ dstsp.Elem().Set(dsts)
+ }
+ case !isPointer:
+ mergeInfo := getMergeInfo(tf)
+ mfi.merge = func(dst, src pointer) {
+ mergeInfo.merge(dst, src)
+ }
+ case isSlice: // E.g., []*pb.T
+ mergeInfo := getMergeInfo(tf)
+ mfi.merge = func(dst, src pointer) {
+ sps := src.getPointerSlice()
+ if sps != nil {
+ dps := dst.getPointerSlice()
+ for _, sp := range sps {
+ var dp pointer
+ if !sp.isNil() {
+ dp = valToPointer(reflect.New(tf))
+ mergeInfo.merge(dp, sp)
+ }
+ dps = append(dps, dp)
+ }
+ if dps == nil {
+ dps = []pointer{}
+ }
+ dst.setPointerSlice(dps)
+ }
+ }
+ default: // E.g., *pb.T
+ mergeInfo := getMergeInfo(tf)
+ mfi.merge = func(dst, src pointer) {
+ sp := src.getPointer()
+ if !sp.isNil() {
+ dp := dst.getPointer()
+ if dp.isNil() {
+ dp = valToPointer(reflect.New(tf))
+ dst.setPointer(dp)
+ }
+ mergeInfo.merge(dp, sp)
+ }
+ }
+ }
+ case reflect.Map:
+ switch {
+ case isPointer || isSlice:
+ panic("bad pointer or slice in map case in " + tf.Name())
+ default: // E.g., map[K]V
+ mfi.merge = func(dst, src pointer) {
+ sm := src.asPointerTo(tf).Elem()
+ if sm.Len() == 0 {
+ return
+ }
+ dm := dst.asPointerTo(tf).Elem()
+ if dm.IsNil() {
+ dm.Set(reflect.MakeMap(tf))
+ }
+
+ switch tf.Elem().Kind() {
+ case reflect.Ptr: // Proto struct (e.g., *T)
+ for _, key := range sm.MapKeys() {
+ val := sm.MapIndex(key)
+ val = reflect.ValueOf(Clone(val.Interface().(Message)))
+ dm.SetMapIndex(key, val)
+ }
+ case reflect.Slice: // E.g. Bytes type (e.g., []byte)
+ for _, key := range sm.MapKeys() {
+ val := sm.MapIndex(key)
+ val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
+ dm.SetMapIndex(key, val)
+ }
+ default: // Basic type (e.g., string)
+ for _, key := range sm.MapKeys() {
+ val := sm.MapIndex(key)
+ dm.SetMapIndex(key, val)
+ }
+ }
+ }
+ }
+ case reflect.Interface:
+ // Must be oneof field.
+ switch {
+ case isPointer || isSlice:
+ panic("bad pointer or slice in interface case in " + tf.Name())
+ default: // E.g., interface{}
+ // TODO: Make this faster?
+ mfi.merge = func(dst, src pointer) {
+ su := src.asPointerTo(tf).Elem()
+ if !su.IsNil() {
+ du := dst.asPointerTo(tf).Elem()
+ typ := su.Elem().Type()
+ if du.IsNil() || du.Elem().Type() != typ {
+ du.Set(reflect.New(typ.Elem())) // Initialize interface if empty
+ }
+ sv := su.Elem().Elem().Field(0)
+ if sv.Kind() == reflect.Ptr && sv.IsNil() {
+ return
+ }
+ dv := du.Elem().Elem().Field(0)
+ if dv.Kind() == reflect.Ptr && dv.IsNil() {
+ dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty
+ }
+ switch sv.Type().Kind() {
+ case reflect.Ptr: // Proto struct (e.g., *T)
+ Merge(dv.Interface().(Message), sv.Interface().(Message))
+ case reflect.Slice: // E.g. Bytes type (e.g., []byte)
+ dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...)))
+ default: // Basic type (e.g., string)
+ dv.Set(sv)
+ }
+ }
+ }
+ }
+ default:
+ panic(fmt.Sprintf("merger not found for type:%s", tf))
+ }
+ mi.fields = append(mi.fields, mfi)
+ }
+
+ mi.unrecognized = invalidField
+ if f, ok := t.FieldByName("XXX_unrecognized"); ok {
+ if f.Type != reflect.TypeOf([]byte{}) {
+ panic("expected XXX_unrecognized to be of type []byte")
+ }
+ mi.unrecognized = toField(&f)
+ }
+
+ atomic.StoreInt32(&mi.initialized, 1)
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go b/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go
@@ -0,0 +1,2249 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "reflect"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "unicode/utf8"
+)
+
+// Unmarshal is the entry point from the generated .pb.go files.
+// This function is not intended to be used by non-generated code.
+// This function is not subject to any compatibility guarantee.
+// msg contains a pointer to a protocol buffer struct.
+// b is the data to be unmarshaled into the protocol buffer.
+// a is a pointer to a place to store cached unmarshal information.
+func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error {
+ // Load the unmarshal information for this message type.
+ // The atomic load ensures memory consistency.
+ u := atomicLoadUnmarshalInfo(&a.unmarshal)
+ if u == nil {
+ // Slow path: find unmarshal info for msg, update a with it.
+ u = getUnmarshalInfo(reflect.TypeOf(msg).Elem())
+ atomicStoreUnmarshalInfo(&a.unmarshal, u)
+ }
+ // Then do the unmarshaling.
+ err := u.unmarshal(toPointer(&msg), b)
+ return err
+}
+
+type unmarshalInfo struct {
+ typ reflect.Type // type of the protobuf struct
+
+ // 0 = only typ field is initialized
+ // 1 = completely initialized
+ initialized int32
+ lock sync.Mutex // prevents double initialization
+ dense []unmarshalFieldInfo // fields indexed by tag #
+ sparse map[uint64]unmarshalFieldInfo // fields indexed by tag #
+ reqFields []string // names of required fields
+ reqMask uint64 // 1<<len(reqFields)-1
+ unrecognized field // offset of []byte to put unrecognized data (or invalidField if we should throw it away)
+ extensions field // offset of extensions field (of type proto.XXX_InternalExtensions), or invalidField if it does not exist
+ oldExtensions field // offset of old-form extensions field (of type map[int]Extension)
+ extensionRanges []ExtensionRange // if non-nil, implies extensions field is valid
+ isMessageSet bool // if true, implies extensions field is valid
+
+ bytesExtensions field // offset of XXX_extensions with type []byte
+}
+
+// An unmarshaler takes a stream of bytes and a pointer to a field of a message.
+// It decodes the field, stores it at f, and returns the unused bytes.
+// w is the wire encoding.
+// b is the data after the tag and wire encoding have been read.
+type unmarshaler func(b []byte, f pointer, w int) ([]byte, error)
+
+type unmarshalFieldInfo struct {
+ // location of the field in the proto message structure.
+ field field
+
+ // function to unmarshal the data for the field.
+ unmarshal unmarshaler
+
+ // if a required field, contains a single set bit at this field's index in the required field list.
+ reqMask uint64
+
+ name string // name of the field, for error reporting
+}
+
+var (
+ unmarshalInfoMap = map[reflect.Type]*unmarshalInfo{}
+ unmarshalInfoLock sync.Mutex
+)
+
+// getUnmarshalInfo returns the data structure which can be
+// subsequently used to unmarshal a message of the given type.
+// t is the type of the message (note: not pointer to message).
+func getUnmarshalInfo(t reflect.Type) *unmarshalInfo {
+ // It would be correct to return a new unmarshalInfo
+ // unconditionally. We would end up allocating one
+ // per occurrence of that type as a message or submessage.
+ // We use a cache here just to reduce memory usage.
+ unmarshalInfoLock.Lock()
+ defer unmarshalInfoLock.Unlock()
+ u := unmarshalInfoMap[t]
+ if u == nil {
+ u = &unmarshalInfo{typ: t}
+ // Note: we just set the type here. The rest of the fields
+ // will be initialized on first use.
+ unmarshalInfoMap[t] = u
+ }
+ return u
+}
+
+// unmarshal does the main work of unmarshaling a message.
+// u provides type information used to unmarshal the message.
+// m is a pointer to a protocol buffer message.
+// b is a byte stream to unmarshal into m.
+// This is top routine used when recursively unmarshaling submessages.
+func (u *unmarshalInfo) unmarshal(m pointer, b []byte) error {
+ if atomic.LoadInt32(&u.initialized) == 0 {
+ u.computeUnmarshalInfo()
+ }
+ if u.isMessageSet {
+ return unmarshalMessageSet(b, m.offset(u.extensions).toExtensions())
+ }
+ var reqMask uint64 // bitmask of required fields we've seen.
+ var errLater error
+ for len(b) > 0 {
+ // Read tag and wire type.
+ // Special case 1 and 2 byte varints.
+ var x uint64
+ if b[0] < 128 {
+ x = uint64(b[0])
+ b = b[1:]
+ } else if len(b) >= 2 && b[1] < 128 {
+ x = uint64(b[0]&0x7f) + uint64(b[1])<<7
+ b = b[2:]
+ } else {
+ var n int
+ x, n = decodeVarint(b)
+ if n == 0 {
+ return io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ }
+ tag := x >> 3
+ wire := int(x) & 7
+
+ // Dispatch on the tag to one of the unmarshal* functions below.
+ var f unmarshalFieldInfo
+ if tag < uint64(len(u.dense)) {
+ f = u.dense[tag]
+ } else {
+ f = u.sparse[tag]
+ }
+ if fn := f.unmarshal; fn != nil {
+ var err error
+ b, err = fn(b, m.offset(f.field), wire)
+ if err == nil {
+ reqMask |= f.reqMask
+ continue
+ }
+ if r, ok := err.(*RequiredNotSetError); ok {
+ // Remember this error, but keep parsing. We need to produce
+ // a full parse even if a required field is missing.
+ if errLater == nil {
+ errLater = r
+ }
+ reqMask |= f.reqMask
+ continue
+ }
+ if err != errInternalBadWireType {
+ if err == errInvalidUTF8 {
+ if errLater == nil {
+ fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
+ errLater = &invalidUTF8Error{fullName}
+ }
+ continue
+ }
+ return err
+ }
+ // Fragments with bad wire type are treated as unknown fields.
+ }
+
+ // Unknown tag.
+ if !u.unrecognized.IsValid() {
+ // Don't keep unrecognized data; just skip it.
+ var err error
+ b, err = skipField(b, wire)
+ if err != nil {
+ return err
+ }
+ continue
+ }
+ // Keep unrecognized data around.
+ // maybe in extensions, maybe in the unrecognized field.
+ z := m.offset(u.unrecognized).toBytes()
+ var emap map[int32]Extension
+ var e Extension
+ for _, r := range u.extensionRanges {
+ if uint64(r.Start) <= tag && tag <= uint64(r.End) {
+ if u.extensions.IsValid() {
+ mp := m.offset(u.extensions).toExtensions()
+ emap = mp.extensionsWrite()
+ e = emap[int32(tag)]
+ z = &e.enc
+ break
+ }
+ if u.oldExtensions.IsValid() {
+ p := m.offset(u.oldExtensions).toOldExtensions()
+ emap = *p
+ if emap == nil {
+ emap = map[int32]Extension{}
+ *p = emap
+ }
+ e = emap[int32(tag)]
+ z = &e.enc
+ break
+ }
+ if u.bytesExtensions.IsValid() {
+ z = m.offset(u.bytesExtensions).toBytes()
+ break
+ }
+ panic("no extensions field available")
+ }
+ }
+ // Use wire type to skip data.
+ var err error
+ b0 := b
+ b, err = skipField(b, wire)
+ if err != nil {
+ return err
+ }
+ *z = encodeVarint(*z, tag<<3|uint64(wire))
+ *z = append(*z, b0[:len(b0)-len(b)]...)
+
+ if emap != nil {
+ emap[int32(tag)] = e
+ }
+ }
+ if reqMask != u.reqMask && errLater == nil {
+ // A required field of this message is missing.
+ for _, n := range u.reqFields {
+ if reqMask&1 == 0 {
+ errLater = &RequiredNotSetError{n}
+ }
+ reqMask >>= 1
+ }
+ }
+ return errLater
+}
+
+// computeUnmarshalInfo fills in u with information for use
+// in unmarshaling protocol buffers of type u.typ.
+func (u *unmarshalInfo) computeUnmarshalInfo() {
+ u.lock.Lock()
+ defer u.lock.Unlock()
+ if u.initialized != 0 {
+ return
+ }
+ t := u.typ
+ n := t.NumField()
+
+ // Set up the "not found" value for the unrecognized byte buffer.
+ // This is the default for proto3.
+ u.unrecognized = invalidField
+ u.extensions = invalidField
+ u.oldExtensions = invalidField
+ u.bytesExtensions = invalidField
+
+ // List of the generated type and offset for each oneof field.
+ type oneofField struct {
+ ityp reflect.Type // interface type of oneof field
+ field field // offset in containing message
+ }
+ var oneofFields []oneofField
+
+ for i := 0; i < n; i++ {
+ f := t.Field(i)
+ if f.Name == "XXX_unrecognized" {
+ // The byte slice used to hold unrecognized input is special.
+ if f.Type != reflect.TypeOf(([]byte)(nil)) {
+ panic("bad type for XXX_unrecognized field: " + f.Type.Name())
+ }
+ u.unrecognized = toField(&f)
+ continue
+ }
+ if f.Name == "XXX_InternalExtensions" {
+ // Ditto here.
+ if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) {
+ panic("bad type for XXX_InternalExtensions field: " + f.Type.Name())
+ }
+ u.extensions = toField(&f)
+ if f.Tag.Get("protobuf_messageset") == "1" {
+ u.isMessageSet = true
+ }
+ continue
+ }
+ if f.Name == "XXX_extensions" {
+ // An older form of the extensions field.
+ if f.Type == reflect.TypeOf((map[int32]Extension)(nil)) {
+ u.oldExtensions = toField(&f)
+ continue
+ } else if f.Type == reflect.TypeOf(([]byte)(nil)) {
+ u.bytesExtensions = toField(&f)
+ continue
+ }
+ panic("bad type for XXX_extensions field: " + f.Type.Name())
+ }
+ if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" {
+ continue
+ }
+
+ oneof := f.Tag.Get("protobuf_oneof")
+ if oneof != "" {
+ oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)})
+ // The rest of oneof processing happens below.
+ continue
+ }
+
+ tags := f.Tag.Get("protobuf")
+ tagArray := strings.Split(tags, ",")
+ if len(tagArray) < 2 {
+ panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags)
+ }
+ tag, err := strconv.Atoi(tagArray[1])
+ if err != nil {
+ panic("protobuf tag field not an integer: " + tagArray[1])
+ }
+
+ name := ""
+ for _, tag := range tagArray[3:] {
+ if strings.HasPrefix(tag, "name=") {
+ name = tag[5:]
+ }
+ }
+
+ // Extract unmarshaling function from the field (its type and tags).
+ unmarshal := fieldUnmarshaler(&f)
+
+ // Required field?
+ var reqMask uint64
+ if tagArray[2] == "req" {
+ bit := len(u.reqFields)
+ u.reqFields = append(u.reqFields, name)
+ reqMask = uint64(1) << uint(bit)
+ // TODO: if we have more than 64 required fields, we end up
+ // not verifying that all required fields are present.
+ // Fix this, perhaps using a count of required fields?
+ }
+
+ // Store the info in the correct slot in the message.
+ u.setTag(tag, toField(&f), unmarshal, reqMask, name)
+ }
+
+ // Find any types associated with oneof fields.
+ // gogo: len(oneofFields) > 0 is needed for embedded oneof messages, without a marshaler and unmarshaler
+ if len(oneofFields) > 0 {
+ var oneofImplementers []interface{}
+ switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
+ case oneofFuncsIface:
+ _, _, _, oneofImplementers = m.XXX_OneofFuncs()
+ case oneofWrappersIface:
+ oneofImplementers = m.XXX_OneofWrappers()
+ }
+ for _, v := range oneofImplementers {
+ tptr := reflect.TypeOf(v) // *Msg_X
+ typ := tptr.Elem() // Msg_X
+
+ f := typ.Field(0) // oneof implementers have one field
+ baseUnmarshal := fieldUnmarshaler(&f)
+ tags := strings.Split(f.Tag.Get("protobuf"), ",")
+ fieldNum, err := strconv.Atoi(tags[1])
+ if err != nil {
+ panic("protobuf tag field not an integer: " + tags[1])
+ }
+ var name string
+ for _, tag := range tags {
+ if strings.HasPrefix(tag, "name=") {
+ name = strings.TrimPrefix(tag, "name=")
+ break
+ }
+ }
+
+ // Find the oneof field that this struct implements.
+ // Might take O(n^2) to process all of the oneofs, but who cares.
+ for _, of := range oneofFields {
+ if tptr.Implements(of.ityp) {
+ // We have found the corresponding interface for this struct.
+ // That lets us know where this struct should be stored
+ // when we encounter it during unmarshaling.
+ unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal)
+ u.setTag(fieldNum, of.field, unmarshal, 0, name)
+ }
+ }
+
+ }
+ }
+
+ // Get extension ranges, if any.
+ fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray")
+ if fn.IsValid() {
+ if !u.extensions.IsValid() && !u.oldExtensions.IsValid() && !u.bytesExtensions.IsValid() {
+ panic("a message with extensions, but no extensions field in " + t.Name())
+ }
+ u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange)
+ }
+
+ // Explicitly disallow tag 0. This will ensure we flag an error
+ // when decoding a buffer of all zeros. Without this code, we
+ // would decode and skip an all-zero buffer of even length.
+ // [0 0] is [tag=0/wiretype=varint varint-encoded-0].
+ u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) {
+ return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w)
+ }, 0, "")
+
+ // Set mask for required field check.
+ u.reqMask = uint64(1)<<uint(len(u.reqFields)) - 1
+
+ atomic.StoreInt32(&u.initialized, 1)
+}
+
+// setTag stores the unmarshal information for the given tag.
+// tag = tag # for field
+// field/unmarshal = unmarshal info for that field.
+// reqMask = if required, bitmask for field position in required field list. 0 otherwise.
+// name = short name of the field.
+func (u *unmarshalInfo) setTag(tag int, field field, unmarshal unmarshaler, reqMask uint64, name string) {
+ i := unmarshalFieldInfo{field: field, unmarshal: unmarshal, reqMask: reqMask, name: name}
+ n := u.typ.NumField()
+ if tag >= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here?
+ for len(u.dense) <= tag {
+ u.dense = append(u.dense, unmarshalFieldInfo{})
+ }
+ u.dense[tag] = i
+ return
+ }
+ if u.sparse == nil {
+ u.sparse = map[uint64]unmarshalFieldInfo{}
+ }
+ u.sparse[uint64(tag)] = i
+}
+
+// fieldUnmarshaler returns an unmarshaler for the given field.
+func fieldUnmarshaler(f *reflect.StructField) unmarshaler {
+ if f.Type.Kind() == reflect.Map {
+ return makeUnmarshalMap(f)
+ }
+ return typeUnmarshaler(f.Type, f.Tag.Get("protobuf"))
+}
+
+// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair.
+func typeUnmarshaler(t reflect.Type, tags string) unmarshaler {
+ tagArray := strings.Split(tags, ",")
+ encoding := tagArray[0]
+ name := "unknown"
+ ctype := false
+ isTime := false
+ isDuration := false
+ isWktPointer := false
+ proto3 := false
+ validateUTF8 := true
+ for _, tag := range tagArray[3:] {
+ if strings.HasPrefix(tag, "name=") {
+ name = tag[5:]
+ }
+ if tag == "proto3" {
+ proto3 = true
+ }
+ if strings.HasPrefix(tag, "customtype=") {
+ ctype = true
+ }
+ if tag == "stdtime" {
+ isTime = true
+ }
+ if tag == "stdduration" {
+ isDuration = true
+ }
+ if tag == "wktptr" {
+ isWktPointer = true
+ }
+ }
+ validateUTF8 = validateUTF8 && proto3
+
+ // Figure out packaging (pointer, slice, or both)
+ slice := false
+ pointer := false
+ if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
+ slice = true
+ t = t.Elem()
+ }
+ if t.Kind() == reflect.Ptr {
+ pointer = true
+ t = t.Elem()
+ }
+
+ if ctype {
+ if reflect.PtrTo(t).Implements(customType) {
+ if slice {
+ return makeUnmarshalCustomSlice(getUnmarshalInfo(t), name)
+ }
+ if pointer {
+ return makeUnmarshalCustomPtr(getUnmarshalInfo(t), name)
+ }
+ return makeUnmarshalCustom(getUnmarshalInfo(t), name)
+ } else {
+ panic(fmt.Sprintf("custom type: type: %v, does not implement the proto.custom interface", t))
+ }
+ }
+
+ if isTime {
+ if pointer {
+ if slice {
+ return makeUnmarshalTimePtrSlice(getUnmarshalInfo(t), name)
+ }
+ return makeUnmarshalTimePtr(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeUnmarshalTimeSlice(getUnmarshalInfo(t), name)
+ }
+ return makeUnmarshalTime(getUnmarshalInfo(t), name)
+ }
+
+ if isDuration {
+ if pointer {
+ if slice {
+ return makeUnmarshalDurationPtrSlice(getUnmarshalInfo(t), name)
+ }
+ return makeUnmarshalDurationPtr(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeUnmarshalDurationSlice(getUnmarshalInfo(t), name)
+ }
+ return makeUnmarshalDuration(getUnmarshalInfo(t), name)
+ }
+
+ if isWktPointer {
+ switch t.Kind() {
+ case reflect.Float64:
+ if pointer {
+ if slice {
+ return makeStdDoubleValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdDoubleValuePtrUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeStdDoubleValueSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdDoubleValueUnmarshaler(getUnmarshalInfo(t), name)
+ case reflect.Float32:
+ if pointer {
+ if slice {
+ return makeStdFloatValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdFloatValuePtrUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeStdFloatValueSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdFloatValueUnmarshaler(getUnmarshalInfo(t), name)
+ case reflect.Int64:
+ if pointer {
+ if slice {
+ return makeStdInt64ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdInt64ValuePtrUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeStdInt64ValueSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdInt64ValueUnmarshaler(getUnmarshalInfo(t), name)
+ case reflect.Uint64:
+ if pointer {
+ if slice {
+ return makeStdUInt64ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdUInt64ValuePtrUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeStdUInt64ValueSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdUInt64ValueUnmarshaler(getUnmarshalInfo(t), name)
+ case reflect.Int32:
+ if pointer {
+ if slice {
+ return makeStdInt32ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdInt32ValuePtrUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeStdInt32ValueSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdInt32ValueUnmarshaler(getUnmarshalInfo(t), name)
+ case reflect.Uint32:
+ if pointer {
+ if slice {
+ return makeStdUInt32ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdUInt32ValuePtrUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeStdUInt32ValueSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdUInt32ValueUnmarshaler(getUnmarshalInfo(t), name)
+ case reflect.Bool:
+ if pointer {
+ if slice {
+ return makeStdBoolValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdBoolValuePtrUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeStdBoolValueSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdBoolValueUnmarshaler(getUnmarshalInfo(t), name)
+ case reflect.String:
+ if pointer {
+ if slice {
+ return makeStdStringValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdStringValuePtrUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeStdStringValueSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdStringValueUnmarshaler(getUnmarshalInfo(t), name)
+ case uint8SliceType:
+ if pointer {
+ if slice {
+ return makeStdBytesValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdBytesValuePtrUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ if slice {
+ return makeStdBytesValueSliceUnmarshaler(getUnmarshalInfo(t), name)
+ }
+ return makeStdBytesValueUnmarshaler(getUnmarshalInfo(t), name)
+ default:
+ panic(fmt.Sprintf("unknown wktpointer type %#v", t))
+ }
+ }
+
+ // We'll never have both pointer and slice for basic types.
+ if pointer && slice && t.Kind() != reflect.Struct {
+ panic("both pointer and slice for basic type in " + t.Name())
+ }
+
+ switch t.Kind() {
+ case reflect.Bool:
+ if pointer {
+ return unmarshalBoolPtr
+ }
+ if slice {
+ return unmarshalBoolSlice
+ }
+ return unmarshalBoolValue
+ case reflect.Int32:
+ switch encoding {
+ case "fixed32":
+ if pointer {
+ return unmarshalFixedS32Ptr
+ }
+ if slice {
+ return unmarshalFixedS32Slice
+ }
+ return unmarshalFixedS32Value
+ case "varint":
+ // this could be int32 or enum
+ if pointer {
+ return unmarshalInt32Ptr
+ }
+ if slice {
+ return unmarshalInt32Slice
+ }
+ return unmarshalInt32Value
+ case "zigzag32":
+ if pointer {
+ return unmarshalSint32Ptr
+ }
+ if slice {
+ return unmarshalSint32Slice
+ }
+ return unmarshalSint32Value
+ }
+ case reflect.Int64:
+ switch encoding {
+ case "fixed64":
+ if pointer {
+ return unmarshalFixedS64Ptr
+ }
+ if slice {
+ return unmarshalFixedS64Slice
+ }
+ return unmarshalFixedS64Value
+ case "varint":
+ if pointer {
+ return unmarshalInt64Ptr
+ }
+ if slice {
+ return unmarshalInt64Slice
+ }
+ return unmarshalInt64Value
+ case "zigzag64":
+ if pointer {
+ return unmarshalSint64Ptr
+ }
+ if slice {
+ return unmarshalSint64Slice
+ }
+ return unmarshalSint64Value
+ }
+ case reflect.Uint32:
+ switch encoding {
+ case "fixed32":
+ if pointer {
+ return unmarshalFixed32Ptr
+ }
+ if slice {
+ return unmarshalFixed32Slice
+ }
+ return unmarshalFixed32Value
+ case "varint":
+ if pointer {
+ return unmarshalUint32Ptr
+ }
+ if slice {
+ return unmarshalUint32Slice
+ }
+ return unmarshalUint32Value
+ }
+ case reflect.Uint64:
+ switch encoding {
+ case "fixed64":
+ if pointer {
+ return unmarshalFixed64Ptr
+ }
+ if slice {
+ return unmarshalFixed64Slice
+ }
+ return unmarshalFixed64Value
+ case "varint":
+ if pointer {
+ return unmarshalUint64Ptr
+ }
+ if slice {
+ return unmarshalUint64Slice
+ }
+ return unmarshalUint64Value
+ }
+ case reflect.Float32:
+ if pointer {
+ return unmarshalFloat32Ptr
+ }
+ if slice {
+ return unmarshalFloat32Slice
+ }
+ return unmarshalFloat32Value
+ case reflect.Float64:
+ if pointer {
+ return unmarshalFloat64Ptr
+ }
+ if slice {
+ return unmarshalFloat64Slice
+ }
+ return unmarshalFloat64Value
+ case reflect.Map:
+ panic("map type in typeUnmarshaler in " + t.Name())
+ case reflect.Slice:
+ if pointer {
+ panic("bad pointer in slice case in " + t.Name())
+ }
+ if slice {
+ return unmarshalBytesSlice
+ }
+ return unmarshalBytesValue
+ case reflect.String:
+ if validateUTF8 {
+ if pointer {
+ return unmarshalUTF8StringPtr
+ }
+ if slice {
+ return unmarshalUTF8StringSlice
+ }
+ return unmarshalUTF8StringValue
+ }
+ if pointer {
+ return unmarshalStringPtr
+ }
+ if slice {
+ return unmarshalStringSlice
+ }
+ return unmarshalStringValue
+ case reflect.Struct:
+ // message or group field
+ if !pointer {
+ switch encoding {
+ case "bytes":
+ if slice {
+ return makeUnmarshalMessageSlice(getUnmarshalInfo(t), name)
+ }
+ return makeUnmarshalMessage(getUnmarshalInfo(t), name)
+ }
+ }
+ switch encoding {
+ case "bytes":
+ if slice {
+ return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name)
+ }
+ return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name)
+ case "group":
+ if slice {
+ return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name)
+ }
+ return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name)
+ }
+ }
+ panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding))
+}
+
+// Below are all the unmarshalers for individual fields of various types.
+
+func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int64(x)
+ *f.toInt64() = v
+ return b, nil
+}
+
+func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int64(x)
+ *f.toInt64Ptr() = &v
+ return b, nil
+}
+
+func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ x, n = decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int64(x)
+ s := f.toInt64Slice()
+ *s = append(*s, v)
+ }
+ return res, nil
+ }
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int64(x)
+ s := f.toInt64Slice()
+ *s = append(*s, v)
+ return b, nil
+}
+
+func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int64(x>>1) ^ int64(x)<<63>>63
+ *f.toInt64() = v
+ return b, nil
+}
+
+func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int64(x>>1) ^ int64(x)<<63>>63
+ *f.toInt64Ptr() = &v
+ return b, nil
+}
+
+func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ x, n = decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int64(x>>1) ^ int64(x)<<63>>63
+ s := f.toInt64Slice()
+ *s = append(*s, v)
+ }
+ return res, nil
+ }
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int64(x>>1) ^ int64(x)<<63>>63
+ s := f.toInt64Slice()
+ *s = append(*s, v)
+ return b, nil
+}
+
+func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := uint64(x)
+ *f.toUint64() = v
+ return b, nil
+}
+
+func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := uint64(x)
+ *f.toUint64Ptr() = &v
+ return b, nil
+}
+
+func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ x, n = decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := uint64(x)
+ s := f.toUint64Slice()
+ *s = append(*s, v)
+ }
+ return res, nil
+ }
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := uint64(x)
+ s := f.toUint64Slice()
+ *s = append(*s, v)
+ return b, nil
+}
+
+func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int32(x)
+ *f.toInt32() = v
+ return b, nil
+}
+
+func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int32(x)
+ f.setInt32Ptr(v)
+ return b, nil
+}
+
+func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ x, n = decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int32(x)
+ f.appendInt32Slice(v)
+ }
+ return res, nil
+ }
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int32(x)
+ f.appendInt32Slice(v)
+ return b, nil
+}
+
+func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int32(x>>1) ^ int32(x)<<31>>31
+ *f.toInt32() = v
+ return b, nil
+}
+
+func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int32(x>>1) ^ int32(x)<<31>>31
+ f.setInt32Ptr(v)
+ return b, nil
+}
+
+func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ x, n = decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int32(x>>1) ^ int32(x)<<31>>31
+ f.appendInt32Slice(v)
+ }
+ return res, nil
+ }
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := int32(x>>1) ^ int32(x)<<31>>31
+ f.appendInt32Slice(v)
+ return b, nil
+}
+
+func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := uint32(x)
+ *f.toUint32() = v
+ return b, nil
+}
+
+func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := uint32(x)
+ *f.toUint32Ptr() = &v
+ return b, nil
+}
+
+func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ x, n = decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := uint32(x)
+ s := f.toUint32Slice()
+ *s = append(*s, v)
+ }
+ return res, nil
+ }
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ v := uint32(x)
+ s := f.toUint32Slice()
+ *s = append(*s, v)
+ return b, nil
+}
+
+func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed64 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
+ *f.toUint64() = v
+ return b[8:], nil
+}
+
+func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed64 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
+ *f.toUint64Ptr() = &v
+ return b[8:], nil
+}
+
+func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
+ s := f.toUint64Slice()
+ *s = append(*s, v)
+ b = b[8:]
+ }
+ return res, nil
+ }
+ if w != WireFixed64 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
+ s := f.toUint64Slice()
+ *s = append(*s, v)
+ return b[8:], nil
+}
+
+func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed64 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
+ *f.toInt64() = v
+ return b[8:], nil
+}
+
+func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed64 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
+ *f.toInt64Ptr() = &v
+ return b[8:], nil
+}
+
+func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
+ s := f.toInt64Slice()
+ *s = append(*s, v)
+ b = b[8:]
+ }
+ return res, nil
+ }
+ if w != WireFixed64 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
+ s := f.toInt64Slice()
+ *s = append(*s, v)
+ return b[8:], nil
+}
+
+func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed32 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
+ *f.toUint32() = v
+ return b[4:], nil
+}
+
+func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed32 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
+ *f.toUint32Ptr() = &v
+ return b[4:], nil
+}
+
+func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
+ s := f.toUint32Slice()
+ *s = append(*s, v)
+ b = b[4:]
+ }
+ return res, nil
+ }
+ if w != WireFixed32 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
+ s := f.toUint32Slice()
+ *s = append(*s, v)
+ return b[4:], nil
+}
+
+func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed32 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
+ *f.toInt32() = v
+ return b[4:], nil
+}
+
+func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed32 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
+ f.setInt32Ptr(v)
+ return b[4:], nil
+}
+
+func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
+ f.appendInt32Slice(v)
+ b = b[4:]
+ }
+ return res, nil
+ }
+ if w != WireFixed32 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
+ f.appendInt32Slice(v)
+ return b[4:], nil
+}
+
+func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ // Note: any length varint is allowed, even though any sane
+ // encoder will use one byte.
+ // See https://github.com/golang/protobuf/issues/76
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ // TODO: check if x>1? Tests seem to indicate no.
+ v := x != 0
+ *f.toBool() = v
+ return b[n:], nil
+}
+
+func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := x != 0
+ *f.toBoolPtr() = &v
+ return b[n:], nil
+}
+
+func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ x, n = decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := x != 0
+ s := f.toBoolSlice()
+ *s = append(*s, v)
+ b = b[n:]
+ }
+ return res, nil
+ }
+ if w != WireVarint {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := x != 0
+ s := f.toBoolSlice()
+ *s = append(*s, v)
+ return b[n:], nil
+}
+
+func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed64 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
+ *f.toFloat64() = v
+ return b[8:], nil
+}
+
+func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed64 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
+ *f.toFloat64Ptr() = &v
+ return b[8:], nil
+}
+
+func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
+ s := f.toFloat64Slice()
+ *s = append(*s, v)
+ b = b[8:]
+ }
+ return res, nil
+ }
+ if w != WireFixed64 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 8 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
+ s := f.toFloat64Slice()
+ *s = append(*s, v)
+ return b[8:], nil
+}
+
+func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed32 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
+ *f.toFloat32() = v
+ return b[4:], nil
+}
+
+func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireFixed32 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
+ *f.toFloat32Ptr() = &v
+ return b[4:], nil
+}
+
+func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) {
+ if w == WireBytes { // packed
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ res := b[x:]
+ b = b[:x]
+ for len(b) > 0 {
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
+ s := f.toFloat32Slice()
+ *s = append(*s, v)
+ b = b[4:]
+ }
+ return res, nil
+ }
+ if w != WireFixed32 {
+ return b, errInternalBadWireType
+ }
+ if len(b) < 4 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
+ s := f.toFloat32Slice()
+ *s = append(*s, v)
+ return b[4:], nil
+}
+
+func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := string(b[:x])
+ *f.toString() = v
+ return b[x:], nil
+}
+
+func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := string(b[:x])
+ *f.toStringPtr() = &v
+ return b[x:], nil
+}
+
+func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := string(b[:x])
+ s := f.toStringSlice()
+ *s = append(*s, v)
+ return b[x:], nil
+}
+
+func unmarshalUTF8StringValue(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := string(b[:x])
+ *f.toString() = v
+ if !utf8.ValidString(v) {
+ return b[x:], errInvalidUTF8
+ }
+ return b[x:], nil
+}
+
+func unmarshalUTF8StringPtr(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := string(b[:x])
+ *f.toStringPtr() = &v
+ if !utf8.ValidString(v) {
+ return b[x:], errInvalidUTF8
+ }
+ return b[x:], nil
+}
+
+func unmarshalUTF8StringSlice(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := string(b[:x])
+ s := f.toStringSlice()
+ *s = append(*s, v)
+ if !utf8.ValidString(v) {
+ return b[x:], errInvalidUTF8
+ }
+ return b[x:], nil
+}
+
+var emptyBuf [0]byte
+
+func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ // The use of append here is a trick which avoids the zeroing
+ // that would be required if we used a make/copy pair.
+ // We append to emptyBuf instead of nil because we want
+ // a non-nil result even when the length is 0.
+ v := append(emptyBuf[:], b[:x]...)
+ *f.toBytes() = v
+ return b[x:], nil
+}
+
+func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := append(emptyBuf[:], b[:x]...)
+ s := f.toBytesSlice()
+ *s = append(*s, v)
+ return b[x:], nil
+}
+
+func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ // First read the message field to see if something is there.
+ // The semantics of multiple submessages are weird. Instead of
+ // the last one winning (as it is for all other fields), multiple
+ // submessages are merged.
+ v := f.getPointer()
+ if v.isNil() {
+ v = valToPointer(reflect.New(sub.typ))
+ f.setPointer(v)
+ }
+ err := sub.unmarshal(v, b[:x])
+ if err != nil {
+ if r, ok := err.(*RequiredNotSetError); ok {
+ r.field = name + "." + r.field
+ } else {
+ return nil, err
+ }
+ }
+ return b[x:], err
+ }
+}
+
+func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return b, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := valToPointer(reflect.New(sub.typ))
+ err := sub.unmarshal(v, b[:x])
+ if err != nil {
+ if r, ok := err.(*RequiredNotSetError); ok {
+ r.field = name + "." + r.field
+ } else {
+ return nil, err
+ }
+ }
+ f.appendPointer(v)
+ return b[x:], err
+ }
+}
+
+func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireStartGroup {
+ return b, errInternalBadWireType
+ }
+ x, y := findEndGroup(b)
+ if x < 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := f.getPointer()
+ if v.isNil() {
+ v = valToPointer(reflect.New(sub.typ))
+ f.setPointer(v)
+ }
+ err := sub.unmarshal(v, b[:x])
+ if err != nil {
+ if r, ok := err.(*RequiredNotSetError); ok {
+ r.field = name + "." + r.field
+ } else {
+ return nil, err
+ }
+ }
+ return b[y:], err
+ }
+}
+
+func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireStartGroup {
+ return b, errInternalBadWireType
+ }
+ x, y := findEndGroup(b)
+ if x < 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := valToPointer(reflect.New(sub.typ))
+ err := sub.unmarshal(v, b[:x])
+ if err != nil {
+ if r, ok := err.(*RequiredNotSetError); ok {
+ r.field = name + "." + r.field
+ } else {
+ return nil, err
+ }
+ }
+ f.appendPointer(v)
+ return b[y:], err
+ }
+}
+
+func makeUnmarshalMap(f *reflect.StructField) unmarshaler {
+ t := f.Type
+ kt := t.Key()
+ vt := t.Elem()
+ tagArray := strings.Split(f.Tag.Get("protobuf"), ",")
+ valTags := strings.Split(f.Tag.Get("protobuf_val"), ",")
+ for _, t := range tagArray {
+ if strings.HasPrefix(t, "customtype=") {
+ valTags = append(valTags, t)
+ }
+ if t == "stdtime" {
+ valTags = append(valTags, t)
+ }
+ if t == "stdduration" {
+ valTags = append(valTags, t)
+ }
+ if t == "wktptr" {
+ valTags = append(valTags, t)
+ }
+ }
+ unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key"))
+ unmarshalVal := typeUnmarshaler(vt, strings.Join(valTags, ","))
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ // The map entry is a submessage. Figure out how big it is.
+ if w != WireBytes {
+ return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes)
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ r := b[x:] // unused data to return
+ b = b[:x] // data for map entry
+
+ // Note: we could use #keys * #values ~= 200 functions
+ // to do map decoding without reflection. Probably not worth it.
+ // Maps will be somewhat slow. Oh well.
+
+ // Read key and value from data.
+ var nerr nonFatal
+ k := reflect.New(kt)
+ v := reflect.New(vt)
+ for len(b) > 0 {
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ wire := int(x) & 7
+ b = b[n:]
+
+ var err error
+ switch x >> 3 {
+ case 1:
+ b, err = unmarshalKey(b, valToPointer(k), wire)
+ case 2:
+ b, err = unmarshalVal(b, valToPointer(v), wire)
+ default:
+ err = errInternalBadWireType // skip unknown tag
+ }
+
+ if nerr.Merge(err) {
+ continue
+ }
+ if err != errInternalBadWireType {
+ return nil, err
+ }
+
+ // Skip past unknown fields.
+ b, err = skipField(b, wire)
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ // Get map, allocate if needed.
+ m := f.asPointerTo(t).Elem() // an addressable map[K]T
+ if m.IsNil() {
+ m.Set(reflect.MakeMap(t))
+ }
+
+ // Insert into map.
+ m.SetMapIndex(k.Elem(), v.Elem())
+
+ return r, nerr.E
+ }
+}
+
+// makeUnmarshalOneof makes an unmarshaler for oneof fields.
+// for:
+// message Msg {
+// oneof F {
+// int64 X = 1;
+// float64 Y = 2;
+// }
+// }
+// typ is the type of the concrete entry for a oneof case (e.g. Msg_X).
+// ityp is the interface type of the oneof field (e.g. isMsg_F).
+// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64).
+// Note that this function will be called once for each case in the oneof.
+func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler {
+ sf := typ.Field(0)
+ field0 := toField(&sf)
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ // Allocate holder for value.
+ v := reflect.New(typ)
+
+ // Unmarshal data into holder.
+ // We unmarshal into the first field of the holder object.
+ var err error
+ var nerr nonFatal
+ b, err = unmarshal(b, valToPointer(v).offset(field0), w)
+ if !nerr.Merge(err) {
+ return nil, err
+ }
+
+ // Write pointer to holder into target field.
+ f.asPointerTo(ityp).Elem().Set(v)
+
+ return b, nerr.E
+ }
+}
+
+// Error used by decode internally.
+var errInternalBadWireType = errors.New("proto: internal error: bad wiretype")
+
+// skipField skips past a field of type wire and returns the remaining bytes.
+func skipField(b []byte, wire int) ([]byte, error) {
+ switch wire {
+ case WireVarint:
+ _, k := decodeVarint(b)
+ if k == 0 {
+ return b, io.ErrUnexpectedEOF
+ }
+ b = b[k:]
+ case WireFixed32:
+ if len(b) < 4 {
+ return b, io.ErrUnexpectedEOF
+ }
+ b = b[4:]
+ case WireFixed64:
+ if len(b) < 8 {
+ return b, io.ErrUnexpectedEOF
+ }
+ b = b[8:]
+ case WireBytes:
+ m, k := decodeVarint(b)
+ if k == 0 || uint64(len(b)-k) < m {
+ return b, io.ErrUnexpectedEOF
+ }
+ b = b[uint64(k)+m:]
+ case WireStartGroup:
+ _, i := findEndGroup(b)
+ if i == -1 {
+ return b, io.ErrUnexpectedEOF
+ }
+ b = b[i:]
+ default:
+ return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire)
+ }
+ return b, nil
+}
+
+// findEndGroup finds the index of the next EndGroup tag.
+// Groups may be nested, so the "next" EndGroup tag is the first
+// unpaired EndGroup.
+// findEndGroup returns the indexes of the start and end of the EndGroup tag.
+// Returns (-1,-1) if it can't find one.
+func findEndGroup(b []byte) (int, int) {
+ depth := 1
+ i := 0
+ for {
+ x, n := decodeVarint(b[i:])
+ if n == 0 {
+ return -1, -1
+ }
+ j := i
+ i += n
+ switch x & 7 {
+ case WireVarint:
+ _, k := decodeVarint(b[i:])
+ if k == 0 {
+ return -1, -1
+ }
+ i += k
+ case WireFixed32:
+ if len(b)-4 < i {
+ return -1, -1
+ }
+ i += 4
+ case WireFixed64:
+ if len(b)-8 < i {
+ return -1, -1
+ }
+ i += 8
+ case WireBytes:
+ m, k := decodeVarint(b[i:])
+ if k == 0 {
+ return -1, -1
+ }
+ i += k
+ if uint64(len(b)-i) < m {
+ return -1, -1
+ }
+ i += int(m)
+ case WireStartGroup:
+ depth++
+ case WireEndGroup:
+ depth--
+ if depth == 0 {
+ return j, i
+ }
+ default:
+ return -1, -1
+ }
+ }
+}
+
+// encodeVarint appends a varint-encoded integer to b and returns the result.
+func encodeVarint(b []byte, x uint64) []byte {
+ for x >= 1<<7 {
+ b = append(b, byte(x&0x7f|0x80))
+ x >>= 7
+ }
+ return append(b, byte(x))
+}
+
+// decodeVarint reads a varint-encoded integer from b.
+// Returns the decoded integer and the number of bytes read.
+// If there is an error, it returns 0,0.
+func decodeVarint(b []byte) (uint64, int) {
+ var x, y uint64
+ if len(b) == 0 {
+ goto bad
+ }
+ x = uint64(b[0])
+ if x < 0x80 {
+ return x, 1
+ }
+ x -= 0x80
+
+ if len(b) <= 1 {
+ goto bad
+ }
+ y = uint64(b[1])
+ x += y << 7
+ if y < 0x80 {
+ return x, 2
+ }
+ x -= 0x80 << 7
+
+ if len(b) <= 2 {
+ goto bad
+ }
+ y = uint64(b[2])
+ x += y << 14
+ if y < 0x80 {
+ return x, 3
+ }
+ x -= 0x80 << 14
+
+ if len(b) <= 3 {
+ goto bad
+ }
+ y = uint64(b[3])
+ x += y << 21
+ if y < 0x80 {
+ return x, 4
+ }
+ x -= 0x80 << 21
+
+ if len(b) <= 4 {
+ goto bad
+ }
+ y = uint64(b[4])
+ x += y << 28
+ if y < 0x80 {
+ return x, 5
+ }
+ x -= 0x80 << 28
+
+ if len(b) <= 5 {
+ goto bad
+ }
+ y = uint64(b[5])
+ x += y << 35
+ if y < 0x80 {
+ return x, 6
+ }
+ x -= 0x80 << 35
+
+ if len(b) <= 6 {
+ goto bad
+ }
+ y = uint64(b[6])
+ x += y << 42
+ if y < 0x80 {
+ return x, 7
+ }
+ x -= 0x80 << 42
+
+ if len(b) <= 7 {
+ goto bad
+ }
+ y = uint64(b[7])
+ x += y << 49
+ if y < 0x80 {
+ return x, 8
+ }
+ x -= 0x80 << 49
+
+ if len(b) <= 8 {
+ goto bad
+ }
+ y = uint64(b[8])
+ x += y << 56
+ if y < 0x80 {
+ return x, 9
+ }
+ x -= 0x80 << 56
+
+ if len(b) <= 9 {
+ goto bad
+ }
+ y = uint64(b[9])
+ x += y << 63
+ if y < 2 {
+ return x, 10
+ }
+
+bad:
+ return 0, 0
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/table_unmarshal_gogo.go b/vendor/github.com/gogo/protobuf/proto/table_unmarshal_gogo.go
@@ -0,0 +1,385 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2018, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import (
+ "io"
+ "reflect"
+)
+
+func makeUnmarshalMessage(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ // First read the message field to see if something is there.
+ // The semantics of multiple submessages are weird. Instead of
+ // the last one winning (as it is for all other fields), multiple
+ // submessages are merged.
+ v := f // gogo: changed from v := f.getPointer()
+ if v.isNil() {
+ v = valToPointer(reflect.New(sub.typ))
+ f.setPointer(v)
+ }
+ err := sub.unmarshal(v, b[:x])
+ if err != nil {
+ if r, ok := err.(*RequiredNotSetError); ok {
+ r.field = name + "." + r.field
+ } else {
+ return nil, err
+ }
+ }
+ return b[x:], err
+ }
+}
+
+func makeUnmarshalMessageSlice(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ v := valToPointer(reflect.New(sub.typ))
+ err := sub.unmarshal(v, b[:x])
+ if err != nil {
+ if r, ok := err.(*RequiredNotSetError); ok {
+ r.field = name + "." + r.field
+ } else {
+ return nil, err
+ }
+ }
+ f.appendRef(v, sub.typ) // gogo: changed from f.appendPointer(v)
+ return b[x:], err
+ }
+}
+
+func makeUnmarshalCustomPtr(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.New(sub.typ))
+ m := s.Interface().(custom)
+ if err := m.Unmarshal(b[:x]); err != nil {
+ return nil, err
+ }
+ return b[x:], nil
+ }
+}
+
+func makeUnmarshalCustomSlice(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := reflect.New(sub.typ)
+ c := m.Interface().(custom)
+ if err := c.Unmarshal(b[:x]); err != nil {
+ return nil, err
+ }
+ v := valToPointer(m)
+ f.appendRef(v, sub.typ)
+ return b[x:], nil
+ }
+}
+
+func makeUnmarshalCustom(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+
+ m := f.asPointerTo(sub.typ).Interface().(custom)
+ if err := m.Unmarshal(b[:x]); err != nil {
+ return nil, err
+ }
+ return b[x:], nil
+ }
+}
+
+func makeUnmarshalTime(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := ×tamp{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ t, err := timestampFromProto(m)
+ if err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(t))
+ return b[x:], nil
+ }
+}
+
+func makeUnmarshalTimePtr(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := ×tamp{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ t, err := timestampFromProto(m)
+ if err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&t))
+ return b[x:], nil
+ }
+}
+
+func makeUnmarshalTimePtrSlice(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := ×tamp{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ t, err := timestampFromProto(m)
+ if err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&t))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeUnmarshalTimeSlice(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := ×tamp{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ t, err := timestampFromProto(m)
+ if err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(t))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeUnmarshalDurationPtr(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &duration{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ d, err := durationFromProto(m)
+ if err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&d))
+ return b[x:], nil
+ }
+}
+
+func makeUnmarshalDuration(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &duration{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ d, err := durationFromProto(m)
+ if err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(d))
+ return b[x:], nil
+ }
+}
+
+func makeUnmarshalDurationPtrSlice(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &duration{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ d, err := durationFromProto(m)
+ if err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&d))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeUnmarshalDurationSlice(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &duration{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ d, err := durationFromProto(m)
+ if err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(d))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/text.go b/vendor/github.com/gogo/protobuf/proto/text.go
@@ -0,0 +1,930 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+// Functions for writing the text protocol buffer format.
+
+import (
+ "bufio"
+ "bytes"
+ "encoding"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "math"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+)
+
+var (
+ newline = []byte("\n")
+ spaces = []byte(" ")
+ endBraceNewline = []byte("}\n")
+ backslashN = []byte{'\\', 'n'}
+ backslashR = []byte{'\\', 'r'}
+ backslashT = []byte{'\\', 't'}
+ backslashDQ = []byte{'\\', '"'}
+ backslashBS = []byte{'\\', '\\'}
+ posInf = []byte("inf")
+ negInf = []byte("-inf")
+ nan = []byte("nan")
+)
+
+type writer interface {
+ io.Writer
+ WriteByte(byte) error
+}
+
+// textWriter is an io.Writer that tracks its indentation level.
+type textWriter struct {
+ ind int
+ complete bool // if the current position is a complete line
+ compact bool // whether to write out as a one-liner
+ w writer
+}
+
+func (w *textWriter) WriteString(s string) (n int, err error) {
+ if !strings.Contains(s, "\n") {
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ w.complete = false
+ return io.WriteString(w.w, s)
+ }
+ // WriteString is typically called without newlines, so this
+ // codepath and its copy are rare. We copy to avoid
+ // duplicating all of Write's logic here.
+ return w.Write([]byte(s))
+}
+
+func (w *textWriter) Write(p []byte) (n int, err error) {
+ newlines := bytes.Count(p, newline)
+ if newlines == 0 {
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ n, err = w.w.Write(p)
+ w.complete = false
+ return n, err
+ }
+
+ frags := bytes.SplitN(p, newline, newlines+1)
+ if w.compact {
+ for i, frag := range frags {
+ if i > 0 {
+ if err := w.w.WriteByte(' '); err != nil {
+ return n, err
+ }
+ n++
+ }
+ nn, err := w.w.Write(frag)
+ n += nn
+ if err != nil {
+ return n, err
+ }
+ }
+ return n, nil
+ }
+
+ for i, frag := range frags {
+ if w.complete {
+ w.writeIndent()
+ }
+ nn, err := w.w.Write(frag)
+ n += nn
+ if err != nil {
+ return n, err
+ }
+ if i+1 < len(frags) {
+ if err := w.w.WriteByte('\n'); err != nil {
+ return n, err
+ }
+ n++
+ }
+ }
+ w.complete = len(frags[len(frags)-1]) == 0
+ return n, nil
+}
+
+func (w *textWriter) WriteByte(c byte) error {
+ if w.compact && c == '\n' {
+ c = ' '
+ }
+ if !w.compact && w.complete {
+ w.writeIndent()
+ }
+ err := w.w.WriteByte(c)
+ w.complete = c == '\n'
+ return err
+}
+
+func (w *textWriter) indent() { w.ind++ }
+
+func (w *textWriter) unindent() {
+ if w.ind == 0 {
+ log.Print("proto: textWriter unindented too far")
+ return
+ }
+ w.ind--
+}
+
+func writeName(w *textWriter, props *Properties) error {
+ if _, err := w.WriteString(props.OrigName); err != nil {
+ return err
+ }
+ if props.Wire != "group" {
+ return w.WriteByte(':')
+ }
+ return nil
+}
+
+func requiresQuotes(u string) bool {
+ // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
+ for _, ch := range u {
+ switch {
+ case ch == '.' || ch == '/' || ch == '_':
+ continue
+ case '0' <= ch && ch <= '9':
+ continue
+ case 'A' <= ch && ch <= 'Z':
+ continue
+ case 'a' <= ch && ch <= 'z':
+ continue
+ default:
+ return true
+ }
+ }
+ return false
+}
+
+// isAny reports whether sv is a google.protobuf.Any message
+func isAny(sv reflect.Value) bool {
+ type wkt interface {
+ XXX_WellKnownType() string
+ }
+ t, ok := sv.Addr().Interface().(wkt)
+ return ok && t.XXX_WellKnownType() == "Any"
+}
+
+// writeProto3Any writes an expanded google.protobuf.Any message.
+//
+// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
+// required messages are not linked in).
+//
+// It returns (true, error) when sv was written in expanded format or an error
+// was encountered.
+func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
+ turl := sv.FieldByName("TypeUrl")
+ val := sv.FieldByName("Value")
+ if !turl.IsValid() || !val.IsValid() {
+ return true, errors.New("proto: invalid google.protobuf.Any message")
+ }
+
+ b, ok := val.Interface().([]byte)
+ if !ok {
+ return true, errors.New("proto: invalid google.protobuf.Any message")
+ }
+
+ parts := strings.Split(turl.String(), "/")
+ mt := MessageType(parts[len(parts)-1])
+ if mt == nil {
+ return false, nil
+ }
+ m := reflect.New(mt.Elem())
+ if err := Unmarshal(b, m.Interface().(Message)); err != nil {
+ return false, nil
+ }
+ w.Write([]byte("["))
+ u := turl.String()
+ if requiresQuotes(u) {
+ writeString(w, u)
+ } else {
+ w.Write([]byte(u))
+ }
+ if w.compact {
+ w.Write([]byte("]:<"))
+ } else {
+ w.Write([]byte("]: <\n"))
+ w.ind++
+ }
+ if err := tm.writeStruct(w, m.Elem()); err != nil {
+ return true, err
+ }
+ if w.compact {
+ w.Write([]byte("> "))
+ } else {
+ w.ind--
+ w.Write([]byte(">\n"))
+ }
+ return true, nil
+}
+
+func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
+ if tm.ExpandAny && isAny(sv) {
+ if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
+ return err
+ }
+ }
+ st := sv.Type()
+ sprops := GetProperties(st)
+ for i := 0; i < sv.NumField(); i++ {
+ fv := sv.Field(i)
+ props := sprops.Prop[i]
+ name := st.Field(i).Name
+
+ if name == "XXX_NoUnkeyedLiteral" {
+ continue
+ }
+
+ if strings.HasPrefix(name, "XXX_") {
+ // There are two XXX_ fields:
+ // XXX_unrecognized []byte
+ // XXX_extensions map[int32]proto.Extension
+ // The first is handled here;
+ // the second is handled at the bottom of this function.
+ if name == "XXX_unrecognized" && !fv.IsNil() {
+ if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if fv.Kind() == reflect.Ptr && fv.IsNil() {
+ // Field not filled in. This could be an optional field or
+ // a required field that wasn't filled in. Either way, there
+ // isn't anything we can show for it.
+ continue
+ }
+ if fv.Kind() == reflect.Slice && fv.IsNil() {
+ // Repeated field that is empty, or a bytes field that is unused.
+ continue
+ }
+
+ if props.Repeated && fv.Kind() == reflect.Slice {
+ // Repeated field.
+ for j := 0; j < fv.Len(); j++ {
+ if err := writeName(w, props); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ v := fv.Index(j)
+ if v.Kind() == reflect.Ptr && v.IsNil() {
+ // A nil message in a repeated field is not valid,
+ // but we can handle that more gracefully than panicking.
+ if _, err := w.Write([]byte("<nil>\n")); err != nil {
+ return err
+ }
+ continue
+ }
+ if len(props.Enum) > 0 {
+ if err := tm.writeEnum(w, v, props); err != nil {
+ return err
+ }
+ } else if err := tm.writeAny(w, v, props); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if fv.Kind() == reflect.Map {
+ // Map fields are rendered as a repeated struct with key/value fields.
+ keys := fv.MapKeys()
+ sort.Sort(mapKeys(keys))
+ for _, key := range keys {
+ val := fv.MapIndex(key)
+ if err := writeName(w, props); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ // open struct
+ if err := w.WriteByte('<'); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ w.indent()
+ // key
+ if _, err := w.WriteString("key:"); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if err := tm.writeAny(w, key, props.MapKeyProp); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ // nil values aren't legal, but we can avoid panicking because of them.
+ if val.Kind() != reflect.Ptr || !val.IsNil() {
+ // value
+ if _, err := w.WriteString("value:"); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if err := tm.writeAny(w, val, props.MapValProp); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ // close struct
+ w.unindent()
+ if err := w.WriteByte('>'); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ continue
+ }
+ if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
+ // empty bytes field
+ continue
+ }
+ if props.proto3 && fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
+ // proto3 non-repeated scalar field; skip if zero value
+ if isProto3Zero(fv) {
+ continue
+ }
+ }
+
+ if fv.Kind() == reflect.Interface {
+ // Check if it is a oneof.
+ if st.Field(i).Tag.Get("protobuf_oneof") != "" {
+ // fv is nil, or holds a pointer to generated struct.
+ // That generated struct has exactly one field,
+ // which has a protobuf struct tag.
+ if fv.IsNil() {
+ continue
+ }
+ inner := fv.Elem().Elem() // interface -> *T -> T
+ tag := inner.Type().Field(0).Tag.Get("protobuf")
+ props = new(Properties) // Overwrite the outer props var, but not its pointee.
+ props.Parse(tag)
+ // Write the value in the oneof, not the oneof itself.
+ fv = inner.Field(0)
+
+ // Special case to cope with malformed messages gracefully:
+ // If the value in the oneof is a nil pointer, don't panic
+ // in writeAny.
+ if fv.Kind() == reflect.Ptr && fv.IsNil() {
+ // Use errors.New so writeAny won't render quotes.
+ msg := errors.New("/* nil */")
+ fv = reflect.ValueOf(&msg).Elem()
+ }
+ }
+ }
+
+ if err := writeName(w, props); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+
+ if len(props.Enum) > 0 {
+ if err := tm.writeEnum(w, fv, props); err != nil {
+ return err
+ }
+ } else if err := tm.writeAny(w, fv, props); err != nil {
+ return err
+ }
+
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+
+ // Extensions (the XXX_extensions field).
+ pv := sv
+ if pv.CanAddr() {
+ pv = sv.Addr()
+ } else {
+ pv = reflect.New(sv.Type())
+ pv.Elem().Set(sv)
+ }
+ if _, err := extendable(pv.Interface()); err == nil {
+ if err := tm.writeExtensions(w, pv); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+var textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
+
+// writeAny writes an arbitrary field.
+func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
+ v = reflect.Indirect(v)
+
+ if props != nil {
+ if len(props.CustomType) > 0 {
+ custom, ok := v.Interface().(Marshaler)
+ if ok {
+ data, err := custom.Marshal()
+ if err != nil {
+ return err
+ }
+ if err := writeString(w, string(data)); err != nil {
+ return err
+ }
+ return nil
+ }
+ } else if len(props.CastType) > 0 {
+ if _, ok := v.Interface().(interface {
+ String() string
+ }); ok {
+ switch v.Kind() {
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
+ reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+ _, err := fmt.Fprintf(w, "%d", v.Interface())
+ return err
+ }
+ }
+ } else if props.StdTime {
+ t, ok := v.Interface().(time.Time)
+ if !ok {
+ return fmt.Errorf("stdtime is not time.Time, but %T", v.Interface())
+ }
+ tproto, err := timestampProto(t)
+ if err != nil {
+ return err
+ }
+ propsCopy := *props // Make a copy so that this is goroutine-safe
+ propsCopy.StdTime = false
+ err = tm.writeAny(w, reflect.ValueOf(tproto), &propsCopy)
+ return err
+ } else if props.StdDuration {
+ d, ok := v.Interface().(time.Duration)
+ if !ok {
+ return fmt.Errorf("stdtime is not time.Duration, but %T", v.Interface())
+ }
+ dproto := durationProto(d)
+ propsCopy := *props // Make a copy so that this is goroutine-safe
+ propsCopy.StdDuration = false
+ err := tm.writeAny(w, reflect.ValueOf(dproto), &propsCopy)
+ return err
+ }
+ }
+
+ // Floats have special cases.
+ if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
+ x := v.Float()
+ var b []byte
+ switch {
+ case math.IsInf(x, 1):
+ b = posInf
+ case math.IsInf(x, -1):
+ b = negInf
+ case math.IsNaN(x):
+ b = nan
+ }
+ if b != nil {
+ _, err := w.Write(b)
+ return err
+ }
+ // Other values are handled below.
+ }
+
+ // We don't attempt to serialise every possible value type; only those
+ // that can occur in protocol buffers.
+ switch v.Kind() {
+ case reflect.Slice:
+ // Should only be a []byte; repeated fields are handled in writeStruct.
+ if err := writeString(w, string(v.Bytes())); err != nil {
+ return err
+ }
+ case reflect.String:
+ if err := writeString(w, v.String()); err != nil {
+ return err
+ }
+ case reflect.Struct:
+ // Required/optional group/message.
+ var bra, ket byte = '<', '>'
+ if props != nil && props.Wire == "group" {
+ bra, ket = '{', '}'
+ }
+ if err := w.WriteByte(bra); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ w.indent()
+ if v.CanAddr() {
+ // Calling v.Interface on a struct causes the reflect package to
+ // copy the entire struct. This is racy with the new Marshaler
+ // since we atomically update the XXX_sizecache.
+ //
+ // Thus, we retrieve a pointer to the struct if possible to avoid
+ // a race since v.Interface on the pointer doesn't copy the struct.
+ //
+ // If v is not addressable, then we are not worried about a race
+ // since it implies that the binary Marshaler cannot possibly be
+ // mutating this value.
+ v = v.Addr()
+ }
+ if v.Type().Implements(textMarshalerType) {
+ text, err := v.Interface().(encoding.TextMarshaler).MarshalText()
+ if err != nil {
+ return err
+ }
+ if _, err = w.Write(text); err != nil {
+ return err
+ }
+ } else {
+ if v.Kind() == reflect.Ptr {
+ v = v.Elem()
+ }
+ if err := tm.writeStruct(w, v); err != nil {
+ return err
+ }
+ }
+ w.unindent()
+ if err := w.WriteByte(ket); err != nil {
+ return err
+ }
+ default:
+ _, err := fmt.Fprint(w, v.Interface())
+ return err
+ }
+ return nil
+}
+
+// equivalent to C's isprint.
+func isprint(c byte) bool {
+ return c >= 0x20 && c < 0x7f
+}
+
+// writeString writes a string in the protocol buffer text format.
+// It is similar to strconv.Quote except we don't use Go escape sequences,
+// we treat the string as a byte sequence, and we use octal escapes.
+// These differences are to maintain interoperability with the other
+// languages' implementations of the text format.
+func writeString(w *textWriter, s string) error {
+ // use WriteByte here to get any needed indent
+ if err := w.WriteByte('"'); err != nil {
+ return err
+ }
+ // Loop over the bytes, not the runes.
+ for i := 0; i < len(s); i++ {
+ var err error
+ // Divergence from C++: we don't escape apostrophes.
+ // There's no need to escape them, and the C++ parser
+ // copes with a naked apostrophe.
+ switch c := s[i]; c {
+ case '\n':
+ _, err = w.w.Write(backslashN)
+ case '\r':
+ _, err = w.w.Write(backslashR)
+ case '\t':
+ _, err = w.w.Write(backslashT)
+ case '"':
+ _, err = w.w.Write(backslashDQ)
+ case '\\':
+ _, err = w.w.Write(backslashBS)
+ default:
+ if isprint(c) {
+ err = w.w.WriteByte(c)
+ } else {
+ _, err = fmt.Fprintf(w.w, "\\%03o", c)
+ }
+ }
+ if err != nil {
+ return err
+ }
+ }
+ return w.WriteByte('"')
+}
+
+func writeUnknownStruct(w *textWriter, data []byte) (err error) {
+ if !w.compact {
+ if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
+ return err
+ }
+ }
+ b := NewBuffer(data)
+ for b.index < len(b.buf) {
+ x, err := b.DecodeVarint()
+ if err != nil {
+ _, ferr := fmt.Fprintf(w, "/* %v */\n", err)
+ return ferr
+ }
+ wire, tag := x&7, x>>3
+ if wire == WireEndGroup {
+ w.unindent()
+ if _, werr := w.Write(endBraceNewline); werr != nil {
+ return werr
+ }
+ continue
+ }
+ if _, ferr := fmt.Fprint(w, tag); ferr != nil {
+ return ferr
+ }
+ if wire != WireStartGroup {
+ if err = w.WriteByte(':'); err != nil {
+ return err
+ }
+ }
+ if !w.compact || wire == WireStartGroup {
+ if err = w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ switch wire {
+ case WireBytes:
+ buf, e := b.DecodeRawBytes(false)
+ if e == nil {
+ _, err = fmt.Fprintf(w, "%q", buf)
+ } else {
+ _, err = fmt.Fprintf(w, "/* %v */", e)
+ }
+ case WireFixed32:
+ x, err = b.DecodeFixed32()
+ err = writeUnknownInt(w, x, err)
+ case WireFixed64:
+ x, err = b.DecodeFixed64()
+ err = writeUnknownInt(w, x, err)
+ case WireStartGroup:
+ err = w.WriteByte('{')
+ w.indent()
+ case WireVarint:
+ x, err = b.DecodeVarint()
+ err = writeUnknownInt(w, x, err)
+ default:
+ _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
+ }
+ if err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func writeUnknownInt(w *textWriter, x uint64, err error) error {
+ if err == nil {
+ _, err = fmt.Fprint(w, x)
+ } else {
+ _, err = fmt.Fprintf(w, "/* %v */", err)
+ }
+ return err
+}
+
+type int32Slice []int32
+
+func (s int32Slice) Len() int { return len(s) }
+func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
+func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+// writeExtensions writes all the extensions in pv.
+// pv is assumed to be a pointer to a protocol message struct that is extendable.
+func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
+ emap := extensionMaps[pv.Type().Elem()]
+ e := pv.Interface().(Message)
+
+ var m map[int32]Extension
+ var mu sync.Locker
+ if em, ok := e.(extensionsBytes); ok {
+ eb := em.GetExtensions()
+ var err error
+ m, err = BytesToExtensionsMap(*eb)
+ if err != nil {
+ return err
+ }
+ mu = notLocker{}
+ } else if _, ok := e.(extendableProto); ok {
+ ep, _ := extendable(e)
+ m, mu = ep.extensionsRead()
+ if m == nil {
+ return nil
+ }
+ }
+
+ // Order the extensions by ID.
+ // This isn't strictly necessary, but it will give us
+ // canonical output, which will also make testing easier.
+
+ mu.Lock()
+ ids := make([]int32, 0, len(m))
+ for id := range m {
+ ids = append(ids, id)
+ }
+ sort.Sort(int32Slice(ids))
+ mu.Unlock()
+
+ for _, extNum := range ids {
+ ext := m[extNum]
+ var desc *ExtensionDesc
+ if emap != nil {
+ desc = emap[extNum]
+ }
+ if desc == nil {
+ // Unknown extension.
+ if err := writeUnknownStruct(w, ext.enc); err != nil {
+ return err
+ }
+ continue
+ }
+
+ pb, err := GetExtension(e, desc)
+ if err != nil {
+ return fmt.Errorf("failed getting extension: %v", err)
+ }
+
+ // Repeated extensions will appear as a slice.
+ if !desc.repeated() {
+ if err := tm.writeExtension(w, desc.Name, pb); err != nil {
+ return err
+ }
+ } else {
+ v := reflect.ValueOf(pb)
+ for i := 0; i < v.Len(); i++ {
+ if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
+ if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
+ return err
+ }
+ if !w.compact {
+ if err := w.WriteByte(' '); err != nil {
+ return err
+ }
+ }
+ if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
+ return err
+ }
+ if err := w.WriteByte('\n'); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (w *textWriter) writeIndent() {
+ if !w.complete {
+ return
+ }
+ remain := w.ind * 2
+ for remain > 0 {
+ n := remain
+ if n > len(spaces) {
+ n = len(spaces)
+ }
+ w.w.Write(spaces[:n])
+ remain -= n
+ }
+ w.complete = false
+}
+
+// TextMarshaler is a configurable text format marshaler.
+type TextMarshaler struct {
+ Compact bool // use compact text format (one line).
+ ExpandAny bool // expand google.protobuf.Any messages of known types
+}
+
+// Marshal writes a given protocol buffer in text format.
+// The only errors returned are from w.
+func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
+ val := reflect.ValueOf(pb)
+ if pb == nil || val.IsNil() {
+ w.Write([]byte("<nil>"))
+ return nil
+ }
+ var bw *bufio.Writer
+ ww, ok := w.(writer)
+ if !ok {
+ bw = bufio.NewWriter(w)
+ ww = bw
+ }
+ aw := &textWriter{
+ w: ww,
+ complete: true,
+ compact: tm.Compact,
+ }
+
+ if etm, ok := pb.(encoding.TextMarshaler); ok {
+ text, err := etm.MarshalText()
+ if err != nil {
+ return err
+ }
+ if _, err = aw.Write(text); err != nil {
+ return err
+ }
+ if bw != nil {
+ return bw.Flush()
+ }
+ return nil
+ }
+ // Dereference the received pointer so we don't have outer < and >.
+ v := reflect.Indirect(val)
+ if err := tm.writeStruct(aw, v); err != nil {
+ return err
+ }
+ if bw != nil {
+ return bw.Flush()
+ }
+ return nil
+}
+
+// Text is the same as Marshal, but returns the string directly.
+func (tm *TextMarshaler) Text(pb Message) string {
+ var buf bytes.Buffer
+ tm.Marshal(&buf, pb)
+ return buf.String()
+}
+
+var (
+ defaultTextMarshaler = TextMarshaler{}
+ compactTextMarshaler = TextMarshaler{Compact: true}
+)
+
+// TODO: consider removing some of the Marshal functions below.
+
+// MarshalText writes a given protocol buffer in text format.
+// The only errors returned are from w.
+func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
+
+// MarshalTextString is the same as MarshalText, but returns the string directly.
+func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
+
+// CompactText writes a given protocol buffer in compact text format (one line).
+func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
+
+// CompactTextString is the same as CompactText, but returns the string directly.
+func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }
diff --git a/vendor/github.com/gogo/protobuf/proto/text_gogo.go b/vendor/github.com/gogo/protobuf/proto/text_gogo.go
@@ -0,0 +1,57 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import (
+ "fmt"
+ "reflect"
+)
+
+func (tm *TextMarshaler) writeEnum(w *textWriter, v reflect.Value, props *Properties) error {
+ m, ok := enumStringMaps[props.Enum]
+ if !ok {
+ if err := tm.writeAny(w, v, props); err != nil {
+ return err
+ }
+ }
+ key := int32(0)
+ if v.Kind() == reflect.Ptr {
+ key = int32(v.Elem().Int())
+ } else {
+ key = int32(v.Int())
+ }
+ s, ok := m[key]
+ if !ok {
+ if err := tm.writeAny(w, v, props); err != nil {
+ return err
+ }
+ }
+ _, err := fmt.Fprint(w, s)
+ return err
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/text_parser.go b/vendor/github.com/gogo/protobuf/proto/text_parser.go
@@ -0,0 +1,1018 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+// Functions for parsing the Text protocol buffer format.
+// TODO: message sets.
+
+import (
+ "encoding"
+ "errors"
+ "fmt"
+ "reflect"
+ "strconv"
+ "strings"
+ "time"
+ "unicode/utf8"
+)
+
+// Error string emitted when deserializing Any and fields are already set
+const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set"
+
+type ParseError struct {
+ Message string
+ Line int // 1-based line number
+ Offset int // 0-based byte offset from start of input
+}
+
+func (p *ParseError) Error() string {
+ if p.Line == 1 {
+ // show offset only for first line
+ return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
+ }
+ return fmt.Sprintf("line %d: %v", p.Line, p.Message)
+}
+
+type token struct {
+ value string
+ err *ParseError
+ line int // line number
+ offset int // byte number from start of input, not start of line
+ unquoted string // the unquoted version of value, if it was a quoted string
+}
+
+func (t *token) String() string {
+ if t.err == nil {
+ return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
+ }
+ return fmt.Sprintf("parse error: %v", t.err)
+}
+
+type textParser struct {
+ s string // remaining input
+ done bool // whether the parsing is finished (success or error)
+ backed bool // whether back() was called
+ offset, line int
+ cur token
+}
+
+func newTextParser(s string) *textParser {
+ p := new(textParser)
+ p.s = s
+ p.line = 1
+ p.cur.line = 1
+ return p
+}
+
+func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
+ pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
+ p.cur.err = pe
+ p.done = true
+ return pe
+}
+
+// Numbers and identifiers are matched by [-+._A-Za-z0-9]
+func isIdentOrNumberChar(c byte) bool {
+ switch {
+ case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
+ return true
+ case '0' <= c && c <= '9':
+ return true
+ }
+ switch c {
+ case '-', '+', '.', '_':
+ return true
+ }
+ return false
+}
+
+func isWhitespace(c byte) bool {
+ switch c {
+ case ' ', '\t', '\n', '\r':
+ return true
+ }
+ return false
+}
+
+func isQuote(c byte) bool {
+ switch c {
+ case '"', '\'':
+ return true
+ }
+ return false
+}
+
+func (p *textParser) skipWhitespace() {
+ i := 0
+ for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
+ if p.s[i] == '#' {
+ // comment; skip to end of line or input
+ for i < len(p.s) && p.s[i] != '\n' {
+ i++
+ }
+ if i == len(p.s) {
+ break
+ }
+ }
+ if p.s[i] == '\n' {
+ p.line++
+ }
+ i++
+ }
+ p.offset += i
+ p.s = p.s[i:len(p.s)]
+ if len(p.s) == 0 {
+ p.done = true
+ }
+}
+
+func (p *textParser) advance() {
+ // Skip whitespace
+ p.skipWhitespace()
+ if p.done {
+ return
+ }
+
+ // Start of non-whitespace
+ p.cur.err = nil
+ p.cur.offset, p.cur.line = p.offset, p.line
+ p.cur.unquoted = ""
+ switch p.s[0] {
+ case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
+ // Single symbol
+ p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
+ case '"', '\'':
+ // Quoted string
+ i := 1
+ for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
+ if p.s[i] == '\\' && i+1 < len(p.s) {
+ // skip escaped char
+ i++
+ }
+ i++
+ }
+ if i >= len(p.s) || p.s[i] != p.s[0] {
+ p.errorf("unmatched quote")
+ return
+ }
+ unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
+ if err != nil {
+ p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
+ return
+ }
+ p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
+ p.cur.unquoted = unq
+ default:
+ i := 0
+ for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
+ i++
+ }
+ if i == 0 {
+ p.errorf("unexpected byte %#x", p.s[0])
+ return
+ }
+ p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
+ }
+ p.offset += len(p.cur.value)
+}
+
+var (
+ errBadUTF8 = errors.New("proto: bad UTF-8")
+)
+
+func unquoteC(s string, quote rune) (string, error) {
+ // This is based on C++'s tokenizer.cc.
+ // Despite its name, this is *not* parsing C syntax.
+ // For instance, "\0" is an invalid quoted string.
+
+ // Avoid allocation in trivial cases.
+ simple := true
+ for _, r := range s {
+ if r == '\\' || r == quote {
+ simple = false
+ break
+ }
+ }
+ if simple {
+ return s, nil
+ }
+
+ buf := make([]byte, 0, 3*len(s)/2)
+ for len(s) > 0 {
+ r, n := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && n == 1 {
+ return "", errBadUTF8
+ }
+ s = s[n:]
+ if r != '\\' {
+ if r < utf8.RuneSelf {
+ buf = append(buf, byte(r))
+ } else {
+ buf = append(buf, string(r)...)
+ }
+ continue
+ }
+
+ ch, tail, err := unescape(s)
+ if err != nil {
+ return "", err
+ }
+ buf = append(buf, ch...)
+ s = tail
+ }
+ return string(buf), nil
+}
+
+func unescape(s string) (ch string, tail string, err error) {
+ r, n := utf8.DecodeRuneInString(s)
+ if r == utf8.RuneError && n == 1 {
+ return "", "", errBadUTF8
+ }
+ s = s[n:]
+ switch r {
+ case 'a':
+ return "\a", s, nil
+ case 'b':
+ return "\b", s, nil
+ case 'f':
+ return "\f", s, nil
+ case 'n':
+ return "\n", s, nil
+ case 'r':
+ return "\r", s, nil
+ case 't':
+ return "\t", s, nil
+ case 'v':
+ return "\v", s, nil
+ case '?':
+ return "?", s, nil // trigraph workaround
+ case '\'', '"', '\\':
+ return string(r), s, nil
+ case '0', '1', '2', '3', '4', '5', '6', '7':
+ if len(s) < 2 {
+ return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
+ }
+ ss := string(r) + s[:2]
+ s = s[2:]
+ i, err := strconv.ParseUint(ss, 8, 8)
+ if err != nil {
+ return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss)
+ }
+ return string([]byte{byte(i)}), s, nil
+ case 'x', 'X', 'u', 'U':
+ var n int
+ switch r {
+ case 'x', 'X':
+ n = 2
+ case 'u':
+ n = 4
+ case 'U':
+ n = 8
+ }
+ if len(s) < n {
+ return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n)
+ }
+ ss := s[:n]
+ s = s[n:]
+ i, err := strconv.ParseUint(ss, 16, 64)
+ if err != nil {
+ return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss)
+ }
+ if r == 'x' || r == 'X' {
+ return string([]byte{byte(i)}), s, nil
+ }
+ if i > utf8.MaxRune {
+ return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss)
+ }
+ return string(rune(i)), s, nil
+ }
+ return "", "", fmt.Errorf(`unknown escape \%c`, r)
+}
+
+// Back off the parser by one token. Can only be done between calls to next().
+// It makes the next advance() a no-op.
+func (p *textParser) back() { p.backed = true }
+
+// Advances the parser and returns the new current token.
+func (p *textParser) next() *token {
+ if p.backed || p.done {
+ p.backed = false
+ return &p.cur
+ }
+ p.advance()
+ if p.done {
+ p.cur.value = ""
+ } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
+ // Look for multiple quoted strings separated by whitespace,
+ // and concatenate them.
+ cat := p.cur
+ for {
+ p.skipWhitespace()
+ if p.done || !isQuote(p.s[0]) {
+ break
+ }
+ p.advance()
+ if p.cur.err != nil {
+ return &p.cur
+ }
+ cat.value += " " + p.cur.value
+ cat.unquoted += p.cur.unquoted
+ }
+ p.done = false // parser may have seen EOF, but we want to return cat
+ p.cur = cat
+ }
+ return &p.cur
+}
+
+func (p *textParser) consumeToken(s string) error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != s {
+ p.back()
+ return p.errorf("expected %q, found %q", s, tok.value)
+ }
+ return nil
+}
+
+// Return a RequiredNotSetError indicating which required field was not set.
+func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
+ st := sv.Type()
+ sprops := GetProperties(st)
+ for i := 0; i < st.NumField(); i++ {
+ if !isNil(sv.Field(i)) {
+ continue
+ }
+
+ props := sprops.Prop[i]
+ if props.Required {
+ return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
+ }
+ }
+ return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen
+}
+
+// Returns the index in the struct for the named field, as well as the parsed tag properties.
+func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
+ i, ok := sprops.decoderOrigNames[name]
+ if ok {
+ return i, sprops.Prop[i], true
+ }
+ return -1, nil, false
+}
+
+// Consume a ':' from the input stream (if the next token is a colon),
+// returning an error if a colon is needed but not present.
+func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != ":" {
+ // Colon is optional when the field is a group or message.
+ needColon := true
+ switch props.Wire {
+ case "group":
+ needColon = false
+ case "bytes":
+ // A "bytes" field is either a message, a string, or a repeated field;
+ // those three become *T, *string and []T respectively, so we can check for
+ // this field being a pointer to a non-string.
+ if typ.Kind() == reflect.Ptr {
+ // *T or *string
+ if typ.Elem().Kind() == reflect.String {
+ break
+ }
+ } else if typ.Kind() == reflect.Slice {
+ // []T or []*T
+ if typ.Elem().Kind() != reflect.Ptr {
+ break
+ }
+ } else if typ.Kind() == reflect.String {
+ // The proto3 exception is for a string field,
+ // which requires a colon.
+ break
+ }
+ needColon = false
+ }
+ if needColon {
+ return p.errorf("expected ':', found %q", tok.value)
+ }
+ p.back()
+ }
+ return nil
+}
+
+func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
+ st := sv.Type()
+ sprops := GetProperties(st)
+ reqCount := sprops.reqCount
+ var reqFieldErr error
+ fieldSet := make(map[string]bool)
+ // A struct is a sequence of "name: value", terminated by one of
+ // '>' or '}', or the end of the input. A name may also be
+ // "[extension]" or "[type/url]".
+ //
+ // The whole struct can also be an expanded Any message, like:
+ // [type/url] < ... struct contents ... >
+ for {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == terminator {
+ break
+ }
+ if tok.value == "[" {
+ // Looks like an extension or an Any.
+ //
+ // TODO: Check whether we need to handle
+ // namespace rooted names (e.g. ".something.Foo").
+ extName, err := p.consumeExtName()
+ if err != nil {
+ return err
+ }
+
+ if s := strings.LastIndex(extName, "/"); s >= 0 {
+ // If it contains a slash, it's an Any type URL.
+ messageName := extName[s+1:]
+ mt := MessageType(messageName)
+ if mt == nil {
+ return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
+ }
+ tok = p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ // consume an optional colon
+ if tok.value == ":" {
+ tok = p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ }
+ var terminator string
+ switch tok.value {
+ case "<":
+ terminator = ">"
+ case "{":
+ terminator = "}"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ v := reflect.New(mt.Elem())
+ if pe := p.readStruct(v.Elem(), terminator); pe != nil {
+ return pe
+ }
+ b, err := Marshal(v.Interface().(Message))
+ if err != nil {
+ return p.errorf("failed to marshal message of type %q: %v", messageName, err)
+ }
+ if fieldSet["type_url"] {
+ return p.errorf(anyRepeatedlyUnpacked, "type_url")
+ }
+ if fieldSet["value"] {
+ return p.errorf(anyRepeatedlyUnpacked, "value")
+ }
+ sv.FieldByName("TypeUrl").SetString(extName)
+ sv.FieldByName("Value").SetBytes(b)
+ fieldSet["type_url"] = true
+ fieldSet["value"] = true
+ continue
+ }
+
+ var desc *ExtensionDesc
+ // This could be faster, but it's functional.
+ // TODO: Do something smarter than a linear scan.
+ for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
+ if d.Name == extName {
+ desc = d
+ break
+ }
+ }
+ if desc == nil {
+ return p.errorf("unrecognized extension %q", extName)
+ }
+
+ props := &Properties{}
+ props.Parse(desc.Tag)
+
+ typ := reflect.TypeOf(desc.ExtensionType)
+ if err := p.checkForColon(props, typ); err != nil {
+ return err
+ }
+
+ rep := desc.repeated()
+
+ // Read the extension structure, and set it in
+ // the value we're constructing.
+ var ext reflect.Value
+ if !rep {
+ ext = reflect.New(typ).Elem()
+ } else {
+ ext = reflect.New(typ.Elem()).Elem()
+ }
+ if err := p.readAny(ext, props); err != nil {
+ if _, ok := err.(*RequiredNotSetError); !ok {
+ return err
+ }
+ reqFieldErr = err
+ }
+ ep := sv.Addr().Interface().(Message)
+ if !rep {
+ SetExtension(ep, desc, ext.Interface())
+ } else {
+ old, err := GetExtension(ep, desc)
+ var sl reflect.Value
+ if err == nil {
+ sl = reflect.ValueOf(old) // existing slice
+ } else {
+ sl = reflect.MakeSlice(typ, 0, 1)
+ }
+ sl = reflect.Append(sl, ext)
+ SetExtension(ep, desc, sl.Interface())
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ continue
+ }
+
+ // This is a normal, non-extension field.
+ name := tok.value
+ var dst reflect.Value
+ fi, props, ok := structFieldByName(sprops, name)
+ if ok {
+ dst = sv.Field(fi)
+ } else if oop, ok := sprops.OneofTypes[name]; ok {
+ // It is a oneof.
+ props = oop.Prop
+ nv := reflect.New(oop.Type.Elem())
+ dst = nv.Elem().Field(0)
+ field := sv.Field(oop.Field)
+ if !field.IsNil() {
+ return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name)
+ }
+ field.Set(nv)
+ }
+ if !dst.IsValid() {
+ return p.errorf("unknown field name %q in %v", name, st)
+ }
+
+ if dst.Kind() == reflect.Map {
+ // Consume any colon.
+ if err := p.checkForColon(props, dst.Type()); err != nil {
+ return err
+ }
+
+ // Construct the map if it doesn't already exist.
+ if dst.IsNil() {
+ dst.Set(reflect.MakeMap(dst.Type()))
+ }
+ key := reflect.New(dst.Type().Key()).Elem()
+ val := reflect.New(dst.Type().Elem()).Elem()
+
+ // The map entry should be this sequence of tokens:
+ // < key : KEY value : VALUE >
+ // However, implementations may omit key or value, and technically
+ // we should support them in any order. See b/28924776 for a time
+ // this went wrong.
+
+ tok := p.next()
+ var terminator string
+ switch tok.value {
+ case "<":
+ terminator = ">"
+ case "{":
+ terminator = "}"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ for {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == terminator {
+ break
+ }
+ switch tok.value {
+ case "key":
+ if err := p.consumeToken(":"); err != nil {
+ return err
+ }
+ if err := p.readAny(key, props.MapKeyProp); err != nil {
+ return err
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ case "value":
+ if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil {
+ return err
+ }
+ if err := p.readAny(val, props.MapValProp); err != nil {
+ return err
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ default:
+ p.back()
+ return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
+ }
+ }
+
+ dst.SetMapIndex(key, val)
+ continue
+ }
+
+ // Check that it's not already set if it's not a repeated field.
+ if !props.Repeated && fieldSet[name] {
+ return p.errorf("non-repeated field %q was repeated", name)
+ }
+
+ if err := p.checkForColon(props, dst.Type()); err != nil {
+ return err
+ }
+
+ // Parse into the field.
+ fieldSet[name] = true
+ if err := p.readAny(dst, props); err != nil {
+ if _, ok := err.(*RequiredNotSetError); !ok {
+ return err
+ }
+ reqFieldErr = err
+ }
+ if props.Required {
+ reqCount--
+ }
+
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+
+ }
+
+ if reqCount > 0 {
+ return p.missingRequiredFieldError(sv)
+ }
+ return reqFieldErr
+}
+
+// consumeExtName consumes extension name or expanded Any type URL and the
+// following ']'. It returns the name or URL consumed.
+func (p *textParser) consumeExtName() (string, error) {
+ tok := p.next()
+ if tok.err != nil {
+ return "", tok.err
+ }
+
+ // If extension name or type url is quoted, it's a single token.
+ if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
+ name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
+ if err != nil {
+ return "", err
+ }
+ return name, p.consumeToken("]")
+ }
+
+ // Consume everything up to "]"
+ var parts []string
+ for tok.value != "]" {
+ parts = append(parts, tok.value)
+ tok = p.next()
+ if tok.err != nil {
+ return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
+ }
+ if p.done && tok.value != "]" {
+ return "", p.errorf("unclosed type_url or extension name")
+ }
+ }
+ return strings.Join(parts, ""), nil
+}
+
+// consumeOptionalSeparator consumes an optional semicolon or comma.
+// It is used in readStruct to provide backward compatibility.
+func (p *textParser) consumeOptionalSeparator() error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value != ";" && tok.value != "," {
+ p.back()
+ }
+ return nil
+}
+
+func (p *textParser) readAny(v reflect.Value, props *Properties) error {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == "" {
+ return p.errorf("unexpected EOF")
+ }
+ if len(props.CustomType) > 0 {
+ if props.Repeated {
+ t := reflect.TypeOf(v.Interface())
+ if t.Kind() == reflect.Slice {
+ tc := reflect.TypeOf(new(Marshaler))
+ ok := t.Elem().Implements(tc.Elem())
+ if ok {
+ fv := v
+ flen := fv.Len()
+ if flen == fv.Cap() {
+ nav := reflect.MakeSlice(v.Type(), flen, 2*flen+1)
+ reflect.Copy(nav, fv)
+ fv.Set(nav)
+ }
+ fv.SetLen(flen + 1)
+
+ // Read one.
+ p.back()
+ return p.readAny(fv.Index(flen), props)
+ }
+ }
+ }
+ if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr {
+ custom := reflect.New(props.ctype.Elem()).Interface().(Unmarshaler)
+ err := custom.Unmarshal([]byte(tok.unquoted))
+ if err != nil {
+ return p.errorf("%v %v: %v", err, v.Type(), tok.value)
+ }
+ v.Set(reflect.ValueOf(custom))
+ } else {
+ custom := reflect.New(reflect.TypeOf(v.Interface())).Interface().(Unmarshaler)
+ err := custom.Unmarshal([]byte(tok.unquoted))
+ if err != nil {
+ return p.errorf("%v %v: %v", err, v.Type(), tok.value)
+ }
+ v.Set(reflect.Indirect(reflect.ValueOf(custom)))
+ }
+ return nil
+ }
+ if props.StdTime {
+ fv := v
+ p.back()
+ props.StdTime = false
+ tproto := ×tamp{}
+ err := p.readAny(reflect.ValueOf(tproto).Elem(), props)
+ props.StdTime = true
+ if err != nil {
+ return err
+ }
+ tim, err := timestampFromProto(tproto)
+ if err != nil {
+ return err
+ }
+ if props.Repeated {
+ t := reflect.TypeOf(v.Interface())
+ if t.Kind() == reflect.Slice {
+ if t.Elem().Kind() == reflect.Ptr {
+ ts := fv.Interface().([]*time.Time)
+ ts = append(ts, &tim)
+ fv.Set(reflect.ValueOf(ts))
+ return nil
+ } else {
+ ts := fv.Interface().([]time.Time)
+ ts = append(ts, tim)
+ fv.Set(reflect.ValueOf(ts))
+ return nil
+ }
+ }
+ }
+ if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr {
+ v.Set(reflect.ValueOf(&tim))
+ } else {
+ v.Set(reflect.Indirect(reflect.ValueOf(&tim)))
+ }
+ return nil
+ }
+ if props.StdDuration {
+ fv := v
+ p.back()
+ props.StdDuration = false
+ dproto := &duration{}
+ err := p.readAny(reflect.ValueOf(dproto).Elem(), props)
+ props.StdDuration = true
+ if err != nil {
+ return err
+ }
+ dur, err := durationFromProto(dproto)
+ if err != nil {
+ return err
+ }
+ if props.Repeated {
+ t := reflect.TypeOf(v.Interface())
+ if t.Kind() == reflect.Slice {
+ if t.Elem().Kind() == reflect.Ptr {
+ ds := fv.Interface().([]*time.Duration)
+ ds = append(ds, &dur)
+ fv.Set(reflect.ValueOf(ds))
+ return nil
+ } else {
+ ds := fv.Interface().([]time.Duration)
+ ds = append(ds, dur)
+ fv.Set(reflect.ValueOf(ds))
+ return nil
+ }
+ }
+ }
+ if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr {
+ v.Set(reflect.ValueOf(&dur))
+ } else {
+ v.Set(reflect.Indirect(reflect.ValueOf(&dur)))
+ }
+ return nil
+ }
+ switch fv := v; fv.Kind() {
+ case reflect.Slice:
+ at := v.Type()
+ if at.Elem().Kind() == reflect.Uint8 {
+ // Special case for []byte
+ if tok.value[0] != '"' && tok.value[0] != '\'' {
+ // Deliberately written out here, as the error after
+ // this switch statement would write "invalid []byte: ...",
+ // which is not as user-friendly.
+ return p.errorf("invalid string: %v", tok.value)
+ }
+ bytes := []byte(tok.unquoted)
+ fv.Set(reflect.ValueOf(bytes))
+ return nil
+ }
+ // Repeated field.
+ if tok.value == "[" {
+ // Repeated field with list notation, like [1,2,3].
+ for {
+ fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
+ err := p.readAny(fv.Index(fv.Len()-1), props)
+ if err != nil {
+ return err
+ }
+ ntok := p.next()
+ if ntok.err != nil {
+ return ntok.err
+ }
+ if ntok.value == "]" {
+ break
+ }
+ if ntok.value != "," {
+ return p.errorf("Expected ']' or ',' found %q", ntok.value)
+ }
+ }
+ return nil
+ }
+ // One value of the repeated field.
+ p.back()
+ fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
+ return p.readAny(fv.Index(fv.Len()-1), props)
+ case reflect.Bool:
+ // true/1/t/True or false/f/0/False.
+ switch tok.value {
+ case "true", "1", "t", "True":
+ fv.SetBool(true)
+ return nil
+ case "false", "0", "f", "False":
+ fv.SetBool(false)
+ return nil
+ }
+ case reflect.Float32, reflect.Float64:
+ v := tok.value
+ // Ignore 'f' for compatibility with output generated by C++, but don't
+ // remove 'f' when the value is "-inf" or "inf".
+ if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
+ v = v[:len(v)-1]
+ }
+ if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
+ fv.SetFloat(f)
+ return nil
+ }
+ case reflect.Int8:
+ if x, err := strconv.ParseInt(tok.value, 0, 8); err == nil {
+ fv.SetInt(x)
+ return nil
+ }
+ case reflect.Int16:
+ if x, err := strconv.ParseInt(tok.value, 0, 16); err == nil {
+ fv.SetInt(x)
+ return nil
+ }
+ case reflect.Int32:
+ if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
+ fv.SetInt(x)
+ return nil
+ }
+
+ if len(props.Enum) == 0 {
+ break
+ }
+ m, ok := enumValueMaps[props.Enum]
+ if !ok {
+ break
+ }
+ x, ok := m[tok.value]
+ if !ok {
+ break
+ }
+ fv.SetInt(int64(x))
+ return nil
+ case reflect.Int64:
+ if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
+ fv.SetInt(x)
+ return nil
+ }
+
+ case reflect.Ptr:
+ // A basic field (indirected through pointer), or a repeated message/group
+ p.back()
+ fv.Set(reflect.New(fv.Type().Elem()))
+ return p.readAny(fv.Elem(), props)
+ case reflect.String:
+ if tok.value[0] == '"' || tok.value[0] == '\'' {
+ fv.SetString(tok.unquoted)
+ return nil
+ }
+ case reflect.Struct:
+ var terminator string
+ switch tok.value {
+ case "{":
+ terminator = "}"
+ case "<":
+ terminator = ">"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
+ return p.readStruct(fv, terminator)
+ case reflect.Uint8:
+ if x, err := strconv.ParseUint(tok.value, 0, 8); err == nil {
+ fv.SetUint(x)
+ return nil
+ }
+ case reflect.Uint16:
+ if x, err := strconv.ParseUint(tok.value, 0, 16); err == nil {
+ fv.SetUint(x)
+ return nil
+ }
+ case reflect.Uint32:
+ if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
+ fv.SetUint(uint64(x))
+ return nil
+ }
+ case reflect.Uint64:
+ if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
+ fv.SetUint(x)
+ return nil
+ }
+ }
+ return p.errorf("invalid %v: %v", v.Type(), tok.value)
+}
+
+// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
+// before starting to unmarshal, so any existing data in pb is always removed.
+// If a required field is not set and no other error occurs,
+// UnmarshalText returns *RequiredNotSetError.
+func UnmarshalText(s string, pb Message) error {
+ if um, ok := pb.(encoding.TextUnmarshaler); ok {
+ return um.UnmarshalText([]byte(s))
+ }
+ pb.Reset()
+ v := reflect.ValueOf(pb)
+ return newTextParser(s).readStruct(v.Elem(), "")
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/timestamp.go b/vendor/github.com/gogo/protobuf/proto/timestamp.go
@@ -0,0 +1,113 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+package proto
+
+// This file implements operations on google.protobuf.Timestamp.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+)
+
+const (
+ // Seconds field of the earliest valid Timestamp.
+ // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
+ minValidSeconds = -62135596800
+ // Seconds field just after the latest valid Timestamp.
+ // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
+ maxValidSeconds = 253402300800
+)
+
+// validateTimestamp determines whether a Timestamp is valid.
+// A valid timestamp represents a time in the range
+// [0001-01-01, 10000-01-01) and has a Nanos field
+// in the range [0, 1e9).
+//
+// If the Timestamp is valid, validateTimestamp returns nil.
+// Otherwise, it returns an error that describes
+// the problem.
+//
+// Every valid Timestamp can be represented by a time.Time, but the converse is not true.
+func validateTimestamp(ts *timestamp) error {
+ if ts == nil {
+ return errors.New("timestamp: nil Timestamp")
+ }
+ if ts.Seconds < minValidSeconds {
+ return fmt.Errorf("timestamp: %#v before 0001-01-01", ts)
+ }
+ if ts.Seconds >= maxValidSeconds {
+ return fmt.Errorf("timestamp: %#v after 10000-01-01", ts)
+ }
+ if ts.Nanos < 0 || ts.Nanos >= 1e9 {
+ return fmt.Errorf("timestamp: %#v: nanos not in range [0, 1e9)", ts)
+ }
+ return nil
+}
+
+// TimestampFromProto converts a google.protobuf.Timestamp proto to a time.Time.
+// It returns an error if the argument is invalid.
+//
+// Unlike most Go functions, if Timestamp returns an error, the first return value
+// is not the zero time.Time. Instead, it is the value obtained from the
+// time.Unix function when passed the contents of the Timestamp, in the UTC
+// locale. This may or may not be a meaningful time; many invalid Timestamps
+// do map to valid time.Times.
+//
+// A nil Timestamp returns an error. The first return value in that case is
+// undefined.
+func timestampFromProto(ts *timestamp) (time.Time, error) {
+ // Don't return the zero value on error, because corresponds to a valid
+ // timestamp. Instead return whatever time.Unix gives us.
+ var t time.Time
+ if ts == nil {
+ t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp
+ } else {
+ t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
+ }
+ return t, validateTimestamp(ts)
+}
+
+// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
+// It returns an error if the resulting Timestamp is invalid.
+func timestampProto(t time.Time) (*timestamp, error) {
+ seconds := t.Unix()
+ nanos := int32(t.Sub(time.Unix(seconds, 0)))
+ ts := ×tamp{
+ Seconds: seconds,
+ Nanos: nanos,
+ }
+ if err := validateTimestamp(ts); err != nil {
+ return nil, err
+ }
+ return ts, nil
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go b/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go
@@ -0,0 +1,49 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2016, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import (
+ "reflect"
+ "time"
+)
+
+var timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
+
+type timestamp struct {
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"`
+}
+
+func (m *timestamp) Reset() { *m = timestamp{} }
+func (*timestamp) ProtoMessage() {}
+func (*timestamp) String() string { return "timestamp<string>" }
+
+func init() {
+ RegisterType((*timestamp)(nil), "gogo.protobuf.proto.timestamp")
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/wrappers.go b/vendor/github.com/gogo/protobuf/proto/wrappers.go
@@ -0,0 +1,1888 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2018, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+import (
+ "io"
+ "reflect"
+)
+
+func makeStdDoubleValueMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ t := ptr.asPointerTo(u.typ).Interface().(*float64)
+ v := &float64Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ t := ptr.asPointerTo(u.typ).Interface().(*float64)
+ v := &float64Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdDoubleValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*float64)
+ v := &float64Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*float64)
+ v := &float64Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdDoubleValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(float64)
+ v := &float64Value{t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(float64)
+ v := &float64Value{t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdDoubleValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*float64)
+ v := &float64Value{*t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*float64)
+ v := &float64Value{*t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdDoubleValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &float64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdDoubleValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &float64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdDoubleValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &float64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdDoubleValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &float64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdFloatValueMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ t := ptr.asPointerTo(u.typ).Interface().(*float32)
+ v := &float32Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ t := ptr.asPointerTo(u.typ).Interface().(*float32)
+ v := &float32Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdFloatValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*float32)
+ v := &float32Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*float32)
+ v := &float32Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdFloatValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(float32)
+ v := &float32Value{t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(float32)
+ v := &float32Value{t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdFloatValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*float32)
+ v := &float32Value{*t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*float32)
+ v := &float32Value{*t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdFloatValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &float32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdFloatValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &float32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdFloatValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &float32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdFloatValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &float32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdInt64ValueMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ t := ptr.asPointerTo(u.typ).Interface().(*int64)
+ v := &int64Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ t := ptr.asPointerTo(u.typ).Interface().(*int64)
+ v := &int64Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdInt64ValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*int64)
+ v := &int64Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*int64)
+ v := &int64Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdInt64ValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(int64)
+ v := &int64Value{t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(int64)
+ v := &int64Value{t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdInt64ValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*int64)
+ v := &int64Value{*t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*int64)
+ v := &int64Value{*t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdInt64ValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &int64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdInt64ValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &int64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdInt64ValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &int64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdInt64ValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &int64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdUInt64ValueMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ t := ptr.asPointerTo(u.typ).Interface().(*uint64)
+ v := &uint64Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ t := ptr.asPointerTo(u.typ).Interface().(*uint64)
+ v := &uint64Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdUInt64ValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*uint64)
+ v := &uint64Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*uint64)
+ v := &uint64Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdUInt64ValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(uint64)
+ v := &uint64Value{t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(uint64)
+ v := &uint64Value{t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdUInt64ValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*uint64)
+ v := &uint64Value{*t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*uint64)
+ v := &uint64Value{*t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdUInt64ValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &uint64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdUInt64ValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &uint64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdUInt64ValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &uint64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdUInt64ValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &uint64Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdInt32ValueMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ t := ptr.asPointerTo(u.typ).Interface().(*int32)
+ v := &int32Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ t := ptr.asPointerTo(u.typ).Interface().(*int32)
+ v := &int32Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdInt32ValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*int32)
+ v := &int32Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*int32)
+ v := &int32Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdInt32ValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(int32)
+ v := &int32Value{t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(int32)
+ v := &int32Value{t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdInt32ValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*int32)
+ v := &int32Value{*t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*int32)
+ v := &int32Value{*t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdInt32ValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &int32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdInt32ValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &int32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdInt32ValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &int32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdInt32ValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &int32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdUInt32ValueMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ t := ptr.asPointerTo(u.typ).Interface().(*uint32)
+ v := &uint32Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ t := ptr.asPointerTo(u.typ).Interface().(*uint32)
+ v := &uint32Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdUInt32ValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*uint32)
+ v := &uint32Value{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*uint32)
+ v := &uint32Value{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdUInt32ValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(uint32)
+ v := &uint32Value{t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(uint32)
+ v := &uint32Value{t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdUInt32ValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*uint32)
+ v := &uint32Value{*t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*uint32)
+ v := &uint32Value{*t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdUInt32ValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &uint32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdUInt32ValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &uint32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdUInt32ValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &uint32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdUInt32ValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &uint32Value{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdBoolValueMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ t := ptr.asPointerTo(u.typ).Interface().(*bool)
+ v := &boolValue{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ t := ptr.asPointerTo(u.typ).Interface().(*bool)
+ v := &boolValue{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdBoolValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*bool)
+ v := &boolValue{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*bool)
+ v := &boolValue{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdBoolValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(bool)
+ v := &boolValue{t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(bool)
+ v := &boolValue{t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdBoolValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*bool)
+ v := &boolValue{*t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*bool)
+ v := &boolValue{*t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdBoolValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &boolValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdBoolValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &boolValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdBoolValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &boolValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdBoolValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &boolValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdStringValueMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ t := ptr.asPointerTo(u.typ).Interface().(*string)
+ v := &stringValue{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ t := ptr.asPointerTo(u.typ).Interface().(*string)
+ v := &stringValue{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdStringValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*string)
+ v := &stringValue{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*string)
+ v := &stringValue{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdStringValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(string)
+ v := &stringValue{t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(string)
+ v := &stringValue{t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdStringValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*string)
+ v := &stringValue{*t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*string)
+ v := &stringValue{*t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdStringValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &stringValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdStringValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &stringValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdStringValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &stringValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdStringValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &stringValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdBytesValueMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ t := ptr.asPointerTo(u.typ).Interface().(*[]byte)
+ v := &bytesValue{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ t := ptr.asPointerTo(u.typ).Interface().(*[]byte)
+ v := &bytesValue{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdBytesValuePtrMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ if ptr.isNil() {
+ return 0
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*[]byte)
+ v := &bytesValue{*t}
+ siz := Size(v)
+ return tagsize + SizeVarint(uint64(siz)) + siz
+ }, func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ if ptr.isNil() {
+ return b, nil
+ }
+ t := ptr.asPointerTo(reflect.PtrTo(u.typ)).Elem().Interface().(*[]byte)
+ v := &bytesValue{*t}
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(len(buf)))
+ b = append(b, buf...)
+ return b, nil
+ }
+}
+
+func makeStdBytesValueSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(u.typ)
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().([]byte)
+ v := &bytesValue{t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(u.typ)
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().([]byte)
+ v := &bytesValue{t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdBytesValuePtrSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
+ return func(ptr pointer, tagsize int) int {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ n := 0
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*[]byte)
+ v := &bytesValue{*t}
+ siz := Size(v)
+ n += siz + SizeVarint(uint64(siz)) + tagsize
+ }
+ return n
+ },
+ func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
+ s := ptr.getSlice(reflect.PtrTo(u.typ))
+ for i := 0; i < s.Len(); i++ {
+ elem := s.Index(i)
+ t := elem.Interface().(*[]byte)
+ v := &bytesValue{*t}
+ siz := Size(v)
+ buf, err := Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ b = appendVarint(b, wiretag)
+ b = appendVarint(b, uint64(siz))
+ b = append(b, buf...)
+ }
+
+ return b, nil
+ }
+}
+
+func makeStdBytesValueUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &bytesValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(sub.typ).Elem()
+ s.Set(reflect.ValueOf(m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdBytesValuePtrUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &bytesValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ s := f.asPointerTo(reflect.PtrTo(sub.typ)).Elem()
+ s.Set(reflect.ValueOf(&m.Value))
+ return b[x:], nil
+ }
+}
+
+func makeStdBytesValuePtrSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &bytesValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(reflect.PtrTo(sub.typ))
+ newSlice := reflect.Append(slice, reflect.ValueOf(&m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
+
+func makeStdBytesValueSliceUnmarshaler(sub *unmarshalInfo, name string) unmarshaler {
+ return func(b []byte, f pointer, w int) ([]byte, error) {
+ if w != WireBytes {
+ return nil, errInternalBadWireType
+ }
+ x, n := decodeVarint(b)
+ if n == 0 {
+ return nil, io.ErrUnexpectedEOF
+ }
+ b = b[n:]
+ if x > uint64(len(b)) {
+ return nil, io.ErrUnexpectedEOF
+ }
+ m := &bytesValue{}
+ if err := Unmarshal(b[:x], m); err != nil {
+ return nil, err
+ }
+ slice := f.getSlice(sub.typ)
+ newSlice := reflect.Append(slice, reflect.ValueOf(m.Value))
+ slice.Set(newSlice)
+ return b[x:], nil
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/proto/wrappers_gogo.go b/vendor/github.com/gogo/protobuf/proto/wrappers_gogo.go
@@ -0,0 +1,113 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2018, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package proto
+
+type float64Value struct {
+ Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *float64Value) Reset() { *m = float64Value{} }
+func (*float64Value) ProtoMessage() {}
+func (*float64Value) String() string { return "float64<string>" }
+
+type float32Value struct {
+ Value float32 `protobuf:"fixed32,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *float32Value) Reset() { *m = float32Value{} }
+func (*float32Value) ProtoMessage() {}
+func (*float32Value) String() string { return "float32<string>" }
+
+type int64Value struct {
+ Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *int64Value) Reset() { *m = int64Value{} }
+func (*int64Value) ProtoMessage() {}
+func (*int64Value) String() string { return "int64<string>" }
+
+type uint64Value struct {
+ Value uint64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *uint64Value) Reset() { *m = uint64Value{} }
+func (*uint64Value) ProtoMessage() {}
+func (*uint64Value) String() string { return "uint64<string>" }
+
+type int32Value struct {
+ Value int32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *int32Value) Reset() { *m = int32Value{} }
+func (*int32Value) ProtoMessage() {}
+func (*int32Value) String() string { return "int32<string>" }
+
+type uint32Value struct {
+ Value uint32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *uint32Value) Reset() { *m = uint32Value{} }
+func (*uint32Value) ProtoMessage() {}
+func (*uint32Value) String() string { return "uint32<string>" }
+
+type boolValue struct {
+ Value bool `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *boolValue) Reset() { *m = boolValue{} }
+func (*boolValue) ProtoMessage() {}
+func (*boolValue) String() string { return "bool<string>" }
+
+type stringValue struct {
+ Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *stringValue) Reset() { *m = stringValue{} }
+func (*stringValue) ProtoMessage() {}
+func (*stringValue) String() string { return "string<string>" }
+
+type bytesValue struct {
+ Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *bytesValue) Reset() { *m = bytesValue{} }
+func (*bytesValue) ProtoMessage() {}
+func (*bytesValue) String() string { return "[]byte<string>" }
+
+func init() {
+ RegisterType((*float64Value)(nil), "gogo.protobuf.proto.DoubleValue")
+ RegisterType((*float32Value)(nil), "gogo.protobuf.proto.FloatValue")
+ RegisterType((*int64Value)(nil), "gogo.protobuf.proto.Int64Value")
+ RegisterType((*uint64Value)(nil), "gogo.protobuf.proto.UInt64Value")
+ RegisterType((*int32Value)(nil), "gogo.protobuf.proto.Int32Value")
+ RegisterType((*uint32Value)(nil), "gogo.protobuf.proto.UInt32Value")
+ RegisterType((*boolValue)(nil), "gogo.protobuf.proto.BoolValue")
+ RegisterType((*stringValue)(nil), "gogo.protobuf.proto.StringValue")
+ RegisterType((*bytesValue)(nil), "gogo.protobuf.proto.BytesValue")
+}
diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/Makefile b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/Makefile
@@ -0,0 +1,36 @@
+# Go support for Protocol Buffers - Google's data interchange format
+#
+# Copyright 2010 The Go Authors. All rights reserved.
+# https://github.com/golang/protobuf
+#
+# 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.
+
+regenerate:
+ go install github.com/gogo/protobuf/protoc-gen-gogo
+ go install github.com/gogo/protobuf/protoc-gen-gostring
+ protoc --gogo_out=. -I=../../protobuf/google/protobuf ../../protobuf/google/protobuf/descriptor.proto
+ protoc --gostring_out=. -I=../../protobuf/google/protobuf ../../protobuf/google/protobuf/descriptor.proto
diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go
@@ -0,0 +1,118 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 The Go Authors. All rights reserved.
+// https://github.com/golang/protobuf
+//
+// 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.
+
+// Package descriptor provides functions for obtaining protocol buffer
+// descriptors for generated Go types.
+//
+// These functions cannot go in package proto because they depend on the
+// generated protobuf descriptor messages, which themselves depend on proto.
+package descriptor
+
+import (
+ "bytes"
+ "compress/gzip"
+ "fmt"
+ "io/ioutil"
+
+ "github.com/gogo/protobuf/proto"
+)
+
+// extractFile extracts a FileDescriptorProto from a gzip'd buffer.
+func extractFile(gz []byte) (*FileDescriptorProto, error) {
+ r, err := gzip.NewReader(bytes.NewReader(gz))
+ if err != nil {
+ return nil, fmt.Errorf("failed to open gzip reader: %v", err)
+ }
+ defer r.Close()
+
+ b, err := ioutil.ReadAll(r)
+ if err != nil {
+ return nil, fmt.Errorf("failed to uncompress descriptor: %v", err)
+ }
+
+ fd := new(FileDescriptorProto)
+ if err := proto.Unmarshal(b, fd); err != nil {
+ return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err)
+ }
+
+ return fd, nil
+}
+
+// Message is a proto.Message with a method to return its descriptor.
+//
+// Message types generated by the protocol compiler always satisfy
+// the Message interface.
+type Message interface {
+ proto.Message
+ Descriptor() ([]byte, []int)
+}
+
+// ForMessage returns a FileDescriptorProto and a DescriptorProto from within it
+// describing the given message.
+func ForMessage(msg Message) (fd *FileDescriptorProto, md *DescriptorProto) {
+ gz, path := msg.Descriptor()
+ fd, err := extractFile(gz)
+ if err != nil {
+ panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err))
+ }
+
+ md = fd.MessageType[path[0]]
+ for _, i := range path[1:] {
+ md = md.NestedType[i]
+ }
+ return fd, md
+}
+
+// Is this field a scalar numeric type?
+func (field *FieldDescriptorProto) IsScalar() bool {
+ if field.Type == nil {
+ return false
+ }
+ switch *field.Type {
+ case FieldDescriptorProto_TYPE_DOUBLE,
+ FieldDescriptorProto_TYPE_FLOAT,
+ FieldDescriptorProto_TYPE_INT64,
+ FieldDescriptorProto_TYPE_UINT64,
+ FieldDescriptorProto_TYPE_INT32,
+ FieldDescriptorProto_TYPE_FIXED64,
+ FieldDescriptorProto_TYPE_FIXED32,
+ FieldDescriptorProto_TYPE_BOOL,
+ FieldDescriptorProto_TYPE_UINT32,
+ FieldDescriptorProto_TYPE_ENUM,
+ FieldDescriptorProto_TYPE_SFIXED32,
+ FieldDescriptorProto_TYPE_SFIXED64,
+ FieldDescriptorProto_TYPE_SINT32,
+ FieldDescriptorProto_TYPE_SINT64:
+ return true
+ default:
+ return false
+ }
+}
diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go
@@ -0,0 +1,2865 @@
+// Code generated by protoc-gen-gogo. DO NOT EDIT.
+// source: descriptor.proto
+
+package descriptor
+
+import (
+ fmt "fmt"
+ proto "github.com/gogo/protobuf/proto"
+ math "math"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package
+
+type FieldDescriptorProto_Type int32
+
+const (
+ // 0 is reserved for errors.
+ // Order is weird for historical reasons.
+ FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1
+ FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
+ // negative values are likely.
+ FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3
+ FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
+ // negative values are likely.
+ FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5
+ FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6
+ FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7
+ FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8
+ FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9
+ // Tag-delimited aggregate.
+ // Group type is deprecated and not supported in proto3. However, Proto3
+ // implementations should still be able to parse the group wire format and
+ // treat group fields as unknown fields.
+ FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10
+ FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11
+ // New in version 2.
+ FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12
+ FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13
+ FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14
+ FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15
+ FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16
+ FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17
+ FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18
+)
+
+var FieldDescriptorProto_Type_name = map[int32]string{
+ 1: "TYPE_DOUBLE",
+ 2: "TYPE_FLOAT",
+ 3: "TYPE_INT64",
+ 4: "TYPE_UINT64",
+ 5: "TYPE_INT32",
+ 6: "TYPE_FIXED64",
+ 7: "TYPE_FIXED32",
+ 8: "TYPE_BOOL",
+ 9: "TYPE_STRING",
+ 10: "TYPE_GROUP",
+ 11: "TYPE_MESSAGE",
+ 12: "TYPE_BYTES",
+ 13: "TYPE_UINT32",
+ 14: "TYPE_ENUM",
+ 15: "TYPE_SFIXED32",
+ 16: "TYPE_SFIXED64",
+ 17: "TYPE_SINT32",
+ 18: "TYPE_SINT64",
+}
+
+var FieldDescriptorProto_Type_value = map[string]int32{
+ "TYPE_DOUBLE": 1,
+ "TYPE_FLOAT": 2,
+ "TYPE_INT64": 3,
+ "TYPE_UINT64": 4,
+ "TYPE_INT32": 5,
+ "TYPE_FIXED64": 6,
+ "TYPE_FIXED32": 7,
+ "TYPE_BOOL": 8,
+ "TYPE_STRING": 9,
+ "TYPE_GROUP": 10,
+ "TYPE_MESSAGE": 11,
+ "TYPE_BYTES": 12,
+ "TYPE_UINT32": 13,
+ "TYPE_ENUM": 14,
+ "TYPE_SFIXED32": 15,
+ "TYPE_SFIXED64": 16,
+ "TYPE_SINT32": 17,
+ "TYPE_SINT64": 18,
+}
+
+func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type {
+ p := new(FieldDescriptorProto_Type)
+ *p = x
+ return p
+}
+
+func (x FieldDescriptorProto_Type) String() string {
+ return proto.EnumName(FieldDescriptorProto_Type_name, int32(x))
+}
+
+func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type")
+ if err != nil {
+ return err
+ }
+ *x = FieldDescriptorProto_Type(value)
+ return nil
+}
+
+func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{4, 0}
+}
+
+type FieldDescriptorProto_Label int32
+
+const (
+ // 0 is reserved for errors
+ FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1
+ FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2
+ FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3
+)
+
+var FieldDescriptorProto_Label_name = map[int32]string{
+ 1: "LABEL_OPTIONAL",
+ 2: "LABEL_REQUIRED",
+ 3: "LABEL_REPEATED",
+}
+
+var FieldDescriptorProto_Label_value = map[string]int32{
+ "LABEL_OPTIONAL": 1,
+ "LABEL_REQUIRED": 2,
+ "LABEL_REPEATED": 3,
+}
+
+func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label {
+ p := new(FieldDescriptorProto_Label)
+ *p = x
+ return p
+}
+
+func (x FieldDescriptorProto_Label) String() string {
+ return proto.EnumName(FieldDescriptorProto_Label_name, int32(x))
+}
+
+func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label")
+ if err != nil {
+ return err
+ }
+ *x = FieldDescriptorProto_Label(value)
+ return nil
+}
+
+func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{4, 1}
+}
+
+// Generated classes can be optimized for speed or code size.
+type FileOptions_OptimizeMode int32
+
+const (
+ FileOptions_SPEED FileOptions_OptimizeMode = 1
+ // etc.
+ FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2
+ FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3
+)
+
+var FileOptions_OptimizeMode_name = map[int32]string{
+ 1: "SPEED",
+ 2: "CODE_SIZE",
+ 3: "LITE_RUNTIME",
+}
+
+var FileOptions_OptimizeMode_value = map[string]int32{
+ "SPEED": 1,
+ "CODE_SIZE": 2,
+ "LITE_RUNTIME": 3,
+}
+
+func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode {
+ p := new(FileOptions_OptimizeMode)
+ *p = x
+ return p
+}
+
+func (x FileOptions_OptimizeMode) String() string {
+ return proto.EnumName(FileOptions_OptimizeMode_name, int32(x))
+}
+
+func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode")
+ if err != nil {
+ return err
+ }
+ *x = FileOptions_OptimizeMode(value)
+ return nil
+}
+
+func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{10, 0}
+}
+
+type FieldOptions_CType int32
+
+const (
+ // Default mode.
+ FieldOptions_STRING FieldOptions_CType = 0
+ FieldOptions_CORD FieldOptions_CType = 1
+ FieldOptions_STRING_PIECE FieldOptions_CType = 2
+)
+
+var FieldOptions_CType_name = map[int32]string{
+ 0: "STRING",
+ 1: "CORD",
+ 2: "STRING_PIECE",
+}
+
+var FieldOptions_CType_value = map[string]int32{
+ "STRING": 0,
+ "CORD": 1,
+ "STRING_PIECE": 2,
+}
+
+func (x FieldOptions_CType) Enum() *FieldOptions_CType {
+ p := new(FieldOptions_CType)
+ *p = x
+ return p
+}
+
+func (x FieldOptions_CType) String() string {
+ return proto.EnumName(FieldOptions_CType_name, int32(x))
+}
+
+func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType")
+ if err != nil {
+ return err
+ }
+ *x = FieldOptions_CType(value)
+ return nil
+}
+
+func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{12, 0}
+}
+
+type FieldOptions_JSType int32
+
+const (
+ // Use the default type.
+ FieldOptions_JS_NORMAL FieldOptions_JSType = 0
+ // Use JavaScript strings.
+ FieldOptions_JS_STRING FieldOptions_JSType = 1
+ // Use JavaScript numbers.
+ FieldOptions_JS_NUMBER FieldOptions_JSType = 2
+)
+
+var FieldOptions_JSType_name = map[int32]string{
+ 0: "JS_NORMAL",
+ 1: "JS_STRING",
+ 2: "JS_NUMBER",
+}
+
+var FieldOptions_JSType_value = map[string]int32{
+ "JS_NORMAL": 0,
+ "JS_STRING": 1,
+ "JS_NUMBER": 2,
+}
+
+func (x FieldOptions_JSType) Enum() *FieldOptions_JSType {
+ p := new(FieldOptions_JSType)
+ *p = x
+ return p
+}
+
+func (x FieldOptions_JSType) String() string {
+ return proto.EnumName(FieldOptions_JSType_name, int32(x))
+}
+
+func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType")
+ if err != nil {
+ return err
+ }
+ *x = FieldOptions_JSType(value)
+ return nil
+}
+
+func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{12, 1}
+}
+
+// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
+// or neither? HTTP based RPC implementation may choose GET verb for safe
+// methods, and PUT verb for idempotent methods instead of the default POST.
+type MethodOptions_IdempotencyLevel int32
+
+const (
+ MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0
+ MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1
+ MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2
+)
+
+var MethodOptions_IdempotencyLevel_name = map[int32]string{
+ 0: "IDEMPOTENCY_UNKNOWN",
+ 1: "NO_SIDE_EFFECTS",
+ 2: "IDEMPOTENT",
+}
+
+var MethodOptions_IdempotencyLevel_value = map[string]int32{
+ "IDEMPOTENCY_UNKNOWN": 0,
+ "NO_SIDE_EFFECTS": 1,
+ "IDEMPOTENT": 2,
+}
+
+func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel {
+ p := new(MethodOptions_IdempotencyLevel)
+ *p = x
+ return p
+}
+
+func (x MethodOptions_IdempotencyLevel) String() string {
+ return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x))
+}
+
+func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel")
+ if err != nil {
+ return err
+ }
+ *x = MethodOptions_IdempotencyLevel(value)
+ return nil
+}
+
+func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{17, 0}
+}
+
+// The protocol compiler can output a FileDescriptorSet containing the .proto
+// files it parses.
+type FileDescriptorSet struct {
+ File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} }
+func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) }
+func (*FileDescriptorSet) ProtoMessage() {}
+func (*FileDescriptorSet) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{0}
+}
+func (m *FileDescriptorSet) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_FileDescriptorSet.Unmarshal(m, b)
+}
+func (m *FileDescriptorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_FileDescriptorSet.Marshal(b, m, deterministic)
+}
+func (m *FileDescriptorSet) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_FileDescriptorSet.Merge(m, src)
+}
+func (m *FileDescriptorSet) XXX_Size() int {
+ return xxx_messageInfo_FileDescriptorSet.Size(m)
+}
+func (m *FileDescriptorSet) XXX_DiscardUnknown() {
+ xxx_messageInfo_FileDescriptorSet.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_FileDescriptorSet proto.InternalMessageInfo
+
+func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto {
+ if m != nil {
+ return m.File
+ }
+ return nil
+}
+
+// Describes a complete .proto file.
+type FileDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"`
+ // Names of files imported by this file.
+ Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"`
+ // Indexes of the public imported files in the dependency list above.
+ PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"`
+ // Indexes of the weak imported files in the dependency list.
+ // For Google-internal migration only. Do not use.
+ WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"`
+ // All top-level definitions in this file.
+ MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"`
+ EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
+ Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"`
+ Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"`
+ Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
+ // This field contains optional information about the original source code.
+ // You may safely remove this entire field without harming runtime
+ // functionality of the descriptors -- the information is needed only by
+ // development tools.
+ SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"`
+ // The syntax of the proto file.
+ // The supported values are "proto2" and "proto3".
+ Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} }
+func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*FileDescriptorProto) ProtoMessage() {}
+func (*FileDescriptorProto) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{1}
+}
+func (m *FileDescriptorProto) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_FileDescriptorProto.Unmarshal(m, b)
+}
+func (m *FileDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_FileDescriptorProto.Marshal(b, m, deterministic)
+}
+func (m *FileDescriptorProto) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_FileDescriptorProto.Merge(m, src)
+}
+func (m *FileDescriptorProto) XXX_Size() int {
+ return xxx_messageInfo_FileDescriptorProto.Size(m)
+}
+func (m *FileDescriptorProto) XXX_DiscardUnknown() {
+ xxx_messageInfo_FileDescriptorProto.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_FileDescriptorProto proto.InternalMessageInfo
+
+func (m *FileDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *FileDescriptorProto) GetPackage() string {
+ if m != nil && m.Package != nil {
+ return *m.Package
+ }
+ return ""
+}
+
+func (m *FileDescriptorProto) GetDependency() []string {
+ if m != nil {
+ return m.Dependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetPublicDependency() []int32 {
+ if m != nil {
+ return m.PublicDependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetWeakDependency() []int32 {
+ if m != nil {
+ return m.WeakDependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto {
+ if m != nil {
+ return m.MessageType
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto {
+ if m != nil {
+ return m.EnumType
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto {
+ if m != nil {
+ return m.Service
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Extension
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetOptions() *FileOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo {
+ if m != nil {
+ return m.SourceCodeInfo
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetSyntax() string {
+ if m != nil && m.Syntax != nil {
+ return *m.Syntax
+ }
+ return ""
+}
+
+// Describes a message type.
+type DescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"`
+ Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"`
+ NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"`
+ EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
+ ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"`
+ OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"`
+ Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"`
+ ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
+ // Reserved field names, which may not be used by fields in the same message.
+ // A given name may only be reserved once.
+ ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *DescriptorProto) Reset() { *m = DescriptorProto{} }
+func (m *DescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto) ProtoMessage() {}
+func (*DescriptorProto) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{2}
+}
+func (m *DescriptorProto) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_DescriptorProto.Unmarshal(m, b)
+}
+func (m *DescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_DescriptorProto.Marshal(b, m, deterministic)
+}
+func (m *DescriptorProto) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_DescriptorProto.Merge(m, src)
+}
+func (m *DescriptorProto) XXX_Size() int {
+ return xxx_messageInfo_DescriptorProto.Size(m)
+}
+func (m *DescriptorProto) XXX_DiscardUnknown() {
+ xxx_messageInfo_DescriptorProto.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_DescriptorProto proto.InternalMessageInfo
+
+func (m *DescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *DescriptorProto) GetField() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Field
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Extension
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetNestedType() []*DescriptorProto {
+ if m != nil {
+ return m.NestedType
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto {
+ if m != nil {
+ return m.EnumType
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange {
+ if m != nil {
+ return m.ExtensionRange
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto {
+ if m != nil {
+ return m.OneofDecl
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetOptions() *MessageOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange {
+ if m != nil {
+ return m.ReservedRange
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetReservedName() []string {
+ if m != nil {
+ return m.ReservedName
+ }
+ return nil
+}
+
+type DescriptorProto_ExtensionRange struct {
+ Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
+ End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
+ Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} }
+func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto_ExtensionRange) ProtoMessage() {}
+func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{2, 0}
+}
+func (m *DescriptorProto_ExtensionRange) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_DescriptorProto_ExtensionRange.Unmarshal(m, b)
+}
+func (m *DescriptorProto_ExtensionRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_DescriptorProto_ExtensionRange.Marshal(b, m, deterministic)
+}
+func (m *DescriptorProto_ExtensionRange) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_DescriptorProto_ExtensionRange.Merge(m, src)
+}
+func (m *DescriptorProto_ExtensionRange) XXX_Size() int {
+ return xxx_messageInfo_DescriptorProto_ExtensionRange.Size(m)
+}
+func (m *DescriptorProto_ExtensionRange) XXX_DiscardUnknown() {
+ xxx_messageInfo_DescriptorProto_ExtensionRange.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_DescriptorProto_ExtensionRange proto.InternalMessageInfo
+
+func (m *DescriptorProto_ExtensionRange) GetStart() int32 {
+ if m != nil && m.Start != nil {
+ return *m.Start
+ }
+ return 0
+}
+
+func (m *DescriptorProto_ExtensionRange) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Range of reserved tag numbers. Reserved tag numbers may not be used by
+// fields or extension ranges in the same message. Reserved ranges may
+// not overlap.
+type DescriptorProto_ReservedRange struct {
+ Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
+ End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} }
+func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto_ReservedRange) ProtoMessage() {}
+func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{2, 1}
+}
+func (m *DescriptorProto_ReservedRange) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_DescriptorProto_ReservedRange.Unmarshal(m, b)
+}
+func (m *DescriptorProto_ReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_DescriptorProto_ReservedRange.Marshal(b, m, deterministic)
+}
+func (m *DescriptorProto_ReservedRange) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_DescriptorProto_ReservedRange.Merge(m, src)
+}
+func (m *DescriptorProto_ReservedRange) XXX_Size() int {
+ return xxx_messageInfo_DescriptorProto_ReservedRange.Size(m)
+}
+func (m *DescriptorProto_ReservedRange) XXX_DiscardUnknown() {
+ xxx_messageInfo_DescriptorProto_ReservedRange.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_DescriptorProto_ReservedRange proto.InternalMessageInfo
+
+func (m *DescriptorProto_ReservedRange) GetStart() int32 {
+ if m != nil && m.Start != nil {
+ return *m.Start
+ }
+ return 0
+}
+
+func (m *DescriptorProto_ReservedRange) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+type ExtensionRangeOptions struct {
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} }
+func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) }
+func (*ExtensionRangeOptions) ProtoMessage() {}
+func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{3}
+}
+
+var extRange_ExtensionRangeOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_ExtensionRangeOptions
+}
+
+func (m *ExtensionRangeOptions) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_ExtensionRangeOptions.Unmarshal(m, b)
+}
+func (m *ExtensionRangeOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_ExtensionRangeOptions.Marshal(b, m, deterministic)
+}
+func (m *ExtensionRangeOptions) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ExtensionRangeOptions.Merge(m, src)
+}
+func (m *ExtensionRangeOptions) XXX_Size() int {
+ return xxx_messageInfo_ExtensionRangeOptions.Size(m)
+}
+func (m *ExtensionRangeOptions) XXX_DiscardUnknown() {
+ xxx_messageInfo_ExtensionRangeOptions.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ExtensionRangeOptions proto.InternalMessageInfo
+
+func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+// Describes a field within a message.
+type FieldDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"`
+ Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"`
+ // If type_name is set, this need not be set. If both this and type_name
+ // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
+ Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"`
+ // For message and enum types, this is the name of the type. If the name
+ // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
+ // rules are used to find the type (i.e. first the nested types within this
+ // message are searched, then within the parent, on up to the root
+ // namespace).
+ TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"`
+ // For extensions, this is the name of the type being extended. It is
+ // resolved in the same manner as type_name.
+ Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"`
+ // For numeric types, contains the original text representation of the value.
+ // For booleans, "true" or "false".
+ // For strings, contains the default text contents (not escaped in any way).
+ // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
+ // TODO(kenton): Base-64 encode?
+ DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"`
+ // If set, gives the index of a oneof in the containing type's oneof_decl
+ // list. This field is a member of that oneof.
+ OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"`
+ // JSON name of this field. The value is set by protocol compiler. If the
+ // user has set a "json_name" option on this field, that option's value
+ // will be used. Otherwise, it's deduced from the field's name by converting
+ // it to camelCase.
+ JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"`
+ Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} }
+func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*FieldDescriptorProto) ProtoMessage() {}
+func (*FieldDescriptorProto) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{4}
+}
+func (m *FieldDescriptorProto) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_FieldDescriptorProto.Unmarshal(m, b)
+}
+func (m *FieldDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_FieldDescriptorProto.Marshal(b, m, deterministic)
+}
+func (m *FieldDescriptorProto) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_FieldDescriptorProto.Merge(m, src)
+}
+func (m *FieldDescriptorProto) XXX_Size() int {
+ return xxx_messageInfo_FieldDescriptorProto.Size(m)
+}
+func (m *FieldDescriptorProto) XXX_DiscardUnknown() {
+ xxx_messageInfo_FieldDescriptorProto.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_FieldDescriptorProto proto.InternalMessageInfo
+
+func (m *FieldDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetNumber() int32 {
+ if m != nil && m.Number != nil {
+ return *m.Number
+ }
+ return 0
+}
+
+func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return FieldDescriptorProto_LABEL_OPTIONAL
+}
+
+func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return FieldDescriptorProto_TYPE_DOUBLE
+}
+
+func (m *FieldDescriptorProto) GetTypeName() string {
+ if m != nil && m.TypeName != nil {
+ return *m.TypeName
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetExtendee() string {
+ if m != nil && m.Extendee != nil {
+ return *m.Extendee
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetDefaultValue() string {
+ if m != nil && m.DefaultValue != nil {
+ return *m.DefaultValue
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetOneofIndex() int32 {
+ if m != nil && m.OneofIndex != nil {
+ return *m.OneofIndex
+ }
+ return 0
+}
+
+func (m *FieldDescriptorProto) GetJsonName() string {
+ if m != nil && m.JsonName != nil {
+ return *m.JsonName
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetOptions() *FieldOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a oneof.
+type OneofDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} }
+func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*OneofDescriptorProto) ProtoMessage() {}
+func (*OneofDescriptorProto) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{5}
+}
+func (m *OneofDescriptorProto) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_OneofDescriptorProto.Unmarshal(m, b)
+}
+func (m *OneofDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_OneofDescriptorProto.Marshal(b, m, deterministic)
+}
+func (m *OneofDescriptorProto) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_OneofDescriptorProto.Merge(m, src)
+}
+func (m *OneofDescriptorProto) XXX_Size() int {
+ return xxx_messageInfo_OneofDescriptorProto.Size(m)
+}
+func (m *OneofDescriptorProto) XXX_DiscardUnknown() {
+ xxx_messageInfo_OneofDescriptorProto.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_OneofDescriptorProto proto.InternalMessageInfo
+
+func (m *OneofDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *OneofDescriptorProto) GetOptions() *OneofOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes an enum type.
+type EnumDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"`
+ Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ // Range of reserved numeric values. Reserved numeric values may not be used
+ // by enum values in the same enum declaration. Reserved ranges may not
+ // overlap.
+ ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
+ // Reserved enum value names, which may not be reused. A given name may only
+ // be reserved once.
+ ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} }
+func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*EnumDescriptorProto) ProtoMessage() {}
+func (*EnumDescriptorProto) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{6}
+}
+func (m *EnumDescriptorProto) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EnumDescriptorProto.Unmarshal(m, b)
+}
+func (m *EnumDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EnumDescriptorProto.Marshal(b, m, deterministic)
+}
+func (m *EnumDescriptorProto) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EnumDescriptorProto.Merge(m, src)
+}
+func (m *EnumDescriptorProto) XXX_Size() int {
+ return xxx_messageInfo_EnumDescriptorProto.Size(m)
+}
+func (m *EnumDescriptorProto) XXX_DiscardUnknown() {
+ xxx_messageInfo_EnumDescriptorProto.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EnumDescriptorProto proto.InternalMessageInfo
+
+func (m *EnumDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func (m *EnumDescriptorProto) GetOptions() *EnumOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange {
+ if m != nil {
+ return m.ReservedRange
+ }
+ return nil
+}
+
+func (m *EnumDescriptorProto) GetReservedName() []string {
+ if m != nil {
+ return m.ReservedName
+ }
+ return nil
+}
+
+// Range of reserved numeric values. Reserved values may not be used by
+// entries in the same enum. Reserved ranges may not overlap.
+//
+// Note that this is distinct from DescriptorProto.ReservedRange in that it
+// is inclusive such that it can appropriately represent the entire int32
+// domain.
+type EnumDescriptorProto_EnumReservedRange struct {
+ Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
+ End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} }
+func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) }
+func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {}
+func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{6, 0}
+}
+func (m *EnumDescriptorProto_EnumReservedRange) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Unmarshal(m, b)
+}
+func (m *EnumDescriptorProto_EnumReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Marshal(b, m, deterministic)
+}
+func (m *EnumDescriptorProto_EnumReservedRange) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Merge(m, src)
+}
+func (m *EnumDescriptorProto_EnumReservedRange) XXX_Size() int {
+ return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Size(m)
+}
+func (m *EnumDescriptorProto_EnumReservedRange) XXX_DiscardUnknown() {
+ xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EnumDescriptorProto_EnumReservedRange proto.InternalMessageInfo
+
+func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 {
+ if m != nil && m.Start != nil {
+ return *m.Start
+ }
+ return 0
+}
+
+func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+// Describes a value within an enum.
+type EnumValueDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"`
+ Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} }
+func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*EnumValueDescriptorProto) ProtoMessage() {}
+func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{7}
+}
+func (m *EnumValueDescriptorProto) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EnumValueDescriptorProto.Unmarshal(m, b)
+}
+func (m *EnumValueDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EnumValueDescriptorProto.Marshal(b, m, deterministic)
+}
+func (m *EnumValueDescriptorProto) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EnumValueDescriptorProto.Merge(m, src)
+}
+func (m *EnumValueDescriptorProto) XXX_Size() int {
+ return xxx_messageInfo_EnumValueDescriptorProto.Size(m)
+}
+func (m *EnumValueDescriptorProto) XXX_DiscardUnknown() {
+ xxx_messageInfo_EnumValueDescriptorProto.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EnumValueDescriptorProto proto.InternalMessageInfo
+
+func (m *EnumValueDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *EnumValueDescriptorProto) GetNumber() int32 {
+ if m != nil && m.Number != nil {
+ return *m.Number
+ }
+ return 0
+}
+
+func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a service.
+type ServiceDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"`
+ Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} }
+func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*ServiceDescriptorProto) ProtoMessage() {}
+func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{8}
+}
+func (m *ServiceDescriptorProto) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_ServiceDescriptorProto.Unmarshal(m, b)
+}
+func (m *ServiceDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_ServiceDescriptorProto.Marshal(b, m, deterministic)
+}
+func (m *ServiceDescriptorProto) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ServiceDescriptorProto.Merge(m, src)
+}
+func (m *ServiceDescriptorProto) XXX_Size() int {
+ return xxx_messageInfo_ServiceDescriptorProto.Size(m)
+}
+func (m *ServiceDescriptorProto) XXX_DiscardUnknown() {
+ xxx_messageInfo_ServiceDescriptorProto.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ServiceDescriptorProto proto.InternalMessageInfo
+
+func (m *ServiceDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto {
+ if m != nil {
+ return m.Method
+ }
+ return nil
+}
+
+func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a method of a service.
+type MethodDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ // Input and output type names. These are resolved in the same way as
+ // FieldDescriptorProto.type_name, but must refer to a message type.
+ InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"`
+ OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"`
+ Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"`
+ // Identifies if client streams multiple client messages
+ ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"`
+ // Identifies if server streams multiple server messages
+ ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} }
+func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*MethodDescriptorProto) ProtoMessage() {}
+func (*MethodDescriptorProto) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{9}
+}
+func (m *MethodDescriptorProto) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_MethodDescriptorProto.Unmarshal(m, b)
+}
+func (m *MethodDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_MethodDescriptorProto.Marshal(b, m, deterministic)
+}
+func (m *MethodDescriptorProto) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MethodDescriptorProto.Merge(m, src)
+}
+func (m *MethodDescriptorProto) XXX_Size() int {
+ return xxx_messageInfo_MethodDescriptorProto.Size(m)
+}
+func (m *MethodDescriptorProto) XXX_DiscardUnknown() {
+ xxx_messageInfo_MethodDescriptorProto.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_MethodDescriptorProto proto.InternalMessageInfo
+
+const Default_MethodDescriptorProto_ClientStreaming bool = false
+const Default_MethodDescriptorProto_ServerStreaming bool = false
+
+func (m *MethodDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetInputType() string {
+ if m != nil && m.InputType != nil {
+ return *m.InputType
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetOutputType() string {
+ if m != nil && m.OutputType != nil {
+ return *m.OutputType
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetOptions() *MethodOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *MethodDescriptorProto) GetClientStreaming() bool {
+ if m != nil && m.ClientStreaming != nil {
+ return *m.ClientStreaming
+ }
+ return Default_MethodDescriptorProto_ClientStreaming
+}
+
+func (m *MethodDescriptorProto) GetServerStreaming() bool {
+ if m != nil && m.ServerStreaming != nil {
+ return *m.ServerStreaming
+ }
+ return Default_MethodDescriptorProto_ServerStreaming
+}
+
+type FileOptions struct {
+ // Sets the Java package where classes generated from this .proto will be
+ // placed. By default, the proto package is used, but this is often
+ // inappropriate because proto packages do not normally start with backwards
+ // domain names.
+ JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"`
+ // If set, all the classes from the .proto file are wrapped in a single
+ // outer class with the given name. This applies to both Proto1
+ // (equivalent to the old "--one_java_file" option) and Proto2 (where
+ // a .proto always translates to a single class, but you may want to
+ // explicitly choose the class name).
+ JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"`
+ // If set true, then the Java code generator will generate a separate .java
+ // file for each top-level message, enum, and service defined in the .proto
+ // file. Thus, these types will *not* be nested inside the outer class
+ // named by java_outer_classname. However, the outer class will still be
+ // generated to contain the file's getDescriptor() method as well as any
+ // top-level extensions defined in the file.
+ JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"`
+ // This option does nothing.
+ JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // Deprecated: Do not use.
+ // If set true, then the Java2 code generator will generate code that
+ // throws an exception whenever an attempt is made to assign a non-UTF-8
+ // byte sequence to a string field.
+ // Message reflection will do the same.
+ // However, an extension field still accepts non-UTF-8 byte sequences.
+ // This option has no effect on when used with the lite runtime.
+ JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"`
+ OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"`
+ // Sets the Go package where structs generated from this .proto will be
+ // placed. If omitted, the Go package will be derived from the following:
+ // - The basename of the package import path, if provided.
+ // - Otherwise, the package statement in the .proto file, if present.
+ // - Otherwise, the basename of the .proto file, without extension.
+ GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"`
+ // Should generic services be generated in each language? "Generic" services
+ // are not specific to any particular RPC system. They are generated by the
+ // main code generators in each language (without additional plugins).
+ // Generic services were the only kind of service generation supported by
+ // early versions of google.protobuf.
+ //
+ // Generic services are now considered deprecated in favor of using plugins
+ // that generate code specific to your particular RPC system. Therefore,
+ // these default to false. Old code which depends on generic services should
+ // explicitly set them to true.
+ CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"`
+ JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"`
+ PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"`
+ PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"`
+ // Is this file deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for everything in the file, or it will be completely ignored; in the very
+ // least, this is a formalization for deprecating files.
+ Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // Enables the use of arenas for the proto messages in this file. This applies
+ // only to generated classes for C++.
+ CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"`
+ // Sets the objective c class prefix which is prepended to all objective c
+ // generated classes from this .proto. There is no default.
+ ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"`
+ // Namespace for generated classes; defaults to the package.
+ CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"`
+ // By default Swift generators will take the proto package and CamelCase it
+ // replacing '.' with underscore and use that to prefix the types/symbols
+ // defined. When this options is provided, they will use this value instead
+ // to prefix the types/symbols defined.
+ SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"`
+ // Sets the php class prefix which is prepended to all php generated classes
+ // from this .proto. Default is empty.
+ PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"`
+ // Use this option to change the namespace of php generated classes. Default
+ // is empty. When this option is empty, the package name will be used for
+ // determining the namespace.
+ PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"`
+ // Use this option to change the namespace of php generated metadata classes.
+ // Default is empty. When this option is empty, the proto file name will be
+ // used for determining the namespace.
+ PhpMetadataNamespace *string `protobuf:"bytes,44,opt,name=php_metadata_namespace,json=phpMetadataNamespace" json:"php_metadata_namespace,omitempty"`
+ // Use this option to change the package of ruby generated classes. Default
+ // is empty. When this option is not set, the package name will be used for
+ // determining the ruby package.
+ RubyPackage *string `protobuf:"bytes,45,opt,name=ruby_package,json=rubyPackage" json:"ruby_package,omitempty"`
+ // The parser stores options it doesn't recognize here.
+ // See the documentation for the "Options" section above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *FileOptions) Reset() { *m = FileOptions{} }
+func (m *FileOptions) String() string { return proto.CompactTextString(m) }
+func (*FileOptions) ProtoMessage() {}
+func (*FileOptions) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{10}
+}
+
+var extRange_FileOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_FileOptions
+}
+
+func (m *FileOptions) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_FileOptions.Unmarshal(m, b)
+}
+func (m *FileOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_FileOptions.Marshal(b, m, deterministic)
+}
+func (m *FileOptions) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_FileOptions.Merge(m, src)
+}
+func (m *FileOptions) XXX_Size() int {
+ return xxx_messageInfo_FileOptions.Size(m)
+}
+func (m *FileOptions) XXX_DiscardUnknown() {
+ xxx_messageInfo_FileOptions.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_FileOptions proto.InternalMessageInfo
+
+const Default_FileOptions_JavaMultipleFiles bool = false
+const Default_FileOptions_JavaStringCheckUtf8 bool = false
+const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED
+const Default_FileOptions_CcGenericServices bool = false
+const Default_FileOptions_JavaGenericServices bool = false
+const Default_FileOptions_PyGenericServices bool = false
+const Default_FileOptions_PhpGenericServices bool = false
+const Default_FileOptions_Deprecated bool = false
+const Default_FileOptions_CcEnableArenas bool = false
+
+func (m *FileOptions) GetJavaPackage() string {
+ if m != nil && m.JavaPackage != nil {
+ return *m.JavaPackage
+ }
+ return ""
+}
+
+func (m *FileOptions) GetJavaOuterClassname() string {
+ if m != nil && m.JavaOuterClassname != nil {
+ return *m.JavaOuterClassname
+ }
+ return ""
+}
+
+func (m *FileOptions) GetJavaMultipleFiles() bool {
+ if m != nil && m.JavaMultipleFiles != nil {
+ return *m.JavaMultipleFiles
+ }
+ return Default_FileOptions_JavaMultipleFiles
+}
+
+// Deprecated: Do not use.
+func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool {
+ if m != nil && m.JavaGenerateEqualsAndHash != nil {
+ return *m.JavaGenerateEqualsAndHash
+ }
+ return false
+}
+
+func (m *FileOptions) GetJavaStringCheckUtf8() bool {
+ if m != nil && m.JavaStringCheckUtf8 != nil {
+ return *m.JavaStringCheckUtf8
+ }
+ return Default_FileOptions_JavaStringCheckUtf8
+}
+
+func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode {
+ if m != nil && m.OptimizeFor != nil {
+ return *m.OptimizeFor
+ }
+ return Default_FileOptions_OptimizeFor
+}
+
+func (m *FileOptions) GetGoPackage() string {
+ if m != nil && m.GoPackage != nil {
+ return *m.GoPackage
+ }
+ return ""
+}
+
+func (m *FileOptions) GetCcGenericServices() bool {
+ if m != nil && m.CcGenericServices != nil {
+ return *m.CcGenericServices
+ }
+ return Default_FileOptions_CcGenericServices
+}
+
+func (m *FileOptions) GetJavaGenericServices() bool {
+ if m != nil && m.JavaGenericServices != nil {
+ return *m.JavaGenericServices
+ }
+ return Default_FileOptions_JavaGenericServices
+}
+
+func (m *FileOptions) GetPyGenericServices() bool {
+ if m != nil && m.PyGenericServices != nil {
+ return *m.PyGenericServices
+ }
+ return Default_FileOptions_PyGenericServices
+}
+
+func (m *FileOptions) GetPhpGenericServices() bool {
+ if m != nil && m.PhpGenericServices != nil {
+ return *m.PhpGenericServices
+ }
+ return Default_FileOptions_PhpGenericServices
+}
+
+func (m *FileOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_FileOptions_Deprecated
+}
+
+func (m *FileOptions) GetCcEnableArenas() bool {
+ if m != nil && m.CcEnableArenas != nil {
+ return *m.CcEnableArenas
+ }
+ return Default_FileOptions_CcEnableArenas
+}
+
+func (m *FileOptions) GetObjcClassPrefix() string {
+ if m != nil && m.ObjcClassPrefix != nil {
+ return *m.ObjcClassPrefix
+ }
+ return ""
+}
+
+func (m *FileOptions) GetCsharpNamespace() string {
+ if m != nil && m.CsharpNamespace != nil {
+ return *m.CsharpNamespace
+ }
+ return ""
+}
+
+func (m *FileOptions) GetSwiftPrefix() string {
+ if m != nil && m.SwiftPrefix != nil {
+ return *m.SwiftPrefix
+ }
+ return ""
+}
+
+func (m *FileOptions) GetPhpClassPrefix() string {
+ if m != nil && m.PhpClassPrefix != nil {
+ return *m.PhpClassPrefix
+ }
+ return ""
+}
+
+func (m *FileOptions) GetPhpNamespace() string {
+ if m != nil && m.PhpNamespace != nil {
+ return *m.PhpNamespace
+ }
+ return ""
+}
+
+func (m *FileOptions) GetPhpMetadataNamespace() string {
+ if m != nil && m.PhpMetadataNamespace != nil {
+ return *m.PhpMetadataNamespace
+ }
+ return ""
+}
+
+func (m *FileOptions) GetRubyPackage() string {
+ if m != nil && m.RubyPackage != nil {
+ return *m.RubyPackage
+ }
+ return ""
+}
+
+func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type MessageOptions struct {
+ // Set true to use the old proto1 MessageSet wire format for extensions.
+ // This is provided for backwards-compatibility with the MessageSet wire
+ // format. You should not use this for any other reason: It's less
+ // efficient, has fewer features, and is more complicated.
+ //
+ // The message must be defined exactly as follows:
+ // message Foo {
+ // option message_set_wire_format = true;
+ // extensions 4 to max;
+ // }
+ // Note that the message cannot have any defined fields; MessageSets only
+ // have extensions.
+ //
+ // All extensions of your type must be singular messages; e.g. they cannot
+ // be int32s, enums, or repeated messages.
+ //
+ // Because this is an option, the above two restrictions are not enforced by
+ // the protocol compiler.
+ MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"`
+ // Disables the generation of the standard "descriptor()" accessor, which can
+ // conflict with a field of the same name. This is meant to make migration
+ // from proto1 easier; new code should avoid fields named "descriptor".
+ NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"`
+ // Is this message deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the message, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating messages.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // Whether the message is an automatically generated map entry type for the
+ // maps field.
+ //
+ // For maps fields:
+ // map<KeyType, ValueType> map_field = 1;
+ // The parsed descriptor looks like:
+ // message MapFieldEntry {
+ // option map_entry = true;
+ // optional KeyType key = 1;
+ // optional ValueType value = 2;
+ // }
+ // repeated MapFieldEntry map_field = 1;
+ //
+ // Implementations may choose not to generate the map_entry=true message, but
+ // use a native map in the target language to hold the keys and values.
+ // The reflection APIs in such implementations still need to work as
+ // if the field is a repeated message field.
+ //
+ // NOTE: Do not set the option in .proto files. Always use the maps syntax
+ // instead. The option should only be implicitly set by the proto compiler
+ // parser.
+ MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *MessageOptions) Reset() { *m = MessageOptions{} }
+func (m *MessageOptions) String() string { return proto.CompactTextString(m) }
+func (*MessageOptions) ProtoMessage() {}
+func (*MessageOptions) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{11}
+}
+
+var extRange_MessageOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_MessageOptions
+}
+
+func (m *MessageOptions) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_MessageOptions.Unmarshal(m, b)
+}
+func (m *MessageOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_MessageOptions.Marshal(b, m, deterministic)
+}
+func (m *MessageOptions) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MessageOptions.Merge(m, src)
+}
+func (m *MessageOptions) XXX_Size() int {
+ return xxx_messageInfo_MessageOptions.Size(m)
+}
+func (m *MessageOptions) XXX_DiscardUnknown() {
+ xxx_messageInfo_MessageOptions.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_MessageOptions proto.InternalMessageInfo
+
+const Default_MessageOptions_MessageSetWireFormat bool = false
+const Default_MessageOptions_NoStandardDescriptorAccessor bool = false
+const Default_MessageOptions_Deprecated bool = false
+
+func (m *MessageOptions) GetMessageSetWireFormat() bool {
+ if m != nil && m.MessageSetWireFormat != nil {
+ return *m.MessageSetWireFormat
+ }
+ return Default_MessageOptions_MessageSetWireFormat
+}
+
+func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool {
+ if m != nil && m.NoStandardDescriptorAccessor != nil {
+ return *m.NoStandardDescriptorAccessor
+ }
+ return Default_MessageOptions_NoStandardDescriptorAccessor
+}
+
+func (m *MessageOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_MessageOptions_Deprecated
+}
+
+func (m *MessageOptions) GetMapEntry() bool {
+ if m != nil && m.MapEntry != nil {
+ return *m.MapEntry
+ }
+ return false
+}
+
+func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type FieldOptions struct {
+ // The ctype option instructs the C++ code generator to use a different
+ // representation of the field than it normally would. See the specific
+ // options below. This option is not yet implemented in the open source
+ // release -- sorry, we'll try to include it in a future version!
+ Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"`
+ // The packed option can be enabled for repeated primitive fields to enable
+ // a more efficient representation on the wire. Rather than repeatedly
+ // writing the tag and type for each element, the entire array is encoded as
+ // a single length-delimited blob. In proto3, only explicit setting it to
+ // false will avoid using packed encoding.
+ Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"`
+ // The jstype option determines the JavaScript type used for values of the
+ // field. The option is permitted only for 64 bit integral and fixed types
+ // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
+ // is represented as JavaScript string, which avoids loss of precision that
+ // can happen when a large value is converted to a floating point JavaScript.
+ // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
+ // use the JavaScript "number" type. The behavior of the default option
+ // JS_NORMAL is implementation dependent.
+ //
+ // This option is an enum to permit additional types to be added, e.g.
+ // goog.math.Integer.
+ Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"`
+ // Should this field be parsed lazily? Lazy applies only to message-type
+ // fields. It means that when the outer message is initially parsed, the
+ // inner message's contents will not be parsed but instead stored in encoded
+ // form. The inner message will actually be parsed when it is first accessed.
+ //
+ // This is only a hint. Implementations are free to choose whether to use
+ // eager or lazy parsing regardless of the value of this option. However,
+ // setting this option true suggests that the protocol author believes that
+ // using lazy parsing on this field is worth the additional bookkeeping
+ // overhead typically needed to implement it.
+ //
+ // This option does not affect the public interface of any generated code;
+ // all method signatures remain the same. Furthermore, thread-safety of the
+ // interface is not affected by this option; const methods remain safe to
+ // call from multiple threads concurrently, while non-const methods continue
+ // to require exclusive access.
+ //
+ //
+ // Note that implementations may choose not to check required fields within
+ // a lazy sub-message. That is, calling IsInitialized() on the outer message
+ // may return true even if the inner message has missing required fields.
+ // This is necessary because otherwise the inner message would have to be
+ // parsed in order to perform the check, defeating the purpose of lazy
+ // parsing. An implementation which chooses not to check required fields
+ // must be consistent about it. That is, for any particular sub-message, the
+ // implementation must either *always* check its required fields, or *never*
+ // check its required fields, regardless of whether or not the message has
+ // been parsed.
+ Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"`
+ // Is this field deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for accessors, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating fields.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // For Google-internal migration only. Do not use.
+ Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *FieldOptions) Reset() { *m = FieldOptions{} }
+func (m *FieldOptions) String() string { return proto.CompactTextString(m) }
+func (*FieldOptions) ProtoMessage() {}
+func (*FieldOptions) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{12}
+}
+
+var extRange_FieldOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_FieldOptions
+}
+
+func (m *FieldOptions) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_FieldOptions.Unmarshal(m, b)
+}
+func (m *FieldOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_FieldOptions.Marshal(b, m, deterministic)
+}
+func (m *FieldOptions) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_FieldOptions.Merge(m, src)
+}
+func (m *FieldOptions) XXX_Size() int {
+ return xxx_messageInfo_FieldOptions.Size(m)
+}
+func (m *FieldOptions) XXX_DiscardUnknown() {
+ xxx_messageInfo_FieldOptions.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_FieldOptions proto.InternalMessageInfo
+
+const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING
+const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL
+const Default_FieldOptions_Lazy bool = false
+const Default_FieldOptions_Deprecated bool = false
+const Default_FieldOptions_Weak bool = false
+
+func (m *FieldOptions) GetCtype() FieldOptions_CType {
+ if m != nil && m.Ctype != nil {
+ return *m.Ctype
+ }
+ return Default_FieldOptions_Ctype
+}
+
+func (m *FieldOptions) GetPacked() bool {
+ if m != nil && m.Packed != nil {
+ return *m.Packed
+ }
+ return false
+}
+
+func (m *FieldOptions) GetJstype() FieldOptions_JSType {
+ if m != nil && m.Jstype != nil {
+ return *m.Jstype
+ }
+ return Default_FieldOptions_Jstype
+}
+
+func (m *FieldOptions) GetLazy() bool {
+ if m != nil && m.Lazy != nil {
+ return *m.Lazy
+ }
+ return Default_FieldOptions_Lazy
+}
+
+func (m *FieldOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_FieldOptions_Deprecated
+}
+
+func (m *FieldOptions) GetWeak() bool {
+ if m != nil && m.Weak != nil {
+ return *m.Weak
+ }
+ return Default_FieldOptions_Weak
+}
+
+func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type OneofOptions struct {
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *OneofOptions) Reset() { *m = OneofOptions{} }
+func (m *OneofOptions) String() string { return proto.CompactTextString(m) }
+func (*OneofOptions) ProtoMessage() {}
+func (*OneofOptions) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{13}
+}
+
+var extRange_OneofOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_OneofOptions
+}
+
+func (m *OneofOptions) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_OneofOptions.Unmarshal(m, b)
+}
+func (m *OneofOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_OneofOptions.Marshal(b, m, deterministic)
+}
+func (m *OneofOptions) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_OneofOptions.Merge(m, src)
+}
+func (m *OneofOptions) XXX_Size() int {
+ return xxx_messageInfo_OneofOptions.Size(m)
+}
+func (m *OneofOptions) XXX_DiscardUnknown() {
+ xxx_messageInfo_OneofOptions.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_OneofOptions proto.InternalMessageInfo
+
+func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type EnumOptions struct {
+ // Set this option to true to allow mapping different tag names to the same
+ // value.
+ AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"`
+ // Is this enum deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating enums.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EnumOptions) Reset() { *m = EnumOptions{} }
+func (m *EnumOptions) String() string { return proto.CompactTextString(m) }
+func (*EnumOptions) ProtoMessage() {}
+func (*EnumOptions) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{14}
+}
+
+var extRange_EnumOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_EnumOptions
+}
+
+func (m *EnumOptions) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EnumOptions.Unmarshal(m, b)
+}
+func (m *EnumOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EnumOptions.Marshal(b, m, deterministic)
+}
+func (m *EnumOptions) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EnumOptions.Merge(m, src)
+}
+func (m *EnumOptions) XXX_Size() int {
+ return xxx_messageInfo_EnumOptions.Size(m)
+}
+func (m *EnumOptions) XXX_DiscardUnknown() {
+ xxx_messageInfo_EnumOptions.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EnumOptions proto.InternalMessageInfo
+
+const Default_EnumOptions_Deprecated bool = false
+
+func (m *EnumOptions) GetAllowAlias() bool {
+ if m != nil && m.AllowAlias != nil {
+ return *m.AllowAlias
+ }
+ return false
+}
+
+func (m *EnumOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_EnumOptions_Deprecated
+}
+
+func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type EnumValueOptions struct {
+ // Is this enum value deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum value, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating enum values.
+ Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} }
+func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) }
+func (*EnumValueOptions) ProtoMessage() {}
+func (*EnumValueOptions) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{15}
+}
+
+var extRange_EnumValueOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_EnumValueOptions
+}
+
+func (m *EnumValueOptions) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_EnumValueOptions.Unmarshal(m, b)
+}
+func (m *EnumValueOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_EnumValueOptions.Marshal(b, m, deterministic)
+}
+func (m *EnumValueOptions) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_EnumValueOptions.Merge(m, src)
+}
+func (m *EnumValueOptions) XXX_Size() int {
+ return xxx_messageInfo_EnumValueOptions.Size(m)
+}
+func (m *EnumValueOptions) XXX_DiscardUnknown() {
+ xxx_messageInfo_EnumValueOptions.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_EnumValueOptions proto.InternalMessageInfo
+
+const Default_EnumValueOptions_Deprecated bool = false
+
+func (m *EnumValueOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_EnumValueOptions_Deprecated
+}
+
+func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type ServiceOptions struct {
+ // Is this service deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the service, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating services.
+ Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *ServiceOptions) Reset() { *m = ServiceOptions{} }
+func (m *ServiceOptions) String() string { return proto.CompactTextString(m) }
+func (*ServiceOptions) ProtoMessage() {}
+func (*ServiceOptions) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{16}
+}
+
+var extRange_ServiceOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_ServiceOptions
+}
+
+func (m *ServiceOptions) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_ServiceOptions.Unmarshal(m, b)
+}
+func (m *ServiceOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_ServiceOptions.Marshal(b, m, deterministic)
+}
+func (m *ServiceOptions) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_ServiceOptions.Merge(m, src)
+}
+func (m *ServiceOptions) XXX_Size() int {
+ return xxx_messageInfo_ServiceOptions.Size(m)
+}
+func (m *ServiceOptions) XXX_DiscardUnknown() {
+ xxx_messageInfo_ServiceOptions.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_ServiceOptions proto.InternalMessageInfo
+
+const Default_ServiceOptions_Deprecated bool = false
+
+func (m *ServiceOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_ServiceOptions_Deprecated
+}
+
+func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type MethodOptions struct {
+ // Is this method deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the method, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating methods.
+ Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *MethodOptions) Reset() { *m = MethodOptions{} }
+func (m *MethodOptions) String() string { return proto.CompactTextString(m) }
+func (*MethodOptions) ProtoMessage() {}
+func (*MethodOptions) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{17}
+}
+
+var extRange_MethodOptions = []proto.ExtensionRange{
+ {Start: 1000, End: 536870911},
+}
+
+func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_MethodOptions
+}
+
+func (m *MethodOptions) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_MethodOptions.Unmarshal(m, b)
+}
+func (m *MethodOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_MethodOptions.Marshal(b, m, deterministic)
+}
+func (m *MethodOptions) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_MethodOptions.Merge(m, src)
+}
+func (m *MethodOptions) XXX_Size() int {
+ return xxx_messageInfo_MethodOptions.Size(m)
+}
+func (m *MethodOptions) XXX_DiscardUnknown() {
+ xxx_messageInfo_MethodOptions.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_MethodOptions proto.InternalMessageInfo
+
+const Default_MethodOptions_Deprecated bool = false
+const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN
+
+func (m *MethodOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_MethodOptions_Deprecated
+}
+
+func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel {
+ if m != nil && m.IdempotencyLevel != nil {
+ return *m.IdempotencyLevel
+ }
+ return Default_MethodOptions_IdempotencyLevel
+}
+
+func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+// A message representing a option the parser does not recognize. This only
+// appears in options protos created by the compiler::Parser class.
+// DescriptorPool resolves these when building Descriptor objects. Therefore,
+// options protos in descriptor objects (e.g. returned by Descriptor::options(),
+// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
+// in them.
+type UninterpretedOption struct {
+ Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"`
+ // The value of the uninterpreted option, in whatever type the tokenizer
+ // identified it as during parsing. Exactly one of these should be set.
+ IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"`
+ PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"`
+ NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"`
+ DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"`
+ StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"`
+ AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} }
+func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) }
+func (*UninterpretedOption) ProtoMessage() {}
+func (*UninterpretedOption) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{18}
+}
+func (m *UninterpretedOption) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_UninterpretedOption.Unmarshal(m, b)
+}
+func (m *UninterpretedOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_UninterpretedOption.Marshal(b, m, deterministic)
+}
+func (m *UninterpretedOption) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_UninterpretedOption.Merge(m, src)
+}
+func (m *UninterpretedOption) XXX_Size() int {
+ return xxx_messageInfo_UninterpretedOption.Size(m)
+}
+func (m *UninterpretedOption) XXX_DiscardUnknown() {
+ xxx_messageInfo_UninterpretedOption.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_UninterpretedOption proto.InternalMessageInfo
+
+func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart {
+ if m != nil {
+ return m.Name
+ }
+ return nil
+}
+
+func (m *UninterpretedOption) GetIdentifierValue() string {
+ if m != nil && m.IdentifierValue != nil {
+ return *m.IdentifierValue
+ }
+ return ""
+}
+
+func (m *UninterpretedOption) GetPositiveIntValue() uint64 {
+ if m != nil && m.PositiveIntValue != nil {
+ return *m.PositiveIntValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetNegativeIntValue() int64 {
+ if m != nil && m.NegativeIntValue != nil {
+ return *m.NegativeIntValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetDoubleValue() float64 {
+ if m != nil && m.DoubleValue != nil {
+ return *m.DoubleValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetStringValue() []byte {
+ if m != nil {
+ return m.StringValue
+ }
+ return nil
+}
+
+func (m *UninterpretedOption) GetAggregateValue() string {
+ if m != nil && m.AggregateValue != nil {
+ return *m.AggregateValue
+ }
+ return ""
+}
+
+// The name of the uninterpreted option. Each string represents a segment in
+// a dot-separated name. is_extension is true iff a segment represents an
+// extension (denoted with parentheses in options specs in .proto files).
+// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
+// "foo.(bar.baz).qux".
+type UninterpretedOption_NamePart struct {
+ NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"`
+ IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} }
+func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) }
+func (*UninterpretedOption_NamePart) ProtoMessage() {}
+func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{18, 0}
+}
+func (m *UninterpretedOption_NamePart) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_UninterpretedOption_NamePart.Unmarshal(m, b)
+}
+func (m *UninterpretedOption_NamePart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_UninterpretedOption_NamePart.Marshal(b, m, deterministic)
+}
+func (m *UninterpretedOption_NamePart) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_UninterpretedOption_NamePart.Merge(m, src)
+}
+func (m *UninterpretedOption_NamePart) XXX_Size() int {
+ return xxx_messageInfo_UninterpretedOption_NamePart.Size(m)
+}
+func (m *UninterpretedOption_NamePart) XXX_DiscardUnknown() {
+ xxx_messageInfo_UninterpretedOption_NamePart.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_UninterpretedOption_NamePart proto.InternalMessageInfo
+
+func (m *UninterpretedOption_NamePart) GetNamePart() string {
+ if m != nil && m.NamePart != nil {
+ return *m.NamePart
+ }
+ return ""
+}
+
+func (m *UninterpretedOption_NamePart) GetIsExtension() bool {
+ if m != nil && m.IsExtension != nil {
+ return *m.IsExtension
+ }
+ return false
+}
+
+// Encapsulates information about the original source file from which a
+// FileDescriptorProto was generated.
+type SourceCodeInfo struct {
+ // A Location identifies a piece of source code in a .proto file which
+ // corresponds to a particular definition. This information is intended
+ // to be useful to IDEs, code indexers, documentation generators, and similar
+ // tools.
+ //
+ // For example, say we have a file like:
+ // message Foo {
+ // optional string foo = 1;
+ // }
+ // Let's look at just the field definition:
+ // optional string foo = 1;
+ // ^ ^^ ^^ ^ ^^^
+ // a bc de f ghi
+ // We have the following locations:
+ // span path represents
+ // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
+ // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
+ // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
+ // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
+ // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
+ //
+ // Notes:
+ // - A location may refer to a repeated field itself (i.e. not to any
+ // particular index within it). This is used whenever a set of elements are
+ // logically enclosed in a single code segment. For example, an entire
+ // extend block (possibly containing multiple extension definitions) will
+ // have an outer location whose path refers to the "extensions" repeated
+ // field without an index.
+ // - Multiple locations may have the same path. This happens when a single
+ // logical declaration is spread out across multiple places. The most
+ // obvious example is the "extend" block again -- there may be multiple
+ // extend blocks in the same scope, each of which will have the same path.
+ // - A location's span is not always a subset of its parent's span. For
+ // example, the "extendee" of an extension declaration appears at the
+ // beginning of the "extend" block and is shared by all extensions within
+ // the block.
+ // - Just because a location's span is a subset of some other location's span
+ // does not mean that it is a descendant. For example, a "group" defines
+ // both a type and a field in a single declaration. Thus, the locations
+ // corresponding to the type and field and their components will overlap.
+ // - Code which tries to interpret locations should probably be designed to
+ // ignore those that it doesn't understand, as more types of locations could
+ // be recorded in the future.
+ Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} }
+func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) }
+func (*SourceCodeInfo) ProtoMessage() {}
+func (*SourceCodeInfo) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{19}
+}
+func (m *SourceCodeInfo) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_SourceCodeInfo.Unmarshal(m, b)
+}
+func (m *SourceCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_SourceCodeInfo.Marshal(b, m, deterministic)
+}
+func (m *SourceCodeInfo) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_SourceCodeInfo.Merge(m, src)
+}
+func (m *SourceCodeInfo) XXX_Size() int {
+ return xxx_messageInfo_SourceCodeInfo.Size(m)
+}
+func (m *SourceCodeInfo) XXX_DiscardUnknown() {
+ xxx_messageInfo_SourceCodeInfo.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_SourceCodeInfo proto.InternalMessageInfo
+
+func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location {
+ if m != nil {
+ return m.Location
+ }
+ return nil
+}
+
+type SourceCodeInfo_Location struct {
+ // Identifies which part of the FileDescriptorProto was defined at this
+ // location.
+ //
+ // Each element is a field number or an index. They form a path from
+ // the root FileDescriptorProto to the place where the definition. For
+ // example, this path:
+ // [ 4, 3, 2, 7, 1 ]
+ // refers to:
+ // file.message_type(3) // 4, 3
+ // .field(7) // 2, 7
+ // .name() // 1
+ // This is because FileDescriptorProto.message_type has field number 4:
+ // repeated DescriptorProto message_type = 4;
+ // and DescriptorProto.field has field number 2:
+ // repeated FieldDescriptorProto field = 2;
+ // and FieldDescriptorProto.name has field number 1:
+ // optional string name = 1;
+ //
+ // Thus, the above path gives the location of a field name. If we removed
+ // the last element:
+ // [ 4, 3, 2, 7 ]
+ // this path refers to the whole field declaration (from the beginning
+ // of the label to the terminating semicolon).
+ Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
+ // Always has exactly three or four elements: start line, start column,
+ // end line (optional, otherwise assumed same as start line), end column.
+ // These are packed into a single field for efficiency. Note that line
+ // and column numbers are zero-based -- typically you will want to add
+ // 1 to each before displaying to a user.
+ Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"`
+ // If this SourceCodeInfo represents a complete declaration, these are any
+ // comments appearing before and after the declaration which appear to be
+ // attached to the declaration.
+ //
+ // A series of line comments appearing on consecutive lines, with no other
+ // tokens appearing on those lines, will be treated as a single comment.
+ //
+ // leading_detached_comments will keep paragraphs of comments that appear
+ // before (but not connected to) the current element. Each paragraph,
+ // separated by empty lines, will be one comment element in the repeated
+ // field.
+ //
+ // Only the comment content is provided; comment markers (e.g. //) are
+ // stripped out. For block comments, leading whitespace and an asterisk
+ // will be stripped from the beginning of each line other than the first.
+ // Newlines are included in the output.
+ //
+ // Examples:
+ //
+ // optional int32 foo = 1; // Comment attached to foo.
+ // // Comment attached to bar.
+ // optional int32 bar = 2;
+ //
+ // optional string baz = 3;
+ // // Comment attached to baz.
+ // // Another line attached to baz.
+ //
+ // // Comment attached to qux.
+ // //
+ // // Another line attached to qux.
+ // optional double qux = 4;
+ //
+ // // Detached comment for corge. This is not leading or trailing comments
+ // // to qux or corge because there are blank lines separating it from
+ // // both.
+ //
+ // // Detached comment for corge paragraph 2.
+ //
+ // optional string corge = 5;
+ // /* Block comment attached
+ // * to corge. Leading asterisks
+ // * will be removed. */
+ // /* Block comment attached to
+ // * grault. */
+ // optional int32 grault = 6;
+ //
+ // // ignored detached comments.
+ LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"`
+ TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"`
+ LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} }
+func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) }
+func (*SourceCodeInfo_Location) ProtoMessage() {}
+func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{19, 0}
+}
+func (m *SourceCodeInfo_Location) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_SourceCodeInfo_Location.Unmarshal(m, b)
+}
+func (m *SourceCodeInfo_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_SourceCodeInfo_Location.Marshal(b, m, deterministic)
+}
+func (m *SourceCodeInfo_Location) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_SourceCodeInfo_Location.Merge(m, src)
+}
+func (m *SourceCodeInfo_Location) XXX_Size() int {
+ return xxx_messageInfo_SourceCodeInfo_Location.Size(m)
+}
+func (m *SourceCodeInfo_Location) XXX_DiscardUnknown() {
+ xxx_messageInfo_SourceCodeInfo_Location.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_SourceCodeInfo_Location proto.InternalMessageInfo
+
+func (m *SourceCodeInfo_Location) GetPath() []int32 {
+ if m != nil {
+ return m.Path
+ }
+ return nil
+}
+
+func (m *SourceCodeInfo_Location) GetSpan() []int32 {
+ if m != nil {
+ return m.Span
+ }
+ return nil
+}
+
+func (m *SourceCodeInfo_Location) GetLeadingComments() string {
+ if m != nil && m.LeadingComments != nil {
+ return *m.LeadingComments
+ }
+ return ""
+}
+
+func (m *SourceCodeInfo_Location) GetTrailingComments() string {
+ if m != nil && m.TrailingComments != nil {
+ return *m.TrailingComments
+ }
+ return ""
+}
+
+func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string {
+ if m != nil {
+ return m.LeadingDetachedComments
+ }
+ return nil
+}
+
+// Describes the relationship between generated code and its original source
+// file. A GeneratedCodeInfo message is associated with only one generated
+// source file, but may contain references to different source .proto files.
+type GeneratedCodeInfo struct {
+ // An Annotation connects some span of text in generated code to an element
+ // of its generating .proto file.
+ Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} }
+func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) }
+func (*GeneratedCodeInfo) ProtoMessage() {}
+func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{20}
+}
+func (m *GeneratedCodeInfo) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_GeneratedCodeInfo.Unmarshal(m, b)
+}
+func (m *GeneratedCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_GeneratedCodeInfo.Marshal(b, m, deterministic)
+}
+func (m *GeneratedCodeInfo) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GeneratedCodeInfo.Merge(m, src)
+}
+func (m *GeneratedCodeInfo) XXX_Size() int {
+ return xxx_messageInfo_GeneratedCodeInfo.Size(m)
+}
+func (m *GeneratedCodeInfo) XXX_DiscardUnknown() {
+ xxx_messageInfo_GeneratedCodeInfo.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_GeneratedCodeInfo proto.InternalMessageInfo
+
+func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation {
+ if m != nil {
+ return m.Annotation
+ }
+ return nil
+}
+
+type GeneratedCodeInfo_Annotation struct {
+ // Identifies the element in the original source .proto file. This field
+ // is formatted the same as SourceCodeInfo.Location.path.
+ Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
+ // Identifies the filesystem path to the original source .proto.
+ SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"`
+ // Identifies the starting offset in bytes in the generated code
+ // that relates to the identified object.
+ Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"`
+ // Identifies the ending offset in bytes in the generated code that
+ // relates to the identified offset. The end offset should be one past
+ // the last relevant byte (so the length of the text = end - begin).
+ End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"`
+ XXX_NoUnkeyedLiteral struct{} `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+ XXX_sizecache int32 `json:"-"`
+}
+
+func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} }
+func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) }
+func (*GeneratedCodeInfo_Annotation) ProtoMessage() {}
+func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) {
+ return fileDescriptor_308767df5ffe18af, []int{20, 0}
+}
+func (m *GeneratedCodeInfo_Annotation) XXX_Unmarshal(b []byte) error {
+ return xxx_messageInfo_GeneratedCodeInfo_Annotation.Unmarshal(m, b)
+}
+func (m *GeneratedCodeInfo_Annotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
+ return xxx_messageInfo_GeneratedCodeInfo_Annotation.Marshal(b, m, deterministic)
+}
+func (m *GeneratedCodeInfo_Annotation) XXX_Merge(src proto.Message) {
+ xxx_messageInfo_GeneratedCodeInfo_Annotation.Merge(m, src)
+}
+func (m *GeneratedCodeInfo_Annotation) XXX_Size() int {
+ return xxx_messageInfo_GeneratedCodeInfo_Annotation.Size(m)
+}
+func (m *GeneratedCodeInfo_Annotation) XXX_DiscardUnknown() {
+ xxx_messageInfo_GeneratedCodeInfo_Annotation.DiscardUnknown(m)
+}
+
+var xxx_messageInfo_GeneratedCodeInfo_Annotation proto.InternalMessageInfo
+
+func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 {
+ if m != nil {
+ return m.Path
+ }
+ return nil
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string {
+ if m != nil && m.SourceFile != nil {
+ return *m.SourceFile
+ }
+ return ""
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 {
+ if m != nil && m.Begin != nil {
+ return *m.Begin
+ }
+ return 0
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value)
+ proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value)
+ proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value)
+ proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value)
+ proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value)
+ proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value)
+ proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet")
+ proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto")
+ proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto")
+ proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange")
+ proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange")
+ proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions")
+ proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto")
+ proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto")
+ proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto")
+ proto.RegisterType((*EnumDescriptorProto_EnumReservedRange)(nil), "google.protobuf.EnumDescriptorProto.EnumReservedRange")
+ proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto")
+ proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto")
+ proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto")
+ proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions")
+ proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions")
+ proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions")
+ proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions")
+ proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions")
+ proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions")
+ proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions")
+ proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions")
+ proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption")
+ proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart")
+ proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo")
+ proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location")
+ proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo")
+ proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation")
+}
+
+func init() { proto.RegisterFile("descriptor.proto", fileDescriptor_308767df5ffe18af) }
+
+var fileDescriptor_308767df5ffe18af = []byte{
+ // 2522 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xcd, 0x6f, 0xdb, 0xc8,
+ 0x15, 0x5f, 0x7d, 0x5a, 0x7a, 0x92, 0x65, 0x7a, 0xec, 0x75, 0x18, 0xef, 0x47, 0x1c, 0xed, 0x66,
+ 0xe3, 0x24, 0xbb, 0xca, 0xc2, 0x49, 0x9c, 0xac, 0x53, 0x6c, 0x2b, 0x4b, 0x8c, 0x57, 0xa9, 0xbe,
+ 0x4a, 0xc9, 0xdd, 0x64, 0x8b, 0x82, 0x18, 0x93, 0x23, 0x89, 0x09, 0x45, 0x72, 0x49, 0x2a, 0x89,
+ 0x83, 0x1e, 0x02, 0xf4, 0x54, 0xa0, 0x7f, 0x40, 0x51, 0x14, 0x3d, 0xf4, 0xb2, 0x40, 0xff, 0x80,
+ 0x02, 0xed, 0xbd, 0xd7, 0x02, 0xbd, 0xf7, 0x50, 0xa0, 0x05, 0xda, 0x3f, 0xa1, 0xc7, 0x62, 0x66,
+ 0x48, 0x8a, 0xd4, 0x47, 0xe2, 0x5d, 0x20, 0xd9, 0x93, 0x3d, 0xef, 0xfd, 0xde, 0x9b, 0x37, 0x8f,
+ 0xbf, 0x79, 0xf3, 0x66, 0x04, 0x82, 0x46, 0x5c, 0xd5, 0xd1, 0x6d, 0xcf, 0x72, 0x2a, 0xb6, 0x63,
+ 0x79, 0x16, 0x5a, 0x1b, 0x5a, 0xd6, 0xd0, 0x20, 0x7c, 0x74, 0x32, 0x19, 0x94, 0x5b, 0xb0, 0x7e,
+ 0x4f, 0x37, 0x48, 0x3d, 0x04, 0xf6, 0x88, 0x87, 0xee, 0x40, 0x7a, 0xa0, 0x1b, 0x44, 0x4c, 0xec,
+ 0xa4, 0x76, 0x0b, 0x7b, 0x1f, 0x56, 0x66, 0x8c, 0x2a, 0x71, 0x8b, 0x2e, 0x15, 0xcb, 0xcc, 0xa2,
+ 0xfc, 0xef, 0x34, 0x6c, 0x2c, 0xd0, 0x22, 0x04, 0x69, 0x13, 0x8f, 0xa9, 0xc7, 0xc4, 0x6e, 0x5e,
+ 0x66, 0xff, 0x23, 0x11, 0x56, 0x6c, 0xac, 0x3e, 0xc6, 0x43, 0x22, 0x26, 0x99, 0x38, 0x18, 0xa2,
+ 0xf7, 0x01, 0x34, 0x62, 0x13, 0x53, 0x23, 0xa6, 0x7a, 0x2a, 0xa6, 0x76, 0x52, 0xbb, 0x79, 0x39,
+ 0x22, 0x41, 0xd7, 0x60, 0xdd, 0x9e, 0x9c, 0x18, 0xba, 0xaa, 0x44, 0x60, 0xb0, 0x93, 0xda, 0xcd,
+ 0xc8, 0x02, 0x57, 0xd4, 0xa7, 0xe0, 0xcb, 0xb0, 0xf6, 0x94, 0xe0, 0xc7, 0x51, 0x68, 0x81, 0x41,
+ 0x4b, 0x54, 0x1c, 0x01, 0xd6, 0xa0, 0x38, 0x26, 0xae, 0x8b, 0x87, 0x44, 0xf1, 0x4e, 0x6d, 0x22,
+ 0xa6, 0xd9, 0xea, 0x77, 0xe6, 0x56, 0x3f, 0xbb, 0xf2, 0x82, 0x6f, 0xd5, 0x3f, 0xb5, 0x09, 0xaa,
+ 0x42, 0x9e, 0x98, 0x93, 0x31, 0xf7, 0x90, 0x59, 0x92, 0x3f, 0xc9, 0x9c, 0x8c, 0x67, 0xbd, 0xe4,
+ 0xa8, 0x99, 0xef, 0x62, 0xc5, 0x25, 0xce, 0x13, 0x5d, 0x25, 0x62, 0x96, 0x39, 0xb8, 0x3c, 0xe7,
+ 0xa0, 0xc7, 0xf5, 0xb3, 0x3e, 0x02, 0x3b, 0x54, 0x83, 0x3c, 0x79, 0xe6, 0x11, 0xd3, 0xd5, 0x2d,
+ 0x53, 0x5c, 0x61, 0x4e, 0x2e, 0x2d, 0xf8, 0x8a, 0xc4, 0xd0, 0x66, 0x5d, 0x4c, 0xed, 0xd0, 0x3e,
+ 0xac, 0x58, 0xb6, 0xa7, 0x5b, 0xa6, 0x2b, 0xe6, 0x76, 0x12, 0xbb, 0x85, 0xbd, 0x77, 0x17, 0x12,
+ 0xa1, 0xc3, 0x31, 0x72, 0x00, 0x46, 0x0d, 0x10, 0x5c, 0x6b, 0xe2, 0xa8, 0x44, 0x51, 0x2d, 0x8d,
+ 0x28, 0xba, 0x39, 0xb0, 0xc4, 0x3c, 0x73, 0x70, 0x61, 0x7e, 0x21, 0x0c, 0x58, 0xb3, 0x34, 0xd2,
+ 0x30, 0x07, 0x96, 0x5c, 0x72, 0x63, 0x63, 0xb4, 0x05, 0x59, 0xf7, 0xd4, 0xf4, 0xf0, 0x33, 0xb1,
+ 0xc8, 0x18, 0xe2, 0x8f, 0xca, 0x7f, 0xce, 0xc2, 0xda, 0x59, 0x28, 0x76, 0x17, 0x32, 0x03, 0xba,
+ 0x4a, 0x31, 0xf9, 0x6d, 0x72, 0xc0, 0x6d, 0xe2, 0x49, 0xcc, 0x7e, 0xc7, 0x24, 0x56, 0xa1, 0x60,
+ 0x12, 0xd7, 0x23, 0x1a, 0x67, 0x44, 0xea, 0x8c, 0x9c, 0x02, 0x6e, 0x34, 0x4f, 0xa9, 0xf4, 0x77,
+ 0xa2, 0xd4, 0x03, 0x58, 0x0b, 0x43, 0x52, 0x1c, 0x6c, 0x0e, 0x03, 0x6e, 0x5e, 0x7f, 0x55, 0x24,
+ 0x15, 0x29, 0xb0, 0x93, 0xa9, 0x99, 0x5c, 0x22, 0xb1, 0x31, 0xaa, 0x03, 0x58, 0x26, 0xb1, 0x06,
+ 0x8a, 0x46, 0x54, 0x43, 0xcc, 0x2d, 0xc9, 0x52, 0x87, 0x42, 0xe6, 0xb2, 0x64, 0x71, 0xa9, 0x6a,
+ 0xa0, 0xcf, 0xa6, 0x54, 0x5b, 0x59, 0xc2, 0x94, 0x16, 0xdf, 0x64, 0x73, 0x6c, 0x3b, 0x86, 0x92,
+ 0x43, 0x28, 0xef, 0x89, 0xe6, 0xaf, 0x2c, 0xcf, 0x82, 0xa8, 0xbc, 0x72, 0x65, 0xb2, 0x6f, 0xc6,
+ 0x17, 0xb6, 0xea, 0x44, 0x87, 0xe8, 0x03, 0x08, 0x05, 0x0a, 0xa3, 0x15, 0xb0, 0x2a, 0x54, 0x0c,
+ 0x84, 0x6d, 0x3c, 0x26, 0xdb, 0xcf, 0xa1, 0x14, 0x4f, 0x0f, 0xda, 0x84, 0x8c, 0xeb, 0x61, 0xc7,
+ 0x63, 0x2c, 0xcc, 0xc8, 0x7c, 0x80, 0x04, 0x48, 0x11, 0x53, 0x63, 0x55, 0x2e, 0x23, 0xd3, 0x7f,
+ 0xd1, 0x8f, 0xa6, 0x0b, 0x4e, 0xb1, 0x05, 0x7f, 0x34, 0xff, 0x45, 0x63, 0x9e, 0x67, 0xd7, 0xbd,
+ 0x7d, 0x1b, 0x56, 0x63, 0x0b, 0x38, 0xeb, 0xd4, 0xe5, 0x5f, 0xc0, 0xdb, 0x0b, 0x5d, 0xa3, 0x07,
+ 0xb0, 0x39, 0x31, 0x75, 0xd3, 0x23, 0x8e, 0xed, 0x10, 0xca, 0x58, 0x3e, 0x95, 0xf8, 0x9f, 0x95,
+ 0x25, 0x9c, 0x3b, 0x8e, 0xa2, 0xb9, 0x17, 0x79, 0x63, 0x32, 0x2f, 0xbc, 0x9a, 0xcf, 0xfd, 0x77,
+ 0x45, 0x78, 0xf1, 0xe2, 0xc5, 0x8b, 0x64, 0xf9, 0x37, 0x59, 0xd8, 0x5c, 0xb4, 0x67, 0x16, 0x6e,
+ 0xdf, 0x2d, 0xc8, 0x9a, 0x93, 0xf1, 0x09, 0x71, 0x58, 0x92, 0x32, 0xb2, 0x3f, 0x42, 0x55, 0xc8,
+ 0x18, 0xf8, 0x84, 0x18, 0x62, 0x7a, 0x27, 0xb1, 0x5b, 0xda, 0xbb, 0x76, 0xa6, 0x5d, 0x59, 0x69,
+ 0x52, 0x13, 0x99, 0x5b, 0xa2, 0xcf, 0x21, 0xed, 0x97, 0x68, 0xea, 0xe1, 0xea, 0xd9, 0x3c, 0xd0,
+ 0xbd, 0x24, 0x33, 0x3b, 0xf4, 0x0e, 0xe4, 0xe9, 0x5f, 0xce, 0x8d, 0x2c, 0x8b, 0x39, 0x47, 0x05,
+ 0x94, 0x17, 0x68, 0x1b, 0x72, 0x6c, 0x9b, 0x68, 0x24, 0x38, 0xda, 0xc2, 0x31, 0x25, 0x96, 0x46,
+ 0x06, 0x78, 0x62, 0x78, 0xca, 0x13, 0x6c, 0x4c, 0x08, 0x23, 0x7c, 0x5e, 0x2e, 0xfa, 0xc2, 0x9f,
+ 0x52, 0x19, 0xba, 0x00, 0x05, 0xbe, 0xab, 0x74, 0x53, 0x23, 0xcf, 0x58, 0xf5, 0xcc, 0xc8, 0x7c,
+ 0xa3, 0x35, 0xa8, 0x84, 0x4e, 0xff, 0xc8, 0xb5, 0xcc, 0x80, 0x9a, 0x6c, 0x0a, 0x2a, 0x60, 0xd3,
+ 0xdf, 0x9e, 0x2d, 0xdc, 0xef, 0x2d, 0x5e, 0xde, 0x2c, 0xa7, 0xca, 0x7f, 0x4a, 0x42, 0x9a, 0xd5,
+ 0x8b, 0x35, 0x28, 0xf4, 0x1f, 0x76, 0x25, 0xa5, 0xde, 0x39, 0x3e, 0x6c, 0x4a, 0x42, 0x02, 0x95,
+ 0x00, 0x98, 0xe0, 0x5e, 0xb3, 0x53, 0xed, 0x0b, 0xc9, 0x70, 0xdc, 0x68, 0xf7, 0xf7, 0x6f, 0x0a,
+ 0xa9, 0xd0, 0xe0, 0x98, 0x0b, 0xd2, 0x51, 0xc0, 0x8d, 0x3d, 0x21, 0x83, 0x04, 0x28, 0x72, 0x07,
+ 0x8d, 0x07, 0x52, 0x7d, 0xff, 0xa6, 0x90, 0x8d, 0x4b, 0x6e, 0xec, 0x09, 0x2b, 0x68, 0x15, 0xf2,
+ 0x4c, 0x72, 0xd8, 0xe9, 0x34, 0x85, 0x5c, 0xe8, 0xb3, 0xd7, 0x97, 0x1b, 0xed, 0x23, 0x21, 0x1f,
+ 0xfa, 0x3c, 0x92, 0x3b, 0xc7, 0x5d, 0x01, 0x42, 0x0f, 0x2d, 0xa9, 0xd7, 0xab, 0x1e, 0x49, 0x42,
+ 0x21, 0x44, 0x1c, 0x3e, 0xec, 0x4b, 0x3d, 0xa1, 0x18, 0x0b, 0xeb, 0xc6, 0x9e, 0xb0, 0x1a, 0x4e,
+ 0x21, 0xb5, 0x8f, 0x5b, 0x42, 0x09, 0xad, 0xc3, 0x2a, 0x9f, 0x22, 0x08, 0x62, 0x6d, 0x46, 0xb4,
+ 0x7f, 0x53, 0x10, 0xa6, 0x81, 0x70, 0x2f, 0xeb, 0x31, 0xc1, 0xfe, 0x4d, 0x01, 0x95, 0x6b, 0x90,
+ 0x61, 0xec, 0x42, 0x08, 0x4a, 0xcd, 0xea, 0xa1, 0xd4, 0x54, 0x3a, 0xdd, 0x7e, 0xa3, 0xd3, 0xae,
+ 0x36, 0x85, 0xc4, 0x54, 0x26, 0x4b, 0x3f, 0x39, 0x6e, 0xc8, 0x52, 0x5d, 0x48, 0x46, 0x65, 0x5d,
+ 0xa9, 0xda, 0x97, 0xea, 0x42, 0xaa, 0xac, 0xc2, 0xe6, 0xa2, 0x3a, 0xb9, 0x70, 0x67, 0x44, 0x3e,
+ 0x71, 0x72, 0xc9, 0x27, 0x66, 0xbe, 0xe6, 0x3e, 0xf1, 0xbf, 0x92, 0xb0, 0xb1, 0xe0, 0xac, 0x58,
+ 0x38, 0xc9, 0x0f, 0x21, 0xc3, 0x29, 0xca, 0x4f, 0xcf, 0x2b, 0x0b, 0x0f, 0x1d, 0x46, 0xd8, 0xb9,
+ 0x13, 0x94, 0xd9, 0x45, 0x3b, 0x88, 0xd4, 0x92, 0x0e, 0x82, 0xba, 0x98, 0xab, 0xe9, 0x3f, 0x9f,
+ 0xab, 0xe9, 0xfc, 0xd8, 0xdb, 0x3f, 0xcb, 0xb1, 0xc7, 0x64, 0xdf, 0xae, 0xb6, 0x67, 0x16, 0xd4,
+ 0xf6, 0xbb, 0xb0, 0x3e, 0xe7, 0xe8, 0xcc, 0x35, 0xf6, 0x97, 0x09, 0x10, 0x97, 0x25, 0xe7, 0x15,
+ 0x95, 0x2e, 0x19, 0xab, 0x74, 0x77, 0x67, 0x33, 0x78, 0x71, 0xf9, 0x47, 0x98, 0xfb, 0xd6, 0xdf,
+ 0x24, 0x60, 0x6b, 0x71, 0xa7, 0xb8, 0x30, 0x86, 0xcf, 0x21, 0x3b, 0x26, 0xde, 0xc8, 0x0a, 0xba,
+ 0xa5, 0x8f, 0x16, 0x9c, 0xc1, 0x54, 0x3d, 0xfb, 0xb1, 0x7d, 0xab, 0xe8, 0x21, 0x9e, 0x5a, 0xd6,
+ 0xee, 0xf1, 0x68, 0xe6, 0x22, 0xfd, 0x55, 0x12, 0xde, 0x5e, 0xe8, 0x7c, 0x61, 0xa0, 0xef, 0x01,
+ 0xe8, 0xa6, 0x3d, 0xf1, 0x78, 0x47, 0xc4, 0x0b, 0x6c, 0x9e, 0x49, 0x58, 0xf1, 0xa2, 0xc5, 0x73,
+ 0xe2, 0x85, 0xfa, 0x14, 0xd3, 0x03, 0x17, 0x31, 0xc0, 0x9d, 0x69, 0xa0, 0x69, 0x16, 0xe8, 0xfb,
+ 0x4b, 0x56, 0x3a, 0x47, 0xcc, 0x4f, 0x41, 0x50, 0x0d, 0x9d, 0x98, 0x9e, 0xe2, 0x7a, 0x0e, 0xc1,
+ 0x63, 0xdd, 0x1c, 0xb2, 0x13, 0x24, 0x77, 0x90, 0x19, 0x60, 0xc3, 0x25, 0xf2, 0x1a, 0x57, 0xf7,
+ 0x02, 0x2d, 0xb5, 0x60, 0x04, 0x72, 0x22, 0x16, 0xd9, 0x98, 0x05, 0x57, 0x87, 0x16, 0xe5, 0x5f,
+ 0xe7, 0xa1, 0x10, 0xe9, 0xab, 0xd1, 0x45, 0x28, 0x3e, 0xc2, 0x4f, 0xb0, 0x12, 0xdc, 0x95, 0x78,
+ 0x26, 0x0a, 0x54, 0xd6, 0xf5, 0xef, 0x4b, 0x9f, 0xc2, 0x26, 0x83, 0x58, 0x13, 0x8f, 0x38, 0x8a,
+ 0x6a, 0x60, 0xd7, 0x65, 0x49, 0xcb, 0x31, 0x28, 0xa2, 0xba, 0x0e, 0x55, 0xd5, 0x02, 0x0d, 0xba,
+ 0x05, 0x1b, 0xcc, 0x62, 0x3c, 0x31, 0x3c, 0xdd, 0x36, 0x88, 0x42, 0x6f, 0x6f, 0x2e, 0x3b, 0x49,
+ 0xc2, 0xc8, 0xd6, 0x29, 0xa2, 0xe5, 0x03, 0x68, 0x44, 0x2e, 0xaa, 0xc3, 0x7b, 0xcc, 0x6c, 0x48,
+ 0x4c, 0xe2, 0x60, 0x8f, 0x28, 0xe4, 0xeb, 0x09, 0x36, 0x5c, 0x05, 0x9b, 0x9a, 0x32, 0xc2, 0xee,
+ 0x48, 0xdc, 0xa4, 0x0e, 0x0e, 0x93, 0x62, 0x42, 0x3e, 0x4f, 0x81, 0x47, 0x3e, 0x4e, 0x62, 0xb0,
+ 0xaa, 0xa9, 0x7d, 0x81, 0xdd, 0x11, 0x3a, 0x80, 0x2d, 0xe6, 0xc5, 0xf5, 0x1c, 0xdd, 0x1c, 0x2a,
+ 0xea, 0x88, 0xa8, 0x8f, 0x95, 0x89, 0x37, 0xb8, 0x23, 0xbe, 0x13, 0x9d, 0x9f, 0x45, 0xd8, 0x63,
+ 0x98, 0x1a, 0x85, 0x1c, 0x7b, 0x83, 0x3b, 0xa8, 0x07, 0x45, 0xfa, 0x31, 0xc6, 0xfa, 0x73, 0xa2,
+ 0x0c, 0x2c, 0x87, 0x1d, 0x8d, 0xa5, 0x05, 0xa5, 0x29, 0x92, 0xc1, 0x4a, 0xc7, 0x37, 0x68, 0x59,
+ 0x1a, 0x39, 0xc8, 0xf4, 0xba, 0x92, 0x54, 0x97, 0x0b, 0x81, 0x97, 0x7b, 0x96, 0x43, 0x09, 0x35,
+ 0xb4, 0xc2, 0x04, 0x17, 0x38, 0xa1, 0x86, 0x56, 0x90, 0xde, 0x5b, 0xb0, 0xa1, 0xaa, 0x7c, 0xcd,
+ 0xba, 0xaa, 0xf8, 0x77, 0x2c, 0x57, 0x14, 0x62, 0xc9, 0x52, 0xd5, 0x23, 0x0e, 0xf0, 0x39, 0xee,
+ 0xa2, 0xcf, 0xe0, 0xed, 0x69, 0xb2, 0xa2, 0x86, 0xeb, 0x73, 0xab, 0x9c, 0x35, 0xbd, 0x05, 0x1b,
+ 0xf6, 0xe9, 0xbc, 0x21, 0x8a, 0xcd, 0x68, 0x9f, 0xce, 0x9a, 0xdd, 0x86, 0x4d, 0x7b, 0x64, 0xcf,
+ 0xdb, 0x5d, 0x8d, 0xda, 0x21, 0x7b, 0x64, 0xcf, 0x1a, 0x5e, 0x62, 0x17, 0x6e, 0x87, 0xa8, 0xd8,
+ 0x23, 0x9a, 0x78, 0x2e, 0x0a, 0x8f, 0x28, 0xd0, 0x75, 0x10, 0x54, 0x55, 0x21, 0x26, 0x3e, 0x31,
+ 0x88, 0x82, 0x1d, 0x62, 0x62, 0x57, 0xbc, 0x10, 0x05, 0x97, 0x54, 0x55, 0x62, 0xda, 0x2a, 0x53,
+ 0xa2, 0xab, 0xb0, 0x6e, 0x9d, 0x3c, 0x52, 0x39, 0x25, 0x15, 0xdb, 0x21, 0x03, 0xfd, 0x99, 0xf8,
+ 0x21, 0xcb, 0xef, 0x1a, 0x55, 0x30, 0x42, 0x76, 0x99, 0x18, 0x5d, 0x01, 0x41, 0x75, 0x47, 0xd8,
+ 0xb1, 0x59, 0x4d, 0x76, 0x6d, 0xac, 0x12, 0xf1, 0x12, 0x87, 0x72, 0x79, 0x3b, 0x10, 0xd3, 0x2d,
+ 0xe1, 0x3e, 0xd5, 0x07, 0x5e, 0xe0, 0xf1, 0x32, 0xdf, 0x12, 0x4c, 0xe6, 0x7b, 0xdb, 0x05, 0x81,
+ 0xa6, 0x22, 0x36, 0xf1, 0x2e, 0x83, 0x95, 0xec, 0x91, 0x1d, 0x9d, 0xf7, 0x03, 0x58, 0xa5, 0xc8,
+ 0xe9, 0xa4, 0x57, 0x78, 0x43, 0x66, 0x8f, 0x22, 0x33, 0xde, 0x84, 0x2d, 0x0a, 0x1a, 0x13, 0x0f,
+ 0x6b, 0xd8, 0xc3, 0x11, 0xf4, 0xc7, 0x0c, 0x4d, 0xf3, 0xde, 0xf2, 0x95, 0xb1, 0x38, 0x9d, 0xc9,
+ 0xc9, 0x69, 0xc8, 0xac, 0x4f, 0x78, 0x9c, 0x54, 0x16, 0x70, 0xeb, 0xb5, 0x35, 0xdd, 0xe5, 0x03,
+ 0x28, 0x46, 0x89, 0x8f, 0xf2, 0xc0, 0xa9, 0x2f, 0x24, 0x68, 0x17, 0x54, 0xeb, 0xd4, 0x69, 0xff,
+ 0xf2, 0x95, 0x24, 0x24, 0x69, 0x1f, 0xd5, 0x6c, 0xf4, 0x25, 0x45, 0x3e, 0x6e, 0xf7, 0x1b, 0x2d,
+ 0x49, 0x48, 0x45, 0x1b, 0xf6, 0xbf, 0x26, 0xa1, 0x14, 0xbf, 0x7b, 0xa1, 0x1f, 0xc0, 0xb9, 0xe0,
+ 0xa1, 0xc4, 0x25, 0x9e, 0xf2, 0x54, 0x77, 0xd8, 0x5e, 0x1c, 0x63, 0x7e, 0x2e, 0x86, 0x6c, 0xd8,
+ 0xf4, 0x51, 0x3d, 0xe2, 0x7d, 0xa9, 0x3b, 0x74, 0xa7, 0x8d, 0xb1, 0x87, 0x9a, 0x70, 0xc1, 0xb4,
+ 0x14, 0xd7, 0xc3, 0xa6, 0x86, 0x1d, 0x4d, 0x99, 0x3e, 0x51, 0x29, 0x58, 0x55, 0x89, 0xeb, 0x5a,
+ 0xfc, 0x0c, 0x0c, 0xbd, 0xbc, 0x6b, 0x5a, 0x3d, 0x1f, 0x3c, 0x3d, 0x1c, 0xaa, 0x3e, 0x74, 0x86,
+ 0xb9, 0xa9, 0x65, 0xcc, 0x7d, 0x07, 0xf2, 0x63, 0x6c, 0x2b, 0xc4, 0xf4, 0x9c, 0x53, 0xd6, 0x71,
+ 0xe7, 0xe4, 0xdc, 0x18, 0xdb, 0x12, 0x1d, 0xbf, 0x99, 0x8b, 0xcf, 0x3f, 0x52, 0x50, 0x8c, 0x76,
+ 0xdd, 0xf4, 0x12, 0xa3, 0xb2, 0x03, 0x2a, 0xc1, 0x4a, 0xd8, 0x07, 0x2f, 0xed, 0xd1, 0x2b, 0x35,
+ 0x7a, 0x72, 0x1d, 0x64, 0x79, 0x2f, 0x2c, 0x73, 0x4b, 0xda, 0x35, 0x50, 0x6a, 0x11, 0xde, 0x7b,
+ 0xe4, 0x64, 0x7f, 0x84, 0x8e, 0x20, 0xfb, 0xc8, 0x65, 0xbe, 0xb3, 0xcc, 0xf7, 0x87, 0x2f, 0xf7,
+ 0x7d, 0xbf, 0xc7, 0x9c, 0xe7, 0xef, 0xf7, 0x94, 0x76, 0x47, 0x6e, 0x55, 0x9b, 0xb2, 0x6f, 0x8e,
+ 0xce, 0x43, 0xda, 0xc0, 0xcf, 0x4f, 0xe3, 0x67, 0x1c, 0x13, 0x9d, 0x35, 0xf1, 0xe7, 0x21, 0xfd,
+ 0x94, 0xe0, 0xc7, 0xf1, 0x93, 0x85, 0x89, 0x5e, 0x23, 0xf5, 0xaf, 0x43, 0x86, 0xe5, 0x0b, 0x01,
+ 0xf8, 0x19, 0x13, 0xde, 0x42, 0x39, 0x48, 0xd7, 0x3a, 0x32, 0xa5, 0xbf, 0x00, 0x45, 0x2e, 0x55,
+ 0xba, 0x0d, 0xa9, 0x26, 0x09, 0xc9, 0xf2, 0x2d, 0xc8, 0xf2, 0x24, 0xd0, 0xad, 0x11, 0xa6, 0x41,
+ 0x78, 0xcb, 0x1f, 0xfa, 0x3e, 0x12, 0x81, 0xf6, 0xb8, 0x75, 0x28, 0xc9, 0x42, 0x32, 0xfa, 0x79,
+ 0x5d, 0x28, 0x46, 0x1b, 0xee, 0x37, 0xc3, 0xa9, 0xbf, 0x24, 0xa0, 0x10, 0x69, 0xa0, 0x69, 0xe7,
+ 0x83, 0x0d, 0xc3, 0x7a, 0xaa, 0x60, 0x43, 0xc7, 0xae, 0x4f, 0x0a, 0x60, 0xa2, 0x2a, 0x95, 0x9c,
+ 0xf5, 0xa3, 0xbd, 0x91, 0xe0, 0x7f, 0x9f, 0x00, 0x61, 0xb6, 0x77, 0x9d, 0x09, 0x30, 0xf1, 0xbd,
+ 0x06, 0xf8, 0xbb, 0x04, 0x94, 0xe2, 0x0d, 0xeb, 0x4c, 0x78, 0x17, 0xbf, 0xd7, 0xf0, 0xfe, 0x99,
+ 0x84, 0xd5, 0x58, 0x9b, 0x7a, 0xd6, 0xe8, 0xbe, 0x86, 0x75, 0x5d, 0x23, 0x63, 0xdb, 0xf2, 0x88,
+ 0xa9, 0x9e, 0x2a, 0x06, 0x79, 0x42, 0x0c, 0xb1, 0xcc, 0x0a, 0xc5, 0xf5, 0x97, 0x37, 0xc2, 0x95,
+ 0xc6, 0xd4, 0xae, 0x49, 0xcd, 0x0e, 0x36, 0x1a, 0x75, 0xa9, 0xd5, 0xed, 0xf4, 0xa5, 0x76, 0xed,
+ 0xa1, 0x72, 0xdc, 0xfe, 0x71, 0xbb, 0xf3, 0x65, 0x5b, 0x16, 0xf4, 0x19, 0xd8, 0x6b, 0xdc, 0xea,
+ 0x5d, 0x10, 0x66, 0x83, 0x42, 0xe7, 0x60, 0x51, 0x58, 0xc2, 0x5b, 0x68, 0x03, 0xd6, 0xda, 0x1d,
+ 0xa5, 0xd7, 0xa8, 0x4b, 0x8a, 0x74, 0xef, 0x9e, 0x54, 0xeb, 0xf7, 0xf8, 0xd3, 0x46, 0x88, 0xee,
+ 0xc7, 0x37, 0xf5, 0x6f, 0x53, 0xb0, 0xb1, 0x20, 0x12, 0x54, 0xf5, 0x2f, 0x25, 0xfc, 0x9e, 0xf4,
+ 0xc9, 0x59, 0xa2, 0xaf, 0xd0, 0xae, 0xa0, 0x8b, 0x1d, 0xcf, 0xbf, 0xc3, 0x5c, 0x01, 0x9a, 0x25,
+ 0xd3, 0xd3, 0x07, 0x3a, 0x71, 0xfc, 0x97, 0x20, 0x7e, 0x53, 0x59, 0x9b, 0xca, 0xf9, 0x63, 0xd0,
+ 0xc7, 0x80, 0x6c, 0xcb, 0xd5, 0x3d, 0xfd, 0x09, 0x51, 0x74, 0x33, 0x78, 0x36, 0xa2, 0x37, 0x97,
+ 0xb4, 0x2c, 0x04, 0x9a, 0x86, 0xe9, 0x85, 0x68, 0x93, 0x0c, 0xf1, 0x0c, 0x9a, 0x16, 0xf0, 0x94,
+ 0x2c, 0x04, 0x9a, 0x10, 0x7d, 0x11, 0x8a, 0x9a, 0x35, 0xa1, 0xed, 0x1c, 0xc7, 0xd1, 0xf3, 0x22,
+ 0x21, 0x17, 0xb8, 0x2c, 0x84, 0xf8, 0x8d, 0xfa, 0xf4, 0xbd, 0xaa, 0x28, 0x17, 0xb8, 0x8c, 0x43,
+ 0x2e, 0xc3, 0x1a, 0x1e, 0x0e, 0x1d, 0xea, 0x3c, 0x70, 0xc4, 0xaf, 0x1e, 0xa5, 0x50, 0xcc, 0x80,
+ 0xdb, 0xf7, 0x21, 0x17, 0xe4, 0x81, 0x1e, 0xc9, 0x34, 0x13, 0x8a, 0xcd, 0xef, 0xd3, 0xc9, 0xdd,
+ 0xbc, 0x9c, 0x33, 0x03, 0xe5, 0x45, 0x28, 0xea, 0xae, 0x32, 0x7d, 0x7e, 0x4f, 0xee, 0x24, 0x77,
+ 0x73, 0x72, 0x41, 0x77, 0xc3, 0xa7, 0xcb, 0xf2, 0x37, 0x49, 0x28, 0xc5, 0x7f, 0x3e, 0x40, 0x75,
+ 0xc8, 0x19, 0x96, 0x8a, 0x19, 0xb5, 0xf8, 0x6f, 0x57, 0xbb, 0xaf, 0xf8, 0xc5, 0xa1, 0xd2, 0xf4,
+ 0xf1, 0x72, 0x68, 0xb9, 0xfd, 0xb7, 0x04, 0xe4, 0x02, 0x31, 0xda, 0x82, 0xb4, 0x8d, 0xbd, 0x11,
+ 0x73, 0x97, 0x39, 0x4c, 0x0a, 0x09, 0x99, 0x8d, 0xa9, 0xdc, 0xb5, 0xb1, 0xc9, 0x28, 0xe0, 0xcb,
+ 0xe9, 0x98, 0x7e, 0x57, 0x83, 0x60, 0x8d, 0xdd, 0x6b, 0xac, 0xf1, 0x98, 0x98, 0x9e, 0x1b, 0x7c,
+ 0x57, 0x5f, 0x5e, 0xf3, 0xc5, 0xe8, 0x1a, 0xac, 0x7b, 0x0e, 0xd6, 0x8d, 0x18, 0x36, 0xcd, 0xb0,
+ 0x42, 0xa0, 0x08, 0xc1, 0x07, 0x70, 0x3e, 0xf0, 0xab, 0x11, 0x0f, 0xab, 0x23, 0xa2, 0x4d, 0x8d,
+ 0xb2, 0xec, 0xfd, 0xe2, 0x9c, 0x0f, 0xa8, 0xfb, 0xfa, 0xc0, 0xb6, 0xfc, 0xf7, 0x04, 0xac, 0x07,
+ 0x37, 0x31, 0x2d, 0x4c, 0x56, 0x0b, 0x00, 0x9b, 0xa6, 0xe5, 0x45, 0xd3, 0x35, 0x4f, 0xe5, 0x39,
+ 0xbb, 0x4a, 0x35, 0x34, 0x92, 0x23, 0x0e, 0xb6, 0xc7, 0x00, 0x53, 0xcd, 0xd2, 0xb4, 0x5d, 0x80,
+ 0x82, 0xff, 0xdb, 0x10, 0xfb, 0x81, 0x91, 0xdf, 0xdd, 0x81, 0x8b, 0xe8, 0x95, 0x0d, 0x6d, 0x42,
+ 0xe6, 0x84, 0x0c, 0x75, 0xd3, 0x7f, 0xf1, 0xe5, 0x83, 0xe0, 0x85, 0x25, 0x1d, 0xbe, 0xb0, 0x1c,
+ 0xfe, 0x0c, 0x36, 0x54, 0x6b, 0x3c, 0x1b, 0xee, 0xa1, 0x30, 0xf3, 0x7e, 0xe0, 0x7e, 0x91, 0xf8,
+ 0x0a, 0xa6, 0x2d, 0xe6, 0xff, 0x12, 0x89, 0x3f, 0x24, 0x53, 0x47, 0xdd, 0xc3, 0x3f, 0x26, 0xb7,
+ 0x8f, 0xb8, 0x69, 0x37, 0x58, 0xa9, 0x4c, 0x06, 0x06, 0x51, 0x69, 0xf4, 0xff, 0x0f, 0x00, 0x00,
+ 0xff, 0xff, 0x88, 0x17, 0xc1, 0xbe, 0x38, 0x1d, 0x00, 0x00,
+}
diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go
@@ -0,0 +1,752 @@
+// Code generated by protoc-gen-gogo. DO NOT EDIT.
+// source: descriptor.proto
+
+package descriptor
+
+import (
+ fmt "fmt"
+ github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
+ proto "github.com/gogo/protobuf/proto"
+ math "math"
+ reflect "reflect"
+ sort "sort"
+ strconv "strconv"
+ strings "strings"
+)
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+func (this *FileDescriptorSet) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&descriptor.FileDescriptorSet{")
+ if this.File != nil {
+ s = append(s, "File: "+fmt.Sprintf("%#v", this.File)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *FileDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 16)
+ s = append(s, "&descriptor.FileDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Package != nil {
+ s = append(s, "Package: "+valueToGoStringDescriptor(this.Package, "string")+",\n")
+ }
+ if this.Dependency != nil {
+ s = append(s, "Dependency: "+fmt.Sprintf("%#v", this.Dependency)+",\n")
+ }
+ if this.PublicDependency != nil {
+ s = append(s, "PublicDependency: "+fmt.Sprintf("%#v", this.PublicDependency)+",\n")
+ }
+ if this.WeakDependency != nil {
+ s = append(s, "WeakDependency: "+fmt.Sprintf("%#v", this.WeakDependency)+",\n")
+ }
+ if this.MessageType != nil {
+ s = append(s, "MessageType: "+fmt.Sprintf("%#v", this.MessageType)+",\n")
+ }
+ if this.EnumType != nil {
+ s = append(s, "EnumType: "+fmt.Sprintf("%#v", this.EnumType)+",\n")
+ }
+ if this.Service != nil {
+ s = append(s, "Service: "+fmt.Sprintf("%#v", this.Service)+",\n")
+ }
+ if this.Extension != nil {
+ s = append(s, "Extension: "+fmt.Sprintf("%#v", this.Extension)+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.SourceCodeInfo != nil {
+ s = append(s, "SourceCodeInfo: "+fmt.Sprintf("%#v", this.SourceCodeInfo)+",\n")
+ }
+ if this.Syntax != nil {
+ s = append(s, "Syntax: "+valueToGoStringDescriptor(this.Syntax, "string")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *DescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 14)
+ s = append(s, "&descriptor.DescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Field != nil {
+ s = append(s, "Field: "+fmt.Sprintf("%#v", this.Field)+",\n")
+ }
+ if this.Extension != nil {
+ s = append(s, "Extension: "+fmt.Sprintf("%#v", this.Extension)+",\n")
+ }
+ if this.NestedType != nil {
+ s = append(s, "NestedType: "+fmt.Sprintf("%#v", this.NestedType)+",\n")
+ }
+ if this.EnumType != nil {
+ s = append(s, "EnumType: "+fmt.Sprintf("%#v", this.EnumType)+",\n")
+ }
+ if this.ExtensionRange != nil {
+ s = append(s, "ExtensionRange: "+fmt.Sprintf("%#v", this.ExtensionRange)+",\n")
+ }
+ if this.OneofDecl != nil {
+ s = append(s, "OneofDecl: "+fmt.Sprintf("%#v", this.OneofDecl)+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.ReservedRange != nil {
+ s = append(s, "ReservedRange: "+fmt.Sprintf("%#v", this.ReservedRange)+",\n")
+ }
+ if this.ReservedName != nil {
+ s = append(s, "ReservedName: "+fmt.Sprintf("%#v", this.ReservedName)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *DescriptorProto_ExtensionRange) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&descriptor.DescriptorProto_ExtensionRange{")
+ if this.Start != nil {
+ s = append(s, "Start: "+valueToGoStringDescriptor(this.Start, "int32")+",\n")
+ }
+ if this.End != nil {
+ s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *DescriptorProto_ReservedRange) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.DescriptorProto_ReservedRange{")
+ if this.Start != nil {
+ s = append(s, "Start: "+valueToGoStringDescriptor(this.Start, "int32")+",\n")
+ }
+ if this.End != nil {
+ s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *ExtensionRangeOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&descriptor.ExtensionRangeOptions{")
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *FieldDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 14)
+ s = append(s, "&descriptor.FieldDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Number != nil {
+ s = append(s, "Number: "+valueToGoStringDescriptor(this.Number, "int32")+",\n")
+ }
+ if this.Label != nil {
+ s = append(s, "Label: "+valueToGoStringDescriptor(this.Label, "FieldDescriptorProto_Label")+",\n")
+ }
+ if this.Type != nil {
+ s = append(s, "Type: "+valueToGoStringDescriptor(this.Type, "FieldDescriptorProto_Type")+",\n")
+ }
+ if this.TypeName != nil {
+ s = append(s, "TypeName: "+valueToGoStringDescriptor(this.TypeName, "string")+",\n")
+ }
+ if this.Extendee != nil {
+ s = append(s, "Extendee: "+valueToGoStringDescriptor(this.Extendee, "string")+",\n")
+ }
+ if this.DefaultValue != nil {
+ s = append(s, "DefaultValue: "+valueToGoStringDescriptor(this.DefaultValue, "string")+",\n")
+ }
+ if this.OneofIndex != nil {
+ s = append(s, "OneofIndex: "+valueToGoStringDescriptor(this.OneofIndex, "int32")+",\n")
+ }
+ if this.JsonName != nil {
+ s = append(s, "JsonName: "+valueToGoStringDescriptor(this.JsonName, "string")+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *OneofDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.OneofDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *EnumDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 9)
+ s = append(s, "&descriptor.EnumDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Value != nil {
+ s = append(s, "Value: "+fmt.Sprintf("%#v", this.Value)+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.ReservedRange != nil {
+ s = append(s, "ReservedRange: "+fmt.Sprintf("%#v", this.ReservedRange)+",\n")
+ }
+ if this.ReservedName != nil {
+ s = append(s, "ReservedName: "+fmt.Sprintf("%#v", this.ReservedName)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *EnumDescriptorProto_EnumReservedRange) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.EnumDescriptorProto_EnumReservedRange{")
+ if this.Start != nil {
+ s = append(s, "Start: "+valueToGoStringDescriptor(this.Start, "int32")+",\n")
+ }
+ if this.End != nil {
+ s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *EnumValueDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&descriptor.EnumValueDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Number != nil {
+ s = append(s, "Number: "+valueToGoStringDescriptor(this.Number, "int32")+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *ServiceDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&descriptor.ServiceDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.Method != nil {
+ s = append(s, "Method: "+fmt.Sprintf("%#v", this.Method)+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *MethodDescriptorProto) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 10)
+ s = append(s, "&descriptor.MethodDescriptorProto{")
+ if this.Name != nil {
+ s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n")
+ }
+ if this.InputType != nil {
+ s = append(s, "InputType: "+valueToGoStringDescriptor(this.InputType, "string")+",\n")
+ }
+ if this.OutputType != nil {
+ s = append(s, "OutputType: "+valueToGoStringDescriptor(this.OutputType, "string")+",\n")
+ }
+ if this.Options != nil {
+ s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n")
+ }
+ if this.ClientStreaming != nil {
+ s = append(s, "ClientStreaming: "+valueToGoStringDescriptor(this.ClientStreaming, "bool")+",\n")
+ }
+ if this.ServerStreaming != nil {
+ s = append(s, "ServerStreaming: "+valueToGoStringDescriptor(this.ServerStreaming, "bool")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *FileOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 25)
+ s = append(s, "&descriptor.FileOptions{")
+ if this.JavaPackage != nil {
+ s = append(s, "JavaPackage: "+valueToGoStringDescriptor(this.JavaPackage, "string")+",\n")
+ }
+ if this.JavaOuterClassname != nil {
+ s = append(s, "JavaOuterClassname: "+valueToGoStringDescriptor(this.JavaOuterClassname, "string")+",\n")
+ }
+ if this.JavaMultipleFiles != nil {
+ s = append(s, "JavaMultipleFiles: "+valueToGoStringDescriptor(this.JavaMultipleFiles, "bool")+",\n")
+ }
+ if this.JavaGenerateEqualsAndHash != nil {
+ s = append(s, "JavaGenerateEqualsAndHash: "+valueToGoStringDescriptor(this.JavaGenerateEqualsAndHash, "bool")+",\n")
+ }
+ if this.JavaStringCheckUtf8 != nil {
+ s = append(s, "JavaStringCheckUtf8: "+valueToGoStringDescriptor(this.JavaStringCheckUtf8, "bool")+",\n")
+ }
+ if this.OptimizeFor != nil {
+ s = append(s, "OptimizeFor: "+valueToGoStringDescriptor(this.OptimizeFor, "FileOptions_OptimizeMode")+",\n")
+ }
+ if this.GoPackage != nil {
+ s = append(s, "GoPackage: "+valueToGoStringDescriptor(this.GoPackage, "string")+",\n")
+ }
+ if this.CcGenericServices != nil {
+ s = append(s, "CcGenericServices: "+valueToGoStringDescriptor(this.CcGenericServices, "bool")+",\n")
+ }
+ if this.JavaGenericServices != nil {
+ s = append(s, "JavaGenericServices: "+valueToGoStringDescriptor(this.JavaGenericServices, "bool")+",\n")
+ }
+ if this.PyGenericServices != nil {
+ s = append(s, "PyGenericServices: "+valueToGoStringDescriptor(this.PyGenericServices, "bool")+",\n")
+ }
+ if this.PhpGenericServices != nil {
+ s = append(s, "PhpGenericServices: "+valueToGoStringDescriptor(this.PhpGenericServices, "bool")+",\n")
+ }
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.CcEnableArenas != nil {
+ s = append(s, "CcEnableArenas: "+valueToGoStringDescriptor(this.CcEnableArenas, "bool")+",\n")
+ }
+ if this.ObjcClassPrefix != nil {
+ s = append(s, "ObjcClassPrefix: "+valueToGoStringDescriptor(this.ObjcClassPrefix, "string")+",\n")
+ }
+ if this.CsharpNamespace != nil {
+ s = append(s, "CsharpNamespace: "+valueToGoStringDescriptor(this.CsharpNamespace, "string")+",\n")
+ }
+ if this.SwiftPrefix != nil {
+ s = append(s, "SwiftPrefix: "+valueToGoStringDescriptor(this.SwiftPrefix, "string")+",\n")
+ }
+ if this.PhpClassPrefix != nil {
+ s = append(s, "PhpClassPrefix: "+valueToGoStringDescriptor(this.PhpClassPrefix, "string")+",\n")
+ }
+ if this.PhpNamespace != nil {
+ s = append(s, "PhpNamespace: "+valueToGoStringDescriptor(this.PhpNamespace, "string")+",\n")
+ }
+ if this.PhpMetadataNamespace != nil {
+ s = append(s, "PhpMetadataNamespace: "+valueToGoStringDescriptor(this.PhpMetadataNamespace, "string")+",\n")
+ }
+ if this.RubyPackage != nil {
+ s = append(s, "RubyPackage: "+valueToGoStringDescriptor(this.RubyPackage, "string")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *MessageOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 9)
+ s = append(s, "&descriptor.MessageOptions{")
+ if this.MessageSetWireFormat != nil {
+ s = append(s, "MessageSetWireFormat: "+valueToGoStringDescriptor(this.MessageSetWireFormat, "bool")+",\n")
+ }
+ if this.NoStandardDescriptorAccessor != nil {
+ s = append(s, "NoStandardDescriptorAccessor: "+valueToGoStringDescriptor(this.NoStandardDescriptorAccessor, "bool")+",\n")
+ }
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.MapEntry != nil {
+ s = append(s, "MapEntry: "+valueToGoStringDescriptor(this.MapEntry, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *FieldOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 11)
+ s = append(s, "&descriptor.FieldOptions{")
+ if this.Ctype != nil {
+ s = append(s, "Ctype: "+valueToGoStringDescriptor(this.Ctype, "FieldOptions_CType")+",\n")
+ }
+ if this.Packed != nil {
+ s = append(s, "Packed: "+valueToGoStringDescriptor(this.Packed, "bool")+",\n")
+ }
+ if this.Jstype != nil {
+ s = append(s, "Jstype: "+valueToGoStringDescriptor(this.Jstype, "FieldOptions_JSType")+",\n")
+ }
+ if this.Lazy != nil {
+ s = append(s, "Lazy: "+valueToGoStringDescriptor(this.Lazy, "bool")+",\n")
+ }
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.Weak != nil {
+ s = append(s, "Weak: "+valueToGoStringDescriptor(this.Weak, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *OneofOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&descriptor.OneofOptions{")
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *EnumOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&descriptor.EnumOptions{")
+ if this.AllowAlias != nil {
+ s = append(s, "AllowAlias: "+valueToGoStringDescriptor(this.AllowAlias, "bool")+",\n")
+ }
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *EnumValueOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.EnumValueOptions{")
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *ServiceOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.ServiceOptions{")
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *MethodOptions) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 7)
+ s = append(s, "&descriptor.MethodOptions{")
+ if this.Deprecated != nil {
+ s = append(s, "Deprecated: "+valueToGoStringDescriptor(this.Deprecated, "bool")+",\n")
+ }
+ if this.IdempotencyLevel != nil {
+ s = append(s, "IdempotencyLevel: "+valueToGoStringDescriptor(this.IdempotencyLevel, "MethodOptions_IdempotencyLevel")+",\n")
+ }
+ if this.UninterpretedOption != nil {
+ s = append(s, "UninterpretedOption: "+fmt.Sprintf("%#v", this.UninterpretedOption)+",\n")
+ }
+ s = append(s, "XXX_InternalExtensions: "+extensionToGoStringDescriptor(this)+",\n")
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *UninterpretedOption) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 11)
+ s = append(s, "&descriptor.UninterpretedOption{")
+ if this.Name != nil {
+ s = append(s, "Name: "+fmt.Sprintf("%#v", this.Name)+",\n")
+ }
+ if this.IdentifierValue != nil {
+ s = append(s, "IdentifierValue: "+valueToGoStringDescriptor(this.IdentifierValue, "string")+",\n")
+ }
+ if this.PositiveIntValue != nil {
+ s = append(s, "PositiveIntValue: "+valueToGoStringDescriptor(this.PositiveIntValue, "uint64")+",\n")
+ }
+ if this.NegativeIntValue != nil {
+ s = append(s, "NegativeIntValue: "+valueToGoStringDescriptor(this.NegativeIntValue, "int64")+",\n")
+ }
+ if this.DoubleValue != nil {
+ s = append(s, "DoubleValue: "+valueToGoStringDescriptor(this.DoubleValue, "float64")+",\n")
+ }
+ if this.StringValue != nil {
+ s = append(s, "StringValue: "+valueToGoStringDescriptor(this.StringValue, "byte")+",\n")
+ }
+ if this.AggregateValue != nil {
+ s = append(s, "AggregateValue: "+valueToGoStringDescriptor(this.AggregateValue, "string")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *UninterpretedOption_NamePart) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 6)
+ s = append(s, "&descriptor.UninterpretedOption_NamePart{")
+ if this.NamePart != nil {
+ s = append(s, "NamePart: "+valueToGoStringDescriptor(this.NamePart, "string")+",\n")
+ }
+ if this.IsExtension != nil {
+ s = append(s, "IsExtension: "+valueToGoStringDescriptor(this.IsExtension, "bool")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *SourceCodeInfo) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&descriptor.SourceCodeInfo{")
+ if this.Location != nil {
+ s = append(s, "Location: "+fmt.Sprintf("%#v", this.Location)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *SourceCodeInfo_Location) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 9)
+ s = append(s, "&descriptor.SourceCodeInfo_Location{")
+ if this.Path != nil {
+ s = append(s, "Path: "+fmt.Sprintf("%#v", this.Path)+",\n")
+ }
+ if this.Span != nil {
+ s = append(s, "Span: "+fmt.Sprintf("%#v", this.Span)+",\n")
+ }
+ if this.LeadingComments != nil {
+ s = append(s, "LeadingComments: "+valueToGoStringDescriptor(this.LeadingComments, "string")+",\n")
+ }
+ if this.TrailingComments != nil {
+ s = append(s, "TrailingComments: "+valueToGoStringDescriptor(this.TrailingComments, "string")+",\n")
+ }
+ if this.LeadingDetachedComments != nil {
+ s = append(s, "LeadingDetachedComments: "+fmt.Sprintf("%#v", this.LeadingDetachedComments)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *GeneratedCodeInfo) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 5)
+ s = append(s, "&descriptor.GeneratedCodeInfo{")
+ if this.Annotation != nil {
+ s = append(s, "Annotation: "+fmt.Sprintf("%#v", this.Annotation)+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func (this *GeneratedCodeInfo_Annotation) GoString() string {
+ if this == nil {
+ return "nil"
+ }
+ s := make([]string, 0, 8)
+ s = append(s, "&descriptor.GeneratedCodeInfo_Annotation{")
+ if this.Path != nil {
+ s = append(s, "Path: "+fmt.Sprintf("%#v", this.Path)+",\n")
+ }
+ if this.SourceFile != nil {
+ s = append(s, "SourceFile: "+valueToGoStringDescriptor(this.SourceFile, "string")+",\n")
+ }
+ if this.Begin != nil {
+ s = append(s, "Begin: "+valueToGoStringDescriptor(this.Begin, "int32")+",\n")
+ }
+ if this.End != nil {
+ s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n")
+ }
+ if this.XXX_unrecognized != nil {
+ s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
+ }
+ s = append(s, "}")
+ return strings.Join(s, "")
+}
+func valueToGoStringDescriptor(v interface{}, typ string) string {
+ rv := reflect.ValueOf(v)
+ if rv.IsNil() {
+ return "nil"
+ }
+ pv := reflect.Indirect(rv).Interface()
+ return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
+}
+func extensionToGoStringDescriptor(m github_com_gogo_protobuf_proto.Message) string {
+ e := github_com_gogo_protobuf_proto.GetUnsafeExtensionsMap(m)
+ if e == nil {
+ return "nil"
+ }
+ s := "proto.NewUnsafeXXX_InternalExtensions(map[int32]proto.Extension{"
+ keys := make([]int, 0, len(e))
+ for k := range e {
+ keys = append(keys, int(k))
+ }
+ sort.Ints(keys)
+ ss := []string{}
+ for _, k := range keys {
+ ss = append(ss, strconv.Itoa(k)+": "+e[int32(k)].GoString())
+ }
+ s += strings.Join(ss, ",") + "})"
+ return s
+}
diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/helper.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/helper.go
@@ -0,0 +1,390 @@
+// Protocol Buffers for Go with Gadgets
+//
+// Copyright (c) 2013, The GoGo Authors. All rights reserved.
+// http://github.com/gogo/protobuf
+//
+// 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.
+//
+// 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.
+
+package descriptor
+
+import (
+ "strings"
+)
+
+func (msg *DescriptorProto) GetMapFields() (*FieldDescriptorProto, *FieldDescriptorProto) {
+ if !msg.GetOptions().GetMapEntry() {
+ return nil, nil
+ }
+ return msg.GetField()[0], msg.GetField()[1]
+}
+
+func dotToUnderscore(r rune) rune {
+ if r == '.' {
+ return '_'
+ }
+ return r
+}
+
+func (field *FieldDescriptorProto) WireType() (wire int) {
+ switch *field.Type {
+ case FieldDescriptorProto_TYPE_DOUBLE:
+ return 1
+ case FieldDescriptorProto_TYPE_FLOAT:
+ return 5
+ case FieldDescriptorProto_TYPE_INT64:
+ return 0
+ case FieldDescriptorProto_TYPE_UINT64:
+ return 0
+ case FieldDescriptorProto_TYPE_INT32:
+ return 0
+ case FieldDescriptorProto_TYPE_UINT32:
+ return 0
+ case FieldDescriptorProto_TYPE_FIXED64:
+ return 1
+ case FieldDescriptorProto_TYPE_FIXED32:
+ return 5
+ case FieldDescriptorProto_TYPE_BOOL:
+ return 0
+ case FieldDescriptorProto_TYPE_STRING:
+ return 2
+ case FieldDescriptorProto_TYPE_GROUP:
+ return 2
+ case FieldDescriptorProto_TYPE_MESSAGE:
+ return 2
+ case FieldDescriptorProto_TYPE_BYTES:
+ return 2
+ case FieldDescriptorProto_TYPE_ENUM:
+ return 0
+ case FieldDescriptorProto_TYPE_SFIXED32:
+ return 5
+ case FieldDescriptorProto_TYPE_SFIXED64:
+ return 1
+ case FieldDescriptorProto_TYPE_SINT32:
+ return 0
+ case FieldDescriptorProto_TYPE_SINT64:
+ return 0
+ }
+ panic("unreachable")
+}
+
+func (field *FieldDescriptorProto) GetKeyUint64() (x uint64) {
+ packed := field.IsPacked()
+ wireType := field.WireType()
+ fieldNumber := field.GetNumber()
+ if packed {
+ wireType = 2
+ }
+ x = uint64(uint32(fieldNumber)<<3 | uint32(wireType))
+ return x
+}
+
+func (field *FieldDescriptorProto) GetKey3Uint64() (x uint64) {
+ packed := field.IsPacked3()
+ wireType := field.WireType()
+ fieldNumber := field.GetNumber()
+ if packed {
+ wireType = 2
+ }
+ x = uint64(uint32(fieldNumber)<<3 | uint32(wireType))
+ return x
+}
+
+func (field *FieldDescriptorProto) GetKey() []byte {
+ x := field.GetKeyUint64()
+ i := 0
+ keybuf := make([]byte, 0)
+ for i = 0; x > 127; i++ {
+ keybuf = append(keybuf, 0x80|uint8(x&0x7F))
+ x >>= 7
+ }
+ keybuf = append(keybuf, uint8(x))
+ return keybuf
+}
+
+func (field *FieldDescriptorProto) GetKey3() []byte {
+ x := field.GetKey3Uint64()
+ i := 0
+ keybuf := make([]byte, 0)
+ for i = 0; x > 127; i++ {
+ keybuf = append(keybuf, 0x80|uint8(x&0x7F))
+ x >>= 7
+ }
+ keybuf = append(keybuf, uint8(x))
+ return keybuf
+}
+
+func (desc *FileDescriptorSet) GetField(packageName, messageName, fieldName string) *FieldDescriptorProto {
+ msg := desc.GetMessage(packageName, messageName)
+ if msg == nil {
+ return nil
+ }
+ for _, field := range msg.GetField() {
+ if field.GetName() == fieldName {
+ return field
+ }
+ }
+ return nil
+}
+
+func (file *FileDescriptorProto) GetMessage(typeName string) *DescriptorProto {
+ for _, msg := range file.GetMessageType() {
+ if msg.GetName() == typeName {
+ return msg
+ }
+ nes := file.GetNestedMessage(msg, strings.TrimPrefix(typeName, msg.GetName()+"."))
+ if nes != nil {
+ return nes
+ }
+ }
+ return nil
+}
+
+func (file *FileDescriptorProto) GetNestedMessage(msg *DescriptorProto, typeName string) *DescriptorProto {
+ for _, nes := range msg.GetNestedType() {
+ if nes.GetName() == typeName {
+ return nes
+ }
+ res := file.GetNestedMessage(nes, strings.TrimPrefix(typeName, nes.GetName()+"."))
+ if res != nil {
+ return res
+ }
+ }
+ return nil
+}
+
+func (desc *FileDescriptorSet) GetMessage(packageName string, typeName string) *DescriptorProto {
+ for _, file := range desc.GetFile() {
+ if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) {
+ continue
+ }
+ for _, msg := range file.GetMessageType() {
+ if msg.GetName() == typeName {
+ return msg
+ }
+ }
+ for _, msg := range file.GetMessageType() {
+ for _, nes := range msg.GetNestedType() {
+ if nes.GetName() == typeName {
+ return nes
+ }
+ if msg.GetName()+"."+nes.GetName() == typeName {
+ return nes
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (desc *FileDescriptorSet) IsProto3(packageName string, typeName string) bool {
+ for _, file := range desc.GetFile() {
+ if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) {
+ continue
+ }
+ for _, msg := range file.GetMessageType() {
+ if msg.GetName() == typeName {
+ return file.GetSyntax() == "proto3"
+ }
+ }
+ for _, msg := range file.GetMessageType() {
+ for _, nes := range msg.GetNestedType() {
+ if nes.GetName() == typeName {
+ return file.GetSyntax() == "proto3"
+ }
+ if msg.GetName()+"."+nes.GetName() == typeName {
+ return file.GetSyntax() == "proto3"
+ }
+ }
+ }
+ }
+ return false
+}
+
+func (msg *DescriptorProto) IsExtendable() bool {
+ return len(msg.GetExtensionRange()) > 0
+}
+
+func (desc *FileDescriptorSet) FindExtension(packageName string, typeName string, fieldName string) (extPackageName string, field *FieldDescriptorProto) {
+ parent := desc.GetMessage(packageName, typeName)
+ if parent == nil {
+ return "", nil
+ }
+ if !parent.IsExtendable() {
+ return "", nil
+ }
+ extendee := "." + packageName + "." + typeName
+ for _, file := range desc.GetFile() {
+ for _, ext := range file.GetExtension() {
+ if strings.Map(dotToUnderscore, file.GetPackage()) == strings.Map(dotToUnderscore, packageName) {
+ if !(ext.GetExtendee() == typeName || ext.GetExtendee() == extendee) {
+ continue
+ }
+ } else {
+ if ext.GetExtendee() != extendee {
+ continue
+ }
+ }
+ if ext.GetName() == fieldName {
+ return file.GetPackage(), ext
+ }
+ }
+ }
+ return "", nil
+}
+
+func (desc *FileDescriptorSet) FindExtensionByFieldNumber(packageName string, typeName string, fieldNum int32) (extPackageName string, field *FieldDescriptorProto) {
+ parent := desc.GetMessage(packageName, typeName)
+ if parent == nil {
+ return "", nil
+ }
+ if !parent.IsExtendable() {
+ return "", nil
+ }
+ extendee := "." + packageName + "." + typeName
+ for _, file := range desc.GetFile() {
+ for _, ext := range file.GetExtension() {
+ if strings.Map(dotToUnderscore, file.GetPackage()) == strings.Map(dotToUnderscore, packageName) {
+ if !(ext.GetExtendee() == typeName || ext.GetExtendee() == extendee) {
+ continue
+ }
+ } else {
+ if ext.GetExtendee() != extendee {
+ continue
+ }
+ }
+ if ext.GetNumber() == fieldNum {
+ return file.GetPackage(), ext
+ }
+ }
+ }
+ return "", nil
+}
+
+func (desc *FileDescriptorSet) FindMessage(packageName string, typeName string, fieldName string) (msgPackageName string, msgName string) {
+ parent := desc.GetMessage(packageName, typeName)
+ if parent == nil {
+ return "", ""
+ }
+ field := parent.GetFieldDescriptor(fieldName)
+ if field == nil {
+ var extPackageName string
+ extPackageName, field = desc.FindExtension(packageName, typeName, fieldName)
+ if field == nil {
+ return "", ""
+ }
+ packageName = extPackageName
+ }
+ typeNames := strings.Split(field.GetTypeName(), ".")
+ if len(typeNames) == 1 {
+ msg := desc.GetMessage(packageName, typeName)
+ if msg == nil {
+ return "", ""
+ }
+ return packageName, msg.GetName()
+ }
+ if len(typeNames) > 2 {
+ for i := 1; i < len(typeNames)-1; i++ {
+ packageName = strings.Join(typeNames[1:len(typeNames)-i], ".")
+ typeName = strings.Join(typeNames[len(typeNames)-i:], ".")
+ msg := desc.GetMessage(packageName, typeName)
+ if msg != nil {
+ typeNames := strings.Split(msg.GetName(), ".")
+ if len(typeNames) == 1 {
+ return packageName, msg.GetName()
+ }
+ return strings.Join(typeNames[1:len(typeNames)-1], "."), typeNames[len(typeNames)-1]
+ }
+ }
+ }
+ return "", ""
+}
+
+func (msg *DescriptorProto) GetFieldDescriptor(fieldName string) *FieldDescriptorProto {
+ for _, field := range msg.GetField() {
+ if field.GetName() == fieldName {
+ return field
+ }
+ }
+ return nil
+}
+
+func (desc *FileDescriptorSet) GetEnum(packageName string, typeName string) *EnumDescriptorProto {
+ for _, file := range desc.GetFile() {
+ if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) {
+ continue
+ }
+ for _, enum := range file.GetEnumType() {
+ if enum.GetName() == typeName {
+ return enum
+ }
+ }
+ }
+ return nil
+}
+
+func (f *FieldDescriptorProto) IsEnum() bool {
+ return *f.Type == FieldDescriptorProto_TYPE_ENUM
+}
+
+func (f *FieldDescriptorProto) IsMessage() bool {
+ return *f.Type == FieldDescriptorProto_TYPE_MESSAGE
+}
+
+func (f *FieldDescriptorProto) IsBytes() bool {
+ return *f.Type == FieldDescriptorProto_TYPE_BYTES
+}
+
+func (f *FieldDescriptorProto) IsRepeated() bool {
+ return f.Label != nil && *f.Label == FieldDescriptorProto_LABEL_REPEATED
+}
+
+func (f *FieldDescriptorProto) IsString() bool {
+ return *f.Type == FieldDescriptorProto_TYPE_STRING
+}
+
+func (f *FieldDescriptorProto) IsBool() bool {
+ return *f.Type == FieldDescriptorProto_TYPE_BOOL
+}
+
+func (f *FieldDescriptorProto) IsRequired() bool {
+ return f.Label != nil && *f.Label == FieldDescriptorProto_LABEL_REQUIRED
+}
+
+func (f *FieldDescriptorProto) IsPacked() bool {
+ return f.Options != nil && f.GetOptions().GetPacked()
+}
+
+func (f *FieldDescriptorProto) IsPacked3() bool {
+ if f.IsRepeated() && f.IsScalar() {
+ if f.Options == nil || f.GetOptions().Packed == nil {
+ return true
+ }
+ return f.Options != nil && f.GetOptions().GetPacked()
+ }
+ return false
+}
+
+func (m *DescriptorProto) HasExtension() bool {
+ return len(m.ExtensionRange) > 0
+}
diff --git a/vendor/github.com/opencontainers/runtime-spec/LICENSE b/vendor/github.com/opencontainers/runtime-spec/LICENSE
@@ -0,0 +1,191 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2015 The Linux Foundation.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go
@@ -0,0 +1,689 @@
+package specs
+
+import "os"
+
+// Spec is the base configuration for the container.
+type Spec struct {
+ // Version of the Open Container Initiative Runtime Specification with which the bundle complies.
+ Version string `json:"ociVersion"`
+ // Process configures the container process.
+ Process *Process `json:"process,omitempty"`
+ // Root configures the container's root filesystem.
+ Root *Root `json:"root,omitempty"`
+ // Hostname configures the container's hostname.
+ Hostname string `json:"hostname,omitempty"`
+ // Mounts configures additional mounts (on top of Root).
+ Mounts []Mount `json:"mounts,omitempty"`
+ // Hooks configures callbacks for container lifecycle events.
+ Hooks *Hooks `json:"hooks,omitempty" platform:"linux,solaris"`
+ // Annotations contains arbitrary metadata for the container.
+ Annotations map[string]string `json:"annotations,omitempty"`
+
+ // Linux is platform-specific configuration for Linux based containers.
+ Linux *Linux `json:"linux,omitempty" platform:"linux"`
+ // Solaris is platform-specific configuration for Solaris based containers.
+ Solaris *Solaris `json:"solaris,omitempty" platform:"solaris"`
+ // Windows is platform-specific configuration for Windows based containers.
+ Windows *Windows `json:"windows,omitempty" platform:"windows"`
+ // VM specifies configuration for virtual-machine-based containers.
+ VM *VM `json:"vm,omitempty" platform:"vm"`
+}
+
+// Process contains information to start a specific application inside the container.
+type Process struct {
+ // Terminal creates an interactive terminal for the container.
+ Terminal bool `json:"terminal,omitempty"`
+ // ConsoleSize specifies the size of the console.
+ ConsoleSize *Box `json:"consoleSize,omitempty"`
+ // User specifies user information for the process.
+ User User `json:"user"`
+ // Args specifies the binary and arguments for the application to execute.
+ Args []string `json:"args,omitempty"`
+ // CommandLine specifies the full command line for the application to execute on Windows.
+ CommandLine string `json:"commandLine,omitempty" platform:"windows"`
+ // Env populates the process environment for the process.
+ Env []string `json:"env,omitempty"`
+ // Cwd is the current working directory for the process and must be
+ // relative to the container's root.
+ Cwd string `json:"cwd"`
+ // Capabilities are Linux capabilities that are kept for the process.
+ Capabilities *LinuxCapabilities `json:"capabilities,omitempty" platform:"linux"`
+ // Rlimits specifies rlimit options to apply to the process.
+ Rlimits []POSIXRlimit `json:"rlimits,omitempty" platform:"linux,solaris"`
+ // NoNewPrivileges controls whether additional privileges could be gained by processes in the container.
+ NoNewPrivileges bool `json:"noNewPrivileges,omitempty" platform:"linux"`
+ // ApparmorProfile specifies the apparmor profile for the container.
+ ApparmorProfile string `json:"apparmorProfile,omitempty" platform:"linux"`
+ // Specify an oom_score_adj for the container.
+ OOMScoreAdj *int `json:"oomScoreAdj,omitempty" platform:"linux"`
+ // SelinuxLabel specifies the selinux context that the container process is run as.
+ SelinuxLabel string `json:"selinuxLabel,omitempty" platform:"linux"`
+}
+
+// LinuxCapabilities specifies the whitelist of capabilities that are kept for a process.
+// http://man7.org/linux/man-pages/man7/capabilities.7.html
+type LinuxCapabilities struct {
+ // Bounding is the set of capabilities checked by the kernel.
+ Bounding []string `json:"bounding,omitempty" platform:"linux"`
+ // Effective is the set of capabilities checked by the kernel.
+ Effective []string `json:"effective,omitempty" platform:"linux"`
+ // Inheritable is the capabilities preserved across execve.
+ Inheritable []string `json:"inheritable,omitempty" platform:"linux"`
+ // Permitted is the limiting superset for effective capabilities.
+ Permitted []string `json:"permitted,omitempty" platform:"linux"`
+ // Ambient is the ambient set of capabilities that are kept.
+ Ambient []string `json:"ambient,omitempty" platform:"linux"`
+}
+
+// Box specifies dimensions of a rectangle. Used for specifying the size of a console.
+type Box struct {
+ // Height is the vertical dimension of a box.
+ Height uint `json:"height"`
+ // Width is the horizontal dimension of a box.
+ Width uint `json:"width"`
+}
+
+// User specifies specific user (and group) information for the container process.
+type User struct {
+ // UID is the user id.
+ UID uint32 `json:"uid" platform:"linux,solaris"`
+ // GID is the group id.
+ GID uint32 `json:"gid" platform:"linux,solaris"`
+ // Umask is the umask for the init process.
+ Umask uint32 `json:"umask,omitempty" platform:"linux,solaris"`
+ // AdditionalGids are additional group ids set for the container's process.
+ AdditionalGids []uint32 `json:"additionalGids,omitempty" platform:"linux,solaris"`
+ // Username is the user name.
+ Username string `json:"username,omitempty" platform:"windows"`
+}
+
+// Root contains information about the container's root filesystem on the host.
+type Root struct {
+ // Path is the absolute path to the container's root filesystem.
+ Path string `json:"path"`
+ // Readonly makes the root filesystem for the container readonly before the process is executed.
+ Readonly bool `json:"readonly,omitempty"`
+}
+
+// Mount specifies a mount for a container.
+type Mount struct {
+ // Destination is the absolute path where the mount will be placed in the container.
+ Destination string `json:"destination"`
+ // Type specifies the mount kind.
+ Type string `json:"type,omitempty" platform:"linux,solaris"`
+ // Source specifies the source path of the mount.
+ Source string `json:"source,omitempty"`
+ // Options are fstab style mount options.
+ Options []string `json:"options,omitempty"`
+}
+
+// Hook specifies a command that is run at a particular event in the lifecycle of a container
+type Hook struct {
+ Path string `json:"path"`
+ Args []string `json:"args,omitempty"`
+ Env []string `json:"env,omitempty"`
+ Timeout *int `json:"timeout,omitempty"`
+}
+
+// Hooks specifies a command that is run in the container at a particular event in the lifecycle of a container
+// Hooks for container setup and teardown
+type Hooks struct {
+ // Prestart is Deprecated. Prestart is a list of hooks to be run before the container process is executed.
+ // It is called in the Runtime Namespace
+ Prestart []Hook `json:"prestart,omitempty"`
+ // CreateRuntime is a list of hooks to be run after the container has been created but before pivot_root or any equivalent operation has been called
+ // It is called in the Runtime Namespace
+ CreateRuntime []Hook `json:"createRuntime,omitempty"`
+ // CreateContainer is a list of hooks to be run after the container has been created but before pivot_root or any equivalent operation has been called
+ // It is called in the Container Namespace
+ CreateContainer []Hook `json:"createContainer,omitempty"`
+ // StartContainer is a list of hooks to be run after the start operation is called but before the container process is started
+ // It is called in the Container Namespace
+ StartContainer []Hook `json:"startContainer,omitempty"`
+ // Poststart is a list of hooks to be run after the container process is started.
+ // It is called in the Runtime Namespace
+ Poststart []Hook `json:"poststart,omitempty"`
+ // Poststop is a list of hooks to be run after the container process exits.
+ // It is called in the Runtime Namespace
+ Poststop []Hook `json:"poststop,omitempty"`
+}
+
+// Linux contains platform-specific configuration for Linux based containers.
+type Linux struct {
+ // UIDMapping specifies user mappings for supporting user namespaces.
+ UIDMappings []LinuxIDMapping `json:"uidMappings,omitempty"`
+ // GIDMapping specifies group mappings for supporting user namespaces.
+ GIDMappings []LinuxIDMapping `json:"gidMappings,omitempty"`
+ // Sysctl are a set of key value pairs that are set for the container on start
+ Sysctl map[string]string `json:"sysctl,omitempty"`
+ // Resources contain cgroup information for handling resource constraints
+ // for the container
+ Resources *LinuxResources `json:"resources,omitempty"`
+ // CgroupsPath specifies the path to cgroups that are created and/or joined by the container.
+ // The path is expected to be relative to the cgroups mountpoint.
+ // If resources are specified, the cgroups at CgroupsPath will be updated based on resources.
+ CgroupsPath string `json:"cgroupsPath,omitempty"`
+ // Namespaces contains the namespaces that are created and/or joined by the container
+ Namespaces []LinuxNamespace `json:"namespaces,omitempty"`
+ // Devices are a list of device nodes that are created for the container
+ Devices []LinuxDevice `json:"devices,omitempty"`
+ // Seccomp specifies the seccomp security settings for the container.
+ Seccomp *LinuxSeccomp `json:"seccomp,omitempty"`
+ // RootfsPropagation is the rootfs mount propagation mode for the container.
+ RootfsPropagation string `json:"rootfsPropagation,omitempty"`
+ // MaskedPaths masks over the provided paths inside the container.
+ MaskedPaths []string `json:"maskedPaths,omitempty"`
+ // ReadonlyPaths sets the provided paths as RO inside the container.
+ ReadonlyPaths []string `json:"readonlyPaths,omitempty"`
+ // MountLabel specifies the selinux context for the mounts in the container.
+ MountLabel string `json:"mountLabel,omitempty"`
+ // IntelRdt contains Intel Resource Director Technology (RDT) information for
+ // handling resource constraints (e.g., L3 cache, memory bandwidth) for the container
+ IntelRdt *LinuxIntelRdt `json:"intelRdt,omitempty"`
+ // Personality contains configuration for the Linux personality syscall
+ Personality *LinuxPersonality `json:"personality,omitempty"`
+}
+
+// LinuxNamespace is the configuration for a Linux namespace
+type LinuxNamespace struct {
+ // Type is the type of namespace
+ Type LinuxNamespaceType `json:"type"`
+ // Path is a path to an existing namespace persisted on disk that can be joined
+ // and is of the same type
+ Path string `json:"path,omitempty"`
+}
+
+// LinuxNamespaceType is one of the Linux namespaces
+type LinuxNamespaceType string
+
+const (
+ // PIDNamespace for isolating process IDs
+ PIDNamespace LinuxNamespaceType = "pid"
+ // NetworkNamespace for isolating network devices, stacks, ports, etc
+ NetworkNamespace LinuxNamespaceType = "network"
+ // MountNamespace for isolating mount points
+ MountNamespace LinuxNamespaceType = "mount"
+ // IPCNamespace for isolating System V IPC, POSIX message queues
+ IPCNamespace LinuxNamespaceType = "ipc"
+ // UTSNamespace for isolating hostname and NIS domain name
+ UTSNamespace LinuxNamespaceType = "uts"
+ // UserNamespace for isolating user and group IDs
+ UserNamespace LinuxNamespaceType = "user"
+ // CgroupNamespace for isolating cgroup hierarchies
+ CgroupNamespace LinuxNamespaceType = "cgroup"
+)
+
+// LinuxIDMapping specifies UID/GID mappings
+type LinuxIDMapping struct {
+ // ContainerID is the starting UID/GID in the container
+ ContainerID uint32 `json:"containerID"`
+ // HostID is the starting UID/GID on the host to be mapped to 'ContainerID'
+ HostID uint32 `json:"hostID"`
+ // Size is the number of IDs to be mapped
+ Size uint32 `json:"size"`
+}
+
+// POSIXRlimit type and restrictions
+type POSIXRlimit struct {
+ // Type of the rlimit to set
+ Type string `json:"type"`
+ // Hard is the hard limit for the specified type
+ Hard uint64 `json:"hard"`
+ // Soft is the soft limit for the specified type
+ Soft uint64 `json:"soft"`
+}
+
+// LinuxHugepageLimit structure corresponds to limiting kernel hugepages
+type LinuxHugepageLimit struct {
+ // Pagesize is the hugepage size
+ // Format: "<size><unit-prefix>B' (e.g. 64KB, 2MB, 1GB, etc.)
+ Pagesize string `json:"pageSize"`
+ // Limit is the limit of "hugepagesize" hugetlb usage
+ Limit uint64 `json:"limit"`
+}
+
+// LinuxInterfacePriority for network interfaces
+type LinuxInterfacePriority struct {
+ // Name is the name of the network interface
+ Name string `json:"name"`
+ // Priority for the interface
+ Priority uint32 `json:"priority"`
+}
+
+// linuxBlockIODevice holds major:minor format supported in blkio cgroup
+type linuxBlockIODevice struct {
+ // Major is the device's major number.
+ Major int64 `json:"major"`
+ // Minor is the device's minor number.
+ Minor int64 `json:"minor"`
+}
+
+// LinuxWeightDevice struct holds a `major:minor weight` pair for weightDevice
+type LinuxWeightDevice struct {
+ linuxBlockIODevice
+ // Weight is the bandwidth rate for the device.
+ Weight *uint16 `json:"weight,omitempty"`
+ // LeafWeight is the bandwidth rate for the device while competing with the cgroup's child cgroups, CFQ scheduler only
+ LeafWeight *uint16 `json:"leafWeight,omitempty"`
+}
+
+// LinuxThrottleDevice struct holds a `major:minor rate_per_second` pair
+type LinuxThrottleDevice struct {
+ linuxBlockIODevice
+ // Rate is the IO rate limit per cgroup per device
+ Rate uint64 `json:"rate"`
+}
+
+// LinuxBlockIO for Linux cgroup 'blkio' resource management
+type LinuxBlockIO struct {
+ // Specifies per cgroup weight
+ Weight *uint16 `json:"weight,omitempty"`
+ // Specifies tasks' weight in the given cgroup while competing with the cgroup's child cgroups, CFQ scheduler only
+ LeafWeight *uint16 `json:"leafWeight,omitempty"`
+ // Weight per cgroup per device, can override BlkioWeight
+ WeightDevice []LinuxWeightDevice `json:"weightDevice,omitempty"`
+ // IO read rate limit per cgroup per device, bytes per second
+ ThrottleReadBpsDevice []LinuxThrottleDevice `json:"throttleReadBpsDevice,omitempty"`
+ // IO write rate limit per cgroup per device, bytes per second
+ ThrottleWriteBpsDevice []LinuxThrottleDevice `json:"throttleWriteBpsDevice,omitempty"`
+ // IO read rate limit per cgroup per device, IO per second
+ ThrottleReadIOPSDevice []LinuxThrottleDevice `json:"throttleReadIOPSDevice,omitempty"`
+ // IO write rate limit per cgroup per device, IO per second
+ ThrottleWriteIOPSDevice []LinuxThrottleDevice `json:"throttleWriteIOPSDevice,omitempty"`
+}
+
+// LinuxMemory for Linux cgroup 'memory' resource management
+type LinuxMemory struct {
+ // Memory limit (in bytes).
+ Limit *int64 `json:"limit,omitempty"`
+ // Memory reservation or soft_limit (in bytes).
+ Reservation *int64 `json:"reservation,omitempty"`
+ // Total memory limit (memory + swap).
+ Swap *int64 `json:"swap,omitempty"`
+ // Kernel memory limit (in bytes).
+ Kernel *int64 `json:"kernel,omitempty"`
+ // Kernel memory limit for tcp (in bytes)
+ KernelTCP *int64 `json:"kernelTCP,omitempty"`
+ // How aggressive the kernel will swap memory pages.
+ Swappiness *uint64 `json:"swappiness,omitempty"`
+ // DisableOOMKiller disables the OOM killer for out of memory conditions
+ DisableOOMKiller *bool `json:"disableOOMKiller,omitempty"`
+ // Enables hierarchical memory accounting
+ UseHierarchy *bool `json:"useHierarchy,omitempty"`
+}
+
+// LinuxCPU for Linux cgroup 'cpu' resource management
+type LinuxCPU struct {
+ // CPU shares (relative weight (ratio) vs. other cgroups with cpu shares).
+ Shares *uint64 `json:"shares,omitempty"`
+ // CPU hardcap limit (in usecs). Allowed cpu time in a given period.
+ Quota *int64 `json:"quota,omitempty"`
+ // CPU period to be used for hardcapping (in usecs).
+ Period *uint64 `json:"period,omitempty"`
+ // How much time realtime scheduling may use (in usecs).
+ RealtimeRuntime *int64 `json:"realtimeRuntime,omitempty"`
+ // CPU period to be used for realtime scheduling (in usecs).
+ RealtimePeriod *uint64 `json:"realtimePeriod,omitempty"`
+ // CPUs to use within the cpuset. Default is to use any CPU available.
+ Cpus string `json:"cpus,omitempty"`
+ // List of memory nodes in the cpuset. Default is to use any available memory node.
+ Mems string `json:"mems,omitempty"`
+}
+
+// LinuxPids for Linux cgroup 'pids' resource management (Linux 4.3)
+type LinuxPids struct {
+ // Maximum number of PIDs. Default is "no limit".
+ Limit int64 `json:"limit"`
+}
+
+// LinuxNetwork identification and priority configuration
+type LinuxNetwork struct {
+ // Set class identifier for container's network packets
+ ClassID *uint32 `json:"classID,omitempty"`
+ // Set priority of network traffic for container
+ Priorities []LinuxInterfacePriority `json:"priorities,omitempty"`
+}
+
+// LinuxRdma for Linux cgroup 'rdma' resource management (Linux 4.11)
+type LinuxRdma struct {
+ // Maximum number of HCA handles that can be opened. Default is "no limit".
+ HcaHandles *uint32 `json:"hcaHandles,omitempty"`
+ // Maximum number of HCA objects that can be created. Default is "no limit".
+ HcaObjects *uint32 `json:"hcaObjects,omitempty"`
+}
+
+// LinuxResources has container runtime resource constraints
+type LinuxResources struct {
+ // Devices configures the device whitelist.
+ Devices []LinuxDeviceCgroup `json:"devices,omitempty"`
+ // Memory restriction configuration
+ Memory *LinuxMemory `json:"memory,omitempty"`
+ // CPU resource restriction configuration
+ CPU *LinuxCPU `json:"cpu,omitempty"`
+ // Task resource restriction configuration.
+ Pids *LinuxPids `json:"pids,omitempty"`
+ // BlockIO restriction configuration
+ BlockIO *LinuxBlockIO `json:"blockIO,omitempty"`
+ // Hugetlb limit (in bytes)
+ HugepageLimits []LinuxHugepageLimit `json:"hugepageLimits,omitempty"`
+ // Network restriction configuration
+ Network *LinuxNetwork `json:"network,omitempty"`
+ // Rdma resource restriction configuration.
+ // Limits are a set of key value pairs that define RDMA resource limits,
+ // where the key is device name and value is resource limits.
+ Rdma map[string]LinuxRdma `json:"rdma,omitempty"`
+}
+
+// LinuxDevice represents the mknod information for a Linux special device file
+type LinuxDevice struct {
+ // Path to the device.
+ Path string `json:"path"`
+ // Device type, block, char, etc.
+ Type string `json:"type"`
+ // Major is the device's major number.
+ Major int64 `json:"major"`
+ // Minor is the device's minor number.
+ Minor int64 `json:"minor"`
+ // FileMode permission bits for the device.
+ FileMode *os.FileMode `json:"fileMode,omitempty"`
+ // UID of the device.
+ UID *uint32 `json:"uid,omitempty"`
+ // Gid of the device.
+ GID *uint32 `json:"gid,omitempty"`
+}
+
+// LinuxDeviceCgroup represents a device rule for the whitelist controller
+type LinuxDeviceCgroup struct {
+ // Allow or deny
+ Allow bool `json:"allow"`
+ // Device type, block, char, etc.
+ Type string `json:"type,omitempty"`
+ // Major is the device's major number.
+ Major *int64 `json:"major,omitempty"`
+ // Minor is the device's minor number.
+ Minor *int64 `json:"minor,omitempty"`
+ // Cgroup access permissions format, rwm.
+ Access string `json:"access,omitempty"`
+}
+
+// LinuxPersonalityDomain refers to a personality domain.
+type LinuxPersonalityDomain string
+
+// LinuxPersonalityFlag refers to an additional personality flag. None are currently defined.
+type LinuxPersonalityFlag string
+
+// Define domain and flags for Personality
+const (
+ // PerLinux is the standard Linux personality
+ PerLinux LinuxPersonalityDomain = "LINUX"
+ // PerLinux32 sets personality to 32 bit
+ PerLinux32 LinuxPersonalityDomain = "LINUX32"
+)
+
+// LinuxPersonality represents the Linux personality syscall input
+type LinuxPersonality struct {
+ // Domain for the personality
+ Domain LinuxPersonalityDomain `json:"domain"`
+ // Additional flags
+ Flags []LinuxPersonalityFlag `json:"flags,omitempty"`
+}
+
+// Solaris contains platform-specific configuration for Solaris application containers.
+type Solaris struct {
+ // SMF FMRI which should go "online" before we start the container process.
+ Milestone string `json:"milestone,omitempty"`
+ // Maximum set of privileges any process in this container can obtain.
+ LimitPriv string `json:"limitpriv,omitempty"`
+ // The maximum amount of shared memory allowed for this container.
+ MaxShmMemory string `json:"maxShmMemory,omitempty"`
+ // Specification for automatic creation of network resources for this container.
+ Anet []SolarisAnet `json:"anet,omitempty"`
+ // Set limit on the amount of CPU time that can be used by container.
+ CappedCPU *SolarisCappedCPU `json:"cappedCPU,omitempty"`
+ // The physical and swap caps on the memory that can be used by this container.
+ CappedMemory *SolarisCappedMemory `json:"cappedMemory,omitempty"`
+}
+
+// SolarisCappedCPU allows users to set limit on the amount of CPU time that can be used by container.
+type SolarisCappedCPU struct {
+ Ncpus string `json:"ncpus,omitempty"`
+}
+
+// SolarisCappedMemory allows users to set the physical and swap caps on the memory that can be used by this container.
+type SolarisCappedMemory struct {
+ Physical string `json:"physical,omitempty"`
+ Swap string `json:"swap,omitempty"`
+}
+
+// SolarisAnet provides the specification for automatic creation of network resources for this container.
+type SolarisAnet struct {
+ // Specify a name for the automatically created VNIC datalink.
+ Linkname string `json:"linkname,omitempty"`
+ // Specify the link over which the VNIC will be created.
+ Lowerlink string `json:"lowerLink,omitempty"`
+ // The set of IP addresses that the container can use.
+ Allowedaddr string `json:"allowedAddress,omitempty"`
+ // Specifies whether allowedAddress limitation is to be applied to the VNIC.
+ Configallowedaddr string `json:"configureAllowedAddress,omitempty"`
+ // The value of the optional default router.
+ Defrouter string `json:"defrouter,omitempty"`
+ // Enable one or more types of link protection.
+ Linkprotection string `json:"linkProtection,omitempty"`
+ // Set the VNIC's macAddress
+ Macaddress string `json:"macAddress,omitempty"`
+}
+
+// Windows defines the runtime configuration for Windows based containers, including Hyper-V containers.
+type Windows struct {
+ // LayerFolders contains a list of absolute paths to directories containing image layers.
+ LayerFolders []string `json:"layerFolders"`
+ // Devices are the list of devices to be mapped into the container.
+ Devices []WindowsDevice `json:"devices,omitempty"`
+ // Resources contains information for handling resource constraints for the container.
+ Resources *WindowsResources `json:"resources,omitempty"`
+ // CredentialSpec contains a JSON object describing a group Managed Service Account (gMSA) specification.
+ CredentialSpec interface{} `json:"credentialSpec,omitempty"`
+ // Servicing indicates if the container is being started in a mode to apply a Windows Update servicing operation.
+ Servicing bool `json:"servicing,omitempty"`
+ // IgnoreFlushesDuringBoot indicates if the container is being started in a mode where disk writes are not flushed during its boot process.
+ IgnoreFlushesDuringBoot bool `json:"ignoreFlushesDuringBoot,omitempty"`
+ // HyperV contains information for running a container with Hyper-V isolation.
+ HyperV *WindowsHyperV `json:"hyperv,omitempty"`
+ // Network restriction configuration.
+ Network *WindowsNetwork `json:"network,omitempty"`
+}
+
+// WindowsDevice represents information about a host device to be mapped into the container.
+type WindowsDevice struct {
+ // Device identifier: interface class GUID, etc.
+ ID string `json:"id"`
+ // Device identifier type: "class", etc.
+ IDType string `json:"idType"`
+}
+
+// WindowsResources has container runtime resource constraints for containers running on Windows.
+type WindowsResources struct {
+ // Memory restriction configuration.
+ Memory *WindowsMemoryResources `json:"memory,omitempty"`
+ // CPU resource restriction configuration.
+ CPU *WindowsCPUResources `json:"cpu,omitempty"`
+ // Storage restriction configuration.
+ Storage *WindowsStorageResources `json:"storage,omitempty"`
+}
+
+// WindowsMemoryResources contains memory resource management settings.
+type WindowsMemoryResources struct {
+ // Memory limit in bytes.
+ Limit *uint64 `json:"limit,omitempty"`
+}
+
+// WindowsCPUResources contains CPU resource management settings.
+type WindowsCPUResources struct {
+ // Number of CPUs available to the container.
+ Count *uint64 `json:"count,omitempty"`
+ // CPU shares (relative weight to other containers with cpu shares).
+ Shares *uint16 `json:"shares,omitempty"`
+ // Specifies the portion of processor cycles that this container can use as a percentage times 100.
+ Maximum *uint16 `json:"maximum,omitempty"`
+}
+
+// WindowsStorageResources contains storage resource management settings.
+type WindowsStorageResources struct {
+ // Specifies maximum Iops for the system drive.
+ Iops *uint64 `json:"iops,omitempty"`
+ // Specifies maximum bytes per second for the system drive.
+ Bps *uint64 `json:"bps,omitempty"`
+ // Sandbox size specifies the minimum size of the system drive in bytes.
+ SandboxSize *uint64 `json:"sandboxSize,omitempty"`
+}
+
+// WindowsNetwork contains network settings for Windows containers.
+type WindowsNetwork struct {
+ // List of HNS endpoints that the container should connect to.
+ EndpointList []string `json:"endpointList,omitempty"`
+ // Specifies if unqualified DNS name resolution is allowed.
+ AllowUnqualifiedDNSQuery bool `json:"allowUnqualifiedDNSQuery,omitempty"`
+ // Comma separated list of DNS suffixes to use for name resolution.
+ DNSSearchList []string `json:"DNSSearchList,omitempty"`
+ // Name (ID) of the container that we will share with the network stack.
+ NetworkSharedContainerName string `json:"networkSharedContainerName,omitempty"`
+ // name (ID) of the network namespace that will be used for the container.
+ NetworkNamespace string `json:"networkNamespace,omitempty"`
+}
+
+// WindowsHyperV contains information for configuring a container to run with Hyper-V isolation.
+type WindowsHyperV struct {
+ // UtilityVMPath is an optional path to the image used for the Utility VM.
+ UtilityVMPath string `json:"utilityVMPath,omitempty"`
+}
+
+// VM contains information for virtual-machine-based containers.
+type VM struct {
+ // Hypervisor specifies hypervisor-related configuration for virtual-machine-based containers.
+ Hypervisor VMHypervisor `json:"hypervisor,omitempty"`
+ // Kernel specifies kernel-related configuration for virtual-machine-based containers.
+ Kernel VMKernel `json:"kernel"`
+ // Image specifies guest image related configuration for virtual-machine-based containers.
+ Image VMImage `json:"image,omitempty"`
+}
+
+// VMHypervisor contains information about the hypervisor to use for a virtual machine.
+type VMHypervisor struct {
+ // Path is the host path to the hypervisor used to manage the virtual machine.
+ Path string `json:"path"`
+ // Parameters specifies parameters to pass to the hypervisor.
+ Parameters []string `json:"parameters,omitempty"`
+}
+
+// VMKernel contains information about the kernel to use for a virtual machine.
+type VMKernel struct {
+ // Path is the host path to the kernel used to boot the virtual machine.
+ Path string `json:"path"`
+ // Parameters specifies parameters to pass to the kernel.
+ Parameters []string `json:"parameters,omitempty"`
+ // InitRD is the host path to an initial ramdisk to be used by the kernel.
+ InitRD string `json:"initrd,omitempty"`
+}
+
+// VMImage contains information about the virtual machine root image.
+type VMImage struct {
+ // Path is the host path to the root image that the VM kernel would boot into.
+ Path string `json:"path"`
+ // Format is the root image format type (e.g. "qcow2", "raw", "vhd", etc).
+ Format string `json:"format"`
+}
+
+// LinuxSeccomp represents syscall restrictions
+type LinuxSeccomp struct {
+ DefaultAction LinuxSeccompAction `json:"defaultAction"`
+ Architectures []Arch `json:"architectures,omitempty"`
+ Flags []LinuxSeccompFlag `json:"flags,omitempty"`
+ Syscalls []LinuxSyscall `json:"syscalls,omitempty"`
+}
+
+// Arch used for additional architectures
+type Arch string
+
+// LinuxSeccompFlag is a flag to pass to seccomp(2).
+type LinuxSeccompFlag string
+
+// Additional architectures permitted to be used for system calls
+// By default only the native architecture of the kernel is permitted
+const (
+ ArchX86 Arch = "SCMP_ARCH_X86"
+ ArchX86_64 Arch = "SCMP_ARCH_X86_64"
+ ArchX32 Arch = "SCMP_ARCH_X32"
+ ArchARM Arch = "SCMP_ARCH_ARM"
+ ArchAARCH64 Arch = "SCMP_ARCH_AARCH64"
+ ArchMIPS Arch = "SCMP_ARCH_MIPS"
+ ArchMIPS64 Arch = "SCMP_ARCH_MIPS64"
+ ArchMIPS64N32 Arch = "SCMP_ARCH_MIPS64N32"
+ ArchMIPSEL Arch = "SCMP_ARCH_MIPSEL"
+ ArchMIPSEL64 Arch = "SCMP_ARCH_MIPSEL64"
+ ArchMIPSEL64N32 Arch = "SCMP_ARCH_MIPSEL64N32"
+ ArchPPC Arch = "SCMP_ARCH_PPC"
+ ArchPPC64 Arch = "SCMP_ARCH_PPC64"
+ ArchPPC64LE Arch = "SCMP_ARCH_PPC64LE"
+ ArchS390 Arch = "SCMP_ARCH_S390"
+ ArchS390X Arch = "SCMP_ARCH_S390X"
+ ArchPARISC Arch = "SCMP_ARCH_PARISC"
+ ArchPARISC64 Arch = "SCMP_ARCH_PARISC64"
+)
+
+// LinuxSeccompAction taken upon Seccomp rule match
+type LinuxSeccompAction string
+
+// Define actions for Seccomp rules
+const (
+ ActKill LinuxSeccompAction = "SCMP_ACT_KILL"
+ ActTrap LinuxSeccompAction = "SCMP_ACT_TRAP"
+ ActErrno LinuxSeccompAction = "SCMP_ACT_ERRNO"
+ ActTrace LinuxSeccompAction = "SCMP_ACT_TRACE"
+ ActAllow LinuxSeccompAction = "SCMP_ACT_ALLOW"
+ ActLog LinuxSeccompAction = "SCMP_ACT_LOG"
+)
+
+// LinuxSeccompOperator used to match syscall arguments in Seccomp
+type LinuxSeccompOperator string
+
+// Define operators for syscall arguments in Seccomp
+const (
+ OpNotEqual LinuxSeccompOperator = "SCMP_CMP_NE"
+ OpLessThan LinuxSeccompOperator = "SCMP_CMP_LT"
+ OpLessEqual LinuxSeccompOperator = "SCMP_CMP_LE"
+ OpEqualTo LinuxSeccompOperator = "SCMP_CMP_EQ"
+ OpGreaterEqual LinuxSeccompOperator = "SCMP_CMP_GE"
+ OpGreaterThan LinuxSeccompOperator = "SCMP_CMP_GT"
+ OpMaskedEqual LinuxSeccompOperator = "SCMP_CMP_MASKED_EQ"
+)
+
+// LinuxSeccompArg used for matching specific syscall arguments in Seccomp
+type LinuxSeccompArg struct {
+ Index uint `json:"index"`
+ Value uint64 `json:"value"`
+ ValueTwo uint64 `json:"valueTwo,omitempty"`
+ Op LinuxSeccompOperator `json:"op"`
+}
+
+// LinuxSyscall is used to match a syscall in Seccomp
+type LinuxSyscall struct {
+ Names []string `json:"names"`
+ Action LinuxSeccompAction `json:"action"`
+ Args []LinuxSeccompArg `json:"args,omitempty"`
+}
+
+// LinuxIntelRdt has container runtime resource constraints for Intel RDT
+// CAT and MBA features which introduced in Linux 4.10 and 4.12 kernel
+type LinuxIntelRdt struct {
+ // The identity for RDT Class of Service
+ ClosID string `json:"closID,omitempty"`
+ // The schema for L3 cache id and capacity bitmask (CBM)
+ // Format: "L3:<cache_id0>=<cbm0>;<cache_id1>=<cbm1>;..."
+ L3CacheSchema string `json:"l3CacheSchema,omitempty"`
+
+ // The schema of memory bandwidth per L3 cache id
+ // Format: "MB:<cache_id0>=bandwidth0;<cache_id1>=bandwidth1;..."
+ // The unit of memory bandwidth is specified in "percentages" by
+ // default, and in "MBps" if MBA Software Controller is enabled.
+ MemBwSchema string `json:"memBwSchema,omitempty"`
+}
diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go
@@ -0,0 +1,17 @@
+package specs
+
+// State holds information about the runtime state of the container.
+type State struct {
+ // Version is the version of the specification that is supported.
+ Version string `json:"ociVersion"`
+ // ID is the container ID
+ ID string `json:"id"`
+ // Status is the runtime status of the container.
+ Status string `json:"status"`
+ // Pid is the process ID for the container process.
+ Pid int `json:"pid,omitempty"`
+ // Bundle is the path to the container's bundle directory.
+ Bundle string `json:"bundle"`
+ // Annotations are key values associated with the container.
+ Annotations map[string]string `json:"annotations,omitempty"`
+}
diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go
@@ -0,0 +1,18 @@
+package specs
+
+import "fmt"
+
+const (
+ // VersionMajor is for an API incompatible changes
+ VersionMajor = 1
+ // VersionMinor is for functionality in a backwards-compatible manner
+ VersionMinor = 0
+ // VersionPatch is for backwards-compatible bug fixes
+ VersionPatch = 2
+
+ // VersionDev indicates development branch. Releases will be empty string.
+ VersionDev = ""
+)
+
+// Version is the specification version that the package types support.
+var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev)
diff --git a/vendor/go.uber.org/automaxprocs/LICENSE b/vendor/go.uber.org/automaxprocs/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2017 Uber Technologies, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+\ No newline at end of file
diff --git a/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroup.go b/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroup.go
@@ -0,0 +1,79 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//go:build linux
+// +build linux
+
+package cgroups
+
+import (
+ "bufio"
+ "io"
+ "os"
+ "path/filepath"
+ "strconv"
+)
+
+// CGroup represents the data structure for a Linux control group.
+type CGroup struct {
+ path string
+}
+
+// NewCGroup returns a new *CGroup from a given path.
+func NewCGroup(path string) *CGroup {
+ return &CGroup{path: path}
+}
+
+// Path returns the path of the CGroup*.
+func (cg *CGroup) Path() string {
+ return cg.path
+}
+
+// ParamPath returns the path of the given cgroup param under itself.
+func (cg *CGroup) ParamPath(param string) string {
+ return filepath.Join(cg.path, param)
+}
+
+// readFirstLine reads the first line from a cgroup param file.
+func (cg *CGroup) readFirstLine(param string) (string, error) {
+ paramFile, err := os.Open(cg.ParamPath(param))
+ if err != nil {
+ return "", err
+ }
+ defer paramFile.Close()
+
+ scanner := bufio.NewScanner(paramFile)
+ if scanner.Scan() {
+ return scanner.Text(), nil
+ }
+ if err := scanner.Err(); err != nil {
+ return "", err
+ }
+ return "", io.ErrUnexpectedEOF
+}
+
+// readInt parses the first line from a cgroup param file as int.
+func (cg *CGroup) readInt(param string) (int, error) {
+ text, err := cg.readFirstLine(param)
+ if err != nil {
+ return 0, err
+ }
+ return strconv.Atoi(text)
+}
diff --git a/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups.go b/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups.go
@@ -0,0 +1,118 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//go:build linux
+// +build linux
+
+package cgroups
+
+const (
+ // _cgroupFSType is the Linux CGroup file system type used in
+ // `/proc/$PID/mountinfo`.
+ _cgroupFSType = "cgroup"
+ // _cgroupSubsysCPU is the CPU CGroup subsystem.
+ _cgroupSubsysCPU = "cpu"
+ // _cgroupSubsysCPUAcct is the CPU accounting CGroup subsystem.
+ _cgroupSubsysCPUAcct = "cpuacct"
+ // _cgroupSubsysCPUSet is the CPUSet CGroup subsystem.
+ _cgroupSubsysCPUSet = "cpuset"
+ // _cgroupSubsysMemory is the Memory CGroup subsystem.
+ _cgroupSubsysMemory = "memory"
+
+ // _cgroupCPUCFSQuotaUsParam is the file name for the CGroup CFS quota
+ // parameter.
+ _cgroupCPUCFSQuotaUsParam = "cpu.cfs_quota_us"
+ // _cgroupCPUCFSPeriodUsParam is the file name for the CGroup CFS period
+ // parameter.
+ _cgroupCPUCFSPeriodUsParam = "cpu.cfs_period_us"
+)
+
+const (
+ _procPathCGroup = "/proc/self/cgroup"
+ _procPathMountInfo = "/proc/self/mountinfo"
+)
+
+// CGroups is a map that associates each CGroup with its subsystem name.
+type CGroups map[string]*CGroup
+
+// NewCGroups returns a new *CGroups from given `mountinfo` and `cgroup` files
+// under for some process under `/proc` file system (see also proc(5) for more
+// information).
+func NewCGroups(procPathMountInfo, procPathCGroup string) (CGroups, error) {
+ cgroupSubsystems, err := parseCGroupSubsystems(procPathCGroup)
+ if err != nil {
+ return nil, err
+ }
+
+ cgroups := make(CGroups)
+ newMountPoint := func(mp *MountPoint) error {
+ if mp.FSType != _cgroupFSType {
+ return nil
+ }
+
+ for _, opt := range mp.SuperOptions {
+ subsys, exists := cgroupSubsystems[opt]
+ if !exists {
+ continue
+ }
+
+ cgroupPath, err := mp.Translate(subsys.Name)
+ if err != nil {
+ return err
+ }
+ cgroups[opt] = NewCGroup(cgroupPath)
+ }
+
+ return nil
+ }
+
+ if err := parseMountInfo(procPathMountInfo, newMountPoint); err != nil {
+ return nil, err
+ }
+ return cgroups, nil
+}
+
+// NewCGroupsForCurrentProcess returns a new *CGroups instance for the current
+// process.
+func NewCGroupsForCurrentProcess() (CGroups, error) {
+ return NewCGroups(_procPathMountInfo, _procPathCGroup)
+}
+
+// CPUQuota returns the CPU quota applied with the CPU cgroup controller.
+// It is a result of `cpu.cfs_quota_us / cpu.cfs_period_us`. If the value of
+// `cpu.cfs_quota_us` was not set (-1), the method returns `(-1, nil)`.
+func (cg CGroups) CPUQuota() (float64, bool, error) {
+ cpuCGroup, exists := cg[_cgroupSubsysCPU]
+ if !exists {
+ return -1, false, nil
+ }
+
+ cfsQuotaUs, err := cpuCGroup.readInt(_cgroupCPUCFSQuotaUsParam)
+ if defined := cfsQuotaUs > 0; err != nil || !defined {
+ return -1, defined, err
+ }
+
+ cfsPeriodUs, err := cpuCGroup.readInt(_cgroupCPUCFSPeriodUsParam)
+ if err != nil {
+ return -1, false, err
+ }
+
+ return float64(cfsQuotaUs) / float64(cfsPeriodUs), true, nil
+}
diff --git a/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups2.go b/vendor/go.uber.org/automaxprocs/internal/cgroups/cgroups2.go
@@ -0,0 +1,151 @@
+// Copyright (c) 2022 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//go:build linux
+// +build linux
+
+package cgroups
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path"
+ "strconv"
+ "strings"
+)
+
+const (
+ // _cgroupv2CPUMax is the file name for the CGroup-V2 CPU max and period
+ // parameter.
+ _cgroupv2CPUMax = "cpu.max"
+ // _cgroupFSType is the Linux CGroup-V2 file system type used in
+ // `/proc/$PID/mountinfo`.
+ _cgroupv2FSType = "cgroup2"
+
+ _cgroupv2MountPoint = "/sys/fs/cgroup"
+
+ _cgroupV2CPUMaxDefaultPeriod = 100000
+ _cgroupV2CPUMaxQuotaMax = "max"
+)
+
+const (
+ _cgroupv2CPUMaxQuotaIndex = iota
+ _cgroupv2CPUMaxPeriodIndex
+)
+
+// ErrNotV2 indicates that the system is not using cgroups2.
+var ErrNotV2 = errors.New("not using cgroups2")
+
+// CGroups2 provides access to cgroups data for systems using cgroups2.
+type CGroups2 struct {
+ mountPoint string
+ cpuMaxFile string
+}
+
+// NewCGroups2ForCurrentProcess builds a CGroups2 for the current process.
+//
+// This returns ErrNotV2 if the system is not using cgroups2.
+func NewCGroups2ForCurrentProcess() (*CGroups2, error) {
+ return newCGroups2FromMountInfo(_procPathMountInfo)
+}
+
+func newCGroups2FromMountInfo(mountInfoPath string) (*CGroups2, error) {
+ isV2, err := isCGroupV2(mountInfoPath)
+ if err != nil {
+ return nil, err
+ }
+
+ if !isV2 {
+ return nil, ErrNotV2
+ }
+
+ return &CGroups2{
+ mountPoint: _cgroupv2MountPoint,
+ cpuMaxFile: _cgroupv2CPUMax,
+ }, nil
+}
+
+func isCGroupV2(procPathMountInfo string) (bool, error) {
+ var (
+ isV2 bool
+ newMountPoint = func(mp *MountPoint) error {
+ isV2 = isV2 || (mp.FSType == _cgroupv2FSType && mp.MountPoint == _cgroupv2MountPoint)
+ return nil
+ }
+ )
+
+ if err := parseMountInfo(procPathMountInfo, newMountPoint); err != nil {
+ return false, err
+ }
+
+ return isV2, nil
+}
+
+// CPUQuota returns the CPU quota applied with the CPU cgroup2 controller.
+// It is a result of reading cpu quota and period from cpu.max file.
+// It will return `cpu.max / cpu.period`. If cpu.max is set to max, it returns
+// (-1, false, nil)
+func (cg *CGroups2) CPUQuota() (float64, bool, error) {
+ cpuMaxParams, err := os.Open(path.Join(cg.mountPoint, cg.cpuMaxFile))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return -1, false, nil
+ }
+ return -1, false, err
+ }
+
+ scanner := bufio.NewScanner(cpuMaxParams)
+ if scanner.Scan() {
+ fields := strings.Fields(scanner.Text())
+ if len(fields) == 0 || len(fields) > 2 {
+ return -1, false, fmt.Errorf("invalid format")
+ }
+
+ if fields[_cgroupv2CPUMaxQuotaIndex] == _cgroupV2CPUMaxQuotaMax {
+ return -1, false, nil
+ }
+
+ max, err := strconv.Atoi(fields[_cgroupv2CPUMaxQuotaIndex])
+ if err != nil {
+ return -1, false, err
+ }
+
+ var period int
+ if len(fields) == 1 {
+ period = _cgroupV2CPUMaxDefaultPeriod
+ } else {
+ period, err = strconv.Atoi(fields[_cgroupv2CPUMaxPeriodIndex])
+ if err != nil {
+ return -1, false, err
+ }
+ }
+
+ return float64(max) / float64(period), true, nil
+ }
+
+ if err := scanner.Err(); err != nil {
+ return -1, false, err
+ }
+
+ return 0, false, io.ErrUnexpectedEOF
+}
diff --git a/vendor/go.uber.org/automaxprocs/internal/cgroups/doc.go b/vendor/go.uber.org/automaxprocs/internal/cgroups/doc.go
@@ -0,0 +1,23 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+// Package cgroups provides utilities to access Linux control group (CGroups)
+// parameters (CPU quota, for example) for a given process.
+package cgroups
diff --git a/vendor/go.uber.org/automaxprocs/internal/cgroups/errors.go b/vendor/go.uber.org/automaxprocs/internal/cgroups/errors.go
@@ -0,0 +1,52 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//go:build linux
+// +build linux
+
+package cgroups
+
+import "fmt"
+
+type cgroupSubsysFormatInvalidError struct {
+ line string
+}
+
+type mountPointFormatInvalidError struct {
+ line string
+}
+
+type pathNotExposedFromMountPointError struct {
+ mountPoint string
+ root string
+ path string
+}
+
+func (err cgroupSubsysFormatInvalidError) Error() string {
+ return fmt.Sprintf("invalid format for CGroupSubsys: %q", err.line)
+}
+
+func (err mountPointFormatInvalidError) Error() string {
+ return fmt.Sprintf("invalid format for MountPoint: %q", err.line)
+}
+
+func (err pathNotExposedFromMountPointError) Error() string {
+ return fmt.Sprintf("path %q is not a descendant of mount point root %q and cannot be exposed from %q", err.path, err.root, err.mountPoint)
+}
diff --git a/vendor/go.uber.org/automaxprocs/internal/cgroups/mountpoint.go b/vendor/go.uber.org/automaxprocs/internal/cgroups/mountpoint.go
@@ -0,0 +1,167 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//go:build linux
+// +build linux
+
+package cgroups
+
+import (
+ "bufio"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+const (
+ _mountInfoSep = " "
+ _mountInfoOptsSep = ","
+ _mountInfoOptionalFieldsSep = "-"
+)
+
+const (
+ _miFieldIDMountID = iota
+ _miFieldIDParentID
+ _miFieldIDDeviceID
+ _miFieldIDRoot
+ _miFieldIDMountPoint
+ _miFieldIDOptions
+ _miFieldIDOptionalFields
+
+ _miFieldCountFirstHalf
+)
+
+const (
+ _miFieldOffsetFSType = iota
+ _miFieldOffsetMountSource
+ _miFieldOffsetSuperOptions
+
+ _miFieldCountSecondHalf
+)
+
+const _miFieldCountMin = _miFieldCountFirstHalf + _miFieldCountSecondHalf
+
+// MountPoint is the data structure for the mount points in
+// `/proc/$PID/mountinfo`. See also proc(5) for more information.
+type MountPoint struct {
+ MountID int
+ ParentID int
+ DeviceID string
+ Root string
+ MountPoint string
+ Options []string
+ OptionalFields []string
+ FSType string
+ MountSource string
+ SuperOptions []string
+}
+
+// NewMountPointFromLine parses a line read from `/proc/$PID/mountinfo` and
+// returns a new *MountPoint.
+func NewMountPointFromLine(line string) (*MountPoint, error) {
+ fields := strings.Split(line, _mountInfoSep)
+
+ if len(fields) < _miFieldCountMin {
+ return nil, mountPointFormatInvalidError{line}
+ }
+
+ mountID, err := strconv.Atoi(fields[_miFieldIDMountID])
+ if err != nil {
+ return nil, err
+ }
+
+ parentID, err := strconv.Atoi(fields[_miFieldIDParentID])
+ if err != nil {
+ return nil, err
+ }
+
+ for i, field := range fields[_miFieldIDOptionalFields:] {
+ if field == _mountInfoOptionalFieldsSep {
+ fsTypeStart := _miFieldIDOptionalFields + i + 1
+
+ if len(fields) != fsTypeStart+_miFieldCountSecondHalf {
+ return nil, mountPointFormatInvalidError{line}
+ }
+
+ miFieldIDFSType := _miFieldOffsetFSType + fsTypeStart
+ miFieldIDMountSource := _miFieldOffsetMountSource + fsTypeStart
+ miFieldIDSuperOptions := _miFieldOffsetSuperOptions + fsTypeStart
+
+ return &MountPoint{
+ MountID: mountID,
+ ParentID: parentID,
+ DeviceID: fields[_miFieldIDDeviceID],
+ Root: fields[_miFieldIDRoot],
+ MountPoint: fields[_miFieldIDMountPoint],
+ Options: strings.Split(fields[_miFieldIDOptions], _mountInfoOptsSep),
+ OptionalFields: fields[_miFieldIDOptionalFields:(fsTypeStart - 1)],
+ FSType: fields[miFieldIDFSType],
+ MountSource: fields[miFieldIDMountSource],
+ SuperOptions: strings.Split(fields[miFieldIDSuperOptions], _mountInfoOptsSep),
+ }, nil
+ }
+ }
+
+ return nil, mountPointFormatInvalidError{line}
+}
+
+// Translate converts an absolute path inside the *MountPoint's file system to
+// the host file system path in the mount namespace the *MountPoint belongs to.
+func (mp *MountPoint) Translate(absPath string) (string, error) {
+ relPath, err := filepath.Rel(mp.Root, absPath)
+
+ if err != nil {
+ return "", err
+ }
+ if relPath == ".." || strings.HasPrefix(relPath, "../") {
+ return "", pathNotExposedFromMountPointError{
+ mountPoint: mp.MountPoint,
+ root: mp.Root,
+ path: absPath,
+ }
+ }
+
+ return filepath.Join(mp.MountPoint, relPath), nil
+}
+
+// parseMountInfo parses procPathMountInfo (usually at `/proc/$PID/mountinfo`)
+// and yields parsed *MountPoint into newMountPoint.
+func parseMountInfo(procPathMountInfo string, newMountPoint func(*MountPoint) error) error {
+ mountInfoFile, err := os.Open(procPathMountInfo)
+ if err != nil {
+ return err
+ }
+ defer mountInfoFile.Close()
+
+ scanner := bufio.NewScanner(mountInfoFile)
+
+ for scanner.Scan() {
+ mountPoint, err := NewMountPointFromLine(scanner.Text())
+ if err != nil {
+ return err
+ }
+ if err := newMountPoint(mountPoint); err != nil {
+ return err
+ }
+ }
+
+ return scanner.Err()
+}
diff --git a/vendor/go.uber.org/automaxprocs/internal/cgroups/subsys.go b/vendor/go.uber.org/automaxprocs/internal/cgroups/subsys.go
@@ -0,0 +1,103 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//go:build linux
+// +build linux
+
+package cgroups
+
+import (
+ "bufio"
+ "os"
+ "strconv"
+ "strings"
+)
+
+const (
+ _cgroupSep = ":"
+ _cgroupSubsysSep = ","
+)
+
+const (
+ _csFieldIDID = iota
+ _csFieldIDSubsystems
+ _csFieldIDName
+ _csFieldCount
+)
+
+// CGroupSubsys represents the data structure for entities in
+// `/proc/$PID/cgroup`. See also proc(5) for more information.
+type CGroupSubsys struct {
+ ID int
+ Subsystems []string
+ Name string
+}
+
+// NewCGroupSubsysFromLine returns a new *CGroupSubsys by parsing a string in
+// the format of `/proc/$PID/cgroup`
+func NewCGroupSubsysFromLine(line string) (*CGroupSubsys, error) {
+ fields := strings.SplitN(line, _cgroupSep, _csFieldCount)
+
+ if len(fields) != _csFieldCount {
+ return nil, cgroupSubsysFormatInvalidError{line}
+ }
+
+ id, err := strconv.Atoi(fields[_csFieldIDID])
+ if err != nil {
+ return nil, err
+ }
+
+ cgroup := &CGroupSubsys{
+ ID: id,
+ Subsystems: strings.Split(fields[_csFieldIDSubsystems], _cgroupSubsysSep),
+ Name: fields[_csFieldIDName],
+ }
+
+ return cgroup, nil
+}
+
+// parseCGroupSubsystems parses procPathCGroup (usually at `/proc/$PID/cgroup`)
+// and returns a new map[string]*CGroupSubsys.
+func parseCGroupSubsystems(procPathCGroup string) (map[string]*CGroupSubsys, error) {
+ cgroupFile, err := os.Open(procPathCGroup)
+ if err != nil {
+ return nil, err
+ }
+ defer cgroupFile.Close()
+
+ scanner := bufio.NewScanner(cgroupFile)
+ subsystems := make(map[string]*CGroupSubsys)
+
+ for scanner.Scan() {
+ cgroup, err := NewCGroupSubsysFromLine(scanner.Text())
+ if err != nil {
+ return nil, err
+ }
+ for _, subsys := range cgroup.Subsystems {
+ subsystems[subsys] = cgroup
+ }
+ }
+
+ if err := scanner.Err(); err != nil {
+ return nil, err
+ }
+
+ return subsystems, nil
+}
diff --git a/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_linux.go b/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_linux.go
@@ -0,0 +1,71 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//go:build linux
+// +build linux
+
+package runtime
+
+import (
+ "errors"
+ "math"
+
+ cg "go.uber.org/automaxprocs/internal/cgroups"
+)
+
+// CPUQuotaToGOMAXPROCS converts the CPU quota applied to the calling process
+// to a valid GOMAXPROCS value.
+func CPUQuotaToGOMAXPROCS(minValue int) (int, CPUQuotaStatus, error) {
+ cgroups, err := newQueryer()
+ if err != nil {
+ return -1, CPUQuotaUndefined, err
+ }
+
+ quota, defined, err := cgroups.CPUQuota()
+ if !defined || err != nil {
+ return -1, CPUQuotaUndefined, err
+ }
+
+ maxProcs := int(math.Floor(quota))
+ if minValue > 0 && maxProcs < minValue {
+ return minValue, CPUQuotaMinUsed, nil
+ }
+ return maxProcs, CPUQuotaUsed, nil
+}
+
+type queryer interface {
+ CPUQuota() (float64, bool, error)
+}
+
+var (
+ _newCgroups2 = cg.NewCGroups2ForCurrentProcess
+ _newCgroups = cg.NewCGroupsForCurrentProcess
+)
+
+func newQueryer() (queryer, error) {
+ cgroups, err := _newCgroups2()
+ if err == nil {
+ return cgroups, nil
+ }
+ if errors.Is(err, cg.ErrNotV2) {
+ return _newCgroups()
+ }
+ return nil, err
+}
diff --git a/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_unsupported.go b/vendor/go.uber.org/automaxprocs/internal/runtime/cpu_quota_unsupported.go
@@ -0,0 +1,31 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//go:build !linux
+// +build !linux
+
+package runtime
+
+// CPUQuotaToGOMAXPROCS converts the CPU quota applied to the calling process
+// to a valid GOMAXPROCS value. This is Linux-specific and not supported in the
+// current OS.
+func CPUQuotaToGOMAXPROCS(_ int) (int, CPUQuotaStatus, error) {
+ return -1, CPUQuotaUndefined, nil
+}
diff --git a/vendor/go.uber.org/automaxprocs/internal/runtime/runtime.go b/vendor/go.uber.org/automaxprocs/internal/runtime/runtime.go
@@ -0,0 +1,33 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+package runtime
+
+// CPUQuotaStatus presents the status of how CPU quota is used
+type CPUQuotaStatus int
+
+const (
+ // CPUQuotaUndefined is returned when CPU quota is undefined
+ CPUQuotaUndefined CPUQuotaStatus = iota
+ // CPUQuotaUsed is returned when a valid CPU quota can be used
+ CPUQuotaUsed
+ // CPUQuotaMinUsed is return when CPU quota is smaller than the min value
+ CPUQuotaMinUsed
+)
diff --git a/vendor/go.uber.org/automaxprocs/maxprocs/maxprocs.go b/vendor/go.uber.org/automaxprocs/maxprocs/maxprocs.go
@@ -0,0 +1,130 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+// Package maxprocs lets Go programs easily configure runtime.GOMAXPROCS to
+// match the configured Linux CPU quota. Unlike the top-level automaxprocs
+// package, it lets the caller configure logging and handle errors.
+package maxprocs // import "go.uber.org/automaxprocs/maxprocs"
+
+import (
+ "os"
+ "runtime"
+
+ iruntime "go.uber.org/automaxprocs/internal/runtime"
+)
+
+const _maxProcsKey = "GOMAXPROCS"
+
+func currentMaxProcs() int {
+ return runtime.GOMAXPROCS(0)
+}
+
+type config struct {
+ printf func(string, ...interface{})
+ procs func(int) (int, iruntime.CPUQuotaStatus, error)
+ minGOMAXPROCS int
+}
+
+func (c *config) log(fmt string, args ...interface{}) {
+ if c.printf != nil {
+ c.printf(fmt, args...)
+ }
+}
+
+// An Option alters the behavior of Set.
+type Option interface {
+ apply(*config)
+}
+
+// Logger uses the supplied printf implementation for log output. By default,
+// Set doesn't log anything.
+func Logger(printf func(string, ...interface{})) Option {
+ return optionFunc(func(cfg *config) {
+ cfg.printf = printf
+ })
+}
+
+// Min sets the minimum GOMAXPROCS value that will be used.
+// Any value below 1 is ignored.
+func Min(n int) Option {
+ return optionFunc(func(cfg *config) {
+ if n >= 1 {
+ cfg.minGOMAXPROCS = n
+ }
+ })
+}
+
+type optionFunc func(*config)
+
+func (of optionFunc) apply(cfg *config) { of(cfg) }
+
+// Set GOMAXPROCS to match the Linux container CPU quota (if any), returning
+// any error encountered and an undo function.
+//
+// Set is a no-op on non-Linux systems and in Linux environments without a
+// configured CPU quota.
+func Set(opts ...Option) (func(), error) {
+ cfg := &config{
+ procs: iruntime.CPUQuotaToGOMAXPROCS,
+ minGOMAXPROCS: 1,
+ }
+ for _, o := range opts {
+ o.apply(cfg)
+ }
+
+ undoNoop := func() {
+ cfg.log("maxprocs: No GOMAXPROCS change to reset")
+ }
+
+ // Honor the GOMAXPROCS environment variable if present. Otherwise, amend
+ // `runtime.GOMAXPROCS()` with the current process' CPU quota if the OS is
+ // Linux, and guarantee a minimum value of 1. The minimum guaranteed value
+ // can be overridden using `maxprocs.Min()`.
+ if max, exists := os.LookupEnv(_maxProcsKey); exists {
+ cfg.log("maxprocs: Honoring GOMAXPROCS=%q as set in environment", max)
+ return undoNoop, nil
+ }
+
+ maxProcs, status, err := cfg.procs(cfg.minGOMAXPROCS)
+ if err != nil {
+ return undoNoop, err
+ }
+
+ if status == iruntime.CPUQuotaUndefined {
+ cfg.log("maxprocs: Leaving GOMAXPROCS=%v: CPU quota undefined", currentMaxProcs())
+ return undoNoop, nil
+ }
+
+ prev := currentMaxProcs()
+ undo := func() {
+ cfg.log("maxprocs: Resetting GOMAXPROCS to %v", prev)
+ runtime.GOMAXPROCS(prev)
+ }
+
+ switch status {
+ case iruntime.CPUQuotaMinUsed:
+ cfg.log("maxprocs: Updating GOMAXPROCS=%v: using minimum allowed GOMAXPROCS", maxProcs)
+ case iruntime.CPUQuotaUsed:
+ cfg.log("maxprocs: Updating GOMAXPROCS=%v: determined from CPU quota", maxProcs)
+ }
+
+ runtime.GOMAXPROCS(maxProcs)
+ return undo, nil
+}
diff --git a/vendor/go.uber.org/automaxprocs/maxprocs/version.go b/vendor/go.uber.org/automaxprocs/maxprocs/version.go
@@ -0,0 +1,24 @@
+// Copyright (c) 2017 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+package maxprocs
+
+// Version is the current package version.
+const Version = "1.5.1"
diff --git a/vendor/modules.txt b/vendor/modules.txt
@@ -69,6 +69,10 @@ codeberg.org/gruf/go-sched
codeberg.org/gruf/go-store/v2/kv
codeberg.org/gruf/go-store/v2/storage
codeberg.org/gruf/go-store/v2/util
+# github.com/KimMachineGun/automemlimit v0.2.4
+## explicit; go 1.19
+github.com/KimMachineGun/automemlimit
+github.com/KimMachineGun/automemlimit/memlimit
# github.com/abema/go-mp4 v0.9.0
## explicit; go 1.14
github.com/abema/go-mp4
@@ -82,9 +86,26 @@ github.com/aymerick/douceur/parser
## explicit; go 1.14
github.com/buckket/go-blurhash
github.com/buckket/go-blurhash/base83
+# github.com/cilium/ebpf v0.4.0
+## explicit; go 1.15
+github.com/cilium/ebpf
+github.com/cilium/ebpf/asm
+github.com/cilium/ebpf/internal
+github.com/cilium/ebpf/internal/btf
+github.com/cilium/ebpf/internal/unix
+github.com/cilium/ebpf/link
+# github.com/containerd/cgroups v1.0.4
+## explicit; go 1.17
+github.com/containerd/cgroups
+github.com/containerd/cgroups/stats/v1
+github.com/containerd/cgroups/v2
+github.com/containerd/cgroups/v2/stats
# github.com/coreos/go-oidc/v3 v3.5.0
## explicit; go 1.14
github.com/coreos/go-oidc/v3/oidc
+# github.com/coreos/go-systemd/v22 v22.3.2
+## explicit; go 1.12
+github.com/coreos/go-systemd/v22/dbus
# github.com/cornelk/hashmap v1.0.8
## explicit; go 1.19
github.com/cornelk/hashmap
@@ -94,6 +115,9 @@ github.com/davecgh/go-spew/spew
# github.com/disintegration/imaging v1.6.2
## explicit
github.com/disintegration/imaging
+# github.com/docker/go-units v0.4.0
+## explicit
+github.com/docker/go-units
# github.com/dsoprea/go-exif/v3 v3.0.0-20210625224831-a6301f85c82b
## explicit; go 1.12
github.com/dsoprea/go-exif/v3
@@ -176,6 +200,14 @@ github.com/goccy/go-json/internal/encoder/vm_color_indent
github.com/goccy/go-json/internal/encoder/vm_indent
github.com/goccy/go-json/internal/errors
github.com/goccy/go-json/internal/runtime
+# github.com/godbus/dbus/v5 v5.0.4
+## explicit; go 1.12
+github.com/godbus/dbus/v5
+# github.com/gogo/protobuf v1.3.2
+## explicit; go 1.15
+github.com/gogo/protobuf/gogoproto
+github.com/gogo/protobuf/proto
+github.com/gogo/protobuf/protoc-gen-gogo/descriptor
# github.com/golang-jwt/jwt v3.2.2+incompatible
## explicit
github.com/golang-jwt/jwt
@@ -325,6 +357,9 @@ github.com/modern-go/reflect2
# github.com/oklog/ulid v1.3.1
## explicit
github.com/oklog/ulid
+# github.com/opencontainers/runtime-spec v1.0.2
+## explicit
+github.com/opencontainers/runtime-spec/specs-go
# github.com/pelletier/go-toml v1.9.5
## explicit; go 1.12
github.com/pelletier/go-toml
@@ -655,6 +690,11 @@ github.com/yuin/goldmark/renderer
github.com/yuin/goldmark/renderer/html
github.com/yuin/goldmark/text
github.com/yuin/goldmark/util
+# go.uber.org/automaxprocs v1.5.1
+## explicit; go 1.18
+go.uber.org/automaxprocs/internal/cgroups
+go.uber.org/automaxprocs/internal/runtime
+go.uber.org/automaxprocs/maxprocs
# golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90
## explicit; go 1.17
golang.org/x/crypto/acme