From 8eaaeaac6957b7c7eff6694b00e792bc00f2c587 Mon Sep 17 00:00:00 2001 From: Matt Moore Date: Fri, 6 Nov 2020 07:24:35 -0800 Subject: [PATCH] Refactor the way timeouts are handled `{Task,Pipeline}Run` now handle timeouts via `EnqueueAfter` on the workqueue. `pkg/timeout` is now removed. We now have consistent `GetTimeout(ctx)` methods on types. --- go.mod | 4 +- go.sum | 15 + .../pipeline/v1beta1/pipelinerun_types.go | 10 + pkg/apis/pipeline/v1beta1/taskrun_types.go | 11 +- .../pipeline/v1beta1/taskrun_types_test.go | 3 +- pkg/reconciler/pipelinerun/controller.go | 13 +- pkg/reconciler/pipelinerun/pipelinerun.go | 25 +- pkg/reconciler/taskrun/controller.go | 14 +- pkg/reconciler/taskrun/taskrun.go | 29 +- pkg/reconciler/taskrun/taskrun_test.go | 37 +- pkg/timeout/handler.go | 281 ----------- pkg/timeout/handler_test.go | 463 ------------------ third_party/LICENSE | 27 - .../github.com/PuerkitoBio/purell/LICENSE | 12 + .../PuerkitoBio/urlesc}/LICENSE | 2 +- .../github.com/emicklei/go-restful/LICENSE | 22 + .../go-openapi/jsonpointer}/LICENSE | 0 .../go-openapi/jsonreference/LICENSE | 202 ++++++++ .../github.com/go-openapi/spec/LICENSE | 202 ++++++++ .../github.com/go-openapi/swag/LICENSE | 202 ++++++++ .../hashicorp/errwrap/errwrap_test.go | 94 ++++ .../hashicorp/go-multierror/append_test.go | 82 ++++ .../hashicorp/go-multierror/flatten_test.go | 46 ++ .../hashicorp/go-multierror/format_test.go | 40 ++ .../hashicorp/go-multierror/group_test.go | 44 ++ .../go-multierror/multierror_test.go | 203 ++++++++ .../hashicorp/go-multierror/prefix_test.go | 33 ++ .../hashicorp/go-multierror/sort_test.go | 52 ++ .../hashicorp/golang-lru/2q_test.go | 306 ++++++++++++ .../hashicorp/golang-lru/arc_test.go | 377 ++++++++++++++ .../hashicorp/golang-lru/lru_test.go | 293 +++++++++++ .../golang-lru/simplelru/lru_test.go | 206 ++++++++ .../github.com/mailru/easyjson/LICENSE | 7 + third_party/k8s.io/kube-openapi/pkg/LICENSE | 202 ++++++++ .../vendor/golang.org/x/crypto/LICENSE | 27 - .../vendor/golang.org/x/sys/cpu/LICENSE | 27 - third_party/vendor/golang.org/x/text/LICENSE | 27 - 37 files changed, 2727 insertions(+), 913 deletions(-) delete mode 100644 pkg/timeout/handler.go delete mode 100644 pkg/timeout/handler_test.go delete mode 100644 third_party/LICENSE create mode 100644 third_party/github.com/PuerkitoBio/purell/LICENSE rename third_party/{vendor/golang.org/x/net => github.com/PuerkitoBio/urlesc}/LICENSE (96%) create mode 100644 third_party/github.com/emicklei/go-restful/LICENSE rename third_party/{k8s.io/kube-openapi/pkg/util/proto => github.com/go-openapi/jsonpointer}/LICENSE (100%) create mode 100644 third_party/github.com/go-openapi/jsonreference/LICENSE create mode 100644 third_party/github.com/go-openapi/spec/LICENSE create mode 100644 third_party/github.com/go-openapi/swag/LICENSE create mode 100644 third_party/github.com/hashicorp/errwrap/errwrap_test.go create mode 100644 third_party/github.com/hashicorp/go-multierror/append_test.go create mode 100644 third_party/github.com/hashicorp/go-multierror/flatten_test.go create mode 100644 third_party/github.com/hashicorp/go-multierror/format_test.go create mode 100644 third_party/github.com/hashicorp/go-multierror/group_test.go create mode 100644 third_party/github.com/hashicorp/go-multierror/multierror_test.go create mode 100644 third_party/github.com/hashicorp/go-multierror/prefix_test.go create mode 100644 third_party/github.com/hashicorp/go-multierror/sort_test.go create mode 100644 third_party/github.com/hashicorp/golang-lru/2q_test.go create mode 100644 third_party/github.com/hashicorp/golang-lru/arc_test.go create mode 100644 third_party/github.com/hashicorp/golang-lru/lru_test.go create mode 100644 third_party/github.com/hashicorp/golang-lru/simplelru/lru_test.go create mode 100644 third_party/github.com/mailru/easyjson/LICENSE create mode 100644 third_party/k8s.io/kube-openapi/pkg/LICENSE delete mode 100644 third_party/vendor/golang.org/x/crypto/LICENSE delete mode 100644 third_party/vendor/golang.org/x/sys/cpu/LICENSE delete mode 100644 third_party/vendor/golang.org/x/text/LICENSE diff --git a/go.mod b/go.mod index fa12fe2fd97..ed6fd52e051 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/tektoncd/pipeline go 1.13 require ( - cloud.google.com/go/storage v1.11.0 + cloud.google.com/go/storage v1.11.0 // indirect github.com/GoogleCloudPlatform/cloud-builders/gcs-fetcher v0.0.0-20191203181535-308b93ad1f39 github.com/cloudevents/sdk-go/v2 v2.1.0 github.com/ghodss/yaml v1.0.0 @@ -22,11 +22,11 @@ require ( golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a // indirect golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d gomodules.xyz/jsonpatch/v2 v2.1.0 - google.golang.org/api v0.31.0 k8s.io/api v0.18.8 k8s.io/apimachinery v0.19.0 k8s.io/client-go v11.0.1-0.20190805182717-6502b5e7b1b5+incompatible k8s.io/code-generator v0.18.8 + k8s.io/klog v1.0.0 k8s.io/kube-openapi v0.0.0-20200410145947-bcb3869e6f29 knative.dev/pkg v0.0.0-20200922164940-4bf40ad82aab ) diff --git a/go.sum b/go.sum index e4f7da52d0e..62c3d595a48 100644 --- a/go.sum +++ b/go.sum @@ -635,7 +635,9 @@ github.com/google/licenseclassifier v0.0.0-20200402202327-879cb1424de0/go.mod h1 github.com/google/licenseclassifier v0.0.0-20200708223521-3d09a0ea2f39/go.mod h1:qsqn2hxC+vURpyBRygGUuinTO42MFRLcsmQ/P8v94+M= github.com/google/mako v0.0.0-20190821191249-122f8dcef9e3/go.mod h1:YzLcVlL+NqWnmUEPuhS1LxDDwGO9WNbVlEXaF4IH35g= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian v2.1.1-0.20190517191504-25dcb96d9e51+incompatible h1:xmapqc1AyLoB+ddYT6r04bD9lIjlOqGaREovi0SzFaE= github.com/google/martian v2.1.1-0.20190517191504-25dcb96d9e51+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0 h1:pMen7vLs8nvgEYhywH3KDWJIJTeEr2ULsVWHWYHQyBs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= @@ -827,6 +829,7 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.5/go.mod h1:9r2w37qlBe7rQ6e1fg1S/9xpWHSnaqNdHD3WcMdbPDA= github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= @@ -928,11 +931,14 @@ github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxzi github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nuid v1.0.0/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms= github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d/go.mod h1:o96djdrsSGy3AWPyBgZMAGfxZNfgntdJG+11KU4QvbU= github.com/ncw/swift v1.0.47/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nwaples/rardecode v1.0.0/go.mod h1:5DzqNKiOdpKKBH87u8VlvAnPZMXcGRhxWkRpHbbfGS0= +github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/octago/sflags v0.2.0/go.mod h1:G0bjdxh4qPRycF74a2B8pU36iTp9QHGx0w0dFZXPt80= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= @@ -945,6 +951,7 @@ github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+ github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/ginkgo v1.12.1 h1:mFwc4LvZ0xpSvDZ3E+k8Yte0hLOMxXUlP+yXtJqkYfQ= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.2/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= @@ -954,6 +961,7 @@ github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1Cpa github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.8.1/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= +github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= github.com/opencontainers/go-digest v0.0.0-20170106003457-a6d0ee40d420/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= @@ -994,6 +1002,7 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= +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/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/pquerna/cachecontrol v0.0.0-20171018203845-0dec1b30a021/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA= @@ -1140,6 +1149,7 @@ github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoH github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/syndtr/gocapability v0.0.0-20170704070218-db04d3cc01c8/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= @@ -1179,6 +1189,7 @@ github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ github.com/urfave/cli v1.18.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/uudashr/gocognit v1.0.1/go.mod h1:j44Ayx2KW4+oB6SWMv8KsmHzZrOInQav7D3cQMJ5JUM= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasthttp v1.2.0/go.mod h1:4vX61m6KN+xDduDNwXrhIAVZaZaZiQ1luJk8LWSxF3s= github.com/valyala/quicktemplate v1.2.0/go.mod h1:EH+4AkTd43SvgIbQHYu59/cJyxDoOVRUAfrukLPuGJ4= @@ -1243,6 +1254,7 @@ go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+ go.uber.org/multierr v1.4.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A= go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee h1:0mgffUl7nfd+FpvXMVz4IDEaUSmT1ysygQC7qYo7sG4= go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.9.2-0.20180814183419-67bc79d13d15/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= @@ -1732,6 +1744,7 @@ gopkg.in/check.v1 v1.0.0-20141024133853-64131543e789/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= @@ -1756,6 +1769,7 @@ gopkg.in/square/go-jose.v2 v2.2.2/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76 gopkg.in/src-d/go-billy.v4 v4.3.2/go.mod h1:nDjArDMp+XMs1aFAESLRjfGSgfvoYN0hDfzEk0GjC98= gopkg.in/src-d/go-git-fixtures.v3 v3.5.0/go.mod h1:dLBcvytrw/TYZsNTWCnkNF2DSIlzWYqTe3rJR56Ac7g= gopkg.in/src-d/go-git.v4 v4.13.1/go.mod h1:nx5NYcxdKxq5fpltdHnPa2Exj4Sx0EclMWZQbYDu2z8= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/warnings.v0 v0.1.1/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= @@ -1770,6 +1784,7 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20190709130402-674ba3eaed22/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= helm.sh/helm/v3 v3.1.1/go.mod h1:WYsFJuMASa/4XUqLyv54s0U/f3mlAaRErGmyy4z921g= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/pkg/apis/pipeline/v1beta1/pipelinerun_types.go b/pkg/apis/pipeline/v1beta1/pipelinerun_types.go index be22562857d..398ba84e7da 100644 --- a/pkg/apis/pipeline/v1beta1/pipelinerun_types.go +++ b/pkg/apis/pipeline/v1beta1/pipelinerun_types.go @@ -17,6 +17,7 @@ limitations under the License. package v1beta1 import ( + "context" "time" "github.com/tektoncd/pipeline/pkg/apis/config" @@ -98,6 +99,15 @@ func (pr *PipelineRun) IsCancelled() bool { return pr.Spec.Status == PipelineRunSpecStatusCancelled } +func (pr *PipelineRun) GetTimeout(ctx context.Context) time.Duration { + // Use the platform default is no timeout is set + if pr.Spec.Timeout == nil { + defaultTimeout := time.Duration(config.FromContextOrDefaults(ctx).Defaults.DefaultTimeoutMinutes) + return defaultTimeout * time.Minute + } + return pr.Spec.Timeout.Duration +} + // GetNamespacedName returns a k8s namespaced name that identifies this PipelineRun func (pr *PipelineRun) GetNamespacedName() types.NamespacedName { return types.NamespacedName{Namespace: pr.Namespace, Name: pr.Name} diff --git a/pkg/apis/pipeline/v1beta1/taskrun_types.go b/pkg/apis/pipeline/v1beta1/taskrun_types.go index 3e511b923aa..bc686f074d7 100644 --- a/pkg/apis/pipeline/v1beta1/taskrun_types.go +++ b/pkg/apis/pipeline/v1beta1/taskrun_types.go @@ -17,9 +17,11 @@ limitations under the License. package v1beta1 import ( + "context" "fmt" "time" + "github.com/tektoncd/pipeline/pkg/apis/config" apisconfig "github.com/tektoncd/pipeline/pkg/apis/config" "github.com/tektoncd/pipeline/pkg/apis/pipeline" corev1 "k8s.io/api/core/v1" @@ -404,11 +406,11 @@ func (tr *TaskRun) IsCancelled() bool { } // HasTimedOut returns true if the TaskRun runtime is beyond the allowed timeout -func (tr *TaskRun) HasTimedOut() bool { +func (tr *TaskRun) HasTimedOut(ctx context.Context) bool { if tr.Status.StartTime.IsZero() { return false } - timeout := tr.GetTimeout() + timeout := tr.GetTimeout(ctx) // If timeout is set to 0 or defaulted to 0, there is no timeout. if timeout == apisconfig.NoTimeoutDuration { return false @@ -417,10 +419,11 @@ func (tr *TaskRun) HasTimedOut() bool { return runtime > timeout } -func (tr *TaskRun) GetTimeout() time.Duration { +func (tr *TaskRun) GetTimeout(ctx context.Context) time.Duration { // Use the platform default is no timeout is set if tr.Spec.Timeout == nil { - return apisconfig.DefaultTimeoutMinutes * time.Minute + defaultTimeout := time.Duration(config.FromContextOrDefaults(ctx).Defaults.DefaultTimeoutMinutes) + return defaultTimeout * time.Minute } return tr.Spec.Timeout.Duration } diff --git a/pkg/apis/pipeline/v1beta1/taskrun_types_test.go b/pkg/apis/pipeline/v1beta1/taskrun_types_test.go index 1982a21b59e..fc3ef8393b3 100644 --- a/pkg/apis/pipeline/v1beta1/taskrun_types_test.go +++ b/pkg/apis/pipeline/v1beta1/taskrun_types_test.go @@ -17,6 +17,7 @@ limitations under the License. package v1beta1_test import ( + "context" "testing" "time" @@ -329,7 +330,7 @@ func TestHasTimedOut(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - result := tc.taskRun.HasTimedOut() + result := tc.taskRun.HasTimedOut(context.Background()) if d := cmp.Diff(result, tc.expectedStatus); d != "" { t.Fatalf(diff.PrintWantGot(d)) } diff --git a/pkg/reconciler/pipelinerun/controller.go b/pkg/reconciler/pipelinerun/controller.go index 728cd296f4b..e6e26475bea 100644 --- a/pkg/reconciler/pipelinerun/controller.go +++ b/pkg/reconciler/pipelinerun/controller.go @@ -33,11 +33,12 @@ import ( resourceinformer "github.com/tektoncd/pipeline/pkg/client/resource/injection/informers/resource/v1alpha1/pipelineresource" cloudeventclient "github.com/tektoncd/pipeline/pkg/reconciler/events/cloudevent" "github.com/tektoncd/pipeline/pkg/reconciler/volumeclaim" - "github.com/tektoncd/pipeline/pkg/timeout" + "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/cache" kubeclient "knative.dev/pkg/client/injection/kube/client" "knative.dev/pkg/configmap" "knative.dev/pkg/controller" + "knative.dev/pkg/kmeta" "knative.dev/pkg/logging" "knative.dev/pkg/tracker" ) @@ -55,7 +56,6 @@ func NewController(namespace string, images pipeline.Images) func(context.Contex pipelineInformer := pipelineinformer.Get(ctx) resourceInformer := resourceinformer.Get(ctx) conditionInformer := conditioninformer.Get(ctx) - timeoutHandler := timeout.NewHandler(ctx.Done(), logger) metrics, err := NewRecorder() if err != nil { logger.Errorf("Failed to create pipelinerun metrics recorder %v", err) @@ -72,7 +72,6 @@ func NewController(namespace string, images pipeline.Images) func(context.Contex taskRunLister: taskRunInformer.Lister(), resourceLister: resourceInformer.Lister(), conditionLister: conditionInformer.Lister(), - timeoutHandler: timeoutHandler, cloudEventClient: cloudeventclient.Get(ctx), metrics: metrics, pvcHandler: volumeclaim.NewPVCHandler(kubeclientset, logger), @@ -86,8 +85,12 @@ func NewController(namespace string, images pipeline.Images) func(context.Contex } }) - timeoutHandler.SetCallbackFunc(impl.EnqueueKey) - go timeoutHandler.CheckTimeouts(ctx, namespace, kubeclientset, pipelineclientset) + c.snooze = func(acc kmeta.Accessor, amnt time.Duration) { + impl.EnqueueKeyAfter(types.NamespacedName{ + Namespace: acc.GetNamespace(), + Name: acc.GetName(), + }, amnt) + } logger.Info("Setting up event handlers") pipelineRunInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ diff --git a/pkg/reconciler/pipelinerun/pipelinerun.go b/pkg/reconciler/pipelinerun/pipelinerun.go index 2fd2e25496b..f6687352742 100644 --- a/pkg/reconciler/pipelinerun/pipelinerun.go +++ b/pkg/reconciler/pipelinerun/pipelinerun.go @@ -46,7 +46,6 @@ import ( "github.com/tektoncd/pipeline/pkg/reconciler/taskrun" tresources "github.com/tektoncd/pipeline/pkg/reconciler/taskrun/resources" "github.com/tektoncd/pipeline/pkg/reconciler/volumeclaim" - "github.com/tektoncd/pipeline/pkg/timeout" "github.com/tektoncd/pipeline/pkg/workspace" "go.uber.org/zap" corev1 "k8s.io/api/core/v1" @@ -56,6 +55,7 @@ import ( "k8s.io/client-go/kubernetes" "knative.dev/pkg/apis" "knative.dev/pkg/controller" + "knative.dev/pkg/kmeta" "knative.dev/pkg/logging" pkgreconciler "knative.dev/pkg/reconciler" "knative.dev/pkg/tracker" @@ -121,9 +121,10 @@ type Reconciler struct { conditionLister listersv1alpha1.ConditionLister cloudEventClient cloudevent.CEClient tracker tracker.Interface - timeoutHandler *timeout.Handler metrics *Recorder pvcHandler volumeclaim.PvcHandler + + snooze func(kmeta.Accessor, time.Duration) } var ( @@ -149,8 +150,6 @@ func (c *Reconciler) ReconcileKind(ctx context.Context, pr *v1beta1.PipelineRun) pr.Status.StartTime = &pr.CreationTimestamp } - // start goroutine to track pipelinerun timeout only startTime is not set - go c.timeoutHandler.Wait(pr.GetNamespacedName(), *pr.Status.StartTime, getPipelineRunTimeout(ctx, pr)) // Emit events. During the first reconcile the status of the PipelineRun may change twice // from not Started to Started and then to Running, so we need to sent the event here // and at the end of 'Reconcile' again. @@ -185,7 +184,6 @@ func (c *Reconciler) ReconcileKind(ctx context.Context, pr *v1beta1.PipelineRun) logger.Errorf("Failed to delete StatefulSet for PipelineRun %s: %v", pr.Name, err) return c.finishReconcileUpdateEmitEvents(ctx, pr, before, err) } - c.timeoutHandler.Release(pr.GetNamespacedName()) if err := c.updateTaskRunsStatusDirectly(pr); err != nil { logger.Errorf("Failed to update TaskRun status for PipelineRun %s: %v", pr.Name, err) return c.finishReconcileUpdateEmitEvents(ctx, pr, before, err) @@ -217,6 +215,15 @@ func (c *Reconciler) ReconcileKind(ctx context.Context, pr *v1beta1.PipelineRun) logger.Errorf("Error while syncing the pipelinerun status: %v", err.Error()) return c.finishReconcileUpdateEmitEvents(ctx, pr, before, err) } + defer func() { + if pr.Status.StartTime == nil { + return + } + // Compute the time since the task started. + elapsed := time.Since(pr.Status.StartTime.Time) + // Snooze this resource until the timeout has elapsed. + c.snooze(pr, pr.GetTimeout(ctx)-elapsed) + }() // Reconcile this copy of the pipelinerun and then write back any status or label // updates regardless of whether the reconciliation errored out. @@ -797,14 +804,6 @@ func combineTaskRunAndTaskSpecAnnotations(pr *v1beta1.PipelineRun, pipelineTask return annotations } -func getPipelineRunTimeout(ctx context.Context, pr *v1beta1.PipelineRun) metav1.Duration { - if pr.Spec.Timeout == nil { - defaultTimeout := time.Duration(config.FromContextOrDefaults(ctx).Defaults.DefaultTimeoutMinutes) - return metav1.Duration{Duration: defaultTimeout * time.Minute} - } - return *pr.Spec.Timeout -} - func getTaskRunTimeout(ctx context.Context, pr *v1beta1.PipelineRun, rprt *resources.ResolvedPipelineRunTask) *metav1.Duration { var taskRunTimeout = &metav1.Duration{Duration: apisconfig.NoTimeoutDuration} diff --git a/pkg/reconciler/taskrun/controller.go b/pkg/reconciler/taskrun/controller.go index c1fb061d1d2..1258cbc7212 100644 --- a/pkg/reconciler/taskrun/controller.go +++ b/pkg/reconciler/taskrun/controller.go @@ -18,6 +18,7 @@ package taskrun import ( "context" + "time" "github.com/tektoncd/pipeline/pkg/apis/config" "github.com/tektoncd/pipeline/pkg/apis/pipeline" @@ -31,12 +32,13 @@ import ( "github.com/tektoncd/pipeline/pkg/pod" cloudeventclient "github.com/tektoncd/pipeline/pkg/reconciler/events/cloudevent" "github.com/tektoncd/pipeline/pkg/reconciler/volumeclaim" - "github.com/tektoncd/pipeline/pkg/timeout" + "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/cache" kubeclient "knative.dev/pkg/client/injection/kube/client" podinformer "knative.dev/pkg/client/injection/kube/informers/core/v1/pod" "knative.dev/pkg/configmap" "knative.dev/pkg/controller" + "knative.dev/pkg/kmeta" "knative.dev/pkg/logging" "knative.dev/pkg/tracker" ) @@ -52,7 +54,6 @@ func NewController(namespace string, images pipeline.Images) func(context.Contex clusterTaskInformer := clustertaskinformer.Get(ctx) podInformer := podinformer.Get(ctx) resourceInformer := resourceinformer.Get(ctx) - timeoutHandler := timeout.NewHandler(ctx.Done(), logger) metrics, err := NewRecorder() if err != nil { logger.Errorf("Failed to create taskrun metrics recorder %v", err) @@ -71,7 +72,6 @@ func NewController(namespace string, images pipeline.Images) func(context.Contex taskLister: taskInformer.Lister(), clusterTaskLister: clusterTaskInformer.Lister(), resourceLister: resourceInformer.Lister(), - timeoutHandler: timeoutHandler, cloudEventClient: cloudeventclient.Get(ctx), metrics: metrics, entrypointCache: entrypointCache, @@ -87,8 +87,12 @@ func NewController(namespace string, images pipeline.Images) func(context.Contex } }) - timeoutHandler.SetCallbackFunc(impl.EnqueueKey) - go timeoutHandler.CheckTimeouts(ctx, namespace, kubeclientset, pipelineclientset) + c.snooze = func(acc kmeta.Accessor, amnt time.Duration) { + impl.EnqueueKeyAfter(types.NamespacedName{ + Namespace: acc.GetNamespace(), + Name: acc.GetName(), + }, amnt) + } logger.Info("Setting up event handlers") taskRunInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ diff --git a/pkg/reconciler/taskrun/taskrun.go b/pkg/reconciler/taskrun/taskrun.go index 66d80d3687e..aec1b0620b5 100644 --- a/pkg/reconciler/taskrun/taskrun.go +++ b/pkg/reconciler/taskrun/taskrun.go @@ -44,7 +44,6 @@ import ( "github.com/tektoncd/pipeline/pkg/reconciler/events/cloudevent" "github.com/tektoncd/pipeline/pkg/reconciler/taskrun/resources" "github.com/tektoncd/pipeline/pkg/reconciler/volumeclaim" - "github.com/tektoncd/pipeline/pkg/timeout" "github.com/tektoncd/pipeline/pkg/workspace" corev1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" @@ -52,6 +51,7 @@ import ( "k8s.io/client-go/kubernetes" "knative.dev/pkg/apis" "knative.dev/pkg/controller" + "knative.dev/pkg/kmeta" "knative.dev/pkg/logging" pkgreconciler "knative.dev/pkg/reconciler" "knative.dev/pkg/tracker" @@ -71,9 +71,10 @@ type Reconciler struct { cloudEventClient cloudevent.CEClient tracker tracker.Interface entrypointCache podconvert.EntrypointCache - timeoutHandler *timeout.Handler metrics *Recorder pvcHandler volumeclaim.PvcHandler + + snooze func(kmeta.Accessor, time.Duration) } // Check that our Reconciler implements taskrunreconciler.Interface @@ -124,7 +125,6 @@ func (c *Reconciler) ReconcileKind(ctx context.Context, tr *v1beta1.TaskRun) pkg // send cloud events. So we stop here an return errors encountered this far. return cloudEventErr } - c.timeoutHandler.Release(tr.GetNamespacedName()) pod, err := c.stopSidecars(ctx, tr) if err != nil { @@ -159,11 +159,20 @@ func (c *Reconciler) ReconcileKind(ctx context.Context, tr *v1beta1.TaskRun) pkg // Check if the TaskRun has timed out; if it is, this will set its status // accordingly. - if tr.HasTimedOut() { - message := fmt.Sprintf("TaskRun %q failed to finish within %q", tr.Name, tr.GetTimeout()) + if tr.HasTimedOut(ctx) { + message := fmt.Sprintf("TaskRun %q failed to finish within %q", tr.Name, tr.GetTimeout(ctx)) err := c.failTaskRun(ctx, tr, v1beta1.TaskRunReasonTimedOut, message) return c.finishReconcileUpdateEmitEvents(ctx, tr, before, err) } + defer func() { + if tr.Status.StartTime == nil { + return + } + // Compute the time since the task started. + elapsed := time.Since(tr.Status.StartTime.Time) + // Snooze this resource until the timeout has elapsed. + c.snooze(tr, tr.GetTimeout(ctx)-elapsed) + }() // prepare fetches all required resources, validates them together with the // taskrun, runs API convertions. Errors that come out of prepare are @@ -414,7 +423,6 @@ func (c *Reconciler) reconcile(ctx context.Context, tr *v1beta1.TaskRun, rtr *re logger.Errorf("Failed to create task run pod for taskrun %q: %v", tr.Name, newErr) return newErr } - go c.timeoutHandler.Wait(tr.GetNamespacedName(), *tr.Status.StartTime, *tr.Spec.Timeout) } if err := c.tracker.Track(tr.GetBuildPodRef(), tr); err != nil { @@ -497,16 +505,13 @@ func (c *Reconciler) updateLabelsAndAnnotations(ctx context.Context, tr *v1beta1 func (c *Reconciler) handlePodCreationError(ctx context.Context, tr *v1beta1.TaskRun, err error) error { switch { case isExceededResourceQuotaError(err): - backoff, currentlyBackingOff := c.timeoutHandler.GetBackoff(tr.GetNamespacedName(), *tr.Status.StartTime, *tr.Spec.Timeout) - if !currentlyBackingOff { - go c.timeoutHandler.SetTimer(tr.GetNamespacedName(), time.Until(backoff.NextAttempt)) - } - msg := fmt.Sprintf("TaskRun Pod exceeded available resources, reattempted %d times", backoff.NumAttempts) + // If we are struggling to create the pod, then it hasn't started. + tr.Status.StartTime = nil tr.Status.SetCondition(&apis.Condition{ Type: apis.ConditionSucceeded, Status: corev1.ConditionUnknown, Reason: podconvert.ReasonExceededResourceQuota, - Message: fmt.Sprintf("%s: %v", msg, err), + Message: fmt.Sprint("TaskRun Pod exceeded available resources: ", err), }) case isTaskRunValidationFailed(err): tr.Status.MarkResourceFailed(podconvert.ReasonFailedValidation, err) diff --git a/pkg/reconciler/taskrun/taskrun_test.go b/pkg/reconciler/taskrun/taskrun_test.go index 5ee5f47b85f..554331c402c 100644 --- a/pkg/reconciler/taskrun/taskrun_test.go +++ b/pkg/reconciler/taskrun/taskrun_test.go @@ -40,7 +40,6 @@ import ( ttesting "github.com/tektoncd/pipeline/pkg/reconciler/testing" "github.com/tektoncd/pipeline/pkg/reconciler/volumeclaim" "github.com/tektoncd/pipeline/pkg/system" - "github.com/tektoncd/pipeline/pkg/timeout" "github.com/tektoncd/pipeline/pkg/version" "github.com/tektoncd/pipeline/pkg/workspace" "github.com/tektoncd/pipeline/test" @@ -59,6 +58,7 @@ import ( "knative.dev/pkg/apis" "knative.dev/pkg/configmap" "knative.dev/pkg/controller" + "knative.dev/pkg/kmeta" "knative.dev/pkg/logging" pkgreconciler "knative.dev/pkg/reconciler" ) @@ -1748,8 +1748,8 @@ func TestReconcileInvalidTaskRuns(t *testing.T) { // Check actions and events actions := clients.Kube.Actions() - if len(actions) != 3 || actions[0].Matches("namespaces", "list") { - t.Errorf("expected 3 actions (first: list namespaces) created by the reconciler, got %d. Actions: %#v", len(actions), actions) + if len(actions) != 2 { + t.Errorf("expected 2 actions, got %d. Actions: %#v", len(actions), actions) } err := checkEvents(t, testAssets.Recorder, tc.name, tc.wantEvents) @@ -1805,8 +1805,8 @@ func TestReconcileTaskRunWithPermanentError(t *testing.T) { // Check actions actions := clients.Kube.Actions() - if len(actions) != 3 || actions[0].Matches("namespaces", "list") { - t.Errorf("expected 3 actions (list namespaces, list configmaps, and watch configmaps) created by the reconciler,"+ + if len(actions) != 2 || !actions[0].Matches("list", "configmaps") || !actions[1].Matches("watch", "configmaps") { + t.Errorf("expected 2 actions (list configmaps, and watch configmaps) created by the reconciler,"+ " got %d. Actions: %#v", len(actions), actions) } @@ -2183,16 +2183,15 @@ func TestHandlePodCreationError(t *testing.T) { taskLister: testAssets.Informers.Task.Lister(), clusterTaskLister: testAssets.Informers.ClusterTask.Lister(), resourceLister: testAssets.Informers.PipelineResource.Lister(), - timeoutHandler: timeout.NewHandler(ctx.Done(), testAssets.Logger), - cloudEventClient: testAssets.Clients.CloudEvents, - metrics: nil, // Not used - entrypointCache: nil, // Not used - pvcHandler: volumeclaim.NewPVCHandler(testAssets.Clients.Kube, testAssets.Logger), + snooze: func(acc kmeta.Accessor, amnt time.Duration) { + t.Error("Unexpected call to snooze.") + }, + cloudEventClient: testAssets.Clients.CloudEvents, + metrics: nil, // Not used + entrypointCache: nil, // Not used + pvcHandler: volumeclaim.NewPVCHandler(testAssets.Clients.Kube, testAssets.Logger), } - // Prevent backoff timer from starting - c.timeoutHandler.SetCallbackFunc(nil) - testcases := []struct { description string err error @@ -3234,11 +3233,13 @@ func TestFailTaskRun(t *testing.T) { taskLister: testAssets.Informers.Task.Lister(), clusterTaskLister: testAssets.Informers.ClusterTask.Lister(), resourceLister: testAssets.Informers.PipelineResource.Lister(), - timeoutHandler: nil, // Not used - cloudEventClient: testAssets.Clients.CloudEvents, - metrics: nil, // Not used - entrypointCache: nil, // Not used - pvcHandler: volumeclaim.NewPVCHandler(testAssets.Clients.Kube, testAssets.Logger), + snooze: func(acc kmeta.Accessor, amnt time.Duration) { + t.Error("Unexpected call to snooze.") + }, + cloudEventClient: testAssets.Clients.CloudEvents, + metrics: nil, // Not used + entrypointCache: nil, // Not used + pvcHandler: volumeclaim.NewPVCHandler(testAssets.Clients.Kube, testAssets.Logger), } err := c.failTaskRun(context.Background(), tc.taskRun, tc.reason, tc.message) diff --git a/pkg/timeout/handler.go b/pkg/timeout/handler.go deleted file mode 100644 index d96e081cd44..00000000000 --- a/pkg/timeout/handler.go +++ /dev/null @@ -1,281 +0,0 @@ -/* -Copyright 2020 The Tekton 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 timeout - -import ( - "context" - "math" - "math/rand" - "sync" - - "time" - - clientset "github.com/tektoncd/pipeline/pkg/client/clientset/versioned" - "github.com/tektoncd/pipeline/pkg/contexts" - "go.uber.org/zap" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" - "knative.dev/pkg/logging/logkey" -) - -const ( - maxBackoffSeconds = 120 -) - -var ( - maxBackoffExponent = math.Ceil(math.Log2(maxBackoffSeconds)) -) - -// StatusKey interface to be implemented by Taskrun Pipelinerun types -type StatusKey interface { - GetRunKey() string -} - -// Backoff contains state of exponential backoff for a given StatusKey -type Backoff struct { - // NumAttempts reflects the number of times a given StatusKey has been delayed - NumAttempts uint - // NextAttempt is the point in time at which this backoff expires - NextAttempt time.Time -} - -// jitterFunc is a func applied to a computed backoff duration to remove uniformity -// from its results. A jitterFunc receives the number of seconds calculated by a -// backoff algorithm and returns the "jittered" result. -type jitterFunc func(numSeconds int) (jitteredSeconds int) - -// Handler knows how to track channels that can be used to communicate with go routines -// which timeout, and the functions to call when that happens. -type Handler struct { - logger *zap.SugaredLogger - - // callbackFunc is the function to call when a run has timed out. - // This is usually set to the function that enqueues the namespaced name for reconciling. - callbackFunc func(types.NamespacedName) - // stopCh is used to signal to all goroutines that they should stop, e.g. because - // the reconciler is stopping - stopCh <-chan struct{} - // done is a map from the name of the Run to the channel to use to indicate that the - // Run is done (and so there is no need to wait on it any longer) - done map[string]chan bool - // doneMut is a mutex that protects access to done to ensure that multiple goroutines - // don't try to update it simultaneously - doneMut sync.Mutex - backoffs map[string]Backoff - backoffsMut sync.Mutex -} - -// NewHandler returns an instance of Handler with the specified stopCh and logger, instantiated -// and ready to track go routines. -func NewHandler( - stopCh <-chan struct{}, - logger *zap.SugaredLogger, -) *Handler { - return &Handler{ - stopCh: stopCh, - done: make(map[string]chan bool), - backoffs: make(map[string]Backoff), - logger: logger, - } -} - -// SetCallbackFunc sets the callback function when timeout occurs -func (t *Handler) SetCallbackFunc(f func(types.NamespacedName)) { - t.callbackFunc = f -} - -// Release deletes channels and data that are specific to a namespacedName -func (t *Handler) Release(n types.NamespacedName) { - t.doneMut.Lock() - defer t.doneMut.Unlock() - - t.backoffsMut.Lock() - defer t.backoffsMut.Unlock() - - if done, ok := t.done[n.String()]; ok { - delete(t.done, n.String()) - close(done) - } - delete(t.backoffs, n.String()) -} - -func (t *Handler) getOrCreateDoneChan(n types.NamespacedName) chan bool { - t.doneMut.Lock() - defer t.doneMut.Unlock() - var done chan bool - var ok bool - if done, ok = t.done[n.String()]; !ok { - done = make(chan bool) - } - t.done[n.String()] = done - return done -} - -// GetBackoff records the number of times it has seen n and calculates an -// appropriate backoff deadline based on that count. Only one backoff per n -// may be active at any moment. Requests for a new backoff in the face of an -// existing one will be ignored and details of the existing backoff will be returned -// instead. Further, if a calculated backoff time is after the timeout of the runKey -// then the time of the timeout will be returned instead. -// -// Returned values are a backoff struct containing a NumAttempts field with the -// number of attempts performed for this n and a NextAttempt field -// describing the time at which the next attempt should be performed. -// Additionally a boolean is returned indicating whether a backoff for n -// is already in progress. -func (t *Handler) GetBackoff(n types.NamespacedName, startTime metav1.Time, timeout metav1.Duration) (Backoff, bool) { - t.backoffsMut.Lock() - defer t.backoffsMut.Unlock() - b := t.backoffs[n.String()] - if time.Now().Before(b.NextAttempt) { - return b, true - } - b.NumAttempts++ - b.NextAttempt = time.Now().Add(backoffDuration(b.NumAttempts, rand.Intn)) - timeoutDeadline := startTime.Time.Add(timeout.Duration) - if timeoutDeadline.Before(b.NextAttempt) { - b.NextAttempt = timeoutDeadline - } - t.backoffs[n.String()] = b - return b, false -} - -func backoffDuration(count uint, jf jitterFunc) time.Duration { - exp := float64(count) - if exp > maxBackoffExponent { - exp = maxBackoffExponent - } - seconds := int(math.Exp2(exp)) - jittered := 1 + jf(seconds) - if jittered > maxBackoffSeconds { - jittered = maxBackoffSeconds - } - return time.Duration(jittered) * time.Second -} - -// checkPipelineRunTimeouts function creates goroutines to wait for pipelinerun to -// finish/timeout in a given namespace -func (t *Handler) checkPipelineRunTimeouts(ctx context.Context, namespace string, pipelineclientset clientset.Interface) { - pipelineRuns, err := pipelineclientset.TektonV1beta1().PipelineRuns(namespace).List(ctx, metav1.ListOptions{}) - if err != nil { - t.logger.Errorf("Can't get pipelinerun list in namespace %s: %s", namespace, err) - return - } - for _, pipelineRun := range pipelineRuns.Items { - pipelineRun := pipelineRun - pipelineRun.SetDefaults(contexts.WithUpgradeViaDefaulting(ctx)) - if pipelineRun.IsDone() || pipelineRun.IsCancelled() { - continue - } - if pipelineRun.HasStarted() { - go t.Wait(pipelineRun.GetNamespacedName(), *pipelineRun.Status.StartTime, *pipelineRun.Spec.Timeout) - } - } -} - -// CheckTimeouts function iterates through a given namespace or all namespaces -// (if empty string) and calls corresponding taskrun/pipelinerun timeout functions -func (t *Handler) CheckTimeouts(ctx context.Context, namespace string, kubeclientset kubernetes.Interface, pipelineclientset clientset.Interface) { - // scoped namespace - namespaceNames := []string{namespace} - // all namespaces - if namespace == "" { - namespaces, err := kubeclientset.CoreV1().Namespaces().List(ctx, metav1.ListOptions{}) - if err != nil { - t.logger.Errorf("Can't get namespaces list: %s", err) - return - } - namespaceNames = make([]string, len(namespaces.Items)) - for i, namespace := range namespaces.Items { - namespaceNames[i] = namespace.GetName() - } - } - - for _, namespace := range namespaceNames { - t.checkTaskRunTimeouts(ctx, namespace, pipelineclientset) - t.checkPipelineRunTimeouts(ctx, namespace, pipelineclientset) - } -} - -// checkTaskRunTimeouts function creates goroutines to wait for pipelinerun to -// finish/timeout in a given namespace -func (t *Handler) checkTaskRunTimeouts(ctx context.Context, namespace string, pipelineclientset clientset.Interface) { - taskruns, err := pipelineclientset.TektonV1beta1().TaskRuns(namespace).List(ctx, metav1.ListOptions{}) - if err != nil { - t.logger.Errorf("Can't get taskrun list in namespace %s: %s", namespace, err) - return - } - for _, taskrun := range taskruns.Items { - taskrun := taskrun - taskrun.SetDefaults(contexts.WithUpgradeViaDefaulting(ctx)) - if taskrun.IsDone() || taskrun.IsCancelled() { - continue - } - if taskrun.HasStarted() { - go t.Wait(taskrun.GetNamespacedName(), *taskrun.Status.StartTime, *taskrun.Spec.Timeout) - } - } -} - -// Wait creates a blocking function for n to wait for -// 1. Stop signal, 2. Completion 3. Or duration to elapse since startTime -// time out, which is determined by checking if the timeout has occurred since the startTime -func (t *Handler) Wait(n types.NamespacedName, startTime metav1.Time, timeout metav1.Duration) { - logger := t.logger.With(zap.String(logkey.Key, n.String())) - if t.callbackFunc == nil { - logger.Errorf("somehow the timeout handler was not initialized with a callback function") - return - } - runtime := time.Since(startTime.Time) - logger.Infof("About to start timeout timer for %s. started at %s, timeout is %s, running for %s", n.String(), startTime.Time, timeout, runtime) - defer t.Release(n) - t.setTimer(n, timeout.Duration-runtime, t.callbackFunc) -} - -// SetTimer creates a blocking function for n to wait for -// 1. Stop signal, 2. TaskRun to complete or 3. a given Duration to elapse. -// -// Since the timer's duration is a parameter rather than being tied to -// the lifetime of the run object no resources are released after the timer -// fires. It is the caller's responsibility to Release() the run when -// work with it has completed. -func (t *Handler) SetTimer(n types.NamespacedName, d time.Duration) { - logger := t.logger.With(zap.String(logkey.Key, n.String())) - if t.callbackFunc == nil { - logger.Errorf("somehow the timeout handler was not initialized with a callback function") - return - } - t.setTimer(n, d, t.callbackFunc) -} - -func (t *Handler) setTimer(n types.NamespacedName, timeout time.Duration, callback func(types.NamespacedName)) { - logger := t.logger.With(zap.String(logkey.Key, n.String())) - done := t.getOrCreateDoneChan(n) - started := time.Now() - select { - case <-t.stopCh: - logger.Infof("stopping timer for %q", n.String()) - return - case <-done: - logger.Infof("%q finished, stopping timer", n.String()) - return - case <-time.After(timeout): - logger.Infof("timer for %q has activated after %s", n.String(), time.Since(started).String()) - callback(n) - } -} diff --git a/pkg/timeout/handler_test.go b/pkg/timeout/handler_test.go deleted file mode 100644 index afa809bc306..00000000000 --- a/pkg/timeout/handler_test.go +++ /dev/null @@ -1,463 +0,0 @@ -/* -Copyright 2020 The Tekton 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 timeout - -import ( - "context" - "fmt" - "sync" - "testing" - "time" - - tb "github.com/tektoncd/pipeline/internal/builder/v1beta1" - "github.com/tektoncd/pipeline/pkg/apis/config" - "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1" - ttesting "github.com/tektoncd/pipeline/pkg/reconciler/testing" - test "github.com/tektoncd/pipeline/test" - "go.uber.org/zap" - "go.uber.org/zap/zaptest/observer" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/wait" - "knative.dev/pkg/apis" -) - -var ( - allNs = "" - testNs = "foo" - simpleStep = tb.Step(testNs, tb.StepCommand("/mycmd")) - simpleTask = tb.Task("test-task", tb.TaskSpec(simpleStep)) -) - -func TestTaskRunCheckTimeouts(t *testing.T) { - taskRunTimedout := tb.TaskRun("test-taskrun-run-timedout", tb.TaskRunNamespace(testNs), tb.TaskRunSpec( - tb.TaskRunTaskRef(simpleTask.Name, tb.TaskRefAPIVersion("a1")), - tb.TaskRunTimeout(1*time.Second), - ), tb.TaskRunStatus(tb.StatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - tb.TaskRunStartTime(time.Now().Add(-10*time.Second)), - )) - - taskRunRunning := tb.TaskRun("test-taskrun-running", tb.TaskRunNamespace(testNs), tb.TaskRunSpec( - tb.TaskRunTaskRef(simpleTask.Name, tb.TaskRefAPIVersion("a1")), - tb.TaskRunTimeout(config.DefaultTimeoutMinutes*time.Minute), - ), tb.TaskRunStatus(tb.StatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - tb.TaskRunStartTime(time.Now()), - )) - - taskRunRunningNilTimeout := tb.TaskRun("test-taskrun-running-nil-timeout", tb.TaskRunNamespace(testNs), tb.TaskRunSpec( - tb.TaskRunTaskRef(simpleTask.Name, tb.TaskRefAPIVersion("a1")), - tb.TaskRunNilTimeout, - ), tb.TaskRunStatus(tb.StatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - tb.TaskRunStartTime(time.Now()), - )) - - taskRunDone := tb.TaskRun("test-taskrun-completed", tb.TaskRunNamespace(testNs), tb.TaskRunSpec( - tb.TaskRunTaskRef(simpleTask.Name, tb.TaskRefAPIVersion("a1")), - tb.TaskRunTimeout(config.DefaultTimeoutMinutes*time.Minute), - ), tb.TaskRunStatus(tb.StatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionTrue}), - )) - - taskRunCancelled := tb.TaskRun("test-taskrun-run-cancelled", tb.TaskRunNamespace(testNs), tb.TaskRunSpec( - tb.TaskRunTaskRef(simpleTask.Name), - tb.TaskRunCancelled, - tb.TaskRunTimeout(1*time.Second), - ), tb.TaskRunStatus(tb.StatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - )) - - d := test.Data{ - TaskRuns: []*v1beta1.TaskRun{taskRunTimedout, taskRunRunning, taskRunDone, taskRunCancelled, taskRunRunningNilTimeout}, - Tasks: []*v1beta1.Task{simpleTask}, - Namespaces: []*corev1.Namespace{{ - ObjectMeta: metav1.ObjectMeta{ - Name: testNs, - }, - }}, - } - ctx, _ := ttesting.SetupFakeContext(t) - c, _ := test.SeedTestData(t, ctx, d) - stopCh := make(chan struct{}) - defer close(stopCh) - observer, _ := observer.New(zap.InfoLevel) - - th := NewHandler(stopCh, zap.New(observer).Sugar()) - gotCallback := sync.Map{} - f := func(n types.NamespacedName) { - gotCallback.Store(n.Name, struct{}{}) - } - - th.SetCallbackFunc(f) - go th.CheckTimeouts(context.Background(), testNs, c.Kube, c.Pipeline) - - for _, tc := range []struct { - name string - taskRun *v1beta1.TaskRun - expectCallback bool - }{{ - name: "timedout", - taskRun: taskRunTimedout, - expectCallback: true, - }, { - name: "running", - taskRun: taskRunRunning, - expectCallback: false, - }, { - name: "running-with-nil-timeout", - taskRun: taskRunRunningNilTimeout, - expectCallback: false, - }, { - name: "completed", - taskRun: taskRunDone, - expectCallback: false, - }, { - name: "cancelled", - taskRun: taskRunCancelled, - expectCallback: false, - }} { - t.Run(tc.name, func(t *testing.T) { - if err := wait.PollImmediate(100*time.Millisecond, 3*time.Second, func() (bool, error) { - if tc.expectCallback { - if _, ok := gotCallback.Load(tc.taskRun.Name); ok { - return true, nil - } - return false, nil - } - // not expecting callback - if _, ok := gotCallback.Load(tc.taskRun.Name); ok { - return false, fmt.Errorf("did not expect call back for %s why", tc.taskRun.Name) - } - return true, nil - }); err != nil { - t.Fatalf("Expected %s callback to be %t but got error: %s", tc.name, tc.expectCallback, err) - } - }) - } - -} - -func TestTaskRunSingleNamespaceCheckTimeouts(t *testing.T) { - taskRunTimedout := tb.TaskRun("test-taskrun-run-timedout-foo", tb.TaskRunNamespace(testNs), tb.TaskRunSpec( - tb.TaskRunTaskRef(simpleTask.Name, tb.TaskRefAPIVersion("a1")), - tb.TaskRunTimeout(1*time.Second), - ), tb.TaskRunStatus(tb.StatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - tb.TaskRunStartTime(time.Now().Add(-10*time.Second)), - )) - - taskRunTimedoutOtherNS := tb.TaskRun("test-taskrun-run-timedout-bar", tb.TaskRunNamespace("otherNS"), tb.TaskRunSpec( - tb.TaskRunTaskRef(simpleTask.Name, tb.TaskRefAPIVersion("a1")), - tb.TaskRunTimeout(1*time.Second), - ), tb.TaskRunStatus(tb.StatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - tb.TaskRunStartTime(time.Now().Add(-10*time.Second)), - )) - - d := test.Data{ - TaskRuns: []*v1beta1.TaskRun{taskRunTimedout, taskRunTimedoutOtherNS}, - Tasks: []*v1beta1.Task{simpleTask}, - Namespaces: []*corev1.Namespace{{ - ObjectMeta: metav1.ObjectMeta{ - Name: testNs, - }, - }}, - } - ctx, _ := ttesting.SetupFakeContext(t) - c, _ := test.SeedTestData(t, ctx, d) - stopCh := make(chan struct{}) - defer close(stopCh) - observer, _ := observer.New(zap.InfoLevel) - - th := NewHandler(stopCh, zap.New(observer).Sugar()) - gotCallback := sync.Map{} - f := func(n types.NamespacedName) { - gotCallback.Store(n.Name, struct{}{}) - } - - th.SetCallbackFunc(f) - // Note that since f843899a11d5d09b29fac750f72f4a7e4882f615 CheckTimeouts is always called - // with a namespace so there is no reason to maintain all namespaces functionality; - // however in #2905 we should remove CheckTimeouts completely - go th.CheckTimeouts(context.Background(), "", c.Kube, c.Pipeline) - - for _, tc := range []struct { - name string - taskRun *v1beta1.TaskRun - expectCallback bool - }{{ - name: "timedout", - taskRun: taskRunTimedout, - expectCallback: true, - }, { - name: "timedout", - taskRun: taskRunTimedoutOtherNS, - expectCallback: false, - }} { - t.Run(tc.name, func(t *testing.T) { - if err := wait.PollImmediate(100*time.Millisecond, 3*time.Second, func() (bool, error) { - if tc.expectCallback { - if _, ok := gotCallback.Load(tc.taskRun.Name); ok { - return true, nil - } - return false, nil - } - // not expecting callback - if _, ok := gotCallback.Load(tc.taskRun.Name); ok { - return false, fmt.Errorf("did not expect call back for %s why", tc.taskRun.Name) - } - return true, nil - }); err != nil { - t.Fatalf("Expected %s callback to be %t but got error: %s", tc.name, tc.expectCallback, err) - } - }) - } - -} - -func TestPipelinRunCheckTimeouts(t *testing.T) { - simplePipeline := tb.Pipeline("test-pipeline", tb.PipelineNamespace(testNs), tb.PipelineSpec( - tb.PipelineTask("hello-world-1", "hello-world"), - )) - prTimeout := tb.PipelineRun("test-pipeline-run-with-timeout", tb.PipelineRunNamespace(testNs), - tb.PipelineRunSpec("test-pipeline", - tb.PipelineRunServiceAccountName("test-sa"), - tb.PipelineRunTimeout(1*time.Second), - ), - tb.PipelineRunStatus( - tb.PipelineRunStartTime(time.Now().AddDate(0, 0, -1))), - ) - ts := tb.Task("hello-world") - - prRunning := tb.PipelineRun("test-pipeline-running", tb.PipelineRunNamespace(testNs), - tb.PipelineRunSpec("test-pipeline", - tb.PipelineRunTimeout(config.DefaultTimeoutMinutes*time.Minute), - ), - tb.PipelineRunStatus(tb.PipelineRunStatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - tb.PipelineRunStartTime(time.Now()), - ), - ) - prRunningNilTimeout := tb.PipelineRun("test-pipeline-running-nil-timeout", tb.PipelineRunNamespace(testNs), - tb.PipelineRunSpec("test-pipeline", - tb.PipelineRunNilTimeout, - ), - tb.PipelineRunStatus(tb.PipelineRunStatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - tb.PipelineRunStartTime(time.Now()), - ), - ) - prDone := tb.PipelineRun("test-pipeline-done", tb.PipelineRunNamespace(testNs), - tb.PipelineRunSpec("test-pipeline", - tb.PipelineRunTimeout(config.DefaultTimeoutMinutes*time.Minute), - ), - tb.PipelineRunStatus(tb.PipelineRunStatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionTrue}), - ), - ) - prCancelled := tb.PipelineRun("test-pipeline-cancel", tb.PipelineRunNamespace(testNs), - tb.PipelineRunSpec("test-pipeline", tb.PipelineRunServiceAccountName("test-sa"), - tb.PipelineRunCancelled, - tb.PipelineRunTimeout(config.DefaultTimeoutMinutes*time.Minute), - ), - tb.PipelineRunStatus(tb.PipelineRunStatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - ), - ) - d := test.Data{ - PipelineRuns: []*v1beta1.PipelineRun{prTimeout, prRunning, prDone, prCancelled, prRunningNilTimeout}, - Pipelines: []*v1beta1.Pipeline{simplePipeline}, - Tasks: []*v1beta1.Task{ts}, - Namespaces: []*corev1.Namespace{{ - ObjectMeta: metav1.ObjectMeta{ - Name: testNs, - }, - }}, - } - - ctx, _ := ttesting.SetupFakeContext(t) - c, _ := test.SeedTestData(t, ctx, d) - stopCh := make(chan struct{}) - defer close(stopCh) - observer, _ := observer.New(zap.InfoLevel) - th := NewHandler(stopCh, zap.New(observer).Sugar()) - - gotCallback := sync.Map{} - f := func(n types.NamespacedName) { - gotCallback.Store(n.Name, struct{}{}) - } - - th.SetCallbackFunc(f) - go th.CheckTimeouts(context.Background(), allNs, c.Kube, c.Pipeline) - for _, tc := range []struct { - name string - pr *v1beta1.PipelineRun - expectCallback bool - }{{ - name: "pr-running", - pr: prRunning, - expectCallback: false, - }, { - name: "pr-running-nil-timeout", - pr: prRunningNilTimeout, - expectCallback: false, - }, { - name: "pr-timedout", - pr: prTimeout, - expectCallback: true, - }, { - name: "pr-completed", - pr: prDone, - expectCallback: false, - }, { - name: "pr-cancel", - pr: prCancelled, - expectCallback: false, - }} { - t.Run(tc.name, func(t *testing.T) { - if err := wait.PollImmediate(1*time.Second, 5*time.Second, func() (bool, error) { - if tc.expectCallback { - if _, ok := gotCallback.Load(tc.pr.Name); ok { - return true, nil - } - return false, nil - } - // not expecting callback - if _, ok := gotCallback.Load(tc.pr.Name); ok { - return false, fmt.Errorf("did not expect call back for %s why", tc.pr.Name) - } - return true, nil - }); err != nil { - t.Fatalf("Expected %s callback to be %t but got error: %s", tc.name, tc.expectCallback, err) - } - }) - } -} - -// TestWithNoFunc does not set taskrun/pipelinerun function and verifies that code does not panic -func TestWithNoFunc(t *testing.T) { - taskRunRunning := tb.TaskRun("test-taskrun-running", tb.TaskRunNamespace(testNs), tb.TaskRunSpec( - tb.TaskRunTaskRef(simpleTask.Name, tb.TaskRefAPIVersion("a1")), - tb.TaskRunTimeout(2*time.Second), - ), tb.TaskRunStatus(tb.StatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - tb.TaskRunStartTime(time.Now().Add(-10*time.Second)), - )) - - d := test.Data{ - TaskRuns: []*v1beta1.TaskRun{taskRunRunning}, - Tasks: []*v1beta1.Task{simpleTask}, - Namespaces: []*corev1.Namespace{{ - ObjectMeta: metav1.ObjectMeta{ - Name: testNs, - }, - }}, - } - ctx, _ := ttesting.SetupFakeContext(t) - c, _ := test.SeedTestData(t, ctx, d) - stopCh := make(chan struct{}) - observer, _ := observer.New(zap.InfoLevel) - testHandler := NewHandler(stopCh, zap.New(observer).Sugar()) - defer func() { - // this delay will ensure there is no race condition between stopCh/ timeout channel getting triggered - time.Sleep(10 * time.Millisecond) - close(stopCh) - if r := recover(); r != nil { - t.Fatal("Expected CheckTimeouts function not to panic") - } - }() - go testHandler.CheckTimeouts(context.Background(), allNs, c.Kube, c.Pipeline) - -} - -// TestSetTaskRunTimer checks that the SetTaskRunTimer method correctly calls the TaskRun -// callback after a set amount of time. -func TestSetTaskRunTimer(t *testing.T) { - taskRun := tb.TaskRun("test-taskrun-arbitrary-timer", tb.TaskRunNamespace(testNs), tb.TaskRunSpec( - tb.TaskRunTaskRef(simpleTask.Name, tb.TaskRefAPIVersion("a1")), - tb.TaskRunTimeout(50*time.Millisecond), - ), tb.TaskRunStatus(tb.StatusCondition(apis.Condition{ - Type: apis.ConditionSucceeded, - Status: corev1.ConditionUnknown}), - tb.TaskRunStartTime(time.Now().Add(-10*time.Second)), - )) - - stopCh := make(chan struct{}) - observer, _ := observer.New(zap.InfoLevel) - testHandler := NewHandler(stopCh, zap.New(observer).Sugar()) - timerDuration := 50 * time.Millisecond - timerFailDeadline := 100 * time.Millisecond - doneCh := make(chan struct{}) - f := func(_ types.NamespacedName) { - close(doneCh) - } - testHandler.SetCallbackFunc(f) - go testHandler.SetTimer(taskRun.GetNamespacedName(), timerDuration) - select { - case <-doneCh: - // The task run timer executed before the failure deadline - case <-time.After(timerFailDeadline): - t.Errorf("timer did not execute task run callback func within expected time") - } -} - -// TestBackoffDuration asserts that the backoffDuration func returns Durations -// within the timeout handler's bounds. -func TestBackoffDuration(t *testing.T) { - testcases := []struct { - description string - inputCount uint - jitterFunc func(int) int - expectedDuration time.Duration - }{ - { - description: "an input count that is too large is rounded to the maximum allowed exponent", - inputCount: uint(maxBackoffExponent + 1), - jitterFunc: func(in int) int { return in }, - expectedDuration: maxBackoffSeconds * time.Second, - }, - { - description: "a jittered number of seconds that is above the maximum allowed is constrained", - inputCount: 1, - jitterFunc: func(in int) int { return maxBackoffSeconds + 1 }, - expectedDuration: maxBackoffSeconds * time.Second, - }, - } - for _, tc := range testcases { - t.Run(tc.description, func(t *testing.T) { - result := backoffDuration(tc.inputCount, tc.jitterFunc) - if result != tc.expectedDuration { - t.Errorf("expected %q received %q", tc.expectedDuration.String(), result.String()) - } - }) - } -} diff --git a/third_party/LICENSE b/third_party/LICENSE deleted file mode 100644 index 6a66aea5eaf..00000000000 --- a/third_party/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/github.com/PuerkitoBio/purell/LICENSE b/third_party/github.com/PuerkitoBio/purell/LICENSE new file mode 100644 index 00000000000..4b9986dea71 --- /dev/null +++ b/third_party/github.com/PuerkitoBio/purell/LICENSE @@ -0,0 +1,12 @@ +Copyright (c) 2012, Martin Angers +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/vendor/golang.org/x/net/LICENSE b/third_party/github.com/PuerkitoBio/urlesc/LICENSE similarity index 96% rename from third_party/vendor/golang.org/x/net/LICENSE rename to third_party/github.com/PuerkitoBio/urlesc/LICENSE index 6a66aea5eaf..74487567632 100644 --- a/third_party/vendor/golang.org/x/net/LICENSE +++ b/third_party/github.com/PuerkitoBio/urlesc/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. +Copyright (c) 2012 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are diff --git a/third_party/github.com/emicklei/go-restful/LICENSE b/third_party/github.com/emicklei/go-restful/LICENSE new file mode 100644 index 00000000000..ece7ec61eff --- /dev/null +++ b/third_party/github.com/emicklei/go-restful/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012,2013 Ernest Micklei + +MIT License + +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/third_party/k8s.io/kube-openapi/pkg/util/proto/LICENSE b/third_party/github.com/go-openapi/jsonpointer/LICENSE similarity index 100% rename from third_party/k8s.io/kube-openapi/pkg/util/proto/LICENSE rename to third_party/github.com/go-openapi/jsonpointer/LICENSE diff --git a/third_party/github.com/go-openapi/jsonreference/LICENSE b/third_party/github.com/go-openapi/jsonreference/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/third_party/github.com/go-openapi/jsonreference/LICENSE @@ -0,0 +1,202 @@ + + 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/third_party/github.com/go-openapi/spec/LICENSE b/third_party/github.com/go-openapi/spec/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/third_party/github.com/go-openapi/spec/LICENSE @@ -0,0 +1,202 @@ + + 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/third_party/github.com/go-openapi/swag/LICENSE b/third_party/github.com/go-openapi/swag/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/third_party/github.com/go-openapi/swag/LICENSE @@ -0,0 +1,202 @@ + + 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/third_party/github.com/hashicorp/errwrap/errwrap_test.go b/third_party/github.com/hashicorp/errwrap/errwrap_test.go new file mode 100644 index 00000000000..5ae5f8e3cde --- /dev/null +++ b/third_party/github.com/hashicorp/errwrap/errwrap_test.go @@ -0,0 +1,94 @@ +package errwrap + +import ( + "fmt" + "testing" +) + +func TestWrappedError_impl(t *testing.T) { + var _ error = new(wrappedError) +} + +func TestGetAll(t *testing.T) { + cases := []struct { + Err error + Msg string + Len int + }{ + {}, + { + fmt.Errorf("foo"), + "foo", + 1, + }, + { + fmt.Errorf("bar"), + "foo", + 0, + }, + { + Wrapf("bar", fmt.Errorf("foo")), + "foo", + 1, + }, + { + Wrapf("{{err}}", fmt.Errorf("foo")), + "foo", + 2, + }, + { + Wrapf("bar", Wrapf("baz", fmt.Errorf("foo"))), + "foo", + 1, + }, + } + + for i, tc := range cases { + actual := GetAll(tc.Err, tc.Msg) + if len(actual) != tc.Len { + t.Fatalf("%d: bad: %#v", i, actual) + } + for _, v := range actual { + if v.Error() != tc.Msg { + t.Fatalf("%d: bad: %#v", i, actual) + } + } + } +} + +func TestGetAllType(t *testing.T) { + cases := []struct { + Err error + Type interface{} + Len int + }{ + {}, + { + fmt.Errorf("foo"), + "foo", + 0, + }, + { + fmt.Errorf("bar"), + fmt.Errorf("foo"), + 1, + }, + { + Wrapf("bar", fmt.Errorf("foo")), + fmt.Errorf("baz"), + 2, + }, + { + Wrapf("bar", Wrapf("baz", fmt.Errorf("foo"))), + Wrapf("", nil), + 0, + }, + } + + for i, tc := range cases { + actual := GetAllType(tc.Err, tc.Type) + if len(actual) != tc.Len { + t.Fatalf("%d: bad: %#v", i, actual) + } + } +} diff --git a/third_party/github.com/hashicorp/go-multierror/append_test.go b/third_party/github.com/hashicorp/go-multierror/append_test.go new file mode 100644 index 00000000000..58ddafa8dde --- /dev/null +++ b/third_party/github.com/hashicorp/go-multierror/append_test.go @@ -0,0 +1,82 @@ +package multierror + +import ( + "errors" + "testing" +) + +func TestAppend_Error(t *testing.T) { + original := &Error{ + Errors: []error{errors.New("foo")}, + } + + result := Append(original, errors.New("bar")) + if len(result.Errors) != 2 { + t.Fatalf("wrong len: %d", len(result.Errors)) + } + + original = &Error{} + result = Append(original, errors.New("bar")) + if len(result.Errors) != 1 { + t.Fatalf("wrong len: %d", len(result.Errors)) + } + + // Test when a typed nil is passed + var e *Error + result = Append(e, errors.New("baz")) + if len(result.Errors) != 1 { + t.Fatalf("wrong len: %d", len(result.Errors)) + } + + // Test flattening + original = &Error{ + Errors: []error{errors.New("foo")}, + } + + result = Append(original, Append(nil, errors.New("foo"), errors.New("bar"))) + if len(result.Errors) != 3 { + t.Fatalf("wrong len: %d", len(result.Errors)) + } +} + +func TestAppend_NilError(t *testing.T) { + var err error + result := Append(err, errors.New("bar")) + if len(result.Errors) != 1 { + t.Fatalf("wrong len: %d", len(result.Errors)) + } +} + +func TestAppend_NilErrorArg(t *testing.T) { + var err error + var nilErr *Error + result := Append(err, nilErr) + if len(result.Errors) != 0 { + t.Fatalf("wrong len: %d", len(result.Errors)) + } +} + +func TestAppend_NilErrorIfaceArg(t *testing.T) { + var err error + var nilErr error + result := Append(err, nilErr) + if len(result.Errors) != 0 { + t.Fatalf("wrong len: %d", len(result.Errors)) + } +} + +func TestAppend_NonError(t *testing.T) { + original := errors.New("foo") + result := Append(original, errors.New("bar")) + if len(result.Errors) != 2 { + t.Fatalf("wrong len: %d", len(result.Errors)) + } +} + +func TestAppend_NonError_Error(t *testing.T) { + original := errors.New("foo") + result := Append(original, Append(nil, errors.New("bar"))) + if len(result.Errors) != 2 { + t.Fatalf("wrong len: %d", len(result.Errors)) + } +} diff --git a/third_party/github.com/hashicorp/go-multierror/flatten_test.go b/third_party/github.com/hashicorp/go-multierror/flatten_test.go new file mode 100644 index 00000000000..e99c4101b5b --- /dev/null +++ b/third_party/github.com/hashicorp/go-multierror/flatten_test.go @@ -0,0 +1,46 @@ +package multierror + +import ( + "errors" + "fmt" + "reflect" + "testing" +) + +func TestFlatten(t *testing.T) { + original := &Error{ + Errors: []error{ + errors.New("one"), + &Error{ + Errors: []error{ + errors.New("two"), + &Error{ + Errors: []error{ + errors.New("three"), + }, + }, + }, + }, + }, + } + + expected := `3 errors occurred: + * one + * two + * three + +` + actual := fmt.Sprintf("%s", Flatten(original)) + + if expected != actual { + t.Fatalf("expected: %s, got: %s", expected, actual) + } +} + +func TestFlatten_nonError(t *testing.T) { + err := errors.New("foo") + actual := Flatten(err) + if !reflect.DeepEqual(actual, err) { + t.Fatalf("bad: %#v", actual) + } +} diff --git a/third_party/github.com/hashicorp/go-multierror/format_test.go b/third_party/github.com/hashicorp/go-multierror/format_test.go new file mode 100644 index 00000000000..2b6da1defcd --- /dev/null +++ b/third_party/github.com/hashicorp/go-multierror/format_test.go @@ -0,0 +1,40 @@ +package multierror + +import ( + "errors" + "testing" +) + +func TestListFormatFuncSingle(t *testing.T) { + expected := `1 error occurred: + * foo + +` + + errors := []error{ + errors.New("foo"), + } + + actual := ListFormatFunc(errors) + if actual != expected { + t.Fatalf("bad: %#v", actual) + } +} + +func TestListFormatFuncMultiple(t *testing.T) { + expected := `2 errors occurred: + * foo + * bar + +` + + errors := []error{ + errors.New("foo"), + errors.New("bar"), + } + + actual := ListFormatFunc(errors) + if actual != expected { + t.Fatalf("bad: %#v", actual) + } +} diff --git a/third_party/github.com/hashicorp/go-multierror/group_test.go b/third_party/github.com/hashicorp/go-multierror/group_test.go new file mode 100644 index 00000000000..9d472fd6655 --- /dev/null +++ b/third_party/github.com/hashicorp/go-multierror/group_test.go @@ -0,0 +1,44 @@ +package multierror + +import ( + "errors" + "strings" + "testing" +) + +func TestGroup(t *testing.T) { + err1 := errors.New("group_test: 1") + err2 := errors.New("group_test: 2") + + cases := []struct { + errs []error + nilResult bool + }{ + {errs: []error{}, nilResult: true}, + {errs: []error{nil}, nilResult: true}, + {errs: []error{err1}}, + {errs: []error{err1, nil}}, + {errs: []error{err1, nil, err2}}, + } + + for _, tc := range cases { + var g Group + + for _, err := range tc.errs { + err := err + g.Go(func() error { return err }) + + } + + gErr := g.Wait() + if gErr != nil { + for i := range tc.errs { + if tc.errs[i] != nil && !strings.Contains(gErr.Error(), tc.errs[i].Error()) { + t.Fatalf("expected error to contain %q, actual: %v", tc.errs[i].Error(), gErr) + } + } + } else if !tc.nilResult { + t.Fatalf("Group.Wait() should not have returned nil for errs: %v", tc.errs) + } + } +} diff --git a/third_party/github.com/hashicorp/go-multierror/multierror_test.go b/third_party/github.com/hashicorp/go-multierror/multierror_test.go new file mode 100644 index 00000000000..972c52d00d6 --- /dev/null +++ b/third_party/github.com/hashicorp/go-multierror/multierror_test.go @@ -0,0 +1,203 @@ +package multierror + +import ( + "errors" + "fmt" + "reflect" + "testing" +) + +func TestError_Impl(t *testing.T) { + var _ error = new(Error) +} + +func TestErrorError_custom(t *testing.T) { + errors := []error{ + errors.New("foo"), + errors.New("bar"), + } + + fn := func(es []error) string { + return "foo" + } + + multi := &Error{Errors: errors, ErrorFormat: fn} + if multi.Error() != "foo" { + t.Fatalf("bad: %s", multi.Error()) + } +} + +func TestErrorError_default(t *testing.T) { + expected := `2 errors occurred: + * foo + * bar + +` + + errors := []error{ + errors.New("foo"), + errors.New("bar"), + } + + multi := &Error{Errors: errors} + if multi.Error() != expected { + t.Fatalf("bad: %s", multi.Error()) + } +} + +func TestErrorErrorOrNil(t *testing.T) { + err := new(Error) + if err.ErrorOrNil() != nil { + t.Fatalf("bad: %#v", err.ErrorOrNil()) + } + + err.Errors = []error{errors.New("foo")} + if v := err.ErrorOrNil(); v == nil { + t.Fatal("should not be nil") + } else if !reflect.DeepEqual(v, err) { + t.Fatalf("bad: %#v", v) + } +} + +func TestErrorWrappedErrors(t *testing.T) { + errors := []error{ + errors.New("foo"), + errors.New("bar"), + } + + multi := &Error{Errors: errors} + if !reflect.DeepEqual(multi.Errors, multi.WrappedErrors()) { + t.Fatalf("bad: %s", multi.WrappedErrors()) + } +} + +func TestErrorUnwrap(t *testing.T) { + t.Run("with errors", func(t *testing.T) { + err := &Error{Errors: []error{ + errors.New("foo"), + errors.New("bar"), + errors.New("baz"), + }} + + var current error = err + for i := 0; i < len(err.Errors); i++ { + current = errors.Unwrap(current) + if !errors.Is(current, err.Errors[i]) { + t.Fatal("should be next value") + } + } + + if errors.Unwrap(current) != nil { + t.Fatal("should be nil at the end") + } + }) + + t.Run("with no errors", func(t *testing.T) { + err := &Error{Errors: nil} + if errors.Unwrap(err) != nil { + t.Fatal("should be nil") + } + }) + + t.Run("with nil multierror", func(t *testing.T) { + var err *Error + if errors.Unwrap(err) != nil { + t.Fatal("should be nil") + } + }) +} + +func TestErrorIs(t *testing.T) { + errBar := errors.New("bar") + + t.Run("with errBar", func(t *testing.T) { + err := &Error{Errors: []error{ + errors.New("foo"), + errBar, + errors.New("baz"), + }} + + if !errors.Is(err, errBar) { + t.Fatal("should be true") + } + }) + + t.Run("with errBar wrapped by fmt.Errorf", func(t *testing.T) { + err := &Error{Errors: []error{ + errors.New("foo"), + fmt.Errorf("errorf: %w", errBar), + errors.New("baz"), + }} + + if !errors.Is(err, errBar) { + t.Fatal("should be true") + } + }) + + t.Run("without errBar", func(t *testing.T) { + err := &Error{Errors: []error{ + errors.New("foo"), + errors.New("baz"), + }} + + if errors.Is(err, errBar) { + t.Fatal("should be false") + } + }) +} + +func TestErrorAs(t *testing.T) { + match := &nestedError{} + + t.Run("with the value", func(t *testing.T) { + err := &Error{Errors: []error{ + errors.New("foo"), + match, + errors.New("baz"), + }} + + var target *nestedError + if !errors.As(err, &target) { + t.Fatal("should be true") + } + if target == nil { + t.Fatal("target should not be nil") + } + }) + + t.Run("with the value wrapped by fmt.Errorf", func(t *testing.T) { + err := &Error{Errors: []error{ + errors.New("foo"), + fmt.Errorf("errorf: %w", match), + errors.New("baz"), + }} + + var target *nestedError + if !errors.As(err, &target) { + t.Fatal("should be true") + } + if target == nil { + t.Fatal("target should not be nil") + } + }) + + t.Run("without the value", func(t *testing.T) { + err := &Error{Errors: []error{ + errors.New("foo"), + errors.New("baz"), + }} + + var target *nestedError + if errors.As(err, &target) { + t.Fatal("should be false") + } + if target != nil { + t.Fatal("target should be nil") + } + }) +} + +// nestedError implements error and is used for tests. +type nestedError struct{} + +func (*nestedError) Error() string { return "" } diff --git a/third_party/github.com/hashicorp/go-multierror/prefix_test.go b/third_party/github.com/hashicorp/go-multierror/prefix_test.go new file mode 100644 index 00000000000..1d4a6f6d333 --- /dev/null +++ b/third_party/github.com/hashicorp/go-multierror/prefix_test.go @@ -0,0 +1,33 @@ +package multierror + +import ( + "errors" + "testing" +) + +func TestPrefix_Error(t *testing.T) { + original := &Error{ + Errors: []error{errors.New("foo")}, + } + + result := Prefix(original, "bar") + if result.(*Error).Errors[0].Error() != "bar foo" { + t.Fatalf("bad: %s", result) + } +} + +func TestPrefix_NilError(t *testing.T) { + var err error + result := Prefix(err, "bar") + if result != nil { + t.Fatalf("bad: %#v", result) + } +} + +func TestPrefix_NonError(t *testing.T) { + original := errors.New("foo") + result := Prefix(original, "bar") + if result.Error() != "bar foo" { + t.Fatalf("bad: %s", result) + } +} diff --git a/third_party/github.com/hashicorp/go-multierror/sort_test.go b/third_party/github.com/hashicorp/go-multierror/sort_test.go new file mode 100644 index 00000000000..7fd04e8c560 --- /dev/null +++ b/third_party/github.com/hashicorp/go-multierror/sort_test.go @@ -0,0 +1,52 @@ +package multierror + +import ( + "errors" + "reflect" + "sort" + "testing" +) + +func TestSortSingle(t *testing.T) { + errFoo := errors.New("foo") + + expected := []error{ + errFoo, + } + + err := &Error{ + Errors: []error{ + errFoo, + }, + } + + sort.Sort(err) + if !reflect.DeepEqual(err.Errors, expected) { + t.Fatalf("bad: %#v", err) + } +} + +func TestSortMultiple(t *testing.T) { + errBar := errors.New("bar") + errBaz := errors.New("baz") + errFoo := errors.New("foo") + + expected := []error{ + errBar, + errBaz, + errFoo, + } + + err := &Error{ + Errors: []error{ + errFoo, + errBar, + errBaz, + }, + } + + sort.Sort(err) + if !reflect.DeepEqual(err.Errors, expected) { + t.Fatalf("bad: %#v", err) + } +} diff --git a/third_party/github.com/hashicorp/golang-lru/2q_test.go b/third_party/github.com/hashicorp/golang-lru/2q_test.go new file mode 100644 index 00000000000..1b0f3518178 --- /dev/null +++ b/third_party/github.com/hashicorp/golang-lru/2q_test.go @@ -0,0 +1,306 @@ +package lru + +import ( + "math/rand" + "testing" +) + +func Benchmark2Q_Rand(b *testing.B) { + l, err := New2Q(8192) + if err != nil { + b.Fatalf("err: %v", err) + } + + trace := make([]int64, b.N*2) + for i := 0; i < b.N*2; i++ { + trace[i] = rand.Int63() % 32768 + } + + b.ResetTimer() + + var hit, miss int + for i := 0; i < 2*b.N; i++ { + if i%2 == 0 { + l.Add(trace[i], trace[i]) + } else { + _, ok := l.Get(trace[i]) + if ok { + hit++ + } else { + miss++ + } + } + } + b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) +} + +func Benchmark2Q_Freq(b *testing.B) { + l, err := New2Q(8192) + if err != nil { + b.Fatalf("err: %v", err) + } + + trace := make([]int64, b.N*2) + for i := 0; i < b.N*2; i++ { + if i%2 == 0 { + trace[i] = rand.Int63() % 16384 + } else { + trace[i] = rand.Int63() % 32768 + } + } + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + l.Add(trace[i], trace[i]) + } + var hit, miss int + for i := 0; i < b.N; i++ { + _, ok := l.Get(trace[i]) + if ok { + hit++ + } else { + miss++ + } + } + b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) +} + +func Test2Q_RandomOps(t *testing.T) { + size := 128 + l, err := New2Q(128) + if err != nil { + t.Fatalf("err: %v", err) + } + + n := 200000 + for i := 0; i < n; i++ { + key := rand.Int63() % 512 + r := rand.Int63() + switch r % 3 { + case 0: + l.Add(key, key) + case 1: + l.Get(key) + case 2: + l.Remove(key) + } + + if l.recent.Len()+l.frequent.Len() > size { + t.Fatalf("bad: recent: %d freq: %d", + l.recent.Len(), l.frequent.Len()) + } + } +} + +func Test2Q_Get_RecentToFrequent(t *testing.T) { + l, err := New2Q(128) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Touch all the entries, should be in t1 + for i := 0; i < 128; i++ { + l.Add(i, i) + } + if n := l.recent.Len(); n != 128 { + t.Fatalf("bad: %d", n) + } + if n := l.frequent.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + + // Get should upgrade to t2 + for i := 0; i < 128; i++ { + _, ok := l.Get(i) + if !ok { + t.Fatalf("missing: %d", i) + } + } + if n := l.recent.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if n := l.frequent.Len(); n != 128 { + t.Fatalf("bad: %d", n) + } + + // Get be from t2 + for i := 0; i < 128; i++ { + _, ok := l.Get(i) + if !ok { + t.Fatalf("missing: %d", i) + } + } + if n := l.recent.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if n := l.frequent.Len(); n != 128 { + t.Fatalf("bad: %d", n) + } +} + +func Test2Q_Add_RecentToFrequent(t *testing.T) { + l, err := New2Q(128) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Add initially to recent + l.Add(1, 1) + if n := l.recent.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + if n := l.frequent.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + + // Add should upgrade to frequent + l.Add(1, 1) + if n := l.recent.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if n := l.frequent.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + + // Add should remain in frequent + l.Add(1, 1) + if n := l.recent.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if n := l.frequent.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } +} + +func Test2Q_Add_RecentEvict(t *testing.T) { + l, err := New2Q(4) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Add 1,2,3,4,5 -> Evict 1 + l.Add(1, 1) + l.Add(2, 2) + l.Add(3, 3) + l.Add(4, 4) + l.Add(5, 5) + if n := l.recent.Len(); n != 4 { + t.Fatalf("bad: %d", n) + } + if n := l.recentEvict.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + if n := l.frequent.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + + // Pull in the recently evicted + l.Add(1, 1) + if n := l.recent.Len(); n != 3 { + t.Fatalf("bad: %d", n) + } + if n := l.recentEvict.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + if n := l.frequent.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + + // Add 6, should cause another recent evict + l.Add(6, 6) + if n := l.recent.Len(); n != 3 { + t.Fatalf("bad: %d", n) + } + if n := l.recentEvict.Len(); n != 2 { + t.Fatalf("bad: %d", n) + } + if n := l.frequent.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } +} + +func Test2Q(t *testing.T) { + l, err := New2Q(128) + if err != nil { + t.Fatalf("err: %v", err) + } + + for i := 0; i < 256; i++ { + l.Add(i, i) + } + if l.Len() != 128 { + t.Fatalf("bad len: %v", l.Len()) + } + + for i, k := range l.Keys() { + if v, ok := l.Get(k); !ok || v != k || v != i+128 { + t.Fatalf("bad key: %v", k) + } + } + for i := 0; i < 128; i++ { + _, ok := l.Get(i) + if ok { + t.Fatalf("should be evicted") + } + } + for i := 128; i < 256; i++ { + _, ok := l.Get(i) + if !ok { + t.Fatalf("should not be evicted") + } + } + for i := 128; i < 192; i++ { + l.Remove(i) + _, ok := l.Get(i) + if ok { + t.Fatalf("should be deleted") + } + } + + l.Purge() + if l.Len() != 0 { + t.Fatalf("bad len: %v", l.Len()) + } + if _, ok := l.Get(200); ok { + t.Fatalf("should contain nothing") + } +} + +// Test that Contains doesn't update recent-ness +func Test2Q_Contains(t *testing.T) { + l, err := New2Q(2) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + if !l.Contains(1) { + t.Errorf("1 should be contained") + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("Contains should not have updated recent-ness of 1") + } +} + +// Test that Peek doesn't update recent-ness +func Test2Q_Peek(t *testing.T) { + l, err := New2Q(2) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + if v, ok := l.Peek(1); !ok || v != 1 { + t.Errorf("1 should be set to 1: %v, %v", v, ok) + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("should not have updated recent-ness of 1") + } +} diff --git a/third_party/github.com/hashicorp/golang-lru/arc_test.go b/third_party/github.com/hashicorp/golang-lru/arc_test.go new file mode 100644 index 00000000000..e2d9b68c6ae --- /dev/null +++ b/third_party/github.com/hashicorp/golang-lru/arc_test.go @@ -0,0 +1,377 @@ +package lru + +import ( + "math/rand" + "testing" + "time" +) + +func init() { + rand.Seed(time.Now().Unix()) +} + +func BenchmarkARC_Rand(b *testing.B) { + l, err := NewARC(8192) + if err != nil { + b.Fatalf("err: %v", err) + } + + trace := make([]int64, b.N*2) + for i := 0; i < b.N*2; i++ { + trace[i] = rand.Int63() % 32768 + } + + b.ResetTimer() + + var hit, miss int + for i := 0; i < 2*b.N; i++ { + if i%2 == 0 { + l.Add(trace[i], trace[i]) + } else { + _, ok := l.Get(trace[i]) + if ok { + hit++ + } else { + miss++ + } + } + } + b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) +} + +func BenchmarkARC_Freq(b *testing.B) { + l, err := NewARC(8192) + if err != nil { + b.Fatalf("err: %v", err) + } + + trace := make([]int64, b.N*2) + for i := 0; i < b.N*2; i++ { + if i%2 == 0 { + trace[i] = rand.Int63() % 16384 + } else { + trace[i] = rand.Int63() % 32768 + } + } + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + l.Add(trace[i], trace[i]) + } + var hit, miss int + for i := 0; i < b.N; i++ { + _, ok := l.Get(trace[i]) + if ok { + hit++ + } else { + miss++ + } + } + b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) +} + +func TestARC_RandomOps(t *testing.T) { + size := 128 + l, err := NewARC(128) + if err != nil { + t.Fatalf("err: %v", err) + } + + n := 200000 + for i := 0; i < n; i++ { + key := rand.Int63() % 512 + r := rand.Int63() + switch r % 3 { + case 0: + l.Add(key, key) + case 1: + l.Get(key) + case 2: + l.Remove(key) + } + + if l.t1.Len()+l.t2.Len() > size { + t.Fatalf("bad: t1: %d t2: %d b1: %d b2: %d p: %d", + l.t1.Len(), l.t2.Len(), l.b1.Len(), l.b2.Len(), l.p) + } + if l.b1.Len()+l.b2.Len() > size { + t.Fatalf("bad: t1: %d t2: %d b1: %d b2: %d p: %d", + l.t1.Len(), l.t2.Len(), l.b1.Len(), l.b2.Len(), l.p) + } + } +} + +func TestARC_Get_RecentToFrequent(t *testing.T) { + l, err := NewARC(128) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Touch all the entries, should be in t1 + for i := 0; i < 128; i++ { + l.Add(i, i) + } + if n := l.t1.Len(); n != 128 { + t.Fatalf("bad: %d", n) + } + if n := l.t2.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + + // Get should upgrade to t2 + for i := 0; i < 128; i++ { + _, ok := l.Get(i) + if !ok { + t.Fatalf("missing: %d", i) + } + } + if n := l.t1.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if n := l.t2.Len(); n != 128 { + t.Fatalf("bad: %d", n) + } + + // Get be from t2 + for i := 0; i < 128; i++ { + _, ok := l.Get(i) + if !ok { + t.Fatalf("missing: %d", i) + } + } + if n := l.t1.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if n := l.t2.Len(); n != 128 { + t.Fatalf("bad: %d", n) + } +} + +func TestARC_Add_RecentToFrequent(t *testing.T) { + l, err := NewARC(128) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Add initially to t1 + l.Add(1, 1) + if n := l.t1.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + if n := l.t2.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + + // Add should upgrade to t2 + l.Add(1, 1) + if n := l.t1.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if n := l.t2.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + + // Add should remain in t2 + l.Add(1, 1) + if n := l.t1.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if n := l.t2.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } +} + +func TestARC_Adaptive(t *testing.T) { + l, err := NewARC(4) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Fill t1 + for i := 0; i < 4; i++ { + l.Add(i, i) + } + if n := l.t1.Len(); n != 4 { + t.Fatalf("bad: %d", n) + } + + // Move to t2 + l.Get(0) + l.Get(1) + if n := l.t2.Len(); n != 2 { + t.Fatalf("bad: %d", n) + } + + // Evict from t1 + l.Add(4, 4) + if n := l.b1.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + + // Current state + // t1 : (MRU) [4, 3] (LRU) + // t2 : (MRU) [1, 0] (LRU) + // b1 : (MRU) [2] (LRU) + // b2 : (MRU) [] (LRU) + + // Add 2, should cause hit on b1 + l.Add(2, 2) + if n := l.b1.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + if l.p != 1 { + t.Fatalf("bad: %d", l.p) + } + if n := l.t2.Len(); n != 3 { + t.Fatalf("bad: %d", n) + } + + // Current state + // t1 : (MRU) [4] (LRU) + // t2 : (MRU) [2, 1, 0] (LRU) + // b1 : (MRU) [3] (LRU) + // b2 : (MRU) [] (LRU) + + // Add 4, should migrate to t2 + l.Add(4, 4) + if n := l.t1.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if n := l.t2.Len(); n != 4 { + t.Fatalf("bad: %d", n) + } + + // Current state + // t1 : (MRU) [] (LRU) + // t2 : (MRU) [4, 2, 1, 0] (LRU) + // b1 : (MRU) [3] (LRU) + // b2 : (MRU) [] (LRU) + + // Add 4, should evict to b2 + l.Add(5, 5) + if n := l.t1.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + if n := l.t2.Len(); n != 3 { + t.Fatalf("bad: %d", n) + } + if n := l.b2.Len(); n != 1 { + t.Fatalf("bad: %d", n) + } + + // Current state + // t1 : (MRU) [5] (LRU) + // t2 : (MRU) [4, 2, 1] (LRU) + // b1 : (MRU) [3] (LRU) + // b2 : (MRU) [0] (LRU) + + // Add 0, should decrease p + l.Add(0, 0) + if n := l.t1.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if n := l.t2.Len(); n != 4 { + t.Fatalf("bad: %d", n) + } + if n := l.b1.Len(); n != 2 { + t.Fatalf("bad: %d", n) + } + if n := l.b2.Len(); n != 0 { + t.Fatalf("bad: %d", n) + } + if l.p != 0 { + t.Fatalf("bad: %d", l.p) + } + + // Current state + // t1 : (MRU) [] (LRU) + // t2 : (MRU) [0, 4, 2, 1] (LRU) + // b1 : (MRU) [5, 3] (LRU) + // b2 : (MRU) [0] (LRU) +} + +func TestARC(t *testing.T) { + l, err := NewARC(128) + if err != nil { + t.Fatalf("err: %v", err) + } + + for i := 0; i < 256; i++ { + l.Add(i, i) + } + if l.Len() != 128 { + t.Fatalf("bad len: %v", l.Len()) + } + + for i, k := range l.Keys() { + if v, ok := l.Get(k); !ok || v != k || v != i+128 { + t.Fatalf("bad key: %v", k) + } + } + for i := 0; i < 128; i++ { + _, ok := l.Get(i) + if ok { + t.Fatalf("should be evicted") + } + } + for i := 128; i < 256; i++ { + _, ok := l.Get(i) + if !ok { + t.Fatalf("should not be evicted") + } + } + for i := 128; i < 192; i++ { + l.Remove(i) + _, ok := l.Get(i) + if ok { + t.Fatalf("should be deleted") + } + } + + l.Purge() + if l.Len() != 0 { + t.Fatalf("bad len: %v", l.Len()) + } + if _, ok := l.Get(200); ok { + t.Fatalf("should contain nothing") + } +} + +// Test that Contains doesn't update recent-ness +func TestARC_Contains(t *testing.T) { + l, err := NewARC(2) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + if !l.Contains(1) { + t.Errorf("1 should be contained") + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("Contains should not have updated recent-ness of 1") + } +} + +// Test that Peek doesn't update recent-ness +func TestARC_Peek(t *testing.T) { + l, err := NewARC(2) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + if v, ok := l.Peek(1); !ok || v != 1 { + t.Errorf("1 should be set to 1: %v, %v", v, ok) + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("should not have updated recent-ness of 1") + } +} diff --git a/third_party/github.com/hashicorp/golang-lru/lru_test.go b/third_party/github.com/hashicorp/golang-lru/lru_test.go new file mode 100644 index 00000000000..b52eafdb8a6 --- /dev/null +++ b/third_party/github.com/hashicorp/golang-lru/lru_test.go @@ -0,0 +1,293 @@ +package lru + +import ( + "math/rand" + "testing" +) + +func BenchmarkLRU_Rand(b *testing.B) { + l, err := New(8192) + if err != nil { + b.Fatalf("err: %v", err) + } + + trace := make([]int64, b.N*2) + for i := 0; i < b.N*2; i++ { + trace[i] = rand.Int63() % 32768 + } + + b.ResetTimer() + + var hit, miss int + for i := 0; i < 2*b.N; i++ { + if i%2 == 0 { + l.Add(trace[i], trace[i]) + } else { + _, ok := l.Get(trace[i]) + if ok { + hit++ + } else { + miss++ + } + } + } + b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) +} + +func BenchmarkLRU_Freq(b *testing.B) { + l, err := New(8192) + if err != nil { + b.Fatalf("err: %v", err) + } + + trace := make([]int64, b.N*2) + for i := 0; i < b.N*2; i++ { + if i%2 == 0 { + trace[i] = rand.Int63() % 16384 + } else { + trace[i] = rand.Int63() % 32768 + } + } + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + l.Add(trace[i], trace[i]) + } + var hit, miss int + for i := 0; i < b.N; i++ { + _, ok := l.Get(trace[i]) + if ok { + hit++ + } else { + miss++ + } + } + b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) +} + +func TestLRU(t *testing.T) { + evictCounter := 0 + onEvicted := func(k interface{}, v interface{}) { + if k != v { + t.Fatalf("Evict values not equal (%v!=%v)", k, v) + } + evictCounter++ + } + l, err := NewWithEvict(128, onEvicted) + if err != nil { + t.Fatalf("err: %v", err) + } + + for i := 0; i < 256; i++ { + l.Add(i, i) + } + if l.Len() != 128 { + t.Fatalf("bad len: %v", l.Len()) + } + + if evictCounter != 128 { + t.Fatalf("bad evict count: %v", evictCounter) + } + + for i, k := range l.Keys() { + if v, ok := l.Get(k); !ok || v != k || v != i+128 { + t.Fatalf("bad key: %v", k) + } + } + for i := 0; i < 128; i++ { + _, ok := l.Get(i) + if ok { + t.Fatalf("should be evicted") + } + } + for i := 128; i < 256; i++ { + _, ok := l.Get(i) + if !ok { + t.Fatalf("should not be evicted") + } + } + for i := 128; i < 192; i++ { + l.Remove(i) + _, ok := l.Get(i) + if ok { + t.Fatalf("should be deleted") + } + } + + l.Get(192) // expect 192 to be last key in l.Keys() + + for i, k := range l.Keys() { + if (i < 63 && k != i+193) || (i == 63 && k != 192) { + t.Fatalf("out of order key: %v", k) + } + } + + l.Purge() + if l.Len() != 0 { + t.Fatalf("bad len: %v", l.Len()) + } + if _, ok := l.Get(200); ok { + t.Fatalf("should contain nothing") + } +} + +// test that Add returns true/false if an eviction occurred +func TestLRUAdd(t *testing.T) { + evictCounter := 0 + onEvicted := func(k interface{}, v interface{}) { + evictCounter++ + } + + l, err := NewWithEvict(1, onEvicted) + if err != nil { + t.Fatalf("err: %v", err) + } + + if l.Add(1, 1) == true || evictCounter != 0 { + t.Errorf("should not have an eviction") + } + if l.Add(2, 2) == false || evictCounter != 1 { + t.Errorf("should have an eviction") + } +} + +// test that Contains doesn't update recent-ness +func TestLRUContains(t *testing.T) { + l, err := New(2) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + if !l.Contains(1) { + t.Errorf("1 should be contained") + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("Contains should not have updated recent-ness of 1") + } +} + +// test that ContainsOrAdd doesn't update recent-ness +func TestLRUContainsOrAdd(t *testing.T) { + l, err := New(2) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + contains, evict := l.ContainsOrAdd(1, 1) + if !contains { + t.Errorf("1 should be contained") + } + if evict { + t.Errorf("nothing should be evicted here") + } + + l.Add(3, 3) + contains, evict = l.ContainsOrAdd(1, 1) + if contains { + t.Errorf("1 should not have been contained") + } + if !evict { + t.Errorf("an eviction should have occurred") + } + if !l.Contains(1) { + t.Errorf("now 1 should be contained") + } +} + +// test that PeekOrAdd doesn't update recent-ness +func TestLRUPeekOrAdd(t *testing.T) { + l, err := New(2) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + previous, contains, evict := l.PeekOrAdd(1, 1) + if !contains { + t.Errorf("1 should be contained") + } + if evict { + t.Errorf("nothing should be evicted here") + } + if previous != 1 { + t.Errorf("previous is not equal to 1") + } + + l.Add(3, 3) + contains, evict = l.ContainsOrAdd(1, 1) + if contains { + t.Errorf("1 should not have been contained") + } + if !evict { + t.Errorf("an eviction should have occurred") + } + if !l.Contains(1) { + t.Errorf("now 1 should be contained") + } +} + +// test that Peek doesn't update recent-ness +func TestLRUPeek(t *testing.T) { + l, err := New(2) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + if v, ok := l.Peek(1); !ok || v != 1 { + t.Errorf("1 should be set to 1: %v, %v", v, ok) + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("should not have updated recent-ness of 1") + } +} + +// test that Resize can upsize and downsize +func TestLRUResize(t *testing.T) { + onEvictCounter := 0 + onEvicted := func(k interface{}, v interface{}) { + onEvictCounter++ + } + l, err := NewWithEvict(2, onEvicted) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Downsize + l.Add(1, 1) + l.Add(2, 2) + evicted := l.Resize(1); + if evicted != 1 { + t.Errorf("1 element should have been evicted: %v", evicted) + } + if onEvictCounter != 1 { + t.Errorf("onEvicted should have been called 1 time: %v", onEvictCounter) + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("Element 1 should have been evicted") + } + + // Upsize + evicted = l.Resize(2); + if evicted != 0 { + t.Errorf("0 elements should have been evicted: %v", evicted) + } + + l.Add(4, 4) + if !l.Contains(3) || !l.Contains(4) { + t.Errorf("Cache should have contained 2 elements") + } +} diff --git a/third_party/github.com/hashicorp/golang-lru/simplelru/lru_test.go b/third_party/github.com/hashicorp/golang-lru/simplelru/lru_test.go new file mode 100644 index 00000000000..bc7f696cc74 --- /dev/null +++ b/third_party/github.com/hashicorp/golang-lru/simplelru/lru_test.go @@ -0,0 +1,206 @@ +package simplelru + +import "testing" + +func TestLRU(t *testing.T) { + evictCounter := 0 + onEvicted := func(k interface{}, v interface{}) { + if k != v { + t.Fatalf("Evict values not equal (%v!=%v)", k, v) + } + evictCounter++ + } + l, err := NewLRU(128, onEvicted) + if err != nil { + t.Fatalf("err: %v", err) + } + + for i := 0; i < 256; i++ { + l.Add(i, i) + } + if l.Len() != 128 { + t.Fatalf("bad len: %v", l.Len()) + } + + if evictCounter != 128 { + t.Fatalf("bad evict count: %v", evictCounter) + } + + for i, k := range l.Keys() { + if v, ok := l.Get(k); !ok || v != k || v != i+128 { + t.Fatalf("bad key: %v", k) + } + } + for i := 0; i < 128; i++ { + _, ok := l.Get(i) + if ok { + t.Fatalf("should be evicted") + } + } + for i := 128; i < 256; i++ { + _, ok := l.Get(i) + if !ok { + t.Fatalf("should not be evicted") + } + } + for i := 128; i < 192; i++ { + ok := l.Remove(i) + if !ok { + t.Fatalf("should be contained") + } + ok = l.Remove(i) + if ok { + t.Fatalf("should not be contained") + } + _, ok = l.Get(i) + if ok { + t.Fatalf("should be deleted") + } + } + + l.Get(192) // expect 192 to be last key in l.Keys() + + for i, k := range l.Keys() { + if (i < 63 && k != i+193) || (i == 63 && k != 192) { + t.Fatalf("out of order key: %v", k) + } + } + + l.Purge() + if l.Len() != 0 { + t.Fatalf("bad len: %v", l.Len()) + } + if _, ok := l.Get(200); ok { + t.Fatalf("should contain nothing") + } +} + +func TestLRU_GetOldest_RemoveOldest(t *testing.T) { + l, err := NewLRU(128, nil) + if err != nil { + t.Fatalf("err: %v", err) + } + for i := 0; i < 256; i++ { + l.Add(i, i) + } + k, _, ok := l.GetOldest() + if !ok { + t.Fatalf("missing") + } + if k.(int) != 128 { + t.Fatalf("bad: %v", k) + } + + k, _, ok = l.RemoveOldest() + if !ok { + t.Fatalf("missing") + } + if k.(int) != 128 { + t.Fatalf("bad: %v", k) + } + + k, _, ok = l.RemoveOldest() + if !ok { + t.Fatalf("missing") + } + if k.(int) != 129 { + t.Fatalf("bad: %v", k) + } +} + +// Test that Add returns true/false if an eviction occurred +func TestLRU_Add(t *testing.T) { + evictCounter := 0 + onEvicted := func(k interface{}, v interface{}) { + evictCounter++ + } + + l, err := NewLRU(1, onEvicted) + if err != nil { + t.Fatalf("err: %v", err) + } + + if l.Add(1, 1) == true || evictCounter != 0 { + t.Errorf("should not have an eviction") + } + if l.Add(2, 2) == false || evictCounter != 1 { + t.Errorf("should have an eviction") + } +} + +// Test that Contains doesn't update recent-ness +func TestLRU_Contains(t *testing.T) { + l, err := NewLRU(2, nil) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + if !l.Contains(1) { + t.Errorf("1 should be contained") + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("Contains should not have updated recent-ness of 1") + } +} + +// Test that Peek doesn't update recent-ness +func TestLRU_Peek(t *testing.T) { + l, err := NewLRU(2, nil) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + if v, ok := l.Peek(1); !ok || v != 1 { + t.Errorf("1 should be set to 1: %v, %v", v, ok) + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("should not have updated recent-ness of 1") + } +} + +// Test that Resize can upsize and downsize +func TestLRU_Resize(t *testing.T) { + onEvictCounter := 0 + onEvicted := func(k interface{}, v interface{}) { + onEvictCounter++ + } + l, err := NewLRU(2, onEvicted) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Downsize + l.Add(1, 1) + l.Add(2, 2) + evicted := l.Resize(1); + if evicted != 1 { + t.Errorf("1 element should have been evicted: %v", evicted) + } + if onEvictCounter != 1 { + t.Errorf("onEvicted should have been called 1 time: %v", onEvictCounter) + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("Element 1 should have been evicted") + } + + // Upsize + evicted = l.Resize(2); + if evicted != 0 { + t.Errorf("0 elements should have been evicted: %v", evicted) + } + + l.Add(4, 4) + if !l.Contains(3) || !l.Contains(4) { + t.Errorf("Cache should have contained 2 elements") + } +} diff --git a/third_party/github.com/mailru/easyjson/LICENSE b/third_party/github.com/mailru/easyjson/LICENSE new file mode 100644 index 00000000000..fbff658f70d --- /dev/null +++ b/third_party/github.com/mailru/easyjson/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2016 Mail.Ru Group + +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/third_party/k8s.io/kube-openapi/pkg/LICENSE b/third_party/k8s.io/kube-openapi/pkg/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/third_party/k8s.io/kube-openapi/pkg/LICENSE @@ -0,0 +1,202 @@ + + 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/third_party/vendor/golang.org/x/crypto/LICENSE b/third_party/vendor/golang.org/x/crypto/LICENSE deleted file mode 100644 index 6a66aea5eaf..00000000000 --- a/third_party/vendor/golang.org/x/crypto/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/vendor/golang.org/x/sys/cpu/LICENSE b/third_party/vendor/golang.org/x/sys/cpu/LICENSE deleted file mode 100644 index 6a66aea5eaf..00000000000 --- a/third_party/vendor/golang.org/x/sys/cpu/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/vendor/golang.org/x/text/LICENSE b/third_party/vendor/golang.org/x/text/LICENSE deleted file mode 100644 index 6a66aea5eaf..00000000000 --- a/third_party/vendor/golang.org/x/text/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.