diff --git a/go.mod b/go.mod index 38f6bcf2d8..4e73c627f2 100644 --- a/go.mod +++ b/go.mod @@ -88,7 +88,7 @@ require ( github.com/google/uuid v1.2.0 github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.4.2 - github.com/k3s-io/helm-controller v0.10.8 + github.com/k3s-io/helm-controller v0.11.7 github.com/k3s-io/kine v0.6.2 github.com/klauspost/compress v1.12.2 github.com/kubernetes-sigs/cri-tools v0.0.0-00010101000000-000000000000 @@ -104,11 +104,11 @@ require ( github.com/opencontainers/selinux v1.8.2 github.com/pierrec/lz4 v2.6.0+incompatible github.com/pkg/errors v0.9.1 - github.com/rancher/dynamiclistener v0.2.3 + github.com/rancher/dynamiclistener v0.2.6 + github.com/rancher/lasso v0.0.0-20210616224652-fc3ebd901c08 github.com/rancher/remotedialer v0.2.0 github.com/rancher/wharfie v0.3.4 - github.com/rancher/wrangler v0.6.2 - github.com/rancher/wrangler-api v0.6.0 + github.com/rancher/wrangler v0.8.5 github.com/robfig/cron/v3 v3.0.1 github.com/rootless-containers/rootlesskit v0.14.0 github.com/sirupsen/logrus v1.8.1 diff --git a/go.sum b/go.sum index 7310099e0e..200f080af3 100644 --- a/go.sum +++ b/go.sum @@ -27,6 +27,7 @@ cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0Zeo cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= dmitri.shuralyov.com/gpu/mtl v0.0.0-20201218220906-28db891af037/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/360EntSecGroup-Skylar/excelize v1.4.1/go.mod h1:vnax29X2usfl7HHkBrX5EvSCJcmH3dT9luvxzu8iGAE= github.com/Azure/azure-sdk-for-go v43.0.0+incompatible h1:/wSNCu0e6EsHFR4Qa3vBEBbicaprEHMyyga9g8RTULI= github.com/Azure/azure-sdk-for-go v43.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 h1:w+iIsaOQNcT7OZ575w+acHgRric5iCyQh+xv+KJ4HB8= @@ -74,11 +75,10 @@ github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb0 github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/goquery v1.5.0/go.mod h1:qD2PgZ9lccMbQlc7eEOjaeRlFQON7xY8kdmcsrnKqMg= github.com/PuerkitoBio/purell v1.1.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= -github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/Rican7/retry v0.1.0 h1:FqK94z34ly8Baa6K+G8Mmza9rYWTKOJk+yckIBB5qVk= @@ -91,6 +91,7 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= +github.com/andybalholm/cascadia v1.0.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e h1:QEF07wC0T1rKkctt1RINW/+RMTVmiwxETico2l3gxJA= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= @@ -209,7 +210,6 @@ github.com/d2g/dhcp4 v0.0.0-20170904100407-a1d1b6c41b1c/go.mod h1:Ct2BUK8SB0YC1S github.com/d2g/dhcp4client v1.0.0/go.mod h1:j0hNfjhrt2SxUOw55nL0ATM/z4Yt3t2Kd1mW34z5W5s= github.com/d2g/dhcp4server v0.0.0-20181031114812-7d4a0a7f59a5/go.mod h1:Eo87+Kg/IX2hfWJfwxMzLyuSZyxSoAug2nGa1G2QAi8= github.com/d2g/hardwareaddr v0.0.0-20190221164911-e7d9fbe030e4/go.mod h1:bMl4RjIciD2oAxI7DmWRx6gbeqrkoLqv3MV0vzNad+I= -github.com/davecgh/go-spew v0.0.0-20151105211317-5215b55f46b2/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -242,6 +242,7 @@ github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3 github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustmop/soup v1.1.2-0.20190516214245-38228baa104e/go.mod h1:CgNC6SGbT+Xb8wGGvzilttZL1mc5sQ/5KkcxsZttMIk= github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153 h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc= github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= @@ -253,7 +254,6 @@ github.com/erikdubbelboer/gspt v0.0.0-20190125194910-e68493906b83 h1:ngHdSomn2My github.com/erikdubbelboer/gspt v0.0.0-20190125194910-e68493906b83/go.mod h1:v6o7m/E9bfvm79dE1iFiF+3T7zLBnrjYjkWMa1J+Hv0= github.com/euank/go-kmsg-parser v2.0.0+incompatible h1:cHD53+PLQuuQyLZeriD1V/esuG4MuU0Pjs5y6iknohY= github.com/euank/go-kmsg-parser v2.0.0+incompatible/go.mod h1:MhmAMZ8V4CYH4ybgdRwPr2TU5ThnS43puaKEMpja1uw= -github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch v4.5.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch v4.9.0+incompatible h1:kLcOMZeuLAJvL2BPWLMIj5oaZQobrkAqrL+WFZwQses= github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= @@ -278,7 +278,6 @@ github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fvbommel/sortorder v1.0.1 h1:dSnXLt4mJYH25uDDGa3biZNQsozaUWDSWeKJ0qqFfzE= github.com/fvbommel/sortorder v1.0.1/go.mod h1:uk88iVf1ovNn1iLfgUVU2F9o5eO30ui720w+kxuqRs0= -github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/globalsign/mgo v0.0.0-20180905125535-1ca0a4f7cbcb/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q= @@ -301,6 +300,7 @@ github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7 github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-logr/logr v0.4.0 h1:K7/B1jt6fIBQVd4Owv2MqGQClcgf0R266+7C/QjRcLc= github.com/go-logr/logr v0.4.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= +github.com/go-logr/zapr v0.1.0/go.mod h1:tabnROwaDl0UNxkVeFRbY8bwB37GwRv0P8lg6aAiEnk= github.com/go-openapi/analysis v0.0.0-20180825180245-b006789cd277/go.mod h1:k70tL6pCuVxPJOHXQ+wIac1FUrvNkHolPie/cLEU6hI= github.com/go-openapi/analysis v0.17.0/go.mod h1:IowGgpVeD0vNm45So8nr+IcQ3pxVtpRoBWb8PVZO0ik= github.com/go-openapi/analysis v0.18.0/go.mod h1:IowGgpVeD0vNm45So8nr+IcQ3pxVtpRoBWb8PVZO0ik= @@ -309,13 +309,11 @@ github.com/go-openapi/analysis v0.19.5/go.mod h1:hkEAkxagaIvIP7VTn8ygJNkd4kAYON2 github.com/go-openapi/errors v0.17.0/go.mod h1:LcZQpmvG4wyF5j4IhA73wkLFQg+QJXOQHVjmcZxhka0= github.com/go-openapi/errors v0.18.0/go.mod h1:LcZQpmvG4wyF5j4IhA73wkLFQg+QJXOQHVjmcZxhka0= github.com/go-openapi/errors v0.19.2/go.mod h1:qX0BLWsyaKfvhluLejVpVNwNRdXZhEbTA4kxxpKBC94= -github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0= github.com/go-openapi/jsonpointer v0.17.0/go.mod h1:cOnomiV+CVVwFLk0A/MExoFMjwdsUdVpsRhURCKh+3M= github.com/go-openapi/jsonpointer v0.18.0/go.mod h1:cOnomiV+CVVwFLk0A/MExoFMjwdsUdVpsRhURCKh+3M= github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg= github.com/go-openapi/jsonpointer v0.19.3 h1:gihV7YNZK1iK6Tgwwsxo2rJbD1GTbdm72325Bq8FI3w= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg= github.com/go-openapi/jsonreference v0.17.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I= github.com/go-openapi/jsonreference v0.18.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I= github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc= @@ -329,7 +327,6 @@ github.com/go-openapi/loads v0.19.4/go.mod h1:zZVHonKd8DXyxyw4yfnVjPzBjIQcLt0CCs github.com/go-openapi/runtime v0.0.0-20180920151709-4f900dc2ade9/go.mod h1:6v9a6LTXWQCdL8k1AO3cvqx5OtZY/Y9wKTgaoP6YRfA= github.com/go-openapi/runtime v0.19.0/go.mod h1:OwNfisksmmaZse4+gpV3Ne9AyMOlP1lt4sK4FXt0O64= github.com/go-openapi/runtime v0.19.4/go.mod h1:X277bwSUBxVlCYR3r7xgZZGKVvBd/29gLDlFGtJ8NL4= -github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc= github.com/go-openapi/spec v0.17.0/go.mod h1:XkF/MOi14NmjsfZ8VtAKf8pIlbZzyoTvZsdfssdxcBI= github.com/go-openapi/spec v0.18.0/go.mod h1:XkF/MOi14NmjsfZ8VtAKf8pIlbZzyoTvZsdfssdxcBI= github.com/go-openapi/spec v0.19.2/go.mod h1:sCxk3jxKgioEJikev4fgkNmwS+3kuYdJtcsZsD5zxMY= @@ -341,7 +338,6 @@ github.com/go-openapi/strfmt v0.18.0/go.mod h1:P82hnJI0CXkErkXi8IKjPbNBM6lV6+5pL github.com/go-openapi/strfmt v0.19.0/go.mod h1:+uW+93UVvGGq2qGaZxdDeJqSAqBqBdl+ZPMF/cC8nDY= github.com/go-openapi/strfmt v0.19.3/go.mod h1:0yX7dbo8mKIvc3XSKp7MNfxw4JytCfCD6+bY1AVL9LU= github.com/go-openapi/strfmt v0.19.5/go.mod h1:eftuHTlB/dI8Uq8JJOyRlieZf+WkkxUuk0dgdHXr2Qk= -github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I= github.com/go-openapi/swag v0.17.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg= github.com/go-openapi/swag v0.18.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg= github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= @@ -374,6 +370,7 @@ github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGw github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20180513044358-24b0969c4cb7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -408,10 +405,8 @@ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-containerregistry v0.0.0-20190617215043-876b8855d23c/go.mod h1:yZAFP63pRshzrEYLXLGPmUt0Ay+2zdjmMN1loCnRLUk= github.com/google/go-containerregistry v0.5.0 h1:eb9sinv4PKm0AUwQGov0mvIdA4pyBGjRofxN4tWnMwM= github.com/google/go-containerregistry v0.5.0/go.mod h1:Ct15B4yir3PLOP5jsy0GNeYVaIZs/MK/Jz5any1wFW0= -github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -433,8 +428,6 @@ github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/googleapis/gnostic v0.0.0-20170426233943-68f4ded48ba9/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= -github.com/googleapis/gnostic v0.2.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= github.com/googleapis/gnostic v0.3.1/go.mod h1:on+2t9HRStVgn95RSsFWFz+6Q0Snyqv1awfrALZdbtU= github.com/googleapis/gnostic v0.4.1 h1:DLJCy1n/vrD4HPjOvYcT8aYQXpPIzoRZONaYwyycI+I= github.com/googleapis/gnostic v0.4.1/go.mod h1:LRhVm6pbyptWbWbuZ38d1eyptfvIytN3ir6b65WBswg= @@ -490,7 +483,7 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO github.com/hugelgupf/socketpair v0.0.0-20190730060125-05d35a94e714/go.mod h1:2Goc3h8EklBH5mspfHFxBnEoURQCGzQQH1ga9Myjvis= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/imdario/mergo v0.3.7/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA= github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= @@ -499,7 +492,6 @@ github.com/insomniacslk/dhcp v0.0.0-20210120172423-cc9239ac6294/go.mod h1:TKl4jN github.com/ishidawataru/sctp v0.0.0-20190723014705-7c296d48a2b5/go.mod h1:DM4VvS+hD/kDi1U1QsX2fnZowwBhqD0Dk3bRPKF/Oc8= github.com/j-keck/arping v0.0.0-20160618110441-2cf9dc699c56/go.mod h1:ymszkNOg6tORTn+6F6j+Jc8TOr5osrynvN6ivFWZ2GA= github.com/jamescun/tuntap v0.0.0-20190712092105-cb1fb277045c/go.mod h1:zzwpsgcYhzzIP5WyF8g9ivCv38cY9uAV9Gu0m3lThhE= -github.com/jetstack/cert-manager v0.7.2/go.mod h1:nbddmhjWxYGt04bxvwVGUSeLhZ2PCyNvd7MpXdq+yWY= github.com/jimstudt/http-authentication v0.0.0-20140401203705-3eca13d6893a/go.mod h1:wK6yTYYcgjHE1Z1QtXACPDjcFJyBskHEdagmnq3vsP8= github.com/jmespath/go-jmespath v0.0.0-20160803190731-bd40a432e4c7/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= @@ -514,7 +506,6 @@ github.com/jsimonetti/rtnetlink v0.0.0-20190606172950-9527aa82566a/go.mod h1:Oz+ github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4/go.mod h1:WGuG/smIU4J/54PblvSbh+xvCZmpJnFgr3ds6Z55XMQ= github.com/jsimonetti/rtnetlink v0.0.0-20201009170750-9c6f07d100c1/go.mod h1:hqoO/u39cqLeBLebZ8fWdE96O7FxrAsRYhnVOdgHxok= github.com/jsimonetti/rtnetlink v0.0.0-20201110080708-d2c240429e6c/go.mod h1:huN4d1phzjhlOsNIjFsw2SVRbwIHj3fJDMEU2SDPTmg= -github.com/json-iterator/go v0.0.0-20180612202835-f2b4162afba3/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68= @@ -535,8 +526,8 @@ github.com/k3s-io/cri-tools v1.21.0-k3s1 h1:MWQtAsx4HCNXenqU/B4V9eU6HMyafkd1PnW6 github.com/k3s-io/cri-tools v1.21.0-k3s1/go.mod h1:Qsz54zxINPR+WVWX9Kc3CTmuDFB1dNLCNV8jE8lUbtU= github.com/k3s-io/etcd v0.5.0-alpha.5.0.20201208200253-50621aee4aea h1:7cwby0GoNAi8IsVrT0q+JfQpB6V76ZaEGhj6qts/mvU= github.com/k3s-io/etcd v0.5.0-alpha.5.0.20201208200253-50621aee4aea/go.mod h1:yVHk9ub3CSBatqGNg7GRmsnfLWtoW60w4eDYfh7vHDg= -github.com/k3s-io/helm-controller v0.10.8 h1:O7zoqUBp3W+6+nRCUWNiAoQMzOX6xw9IsBDXc5lP3Ns= -github.com/k3s-io/helm-controller v0.10.8/go.mod h1:nZP8FH3KZrNNUf5r+SwwiMR63HS6lxdHdpHijgPfF74= +github.com/k3s-io/helm-controller v0.11.7 h1:fNpBImB3h5aHvPf3zwU9sFWmeVQh0nTG1sLCoBhEeUg= +github.com/k3s-io/helm-controller v0.11.7/go.mod h1:z0ExsRRIkTO/QC//3/Esn5ItTD6AiQSluwzMaS7RI/4= github.com/k3s-io/kine v0.6.2 h1:1aJTPfB8HG4exqMKFVE5H0z4bepF05tJHtYNXotWXa4= github.com/k3s-io/kine v0.6.2/go.mod h1:rzCs93+rQHZGOiewMd84PDrER92QeZ6eeHbWkfEy4+w= github.com/k3s-io/kubernetes v1.21.6-k3s1 h1:HsiQ/OtXP0H72QkQJu5AqL6lohRDzx4VuEVtkSErvRs= @@ -602,9 +593,6 @@ github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgo github.com/klauspost/cpuid v1.2.3/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/cpuid v1.3.1 h1:5JNjFYYQrZeKRJ0734q51WCEEn2huer72Dc7K+R/b6s= github.com/klauspost/cpuid v1.3.1/go.mod h1:bYW4mA6ZgKPob1/Dlai2LviZJO7KGI3uoWLd42rAQw4= -github.com/knative/build v0.6.0/go.mod h1:/sU74ZQkwlYA5FwYDJhYTy61i/Kn+5eWfln2jDbw3Qo= -github.com/knative/pkg v0.0.0-20190514205332-5e4512dcb2ca/go.mod h1:7Ijfhw7rfB+H9VtosIsDYvZQ+qYTz7auK3fHW/5z4ww= -github.com/knative/serving v0.6.1/go.mod h1:ljvMfwQy2qanaM/8xnBSK4Mz3Vv2NawC2fo5kFRJS1A= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -633,7 +621,6 @@ github.com/lucas-clemente/quic-go v0.10.2/go.mod h1:hvaRS9IHjFLMq76puFJeWNfmn+H7 github.com/lucas-clemente/quic-go-certificates v0.0.0-20160823095156-d2f86524cced/go.mod h1:NCcRLrOTZbzhZvixZLlERbJtDtYsmMw8Jc4vS8Z0g58= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= -github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= @@ -642,7 +629,6 @@ github.com/mailru/easyjson v0.7.0 h1:aizVhC/NAAcKWb+5QsU1iNOZb4Yws5UO2I+aIprQITM github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs= github.com/markbates/pkger v0.17.1/go.mod h1:0JoVlrol20BSywW79rN3kdFFsE5xYM+rSCQDXbLhiuI= github.com/marten-seemann/qtls v0.2.3/go.mod h1:xzjG7avBwGGbdZ8dTGxlBnLArsVKLvwmjgmPuiQEcYk= -github.com/mattbaird/jsonpatch v0.0.0-20171005235357-81af80346b1a/go.mod h1:M1qoD/MqPgTZIk0EWKB38wE28ACRfVcn+cU08jyArI0= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= @@ -698,6 +684,7 @@ github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQz github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/moby/ipvs v1.0.1 h1:aoZ7fhLTXgDbzVrAnvV+XbKOU8kOET7B3+xULDF/1o0= github.com/moby/ipvs v1.0.1/go.mod h1:2pngiyseZbIKXNv7hsKj3O9UEz30c53MT9005gt2hxQ= +github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= github.com/moby/spdystream v0.2.0 h1:cjW1zVyyoiM0T7b6UoySUFqzXMoqRckQtXwGPiBhOM8= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= github.com/moby/sys/mountinfo v0.4.0/go.mod h1:rEr8tzG/lsIZHBtN/JjGG+LMYx9eXgW2JI+6q0qou+A= @@ -711,11 +698,11 @@ github.com/moby/vpnkit v0.5.0/go.mod h1:KyjUrL9cb6ZSNNAUwZfqRjhwwgJ3BJN+kXh0t43W github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180320133207-05fbef0ca5da/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mohae/deepcopy v0.0.0-20170603005431-491d3605edfb/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0= github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4= github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= @@ -743,6 +730,7 @@ github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:v github.com/olekukonko/tablewriter v0.0.4/go.mod h1:zq6QwlOf5SlnkVbMSr5EoBv3636FWnp+qbPhuoO21uA= github.com/onsi/ginkgo v0.0.0-20151202141238-7f8ab55aaf3b/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.4.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= @@ -754,9 +742,11 @@ github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= github.com/onsi/gomega v0.0.0-20151007035656-2152b45fa28a/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= +github.com/onsi/gomega v1.3.0/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 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/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.11.0 h1:+CqWgvj0OZycCaqclBD1pxKHAU+tOkHmQIWvDHq2aug= @@ -774,6 +764,7 @@ github.com/opencontainers/selinux v1.8.0/go.mod h1:RScLhm78qiWa2gbVCcGkC7tCGdgk3 github.com/opencontainers/selinux v1.8.2 h1:c4ca10UMgRcvZ6h0K4HtS15UaVSBEaE+iln2LVpAuGc= github.com/opencontainers/selinux v1.8.2/go.mod h1:MUIHuUEvKB1wtJjQdOyYRgOnLD2xAPP8dBsCoU0KuF8= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/paulmach/orb v0.1.3/go.mod h1:VFlX/8C+IQ1p6FTRRKzKoOPJnvEtA5G0Veuqwbu//Vk= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pborman/uuid v1.2.1/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= @@ -785,13 +776,13 @@ github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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 h1:0XM1XL/OFFJjXsYXlG30spTkV/E9+gmd5GD1w2HE8xM= github.com/pquerna/cachecontrol v0.0.0-20171018203845-0dec1b30a021/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM= github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= @@ -803,12 +794,14 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1: github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.0-20190522114515-bc1a522cf7b1/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= @@ -817,23 +810,20 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O github.com/prometheus/procfs v0.2.0 h1:wH4vA7pcjKuZzjF7lM8awk4fnuJO6idemZXoKnULUx4= github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= +github.com/qri-io/starlib v0.4.2-0.20200213133954-ff2e8cd5ef8d/go.mod h1:7DPO4domFU579Ga6E61sB9VFNaniPVwJP5C4bBCu3wA= github.com/quobyte/api v0.1.8/go.mod h1:jL7lIHrmqQ7yh05OJ+eEEdHr0u/kmT1Ff9iHd+4H6VI= -github.com/rancher/dynamiclistener v0.2.3 h1:FHn0Gkx+kIUqsFs3zMMR2QC9ufH/AoBLqO5zH5hbtqw= -github.com/rancher/dynamiclistener v0.2.3/go.mod h1:9WusTANoiRr8cDWCTtf5txieulezHbpv4vhLADPp0zU= -github.com/rancher/moq v0.0.0-20190404221404-ee5226d43009/go.mod h1:wpITyDPTi/Na5h73XkbuEf2AP9fbgrIGqqxVzFhYD6U= +github.com/rancher/dynamiclistener v0.2.6 h1:qcNhQQOidheum5K6mtLxDTJQMTWKm1zm/PjZ5x0xV7A= +github.com/rancher/dynamiclistener v0.2.6/go.mod h1:iXFvJLvLjmTzEJBrLFZl9UaMfDLOhv6fHp9fHQRlHGg= +github.com/rancher/lasso v0.0.0-20210616224652-fc3ebd901c08 h1:NxR8Fh0eE7/5/5Zvlog9B5NVjWKqBSb1WYMUF7/IE5c= +github.com/rancher/lasso v0.0.0-20210616224652-fc3ebd901c08/go.mod h1:9qZd/S8DqWzfKtjKGgSoHqGEByYmUE3qRaBaaAHwfEM= github.com/rancher/remotedialer v0.2.0 h1:xD7t3K6JYwTdAsxmGtTHQMkEkFgKouQ1foLxVW424Dc= github.com/rancher/remotedialer v0.2.0/go.mod h1:tkU8ZvrR5lRgaKWaX71nAy6daeqvPFx/lJEnbW7tXSI= github.com/rancher/wharfie v0.3.4 h1:wVqFW1cyRA20zY90Z56VrjG0lWg3oFmf/4ryr5Dkkis= github.com/rancher/wharfie v0.3.4/go.mod h1:cb8mSczpmw7ItbPF3K1W7crWuJLVdyV49sZZuaY4BS8= -github.com/rancher/wrangler v0.1.4/go.mod h1:EYP7cqpg42YqElaCm+U9ieSrGQKAXxUH5xsr+XGpWyE= github.com/rancher/wrangler v0.4.0/go.mod h1:1cR91WLhZgkZ+U4fV9nVuXqKurWbgXcIReU4wnQvTN8= -github.com/rancher/wrangler v0.6.0/go.mod h1:L4HtjPeX8iqLgsxfJgz+JjKMcX2q3qbRXSeTlC/CSd4= -github.com/rancher/wrangler v0.6.1/go.mod h1:L4HtjPeX8iqLgsxfJgz+JjKMcX2q3qbRXSeTlC/CSd4= -github.com/rancher/wrangler v0.6.2 h1:fh2afMK4H6t0D4S0J5rNYDXtyPuJ0qct0BwP0Zx4QvM= -github.com/rancher/wrangler v0.6.2/go.mod h1:L4HtjPeX8iqLgsxfJgz+JjKMcX2q3qbRXSeTlC/CSd4= -github.com/rancher/wrangler-api v0.2.0/go.mod h1:zTPdNLZO07KvRaVOx6XQbKBSV55Fnn4s7nqmrMPJqd8= -github.com/rancher/wrangler-api v0.6.0 h1:d/b0AkgZ+x41EYLIcUJiogtU3Y11Mqss2zr9VEKycRk= -github.com/rancher/wrangler-api v0.6.0/go.mod h1:RbuDkPNHhxcXuwAbLVvEAhH+UPAh+MIkpEd2fcGc0MM= +github.com/rancher/wrangler v0.8.3/go.mod h1:dKEaHNB4izxmPUtpq1Hvr3z3Oh+9k5pCZyFO9sUhlaY= +github.com/rancher/wrangler v0.8.5 h1:aHUVvJrOhD6CGrAELWKDpo1MBDC8vKtEQZvjMPnw2cs= +github.com/rancher/wrangler v0.8.5/go.mod h1:dKEaHNB4izxmPUtpq1Hvr3z3Oh+9k5pCZyFO9sUhlaY= github.com/remyoudompheng/bigfft v0.0.0-20170806203942-52369c62f446/go.mod h1:uYEyJGbgTkfkS4+E/PavXkNJcbFIpEtjt2B0KDQ5+9M= github.com/robfig/cron v1.1.0 h1:jk4/Hud3TTdcrJgUOBgsqrZBarcxl6ADIjSC2iniwLY= github.com/robfig/cron v1.1.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k= @@ -907,8 +897,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= -github.com/stretchr/testify v0.0.0-20151208002404-e3a8ff8ce365/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.2.3-0.20181224173747-660f15d67dbb/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/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= @@ -920,7 +910,6 @@ github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 h1:kdXcSzyDtse github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= github.com/tchap/go-patricia v2.3.0+incompatible h1:GkY4dP3cEfEASBPPkWd+AmjYxhmDkqO9/zg7R0lSQRs= github.com/tchap/go-patricia v2.3.0+incompatible/go.mod h1:bmLyhP68RS6kStMGxByiQ23RP/odRBOTVjwp2cDyi6I= -github.com/tektoncd/pipeline v0.4.0/go.mod h1:IZzJdiX9EqEMuUcgdnElozdYYRh0/ZRC+NKMLj1K3Yw= github.com/tencentcloud/tencentcloud-sdk-go v1.0.67/go.mod h1:asUz5BPXxgoPGaRgZaVm1iGcUAuHyYUo1nXqKa83cvI= github.com/thecodeteam/goscaleio v0.1.0/go.mod h1:68sdkZAsK8bvEwBlbQnlLS+xU+hvLYM/iQ8KXej1AwM= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= @@ -970,6 +959,7 @@ go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3 h1:8sGtKOrtQqkN1bp2AtX+misvLIlOmsEsNd+9NIcPEm8= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.starlark.net v0.0.0-20190528202925-30ae18b8564f/go.mod h1:c1/X6cHgvdXj6pUlmWKMkuqRnW4K8x2vwt6JAaaircg= go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 h1:+FNtrFTmVw0YZGpBGX56XDee331t6JAXeK2bcyhLOOc= go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5/go.mod h1:nmDLcffg48OtT/PSW0Hg7FvpRQsQh5OSqIylirxKC7o= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= @@ -977,6 +967,7 @@ go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g= @@ -1025,7 +1016,6 @@ golang.org/x/net v0.0.0-20210224082022-3d97a244fca7 h1:OgUuv8lsRpBibGNbSizVwKWly golang.org/x/net v0.0.0-20210224082022-3d97a244fca7/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190402181905-9f3314589c9a/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= @@ -1047,9 +1037,9 @@ golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXR golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d h1:SZxvLBoTP5yHO3Frd4z4vrF+DBX9vMVanchswa69toE= golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20171227012246-e19ae1496984/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -1067,7 +1057,6 @@ golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190125232054-d66bd3c5d5a6/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -1121,6 +1110,7 @@ golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gomodules.xyz/jsonpatch/v2 v2.0.1/go.mod h1:IhYNNY4jnS53ZnfE4PAmpKtDpTCj1JFXc+3mwe7XcUU= gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= gonum.org/v1/gonum v0.0.0-20190331200053-3d26580ed485/go.mod h1:2ltnJ7xHfj0zHS40VVPYEAAMTa3ZGguvHGBSJeRWqE0= gonum.org/v1/gonum v0.6.2 h1:4r+yNT0+8SWcOkXP+63H2zQbN+USnC73cjGUxnDF94Q= @@ -1185,6 +1175,7 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWD gopkg.in/warnings.v0 v0.1.1 h1:XM28wIgFzaBmeZ5dNHIpWLQpt/9DGKxk+rCg/22nnYE= gopkg.in/warnings.v0 v0.1.1/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= +gopkg.in/yaml.v2 v2.0.0/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -1195,6 +1186,8 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200121175148-a6ecf24a6d71/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= @@ -1211,8 +1204,6 @@ honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= inet.af/tcpproxy v0.0.0-20200125044825-b6bb9b5b8252 h1:gmJCKidOfjKDUHF1jjke+I+2iQIyE3HNNxu2OKO/FUI= inet.af/tcpproxy v0.0.0-20200125044825-b6bb9b5b8252/go.mod h1:zq+R+tLcdHugi7Jt+FtIQY6m6wtX34lr2CdQVH2fhW0= -k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= -k8s.io/gengo v0.0.0-20190327210449-e17681d19d3a/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/gengo v0.0.0-20191120174120-e74f70b9b27e/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/gengo v0.0.0-20200114144118-36b2048a9120/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/gengo v0.0.0-20200413195148-3a45101e95ac/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= @@ -1221,7 +1212,6 @@ k8s.io/gengo v0.0.0-20201214224949-b6c5ce23f027 h1:Uusb3oh8XcdzDF/ndlI4ToKTYVlkC k8s.io/gengo v0.0.0-20201214224949-b6c5ce23f027/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= k8s.io/heapster v1.2.0-beta.1 h1:lUsE/AHOMHpi3MLlBEkaU8Esxm5QhdyCrv1o7ot0s84= k8s.io/heapster v1.2.0-beta.1/go.mod h1:h1uhptVXMwC8xtZBYsPXKVi8fpdlYkTs6k949KozGrM= -k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= k8s.io/klog v0.3.0/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= k8s.io/klog v1.0.0 h1:Pt+yjF5aB1xDSVbau4VsWe+dQNzA0qv1LlXdC2dF6Q8= k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= @@ -1231,11 +1221,11 @@ k8s.io/klog/v2 v2.4.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= k8s.io/klog/v2 v2.8.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec= k8s.io/klog/v2 v2.9.0 h1:D7HV+n1V57XeZ0m6tdRkfknthUaM06VFbWldOFh8kzM= k8s.io/klog/v2 v2.9.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec= -k8s.io/kube-openapi v0.0.0-20190502190224-411b2483e503/go.mod h1:iU+ZGYsNlvU9XKUSso6SQfKTCCw7lFduMZy26Mgr2Fw= k8s.io/kube-openapi v0.0.0-20210305001622-591a79e4bda7 h1:vEx13qjvaZ4yfObSSXW7BrMc/KQBBT/Jyee8XtLf4x0= k8s.io/kube-openapi v0.0.0-20210305001622-591a79e4bda7/go.mod h1:wXW5VT87nVfh/iLV8FpR2uDvrFyomxbtb1KivDbvPTE= k8s.io/system-validators v1.4.0/go.mod h1:bPldcLgkIUK22ALflnsXk8pvkTEndYdNuaHH6gRrl0Q= -k8s.io/utils v0.0.0-20190506122338-8fab8cb257d5/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= +k8s.io/utils v0.0.0-20190801114015-581e00157fb1/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= +k8s.io/utils v0.0.0-20191114184206-e782cd3c129f/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= k8s.io/utils v0.0.0-20201110183641-67b214c5f920 h1:CbnUZsM497iRC5QMVkHwyl8s2tB3g7yaSHkYPkpgelw= k8s.io/utils v0.0.0-20201110183641-67b214c5f920/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= modernc.org/cc v1.0.0/go.mod h1:1Sk4//wdnYJiUIxnW8ddKpaOJCF37yAdqYnkxUpaYxw= @@ -1249,18 +1239,20 @@ rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.22 h1:fmRfl9WJ4ApJn7LxNuED4m0t18qivVQOxP6aAYG9J6c= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.22/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= +sigs.k8s.io/cli-utils v0.16.0/go.mod h1:9Jqm9K2W6ShhCxsEuaz6HSRKKOXigPUx3ZfypGgxBLY= +sigs.k8s.io/controller-runtime v0.4.0/go.mod h1:ApC79lpY3PHW9xj/w9pj+lYkLgwAAUZwfXkME1Lajns= sigs.k8s.io/kustomize/api v0.8.8 h1:G2z6JPSSjtWWgMeWSoHdXqyftJNmMmyxXpwENGoOtGE= sigs.k8s.io/kustomize/api v0.8.8/go.mod h1:He1zoK0nk43Pc6NlV085xDXDXTNprtcyKZVm3swsdNY= sigs.k8s.io/kustomize/cmd/config v0.9.10/go.mod h1:Mrby0WnRH7hA6OwOYnYpfpiY0WJIMgYrEDfwOeFdMK0= sigs.k8s.io/kustomize/kustomize/v4 v4.1.2 h1:iP3ckqMIftwsIKnMqtztReSkkPJvhqNc5QiOpMoFpbY= sigs.k8s.io/kustomize/kustomize/v4 v4.1.2/go.mod h1:PxBvo4WGYlCLeRPL+ziT64wBXqbgfcalOS/SXa/tcyo= +sigs.k8s.io/kustomize/kyaml v0.4.0/go.mod h1:XJL84E6sOFeNrQ7CADiemc1B0EjIxHo3OhW4o1aJYNw= sigs.k8s.io/kustomize/kyaml v0.10.17 h1:4zrV0ym5AYa0e512q7K3Wp1u7mzoWW0xR3UHJcGWGIg= sigs.k8s.io/kustomize/kyaml v0.10.17/go.mod h1:mlQFagmkm1P+W4lZJbJ/yaxMd8PqMRSC4cPcfUVt5Hg= -sigs.k8s.io/structured-merge-diff v0.0.0-20190426204423-ea680f03cc65 h1:xJNnO2qzHtgVCSPoGkkltSpyEX7D7IJw1TmbE3G/7lY= -sigs.k8s.io/structured-merge-diff v0.0.0-20190426204423-ea680f03cc65/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI= sigs.k8s.io/structured-merge-diff/v4 v4.0.2/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.1.2 h1:Hr/htKFmJEbtMgS/UD0N+gtgctAqz81t3nu+sPzynno= sigs.k8s.io/structured-merge-diff/v4 v4.1.2/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4= +sigs.k8s.io/testing_frameworks v0.1.2/go.mod h1:ToQrwSC3s8Xf/lADdZp3Mktcql9CG0UAmdJG9th5i0w= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sigs.k8s.io/yaml v1.2.0 h1:kr/MCeFWJWTwyaHoR9c8EjH9OumOmoF9YGiZd7lFm/Q= sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= diff --git a/pkg/agent/netpol/utils/ipset_test.go b/pkg/agent/netpol/utils/ipset_test.go index 486b42b6f2..6a68193101 100644 --- a/pkg/agent/netpol/utils/ipset_test.go +++ b/pkg/agent/netpol/utils/ipset_test.go @@ -1,6 +1,8 @@ // Apache License v2.0 (copyright Cloud Native Labs & Rancher Labs) // - modified from https://github.com/cloudnativelabs/kube-router/blob/73b1b03b32c5755b240f6c077bb097abe3888314/pkg/utils/ipset_test.go +// +build !windows + package utils import "testing" diff --git a/pkg/apiaddresses/controller.go b/pkg/apiaddresses/controller.go index 7601f40da6..c44749f69b 100644 --- a/pkg/apiaddresses/controller.go +++ b/pkg/apiaddresses/controller.go @@ -9,7 +9,7 @@ import ( "github.com/rancher/k3s/pkg/etcd" "github.com/rancher/k3s/pkg/util" "github.com/rancher/k3s/pkg/version" - controllerv1 "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + controllerv1 "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" etcdv3 "go.etcd.io/etcd/clientv3" v1 "k8s.io/api/core/v1" ) diff --git a/pkg/cluster/https.go b/pkg/cluster/https.go index 5f14f5c2c1..4feb3e46ae 100644 --- a/pkg/cluster/https.go +++ b/pkg/cluster/https.go @@ -18,7 +18,7 @@ import ( "github.com/rancher/k3s/pkg/daemons/config" "github.com/rancher/k3s/pkg/etcd" "github.com/rancher/k3s/pkg/version" - "github.com/rancher/wrangler-api/pkg/generated/controllers/core" + "github.com/rancher/wrangler/pkg/generated/controllers/core" "github.com/sirupsen/logrus" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) diff --git a/pkg/codegen/main.go b/pkg/codegen/main.go index 66af50f908..d3067cd15a 100644 --- a/pkg/codegen/main.go +++ b/pkg/codegen/main.go @@ -75,7 +75,8 @@ func main() { Types: []interface{}{ v1.Addon{}, }, - GenerateTypes: true, + GenerateTypes: true, + GenerateClients: true, }, }, }) diff --git a/pkg/daemons/config/types.go b/pkg/daemons/config/types.go index b95cc1564f..c594615642 100644 --- a/pkg/daemons/config/types.go +++ b/pkg/daemons/config/types.go @@ -11,7 +11,7 @@ import ( "time" "github.com/k3s-io/kine/pkg/endpoint" - "github.com/rancher/wrangler-api/pkg/generated/controllers/core" + "github.com/rancher/wrangler/pkg/generated/controllers/core" utilnet "k8s.io/apimachinery/pkg/util/net" "k8s.io/apiserver/pkg/authentication/authenticator" ) diff --git a/pkg/daemons/control/server.go b/pkg/daemons/control/server.go index 8ed550cf41..d327a9ca57 100644 --- a/pkg/daemons/control/server.go +++ b/pkg/daemons/control/server.go @@ -17,7 +17,7 @@ import ( "github.com/rancher/k3s/pkg/daemons/executor" "github.com/rancher/k3s/pkg/util" "github.com/rancher/k3s/pkg/version" - "github.com/rancher/wrangler-api/pkg/generated/controllers/rbac" + "github.com/rancher/wrangler/pkg/generated/controllers/rbac" "github.com/sirupsen/logrus" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/pkg/etcd/etcd.go b/pkg/etcd/etcd.go index 489c8c889d..f266640c51 100644 --- a/pkg/etcd/etcd.go +++ b/pkg/etcd/etcd.go @@ -27,7 +27,7 @@ import ( "github.com/rancher/k3s/pkg/daemons/control/deps" "github.com/rancher/k3s/pkg/daemons/executor" "github.com/rancher/k3s/pkg/version" - controllerv1 "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + controllerv1 "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" "github.com/robfig/cron/v3" "github.com/sirupsen/logrus" etcd "go.etcd.io/etcd/clientv3" diff --git a/pkg/etcd/member_controller.go b/pkg/etcd/member_controller.go index e019ff6fda..c355897ad0 100644 --- a/pkg/etcd/member_controller.go +++ b/pkg/etcd/member_controller.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/rancher/k3s/pkg/version" - controllerv1 "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + controllerv1 "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" ) diff --git a/pkg/etcd/metadata_controller.go b/pkg/etcd/metadata_controller.go index 6d56e32372..39b4bf3fd7 100644 --- a/pkg/etcd/metadata_controller.go +++ b/pkg/etcd/metadata_controller.go @@ -5,7 +5,7 @@ import ( "os" "time" - controllerv1 "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + controllerv1 "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" ) diff --git a/pkg/flock/flock_int_test.go b/pkg/flock/flock_int_test.go index 509cda6f38..1b4a36cc35 100644 --- a/pkg/flock/flock_int_test.go +++ b/pkg/flock/flock_int_test.go @@ -1,3 +1,5 @@ +// +build !windows + package flock_test import ( diff --git a/pkg/generated/controllers/k3s.cattle.io/factory.go b/pkg/generated/controllers/k3s.cattle.io/factory.go index 9191cb0d80..f5c93e2351 100644 --- a/pkg/generated/controllers/k3s.cattle.io/factory.go +++ b/pkg/generated/controllers/k3s.cattle.io/factory.go @@ -19,28 +19,12 @@ limitations under the License. package k3s import ( - "context" - "time" - - clientset "github.com/rancher/k3s/pkg/generated/clientset/versioned" - scheme "github.com/rancher/k3s/pkg/generated/clientset/versioned/scheme" - informers "github.com/rancher/k3s/pkg/generated/informers/externalversions" "github.com/rancher/wrangler/pkg/generic" - "github.com/rancher/wrangler/pkg/schemes" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/rest" ) -func init() { - scheme.AddToScheme(schemes.All) -} - type Factory struct { - synced bool - informerFactory informers.SharedInformerFactory - clientset clientset.Interface - controllerManager *generic.ControllerManager - threadiness map[schema.GroupVersionKind]int + *generic.Factory } func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { @@ -61,66 +45,23 @@ func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (* }) } -type FactoryOptions struct { - Namespace string - Resync time.Duration -} +type FactoryOptions = generic.FactoryOptions func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { - if opts == nil { - opts = &FactoryOptions{} - } - - cs, err := clientset.NewForConfig(config) - if err != nil { - return nil, err - } - - resync := opts.Resync - if resync == 0 { - resync = 2 * time.Hour - } - - if opts.Namespace == "" { - informerFactory := informers.NewSharedInformerFactory(cs, resync) - return NewFactory(cs, informerFactory), nil - } - - informerFactory := informers.NewSharedInformerFactoryWithOptions(cs, resync, informers.WithNamespace(opts.Namespace)) - return NewFactory(cs, informerFactory), nil -} - -func NewFactory(clientset clientset.Interface, informerFactory informers.SharedInformerFactory) *Factory { + f, err := generic.NewFactoryFromConfigWithOptions(config, opts) return &Factory{ - threadiness: map[schema.GroupVersionKind]int{}, - controllerManager: &generic.ControllerManager{}, - clientset: clientset, - informerFactory: informerFactory, + Factory: f, + }, err +} + +func NewFactoryFromConfigWithOptionsOrDie(config *rest.Config, opts *FactoryOptions) *Factory { + f, err := NewFactoryFromConfigWithOptions(config, opts) + if err != nil { + panic(err) } -} - -func (c *Factory) Controllers() map[schema.GroupVersionKind]*generic.Controller { - return c.controllerManager.Controllers() -} - -func (c *Factory) SetThreadiness(gvk schema.GroupVersionKind, threadiness int) { - c.threadiness[gvk] = threadiness -} - -func (c *Factory) Sync(ctx context.Context) error { - c.informerFactory.Start(ctx.Done()) - c.informerFactory.WaitForCacheSync(ctx.Done()) - return nil -} - -func (c *Factory) Start(ctx context.Context, defaultThreadiness int) error { - if err := c.Sync(ctx); err != nil { - return err - } - - return c.controllerManager.Start(ctx, defaultThreadiness, c.threadiness) + return f } func (c *Factory) K3s() Interface { - return New(c.controllerManager, c.informerFactory.K3s(), c.clientset) + return New(c.ControllerFactory()) } diff --git a/pkg/generated/controllers/k3s.cattle.io/interface.go b/pkg/generated/controllers/k3s.cattle.io/interface.go index 201695983c..d327e83d26 100644 --- a/pkg/generated/controllers/k3s.cattle.io/interface.go +++ b/pkg/generated/controllers/k3s.cattle.io/interface.go @@ -19,10 +19,8 @@ limitations under the License. package k3s import ( - clientset "github.com/rancher/k3s/pkg/generated/clientset/versioned" v1 "github.com/rancher/k3s/pkg/generated/controllers/k3s.cattle.io/v1" - informers "github.com/rancher/k3s/pkg/generated/informers/externalversions/k3s.cattle.io" - "github.com/rancher/wrangler/pkg/generic" + "github.com/rancher/lasso/pkg/controller" ) type Interface interface { @@ -30,21 +28,16 @@ type Interface interface { } type group struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.Interface + controllerFactory controller.SharedControllerFactory } // New returns a new Interface. -func New(controllerManager *generic.ControllerManager, informers informers.Interface, - client clientset.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &group{ - controllerManager: controllerManager, - informers: informers, - client: client, + controllerFactory: controllerFactory, } } func (g *group) V1() v1.Interface { - return v1.New(g.controllerManager, g.client.K3sV1(), g.informers.V1()) + return v1.New(g.controllerFactory) } diff --git a/pkg/generated/controllers/k3s.cattle.io/v1/addon.go b/pkg/generated/controllers/k3s.cattle.io/v1/addon.go index 70821f25b4..bc0250615a 100644 --- a/pkg/generated/controllers/k3s.cattle.io/v1/addon.go +++ b/pkg/generated/controllers/k3s.cattle.io/v1/addon.go @@ -23,9 +23,8 @@ import ( "time" v1 "github.com/rancher/k3s/pkg/apis/k3s.cattle.io/v1" - clientset "github.com/rancher/k3s/pkg/generated/clientset/versioned/typed/k3s.cattle.io/v1" - informers "github.com/rancher/k3s/pkg/generated/informers/externalversions/k3s.cattle.io/v1" - listers "github.com/rancher/k3s/pkg/generated/listers/k3s.cattle.io/v1" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -78,18 +77,22 @@ type AddonCache interface { type AddonIndexer func(obj *v1.Addon) ([]string, error) type addonController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.AddonsGetter - informer informers.AddonInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewAddonController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.AddonsGetter, informer informers.AddonInformer) AddonController { +func NewAddonController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) AddonController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &addonController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdateAddonDeepCopyOnChange(client AddonClient, obj *v1.Addon, handler func } func (c *addonController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *addonController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *addonController) OnChange(ctx context.Context, name string, sync AddonHandler) { @@ -149,20 +151,19 @@ func (c *addonController) OnChange(ctx context.Context, name string, sync AddonH } func (c *addonController) OnRemove(ctx context.Context, name string, sync AddonHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromAddonHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromAddonHandlerToHandler(sync))) } func (c *addonController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *addonController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *addonController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *addonController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *addonController) GroupVersionKind() schema.GroupVersionKind { func (c *addonController) Cache() AddonCache { return &addonCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *addonController) Create(obj *v1.Addon) (*v1.Addon, error) { - return c.clientGetter.Addons(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Addon{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *addonController) Update(obj *v1.Addon) (*v1.Addon, error) { - return c.clientGetter.Addons(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Addon{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *addonController) UpdateStatus(obj *v1.Addon) (*v1.Addon, error) { - return c.clientGetter.Addons(obj.Namespace).UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Addon{} + return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *addonController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Addons(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *addonController) Get(namespace, name string, options metav1.GetOptions) (*v1.Addon, error) { - return c.clientGetter.Addons(namespace).Get(context.TODO(), name, options) + result := &v1.Addon{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *addonController) List(namespace string, opts metav1.ListOptions) (*v1.AddonList, error) { - return c.clientGetter.Addons(namespace).List(context.TODO(), opts) + result := &v1.AddonList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *addonController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Addons(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *addonController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Addon, err error) { - return c.clientGetter.Addons(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *addonController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Addon, error) { + result := &v1.Addon{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type addonCache struct { - lister listers.AddonLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *addonCache) Get(namespace, name string) (*v1.Addon, error) { - return c.lister.Addons(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Addon), nil } -func (c *addonCache) List(namespace string, selector labels.Selector) ([]*v1.Addon, error) { - return c.lister.Addons(namespace).List(selector) +func (c *addonCache) List(namespace string, selector labels.Selector) (ret []*v1.Addon, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Addon)) + }) + + return ret, err } func (c *addonCache) AddIndexer(indexName string, indexer AddonIndexer) { @@ -299,12 +318,20 @@ func (a *addonStatusHandler) sync(key string, obj *v1.Addon) (*v1.Addon, error) } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *addonGeneratingHandler) Remove(key string, obj *v1.Addon) (*v1.Addon, e } func (a *addonGeneratingHandler) Handle(obj *v1.Addon, status v1.AddonStatus) (v1.AddonStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.AddonGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/pkg/generated/controllers/k3s.cattle.io/v1/interface.go b/pkg/generated/controllers/k3s.cattle.io/v1/interface.go index 89a3e7a345..a8b64d3886 100644 --- a/pkg/generated/controllers/k3s.cattle.io/v1/interface.go +++ b/pkg/generated/controllers/k3s.cattle.io/v1/interface.go @@ -20,30 +20,29 @@ package v1 import ( v1 "github.com/rancher/k3s/pkg/apis/k3s.cattle.io/v1" - clientset "github.com/rancher/k3s/pkg/generated/clientset/versioned/typed/k3s.cattle.io/v1" - informers "github.com/rancher/k3s/pkg/generated/informers/externalversions/k3s.cattle.io/v1" - "github.com/rancher/wrangler/pkg/generic" + "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/schemes" + "k8s.io/apimachinery/pkg/runtime/schema" ) +func init() { + schemes.Register(v1.AddToScheme) +} + type Interface interface { Addon() AddonController } -func New(controllerManager *generic.ControllerManager, client clientset.K3sV1Interface, - informers informers.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &version{ - controllerManager: controllerManager, - client: client, - informers: informers, + controllerFactory: controllerFactory, } } type version struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.K3sV1Interface + controllerFactory controller.SharedControllerFactory } func (c *version) Addon() AddonController { - return NewAddonController(v1.SchemeGroupVersion.WithKind("Addon"), c.controllerManager, c.client, c.informers.Addons()) + return NewAddonController(schema.GroupVersionKind{Group: "k3s.cattle.io", Version: "v1", Kind: "Addon"}, "addons", true, c.controllerFactory) } diff --git a/pkg/generated/informers/externalversions/factory.go b/pkg/generated/informers/externalversions/factory.go deleted file mode 100644 index 2b1d5c3f9f..0000000000 --- a/pkg/generated/informers/externalversions/factory.go +++ /dev/null @@ -1,180 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package externalversions - -import ( - reflect "reflect" - sync "sync" - time "time" - - versioned "github.com/rancher/k3s/pkg/generated/clientset/versioned" - internalinterfaces "github.com/rancher/k3s/pkg/generated/informers/externalversions/internalinterfaces" - k3scattleio "github.com/rancher/k3s/pkg/generated/informers/externalversions/k3s.cattle.io" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" -) - -// SharedInformerOption defines the functional option type for SharedInformerFactory. -type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory - -type sharedInformerFactory struct { - client versioned.Interface - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc - lock sync.Mutex - defaultResync time.Duration - customResync map[reflect.Type]time.Duration - - informers map[reflect.Type]cache.SharedIndexInformer - // startedInformers is used for tracking which informers have been started. - // This allows Start() to be called multiple times safely. - startedInformers map[reflect.Type]bool -} - -// WithCustomResyncConfig sets a custom resync period for the specified informer types. -func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - for k, v := range resyncConfig { - factory.customResync[reflect.TypeOf(k)] = v - } - return factory - } -} - -// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory. -func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.tweakListOptions = tweakListOptions - return factory - } -} - -// WithNamespace limits the SharedInformerFactory to the specified namespace. -func WithNamespace(namespace string) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.namespace = namespace - return factory - } -} - -// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces. -func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync) -} - -// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory. -// Listers obtained via this SharedInformerFactory will be subject to the same filters -// as specified here. -// Deprecated: Please use NewSharedInformerFactoryWithOptions instead -func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions)) -} - -// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. -func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory { - factory := &sharedInformerFactory{ - client: client, - namespace: v1.NamespaceAll, - defaultResync: defaultResync, - informers: make(map[reflect.Type]cache.SharedIndexInformer), - startedInformers: make(map[reflect.Type]bool), - customResync: make(map[reflect.Type]time.Duration), - } - - // Apply all options - for _, opt := range options { - factory = opt(factory) - } - - return factory -} - -// Start initializes all requested informers. -func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { - f.lock.Lock() - defer f.lock.Unlock() - - for informerType, informer := range f.informers { - if !f.startedInformers[informerType] { - go informer.Run(stopCh) - f.startedInformers[informerType] = true - } - } -} - -// WaitForCacheSync waits for all started informers' cache were synced. -func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool { - informers := func() map[reflect.Type]cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informers := map[reflect.Type]cache.SharedIndexInformer{} - for informerType, informer := range f.informers { - if f.startedInformers[informerType] { - informers[informerType] = informer - } - } - return informers - }() - - res := map[reflect.Type]bool{} - for informType, informer := range informers { - res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced) - } - return res -} - -// InternalInformerFor returns the SharedIndexInformer for obj using an internal -// client. -func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informerType := reflect.TypeOf(obj) - informer, exists := f.informers[informerType] - if exists { - return informer - } - - resyncPeriod, exists := f.customResync[informerType] - if !exists { - resyncPeriod = f.defaultResync - } - - informer = newFunc(f.client, resyncPeriod) - f.informers[informerType] = informer - - return informer -} - -// SharedInformerFactory provides shared informers for resources in all known -// API group versions. -type SharedInformerFactory interface { - internalinterfaces.SharedInformerFactory - ForResource(resource schema.GroupVersionResource) (GenericInformer, error) - WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool - - K3s() k3scattleio.Interface -} - -func (f *sharedInformerFactory) K3s() k3scattleio.Interface { - return k3scattleio.New(f, f.namespace, f.tweakListOptions) -} diff --git a/pkg/generated/informers/externalversions/generic.go b/pkg/generated/informers/externalversions/generic.go deleted file mode 100644 index c7c1ef8605..0000000000 --- a/pkg/generated/informers/externalversions/generic.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package externalversions - -import ( - "fmt" - - v1 "github.com/rancher/k3s/pkg/apis/k3s.cattle.io/v1" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" -) - -// GenericInformer is type of SharedIndexInformer which will locate and delegate to other -// sharedInformers based on type -type GenericInformer interface { - Informer() cache.SharedIndexInformer - Lister() cache.GenericLister -} - -type genericInformer struct { - informer cache.SharedIndexInformer - resource schema.GroupResource -} - -// Informer returns the SharedIndexInformer. -func (f *genericInformer) Informer() cache.SharedIndexInformer { - return f.informer -} - -// Lister returns the GenericLister. -func (f *genericInformer) Lister() cache.GenericLister { - return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource) -} - -// ForResource gives generic access to a shared informer of the matching type -// TODO extend this to unknown resources with a client pool -func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { - switch resource { - // Group=k3s.cattle.io, Version=v1 - case v1.SchemeGroupVersion.WithResource("addons"): - return &genericInformer{resource: resource.GroupResource(), informer: f.K3s().V1().Addons().Informer()}, nil - - } - - return nil, fmt.Errorf("no informer found for %v", resource) -} diff --git a/pkg/generated/informers/externalversions/internalinterfaces/factory_interfaces.go b/pkg/generated/informers/externalversions/internalinterfaces/factory_interfaces.go deleted file mode 100644 index 70fe8bf9b4..0000000000 --- a/pkg/generated/informers/externalversions/internalinterfaces/factory_interfaces.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package internalinterfaces - -import ( - time "time" - - versioned "github.com/rancher/k3s/pkg/generated/clientset/versioned" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - cache "k8s.io/client-go/tools/cache" -) - -// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. -type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer - -// SharedInformerFactory a small interface to allow for adding an informer without an import cycle -type SharedInformerFactory interface { - Start(stopCh <-chan struct{}) - InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer -} - -// TweakListOptionsFunc is a function that transforms a v1.ListOptions. -type TweakListOptionsFunc func(*v1.ListOptions) diff --git a/pkg/generated/informers/externalversions/k3s.cattle.io/interface.go b/pkg/generated/informers/externalversions/k3s.cattle.io/interface.go deleted file mode 100644 index 8bf844775c..0000000000 --- a/pkg/generated/informers/externalversions/k3s.cattle.io/interface.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package k3s - -import ( - internalinterfaces "github.com/rancher/k3s/pkg/generated/informers/externalversions/internalinterfaces" - v1 "github.com/rancher/k3s/pkg/generated/informers/externalversions/k3s.cattle.io/v1" -) - -// Interface provides access to each of this group's versions. -type Interface interface { - // V1 provides access to shared informers for resources in V1. - V1() v1.Interface -} - -type group struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// V1 returns a new v1.Interface. -func (g *group) V1() v1.Interface { - return v1.New(g.factory, g.namespace, g.tweakListOptions) -} diff --git a/pkg/generated/informers/externalversions/k3s.cattle.io/v1/addon.go b/pkg/generated/informers/externalversions/k3s.cattle.io/v1/addon.go deleted file mode 100644 index 34fa427674..0000000000 --- a/pkg/generated/informers/externalversions/k3s.cattle.io/v1/addon.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - "context" - time "time" - - k3scattleiov1 "github.com/rancher/k3s/pkg/apis/k3s.cattle.io/v1" - versioned "github.com/rancher/k3s/pkg/generated/clientset/versioned" - internalinterfaces "github.com/rancher/k3s/pkg/generated/informers/externalversions/internalinterfaces" - v1 "github.com/rancher/k3s/pkg/generated/listers/k3s.cattle.io/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// AddonInformer provides access to a shared informer and lister for -// Addons. -type AddonInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1.AddonLister -} - -type addonInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewAddonInformer constructs a new informer for Addon type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewAddonInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredAddonInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredAddonInformer constructs a new informer for Addon type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredAddonInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.K3sV1().Addons(namespace).List(context.TODO(), options) - }, - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.K3sV1().Addons(namespace).Watch(context.TODO(), options) - }, - }, - &k3scattleiov1.Addon{}, - resyncPeriod, - indexers, - ) -} - -func (f *addonInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredAddonInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *addonInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&k3scattleiov1.Addon{}, f.defaultInformer) -} - -func (f *addonInformer) Lister() v1.AddonLister { - return v1.NewAddonLister(f.Informer().GetIndexer()) -} diff --git a/pkg/generated/informers/externalversions/k3s.cattle.io/v1/interface.go b/pkg/generated/informers/externalversions/k3s.cattle.io/v1/interface.go deleted file mode 100644 index 855c7c0b37..0000000000 --- a/pkg/generated/informers/externalversions/k3s.cattle.io/v1/interface.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - internalinterfaces "github.com/rancher/k3s/pkg/generated/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // Addons returns a AddonInformer. - Addons() AddonInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// Addons returns a AddonInformer. -func (v *version) Addons() AddonInformer { - return &addonInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/pkg/generated/listers/k3s.cattle.io/v1/addon.go b/pkg/generated/listers/k3s.cattle.io/v1/addon.go deleted file mode 100644 index a08fb76429..0000000000 --- a/pkg/generated/listers/k3s.cattle.io/v1/addon.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - v1 "github.com/rancher/k3s/pkg/apis/k3s.cattle.io/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// AddonLister helps list Addons. -// All objects returned here must be treated as read-only. -type AddonLister interface { - // List lists all Addons in the indexer. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1.Addon, err error) - // Addons returns an object that can list and get Addons. - Addons(namespace string) AddonNamespaceLister - AddonListerExpansion -} - -// addonLister implements the AddonLister interface. -type addonLister struct { - indexer cache.Indexer -} - -// NewAddonLister returns a new AddonLister. -func NewAddonLister(indexer cache.Indexer) AddonLister { - return &addonLister{indexer: indexer} -} - -// List lists all Addons in the indexer. -func (s *addonLister) List(selector labels.Selector) (ret []*v1.Addon, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Addon)) - }) - return ret, err -} - -// Addons returns an object that can list and get Addons. -func (s *addonLister) Addons(namespace string) AddonNamespaceLister { - return addonNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// AddonNamespaceLister helps list and get Addons. -// All objects returned here must be treated as read-only. -type AddonNamespaceLister interface { - // List lists all Addons in the indexer for a given namespace. - // Objects returned here must be treated as read-only. - List(selector labels.Selector) (ret []*v1.Addon, err error) - // Get retrieves the Addon from the indexer for a given namespace and name. - // Objects returned here must be treated as read-only. - Get(name string) (*v1.Addon, error) - AddonNamespaceListerExpansion -} - -// addonNamespaceLister implements the AddonNamespaceLister -// interface. -type addonNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all Addons in the indexer for a given namespace. -func (s addonNamespaceLister) List(selector labels.Selector) (ret []*v1.Addon, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Addon)) - }) - return ret, err -} - -// Get retrieves the Addon from the indexer for a given namespace and name. -func (s addonNamespaceLister) Get(name string) (*v1.Addon, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1.Resource("addon"), name) - } - return obj.(*v1.Addon), nil -} diff --git a/pkg/generated/listers/k3s.cattle.io/v1/expansion_generated.go b/pkg/generated/listers/k3s.cattle.io/v1/expansion_generated.go deleted file mode 100644 index b4881de9ef..0000000000 --- a/pkg/generated/listers/k3s.cattle.io/v1/expansion_generated.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -// AddonListerExpansion allows custom methods to be added to -// AddonLister. -type AddonListerExpansion interface{} - -// AddonNamespaceListerExpansion allows custom methods to be added to -// AddonNamespaceLister. -type AddonNamespaceListerExpansion interface{} diff --git a/pkg/node/controller.go b/pkg/node/controller.go index c32bdc65bb..0ec5086d94 100644 --- a/pkg/node/controller.go +++ b/pkg/node/controller.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" "github.com/rancher/k3s/pkg/nodepassword" - coreclient "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + coreclient "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" "github.com/sirupsen/logrus" core "k8s.io/api/core/v1" ) diff --git a/pkg/nodepassword/nodepassword.go b/pkg/nodepassword/nodepassword.go index 91e0811c50..ddec742d12 100644 --- a/pkg/nodepassword/nodepassword.go +++ b/pkg/nodepassword/nodepassword.go @@ -10,7 +10,7 @@ import ( "github.com/rancher/k3s/pkg/authenticator/hash" "github.com/rancher/k3s/pkg/passwd" "github.com/rancher/k3s/pkg/version" - coreclient "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + coreclient "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" diff --git a/pkg/rootlessports/controller.go b/pkg/rootlessports/controller.go index 1ca441e92e..7b74740139 100644 --- a/pkg/rootlessports/controller.go +++ b/pkg/rootlessports/controller.go @@ -7,7 +7,7 @@ import ( "time" "github.com/rancher/k3s/pkg/rootless" - coreClients "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + coreClients "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" "github.com/rootless-containers/rootlesskit/pkg/api/client" "github.com/rootless-containers/rootlesskit/pkg/port" "github.com/sirupsen/logrus" diff --git a/pkg/rootlessports/controller_windows.go b/pkg/rootlessports/controller_windows.go index 7b88d2e1e8..56d9982e58 100644 --- a/pkg/rootlessports/controller_windows.go +++ b/pkg/rootlessports/controller_windows.go @@ -3,7 +3,7 @@ package rootlessports import ( "context" - coreClients "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + coreClients "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" ) func Register(ctx context.Context, serviceController coreClients.ServiceController, enabled bool, httpsPort int) error { diff --git a/pkg/server/context.go b/pkg/server/context.go index d30f66486c..f420aeb3a5 100644 --- a/pkg/server/context.go +++ b/pkg/server/context.go @@ -10,12 +10,12 @@ import ( "github.com/rancher/k3s/pkg/deploy" "github.com/rancher/k3s/pkg/generated/controllers/k3s.cattle.io" "github.com/rancher/k3s/pkg/version" - "github.com/rancher/wrangler-api/pkg/generated/controllers/apps" - "github.com/rancher/wrangler-api/pkg/generated/controllers/batch" - "github.com/rancher/wrangler-api/pkg/generated/controllers/core" - "github.com/rancher/wrangler-api/pkg/generated/controllers/rbac" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/crd" + "github.com/rancher/wrangler/pkg/generated/controllers/apps" + "github.com/rancher/wrangler/pkg/generated/controllers/batch" + "github.com/rancher/wrangler/pkg/generated/controllers/core" + "github.com/rancher/wrangler/pkg/generated/controllers/rbac" "github.com/rancher/wrangler/pkg/start" "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/apis/meta/v1/validation" diff --git a/pkg/server/router.go b/pkg/server/router.go index 73ca538459..db45c8895f 100644 --- a/pkg/server/router.go +++ b/pkg/server/router.go @@ -23,7 +23,7 @@ import ( "github.com/rancher/k3s/pkg/daemons/config" "github.com/rancher/k3s/pkg/nodepassword" "github.com/rancher/k3s/pkg/version" - coreclient "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + coreclient "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/util/json" ) diff --git a/pkg/server/server.go b/pkg/server/server.go index 439079ba79..31827ec410 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -29,7 +29,7 @@ import ( "github.com/rancher/k3s/pkg/static" "github.com/rancher/k3s/pkg/util" "github.com/rancher/k3s/pkg/version" - v1 "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + v1 "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" "github.com/rancher/wrangler/pkg/leader" "github.com/rancher/wrangler/pkg/resolvehome" "github.com/sirupsen/logrus" diff --git a/pkg/servicelb/controller.go b/pkg/servicelb/controller.go index 983b86aa68..f1c246aeed 100644 --- a/pkg/servicelb/controller.go +++ b/pkg/servicelb/controller.go @@ -7,10 +7,10 @@ import ( "strconv" "github.com/rancher/k3s/pkg/version" - appclient "github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1" - coreclient "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" + appclient "github.com/rancher/wrangler/pkg/generated/controllers/apps/v1" + coreclient "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" "github.com/rancher/wrangler/pkg/objectset" "github.com/rancher/wrangler/pkg/relatedresource" "github.com/rancher/wrangler/pkg/slice" diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/clientset.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/clientset.go deleted file mode 100644 index fbc977bb15..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/clientset.go +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package versioned - -import ( - "fmt" - - helmv1 "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1" - discovery "k8s.io/client-go/discovery" - rest "k8s.io/client-go/rest" - flowcontrol "k8s.io/client-go/util/flowcontrol" -) - -type Interface interface { - Discovery() discovery.DiscoveryInterface - HelmV1() helmv1.HelmV1Interface -} - -// Clientset contains the clients for groups. Each group has exactly one -// version included in a Clientset. -type Clientset struct { - *discovery.DiscoveryClient - helmV1 *helmv1.HelmV1Client -} - -// HelmV1 retrieves the HelmV1Client -func (c *Clientset) HelmV1() helmv1.HelmV1Interface { - return c.helmV1 -} - -// Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - if c == nil { - return nil - } - return c.DiscoveryClient -} - -// NewForConfig creates a new Clientset for the given config. -// If config's RateLimiter is not set and QPS and Burst are acceptable, -// NewForConfig will generate a rate-limiter in configShallowCopy. -func NewForConfig(c *rest.Config) (*Clientset, error) { - configShallowCopy := *c - if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { - if configShallowCopy.Burst <= 0 { - return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0") - } - configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) - } - var cs Clientset - var err error - cs.helmV1, err = helmv1.NewForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - - cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - return &cs, nil -} - -// NewForConfigOrDie creates a new Clientset for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *Clientset { - var cs Clientset - cs.helmV1 = helmv1.NewForConfigOrDie(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) - return &cs -} - -// New creates a new Clientset for the given RESTClient. -func New(c rest.Interface) *Clientset { - var cs Clientset - cs.helmV1 = helmv1.New(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClient(c) - return &cs -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/doc.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/doc.go deleted file mode 100644 index 78439a3c14..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -// This package has the automatically generated clientset. -package versioned diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme/doc.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme/doc.go deleted file mode 100644 index 6bd144ec29..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -// This package contains the scheme of the automatically generated clientset. -package scheme diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme/register.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme/register.go deleted file mode 100644 index 0f3e2263b7..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme/register.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package scheme - -import ( - helmv1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -var Scheme = runtime.NewScheme() -var Codecs = serializer.NewCodecFactory(Scheme) -var ParameterCodec = runtime.NewParameterCodec(Scheme) -var localSchemeBuilder = runtime.SchemeBuilder{ - helmv1.AddToScheme, -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -var AddToScheme = localSchemeBuilder.AddToScheme - -func init() { - v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) - utilruntime.Must(AddToScheme(Scheme)) -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/doc.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/doc.go deleted file mode 100644 index 761c8c49d4..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -// This package has the automatically generated typed clients. -package v1 diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/generated_expansion.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/generated_expansion.go deleted file mode 100644 index 81557737a1..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/generated_expansion.go +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -type HelmChartExpansion interface{} - -type HelmChartConfigExpansion interface{} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/helm.cattle.io_client.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/helm.cattle.io_client.go deleted file mode 100644 index a45e3f55a2..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/helm.cattle.io_client.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme" - rest "k8s.io/client-go/rest" -) - -type HelmV1Interface interface { - RESTClient() rest.Interface - HelmChartsGetter - HelmChartConfigsGetter -} - -// HelmV1Client is used to interact with features provided by the helm.cattle.io group. -type HelmV1Client struct { - restClient rest.Interface -} - -func (c *HelmV1Client) HelmCharts(namespace string) HelmChartInterface { - return newHelmCharts(c, namespace) -} - -func (c *HelmV1Client) HelmChartConfigs(namespace string) HelmChartConfigInterface { - return newHelmChartConfigs(c, namespace) -} - -// NewForConfig creates a new HelmV1Client for the given config. -func NewForConfig(c *rest.Config) (*HelmV1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - client, err := rest.RESTClientFor(&config) - if err != nil { - return nil, err - } - return &HelmV1Client{client}, nil -} - -// NewForConfigOrDie creates a new HelmV1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *HelmV1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new HelmV1Client for the given RESTClient. -func New(c rest.Interface) *HelmV1Client { - return &HelmV1Client{c} -} - -func setConfigDefaults(config *rest.Config) error { - gv := v1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } - - return nil -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *HelmV1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/helmchart.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/helmchart.go deleted file mode 100644 index b1e495463d..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/helmchart.go +++ /dev/null @@ -1,195 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - "context" - "time" - - v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - scheme "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// HelmChartsGetter has a method to return a HelmChartInterface. -// A group's client should implement this interface. -type HelmChartsGetter interface { - HelmCharts(namespace string) HelmChartInterface -} - -// HelmChartInterface has methods to work with HelmChart resources. -type HelmChartInterface interface { - Create(ctx context.Context, helmChart *v1.HelmChart, opts metav1.CreateOptions) (*v1.HelmChart, error) - Update(ctx context.Context, helmChart *v1.HelmChart, opts metav1.UpdateOptions) (*v1.HelmChart, error) - UpdateStatus(ctx context.Context, helmChart *v1.HelmChart, opts metav1.UpdateOptions) (*v1.HelmChart, error) - Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error - Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.HelmChart, error) - List(ctx context.Context, opts metav1.ListOptions) (*v1.HelmChartList, error) - Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.HelmChart, err error) - HelmChartExpansion -} - -// helmCharts implements HelmChartInterface -type helmCharts struct { - client rest.Interface - ns string -} - -// newHelmCharts returns a HelmCharts -func newHelmCharts(c *HelmV1Client, namespace string) *helmCharts { - return &helmCharts{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the helmChart, and returns the corresponding helmChart object, and an error if there is any. -func (c *helmCharts) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.HelmChart, err error) { - result = &v1.HelmChart{} - err = c.client.Get(). - Namespace(c.ns). - Resource("helmcharts"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of HelmCharts that match those selectors. -func (c *helmCharts) List(ctx context.Context, opts metav1.ListOptions) (result *v1.HelmChartList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1.HelmChartList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("helmcharts"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested helmCharts. -func (c *helmCharts) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("helmcharts"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a helmChart and creates it. Returns the server's representation of the helmChart, and an error, if there is any. -func (c *helmCharts) Create(ctx context.Context, helmChart *v1.HelmChart, opts metav1.CreateOptions) (result *v1.HelmChart, err error) { - result = &v1.HelmChart{} - err = c.client.Post(). - Namespace(c.ns). - Resource("helmcharts"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(helmChart). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a helmChart and updates it. Returns the server's representation of the helmChart, and an error, if there is any. -func (c *helmCharts) Update(ctx context.Context, helmChart *v1.HelmChart, opts metav1.UpdateOptions) (result *v1.HelmChart, err error) { - result = &v1.HelmChart{} - err = c.client.Put(). - Namespace(c.ns). - Resource("helmcharts"). - Name(helmChart.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(helmChart). - Do(ctx). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *helmCharts) UpdateStatus(ctx context.Context, helmChart *v1.HelmChart, opts metav1.UpdateOptions) (result *v1.HelmChart, err error) { - result = &v1.HelmChart{} - err = c.client.Put(). - Namespace(c.ns). - Resource("helmcharts"). - Name(helmChart.Name). - SubResource("status"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(helmChart). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the helmChart and deletes it. Returns an error if one occurs. -func (c *helmCharts) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("helmcharts"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *helmCharts) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("helmcharts"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched helmChart. -func (c *helmCharts) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.HelmChart, err error) { - result = &v1.HelmChart{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("helmcharts"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/helmchartconfig.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/helmchartconfig.go deleted file mode 100644 index 4255a562f2..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1/helmchartconfig.go +++ /dev/null @@ -1,178 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - "context" - "time" - - v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - scheme "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// HelmChartConfigsGetter has a method to return a HelmChartConfigInterface. -// A group's client should implement this interface. -type HelmChartConfigsGetter interface { - HelmChartConfigs(namespace string) HelmChartConfigInterface -} - -// HelmChartConfigInterface has methods to work with HelmChartConfig resources. -type HelmChartConfigInterface interface { - Create(ctx context.Context, helmChartConfig *v1.HelmChartConfig, opts metav1.CreateOptions) (*v1.HelmChartConfig, error) - Update(ctx context.Context, helmChartConfig *v1.HelmChartConfig, opts metav1.UpdateOptions) (*v1.HelmChartConfig, error) - Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error - DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error - Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.HelmChartConfig, error) - List(ctx context.Context, opts metav1.ListOptions) (*v1.HelmChartConfigList, error) - Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) - Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.HelmChartConfig, err error) - HelmChartConfigExpansion -} - -// helmChartConfigs implements HelmChartConfigInterface -type helmChartConfigs struct { - client rest.Interface - ns string -} - -// newHelmChartConfigs returns a HelmChartConfigs -func newHelmChartConfigs(c *HelmV1Client, namespace string) *helmChartConfigs { - return &helmChartConfigs{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the helmChartConfig, and returns the corresponding helmChartConfig object, and an error if there is any. -func (c *helmChartConfigs) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.HelmChartConfig, err error) { - result = &v1.HelmChartConfig{} - err = c.client.Get(). - Namespace(c.ns). - Resource("helmchartconfigs"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(ctx). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of HelmChartConfigs that match those selectors. -func (c *helmChartConfigs) List(ctx context.Context, opts metav1.ListOptions) (result *v1.HelmChartConfigList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - result = &v1.HelmChartConfigList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("helmchartconfigs"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Do(ctx). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested helmChartConfigs. -func (c *helmChartConfigs) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("helmchartconfigs"). - VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). - Watch(ctx) -} - -// Create takes the representation of a helmChartConfig and creates it. Returns the server's representation of the helmChartConfig, and an error, if there is any. -func (c *helmChartConfigs) Create(ctx context.Context, helmChartConfig *v1.HelmChartConfig, opts metav1.CreateOptions) (result *v1.HelmChartConfig, err error) { - result = &v1.HelmChartConfig{} - err = c.client.Post(). - Namespace(c.ns). - Resource("helmchartconfigs"). - VersionedParams(&opts, scheme.ParameterCodec). - Body(helmChartConfig). - Do(ctx). - Into(result) - return -} - -// Update takes the representation of a helmChartConfig and updates it. Returns the server's representation of the helmChartConfig, and an error, if there is any. -func (c *helmChartConfigs) Update(ctx context.Context, helmChartConfig *v1.HelmChartConfig, opts metav1.UpdateOptions) (result *v1.HelmChartConfig, err error) { - result = &v1.HelmChartConfig{} - err = c.client.Put(). - Namespace(c.ns). - Resource("helmchartconfigs"). - Name(helmChartConfig.Name). - VersionedParams(&opts, scheme.ParameterCodec). - Body(helmChartConfig). - Do(ctx). - Into(result) - return -} - -// Delete takes name of the helmChartConfig and deletes it. Returns an error if one occurs. -func (c *helmChartConfigs) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("helmchartconfigs"). - Name(name). - Body(&opts). - Do(ctx). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *helmChartConfigs) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { - var timeout time.Duration - if listOpts.TimeoutSeconds != nil { - timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second - } - return c.client.Delete(). - Namespace(c.ns). - Resource("helmchartconfigs"). - VersionedParams(&listOpts, scheme.ParameterCodec). - Timeout(timeout). - Body(&opts). - Do(ctx). - Error() -} - -// Patch applies the patch and returns the patched helmChartConfig. -func (c *helmChartConfigs) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.HelmChartConfig, err error) { - result = &v1.HelmChartConfig{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("helmchartconfigs"). - Name(name). - SubResource(subresources...). - VersionedParams(&opts, scheme.ParameterCodec). - Body(data). - Do(ctx). - Into(result) - return -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/factory.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/factory.go index e3d11f22c0..a5fbac3083 100644 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/factory.go +++ b/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/factory.go @@ -19,28 +19,12 @@ limitations under the License. package helm import ( - "context" - "time" - - clientset "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned" - scheme "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme" - informers "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions" "github.com/rancher/wrangler/pkg/generic" - "github.com/rancher/wrangler/pkg/schemes" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/rest" ) -func init() { - scheme.AddToScheme(schemes.All) -} - type Factory struct { - synced bool - informerFactory informers.SharedInformerFactory - clientset clientset.Interface - controllerManager *generic.ControllerManager - threadiness map[schema.GroupVersionKind]int + *generic.Factory } func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { @@ -61,66 +45,23 @@ func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (* }) } -type FactoryOptions struct { - Namespace string - Resync time.Duration -} +type FactoryOptions = generic.FactoryOptions func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { - if opts == nil { - opts = &FactoryOptions{} - } - - cs, err := clientset.NewForConfig(config) - if err != nil { - return nil, err - } - - resync := opts.Resync - if resync == 0 { - resync = 2 * time.Hour - } - - if opts.Namespace == "" { - informerFactory := informers.NewSharedInformerFactory(cs, resync) - return NewFactory(cs, informerFactory), nil - } - - informerFactory := informers.NewSharedInformerFactoryWithOptions(cs, resync, informers.WithNamespace(opts.Namespace)) - return NewFactory(cs, informerFactory), nil -} - -func NewFactory(clientset clientset.Interface, informerFactory informers.SharedInformerFactory) *Factory { + f, err := generic.NewFactoryFromConfigWithOptions(config, opts) return &Factory{ - threadiness: map[schema.GroupVersionKind]int{}, - controllerManager: &generic.ControllerManager{}, - clientset: clientset, - informerFactory: informerFactory, + Factory: f, + }, err +} + +func NewFactoryFromConfigWithOptionsOrDie(config *rest.Config, opts *FactoryOptions) *Factory { + f, err := NewFactoryFromConfigWithOptions(config, opts) + if err != nil { + panic(err) } -} - -func (c *Factory) Controllers() map[schema.GroupVersionKind]*generic.Controller { - return c.controllerManager.Controllers() -} - -func (c *Factory) SetThreadiness(gvk schema.GroupVersionKind, threadiness int) { - c.threadiness[gvk] = threadiness -} - -func (c *Factory) Sync(ctx context.Context) error { - c.informerFactory.Start(ctx.Done()) - c.informerFactory.WaitForCacheSync(ctx.Done()) - return nil -} - -func (c *Factory) Start(ctx context.Context, defaultThreadiness int) error { - if err := c.Sync(ctx); err != nil { - return err - } - - return c.controllerManager.Start(ctx, defaultThreadiness, c.threadiness) + return f } func (c *Factory) Helm() Interface { - return New(c.controllerManager, c.informerFactory.Helm(), c.clientset) + return New(c.ControllerFactory()) } diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/interface.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/interface.go index 9956ba4653..98b580076d 100644 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/interface.go +++ b/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/interface.go @@ -19,10 +19,8 @@ limitations under the License. package helm import ( - clientset "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned" v1 "github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1" - informers "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io" - "github.com/rancher/wrangler/pkg/generic" + "github.com/rancher/lasso/pkg/controller" ) type Interface interface { @@ -30,21 +28,16 @@ type Interface interface { } type group struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.Interface + controllerFactory controller.SharedControllerFactory } // New returns a new Interface. -func New(controllerManager *generic.ControllerManager, informers informers.Interface, - client clientset.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &group{ - controllerManager: controllerManager, - informers: informers, - client: client, + controllerFactory: controllerFactory, } } func (g *group) V1() v1.Interface { - return v1.New(g.controllerManager, g.client.HelmV1(), g.informers.V1()) + return v1.New(g.controllerFactory) } diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/helmchart.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/helmchart.go index a4d266c582..0adc7347dc 100644 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/helmchart.go +++ b/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/helmchart.go @@ -23,9 +23,8 @@ import ( "time" v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - clientset "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1" - informers "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1" - listers "github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -78,18 +77,22 @@ type HelmChartCache interface { type HelmChartIndexer func(obj *v1.HelmChart) ([]string, error) type helmChartController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.HelmChartsGetter - informer informers.HelmChartInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewHelmChartController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.HelmChartsGetter, informer informers.HelmChartInformer) HelmChartController { +func NewHelmChartController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) HelmChartController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &helmChartController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdateHelmChartDeepCopyOnChange(client HelmChartClient, obj *v1.HelmChart, } func (c *helmChartController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *helmChartController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *helmChartController) OnChange(ctx context.Context, name string, sync HelmChartHandler) { @@ -149,20 +151,19 @@ func (c *helmChartController) OnChange(ctx context.Context, name string, sync He } func (c *helmChartController) OnRemove(ctx context.Context, name string, sync HelmChartHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromHelmChartHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromHelmChartHandlerToHandler(sync))) } func (c *helmChartController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *helmChartController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *helmChartController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *helmChartController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *helmChartController) GroupVersionKind() schema.GroupVersionKind { func (c *helmChartController) Cache() HelmChartCache { return &helmChartCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *helmChartController) Create(obj *v1.HelmChart) (*v1.HelmChart, error) { - return c.clientGetter.HelmCharts(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.HelmChart{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *helmChartController) Update(obj *v1.HelmChart) (*v1.HelmChart, error) { - return c.clientGetter.HelmCharts(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.HelmChart{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *helmChartController) UpdateStatus(obj *v1.HelmChart) (*v1.HelmChart, error) { - return c.clientGetter.HelmCharts(obj.Namespace).UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.HelmChart{} + return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *helmChartController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.HelmCharts(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *helmChartController) Get(namespace, name string, options metav1.GetOptions) (*v1.HelmChart, error) { - return c.clientGetter.HelmCharts(namespace).Get(context.TODO(), name, options) + result := &v1.HelmChart{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *helmChartController) List(namespace string, opts metav1.ListOptions) (*v1.HelmChartList, error) { - return c.clientGetter.HelmCharts(namespace).List(context.TODO(), opts) + result := &v1.HelmChartList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *helmChartController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.HelmCharts(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *helmChartController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.HelmChart, err error) { - return c.clientGetter.HelmCharts(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *helmChartController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.HelmChart, error) { + result := &v1.HelmChart{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type helmChartCache struct { - lister listers.HelmChartLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *helmChartCache) Get(namespace, name string) (*v1.HelmChart, error) { - return c.lister.HelmCharts(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.HelmChart), nil } -func (c *helmChartCache) List(namespace string, selector labels.Selector) ([]*v1.HelmChart, error) { - return c.lister.HelmCharts(namespace).List(selector) +func (c *helmChartCache) List(namespace string, selector labels.Selector) (ret []*v1.HelmChart, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.HelmChart)) + }) + + return ret, err } func (c *helmChartCache) AddIndexer(indexName string, indexer HelmChartIndexer) { @@ -299,12 +318,20 @@ func (a *helmChartStatusHandler) sync(key string, obj *v1.HelmChart) (*v1.HelmCh } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *helmChartGeneratingHandler) Remove(key string, obj *v1.HelmChart) (*v1. } func (a *helmChartGeneratingHandler) Handle(obj *v1.HelmChart, status v1.HelmChartStatus) (v1.HelmChartStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.HelmChartGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/helmchartconfig.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/helmchartconfig.go index 9d120a1399..73f1d97cf0 100644 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/helmchartconfig.go +++ b/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/helmchartconfig.go @@ -23,11 +23,11 @@ import ( "time" v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - clientset "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1" - informers "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1" - listers "github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -74,18 +74,22 @@ type HelmChartConfigCache interface { type HelmChartConfigIndexer func(obj *v1.HelmChartConfig) ([]string, error) type helmChartConfigController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.HelmChartConfigsGetter - informer informers.HelmChartConfigInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewHelmChartConfigController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.HelmChartConfigsGetter, informer informers.HelmChartConfigInformer) HelmChartConfigController { +func NewHelmChartConfigController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) HelmChartConfigController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &helmChartConfigController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -132,12 +136,11 @@ func UpdateHelmChartConfigDeepCopyOnChange(client HelmChartConfigClient, obj *v1 } func (c *helmChartConfigController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *helmChartConfigController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *helmChartConfigController) OnChange(ctx context.Context, name string, sync HelmChartConfigHandler) { @@ -145,20 +148,19 @@ func (c *helmChartConfigController) OnChange(ctx context.Context, name string, s } func (c *helmChartConfigController) OnRemove(ctx context.Context, name string, sync HelmChartConfigHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromHelmChartConfigHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromHelmChartConfigHandlerToHandler(sync))) } func (c *helmChartConfigController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *helmChartConfigController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *helmChartConfigController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *helmChartConfigController) GroupVersionKind() schema.GroupVersionKind { @@ -167,53 +169,70 @@ func (c *helmChartConfigController) GroupVersionKind() schema.GroupVersionKind { func (c *helmChartConfigController) Cache() HelmChartConfigCache { return &helmChartConfigCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *helmChartConfigController) Create(obj *v1.HelmChartConfig) (*v1.HelmChartConfig, error) { - return c.clientGetter.HelmChartConfigs(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.HelmChartConfig{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *helmChartConfigController) Update(obj *v1.HelmChartConfig) (*v1.HelmChartConfig, error) { - return c.clientGetter.HelmChartConfigs(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.HelmChartConfig{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *helmChartConfigController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.HelmChartConfigs(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *helmChartConfigController) Get(namespace, name string, options metav1.GetOptions) (*v1.HelmChartConfig, error) { - return c.clientGetter.HelmChartConfigs(namespace).Get(context.TODO(), name, options) + result := &v1.HelmChartConfig{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *helmChartConfigController) List(namespace string, opts metav1.ListOptions) (*v1.HelmChartConfigList, error) { - return c.clientGetter.HelmChartConfigs(namespace).List(context.TODO(), opts) + result := &v1.HelmChartConfigList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *helmChartConfigController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.HelmChartConfigs(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *helmChartConfigController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.HelmChartConfig, err error) { - return c.clientGetter.HelmChartConfigs(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *helmChartConfigController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.HelmChartConfig, error) { + result := &v1.HelmChartConfig{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type helmChartConfigCache struct { - lister listers.HelmChartConfigLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *helmChartConfigCache) Get(namespace, name string) (*v1.HelmChartConfig, error) { - return c.lister.HelmChartConfigs(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.HelmChartConfig), nil } -func (c *helmChartConfigCache) List(namespace string, selector labels.Selector) ([]*v1.HelmChartConfig, error) { - return c.lister.HelmChartConfigs(namespace).List(selector) +func (c *helmChartConfigCache) List(namespace string, selector labels.Selector) (ret []*v1.HelmChartConfig, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.HelmChartConfig)) + }) + + return ret, err } func (c *helmChartConfigCache) AddIndexer(indexName string, indexer HelmChartConfigIndexer) { diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/interface.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/interface.go index d3decb6cd2..e1783f31c5 100644 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/interface.go +++ b/vendor/github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1/interface.go @@ -20,34 +20,33 @@ package v1 import ( v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - clientset "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1" - informers "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1" - "github.com/rancher/wrangler/pkg/generic" + "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/schemes" + "k8s.io/apimachinery/pkg/runtime/schema" ) +func init() { + schemes.Register(v1.AddToScheme) +} + type Interface interface { HelmChart() HelmChartController HelmChartConfig() HelmChartConfigController } -func New(controllerManager *generic.ControllerManager, client clientset.HelmV1Interface, - informers informers.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &version{ - controllerManager: controllerManager, - client: client, - informers: informers, + controllerFactory: controllerFactory, } } type version struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.HelmV1Interface + controllerFactory controller.SharedControllerFactory } func (c *version) HelmChart() HelmChartController { - return NewHelmChartController(v1.SchemeGroupVersion.WithKind("HelmChart"), c.controllerManager, c.client, c.informers.HelmCharts()) + return NewHelmChartController(schema.GroupVersionKind{Group: "helm.cattle.io", Version: "v1", Kind: "HelmChart"}, "helmcharts", true, c.controllerFactory) } func (c *version) HelmChartConfig() HelmChartConfigController { - return NewHelmChartConfigController(v1.SchemeGroupVersion.WithKind("HelmChartConfig"), c.controllerManager, c.client, c.informers.HelmChartConfigs()) + return NewHelmChartConfigController(schema.GroupVersionKind{Group: "helm.cattle.io", Version: "v1", Kind: "HelmChartConfig"}, "helmchartconfigs", true, c.controllerFactory) } diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/factory.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/factory.go deleted file mode 100644 index cab6834c71..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/factory.go +++ /dev/null @@ -1,180 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package externalversions - -import ( - reflect "reflect" - sync "sync" - time "time" - - versioned "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned" - helmcattleio "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io" - internalinterfaces "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/internalinterfaces" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" -) - -// SharedInformerOption defines the functional option type for SharedInformerFactory. -type SharedInformerOption func(*sharedInformerFactory) *sharedInformerFactory - -type sharedInformerFactory struct { - client versioned.Interface - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc - lock sync.Mutex - defaultResync time.Duration - customResync map[reflect.Type]time.Duration - - informers map[reflect.Type]cache.SharedIndexInformer - // startedInformers is used for tracking which informers have been started. - // This allows Start() to be called multiple times safely. - startedInformers map[reflect.Type]bool -} - -// WithCustomResyncConfig sets a custom resync period for the specified informer types. -func WithCustomResyncConfig(resyncConfig map[v1.Object]time.Duration) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - for k, v := range resyncConfig { - factory.customResync[reflect.TypeOf(k)] = v - } - return factory - } -} - -// WithTweakListOptions sets a custom filter on all listers of the configured SharedInformerFactory. -func WithTweakListOptions(tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.tweakListOptions = tweakListOptions - return factory - } -} - -// WithNamespace limits the SharedInformerFactory to the specified namespace. -func WithNamespace(namespace string) SharedInformerOption { - return func(factory *sharedInformerFactory) *sharedInformerFactory { - factory.namespace = namespace - return factory - } -} - -// NewSharedInformerFactory constructs a new instance of sharedInformerFactory for all namespaces. -func NewSharedInformerFactory(client versioned.Interface, defaultResync time.Duration) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync) -} - -// NewFilteredSharedInformerFactory constructs a new instance of sharedInformerFactory. -// Listers obtained via this SharedInformerFactory will be subject to the same filters -// as specified here. -// Deprecated: Please use NewSharedInformerFactoryWithOptions instead -func NewFilteredSharedInformerFactory(client versioned.Interface, defaultResync time.Duration, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) SharedInformerFactory { - return NewSharedInformerFactoryWithOptions(client, defaultResync, WithNamespace(namespace), WithTweakListOptions(tweakListOptions)) -} - -// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. -func NewSharedInformerFactoryWithOptions(client versioned.Interface, defaultResync time.Duration, options ...SharedInformerOption) SharedInformerFactory { - factory := &sharedInformerFactory{ - client: client, - namespace: v1.NamespaceAll, - defaultResync: defaultResync, - informers: make(map[reflect.Type]cache.SharedIndexInformer), - startedInformers: make(map[reflect.Type]bool), - customResync: make(map[reflect.Type]time.Duration), - } - - // Apply all options - for _, opt := range options { - factory = opt(factory) - } - - return factory -} - -// Start initializes all requested informers. -func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) { - f.lock.Lock() - defer f.lock.Unlock() - - for informerType, informer := range f.informers { - if !f.startedInformers[informerType] { - go informer.Run(stopCh) - f.startedInformers[informerType] = true - } - } -} - -// WaitForCacheSync waits for all started informers' cache were synced. -func (f *sharedInformerFactory) WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool { - informers := func() map[reflect.Type]cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informers := map[reflect.Type]cache.SharedIndexInformer{} - for informerType, informer := range f.informers { - if f.startedInformers[informerType] { - informers[informerType] = informer - } - } - return informers - }() - - res := map[reflect.Type]bool{} - for informType, informer := range informers { - res[informType] = cache.WaitForCacheSync(stopCh, informer.HasSynced) - } - return res -} - -// InternalInformerFor returns the SharedIndexInformer for obj using an internal -// client. -func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internalinterfaces.NewInformerFunc) cache.SharedIndexInformer { - f.lock.Lock() - defer f.lock.Unlock() - - informerType := reflect.TypeOf(obj) - informer, exists := f.informers[informerType] - if exists { - return informer - } - - resyncPeriod, exists := f.customResync[informerType] - if !exists { - resyncPeriod = f.defaultResync - } - - informer = newFunc(f.client, resyncPeriod) - f.informers[informerType] = informer - - return informer -} - -// SharedInformerFactory provides shared informers for resources in all known -// API group versions. -type SharedInformerFactory interface { - internalinterfaces.SharedInformerFactory - ForResource(resource schema.GroupVersionResource) (GenericInformer, error) - WaitForCacheSync(stopCh <-chan struct{}) map[reflect.Type]bool - - Helm() helmcattleio.Interface -} - -func (f *sharedInformerFactory) Helm() helmcattleio.Interface { - return helmcattleio.New(f, f.namespace, f.tweakListOptions) -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/generic.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/generic.go deleted file mode 100644 index edb7ac4203..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/generic.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package externalversions - -import ( - "fmt" - - v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - schema "k8s.io/apimachinery/pkg/runtime/schema" - cache "k8s.io/client-go/tools/cache" -) - -// GenericInformer is type of SharedIndexInformer which will locate and delegate to other -// sharedInformers based on type -type GenericInformer interface { - Informer() cache.SharedIndexInformer - Lister() cache.GenericLister -} - -type genericInformer struct { - informer cache.SharedIndexInformer - resource schema.GroupResource -} - -// Informer returns the SharedIndexInformer. -func (f *genericInformer) Informer() cache.SharedIndexInformer { - return f.informer -} - -// Lister returns the GenericLister. -func (f *genericInformer) Lister() cache.GenericLister { - return cache.NewGenericLister(f.Informer().GetIndexer(), f.resource) -} - -// ForResource gives generic access to a shared informer of the matching type -// TODO extend this to unknown resources with a client pool -func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { - switch resource { - // Group=helm.cattle.io, Version=v1 - case v1.SchemeGroupVersion.WithResource("helmcharts"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Helm().V1().HelmCharts().Informer()}, nil - case v1.SchemeGroupVersion.WithResource("helmchartconfigs"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Helm().V1().HelmChartConfigs().Informer()}, nil - - } - - return nil, fmt.Errorf("no informer found for %v", resource) -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/interface.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/interface.go deleted file mode 100644 index 2e2f4cacb0..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/interface.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package helm - -import ( - v1 "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1" - internalinterfaces "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/internalinterfaces" -) - -// Interface provides access to each of this group's versions. -type Interface interface { - // V1 provides access to shared informers for resources in V1. - V1() v1.Interface -} - -type group struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// V1 returns a new v1.Interface. -func (g *group) V1() v1.Interface { - return v1.New(g.factory, g.namespace, g.tweakListOptions) -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1/helmchart.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1/helmchart.go deleted file mode 100644 index 24952b07e1..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1/helmchart.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - "context" - time "time" - - helmcattleiov1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - versioned "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned" - internalinterfaces "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/internalinterfaces" - v1 "github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// HelmChartInformer provides access to a shared informer and lister for -// HelmCharts. -type HelmChartInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1.HelmChartLister -} - -type helmChartInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewHelmChartInformer constructs a new informer for HelmChart type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewHelmChartInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredHelmChartInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredHelmChartInformer constructs a new informer for HelmChart type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredHelmChartInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.HelmV1().HelmCharts(namespace).List(context.TODO(), options) - }, - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.HelmV1().HelmCharts(namespace).Watch(context.TODO(), options) - }, - }, - &helmcattleiov1.HelmChart{}, - resyncPeriod, - indexers, - ) -} - -func (f *helmChartInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredHelmChartInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *helmChartInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&helmcattleiov1.HelmChart{}, f.defaultInformer) -} - -func (f *helmChartInformer) Lister() v1.HelmChartLister { - return v1.NewHelmChartLister(f.Informer().GetIndexer()) -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1/helmchartconfig.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1/helmchartconfig.go deleted file mode 100644 index 29b0163063..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1/helmchartconfig.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - "context" - time "time" - - helmcattleiov1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - versioned "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned" - internalinterfaces "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/internalinterfaces" - v1 "github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// HelmChartConfigInformer provides access to a shared informer and lister for -// HelmChartConfigs. -type HelmChartConfigInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1.HelmChartConfigLister -} - -type helmChartConfigInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewHelmChartConfigInformer constructs a new informer for HelmChartConfig type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewHelmChartConfigInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredHelmChartConfigInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredHelmChartConfigInformer constructs a new informer for HelmChartConfig type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredHelmChartConfigInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.HelmV1().HelmChartConfigs(namespace).List(context.TODO(), options) - }, - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.HelmV1().HelmChartConfigs(namespace).Watch(context.TODO(), options) - }, - }, - &helmcattleiov1.HelmChartConfig{}, - resyncPeriod, - indexers, - ) -} - -func (f *helmChartConfigInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredHelmChartConfigInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *helmChartConfigInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&helmcattleiov1.HelmChartConfig{}, f.defaultInformer) -} - -func (f *helmChartConfigInformer) Lister() v1.HelmChartConfigLister { - return v1.NewHelmChartConfigLister(f.Informer().GetIndexer()) -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1/interface.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1/interface.go deleted file mode 100644 index ca4db2fbad..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1/interface.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - internalinterfaces "github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // HelmCharts returns a HelmChartInformer. - HelmCharts() HelmChartInformer - // HelmChartConfigs returns a HelmChartConfigInformer. - HelmChartConfigs() HelmChartConfigInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// HelmCharts returns a HelmChartInformer. -func (v *version) HelmCharts() HelmChartInformer { - return &helmChartInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// HelmChartConfigs returns a HelmChartConfigInformer. -func (v *version) HelmChartConfigs() HelmChartConfigInformer { - return &helmChartConfigInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/internalinterfaces/factory_interfaces.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/internalinterfaces/factory_interfaces.go deleted file mode 100644 index ceb8abdce6..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/internalinterfaces/factory_interfaces.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package internalinterfaces - -import ( - time "time" - - versioned "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - cache "k8s.io/client-go/tools/cache" -) - -// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. -type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer - -// SharedInformerFactory a small interface to allow for adding an informer without an import cycle -type SharedInformerFactory interface { - Start(stopCh <-chan struct{}) - InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer -} - -// TweakListOptionsFunc is a function that transforms a v1.ListOptions. -type TweakListOptionsFunc func(*v1.ListOptions) diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1/expansion_generated.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1/expansion_generated.go deleted file mode 100644 index 3a70312b2c..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1/expansion_generated.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -// HelmChartListerExpansion allows custom methods to be added to -// HelmChartLister. -type HelmChartListerExpansion interface{} - -// HelmChartNamespaceListerExpansion allows custom methods to be added to -// HelmChartNamespaceLister. -type HelmChartNamespaceListerExpansion interface{} - -// HelmChartConfigListerExpansion allows custom methods to be added to -// HelmChartConfigLister. -type HelmChartConfigListerExpansion interface{} - -// HelmChartConfigNamespaceListerExpansion allows custom methods to be added to -// HelmChartConfigNamespaceLister. -type HelmChartConfigNamespaceListerExpansion interface{} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1/helmchart.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1/helmchart.go deleted file mode 100644 index 3a74af99f1..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1/helmchart.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// HelmChartLister helps list HelmCharts. -type HelmChartLister interface { - // List lists all HelmCharts in the indexer. - List(selector labels.Selector) (ret []*v1.HelmChart, err error) - // HelmCharts returns an object that can list and get HelmCharts. - HelmCharts(namespace string) HelmChartNamespaceLister - HelmChartListerExpansion -} - -// helmChartLister implements the HelmChartLister interface. -type helmChartLister struct { - indexer cache.Indexer -} - -// NewHelmChartLister returns a new HelmChartLister. -func NewHelmChartLister(indexer cache.Indexer) HelmChartLister { - return &helmChartLister{indexer: indexer} -} - -// List lists all HelmCharts in the indexer. -func (s *helmChartLister) List(selector labels.Selector) (ret []*v1.HelmChart, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.HelmChart)) - }) - return ret, err -} - -// HelmCharts returns an object that can list and get HelmCharts. -func (s *helmChartLister) HelmCharts(namespace string) HelmChartNamespaceLister { - return helmChartNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// HelmChartNamespaceLister helps list and get HelmCharts. -type HelmChartNamespaceLister interface { - // List lists all HelmCharts in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1.HelmChart, err error) - // Get retrieves the HelmChart from the indexer for a given namespace and name. - Get(name string) (*v1.HelmChart, error) - HelmChartNamespaceListerExpansion -} - -// helmChartNamespaceLister implements the HelmChartNamespaceLister -// interface. -type helmChartNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all HelmCharts in the indexer for a given namespace. -func (s helmChartNamespaceLister) List(selector labels.Selector) (ret []*v1.HelmChart, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.HelmChart)) - }) - return ret, err -} - -// Get retrieves the HelmChart from the indexer for a given namespace and name. -func (s helmChartNamespaceLister) Get(name string) (*v1.HelmChart, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1.Resource("helmchart"), name) - } - return obj.(*v1.HelmChart), nil -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1/helmchartconfig.go b/vendor/github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1/helmchartconfig.go deleted file mode 100644 index 0dfe286738..0000000000 --- a/vendor/github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1/helmchartconfig.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// HelmChartConfigLister helps list HelmChartConfigs. -type HelmChartConfigLister interface { - // List lists all HelmChartConfigs in the indexer. - List(selector labels.Selector) (ret []*v1.HelmChartConfig, err error) - // HelmChartConfigs returns an object that can list and get HelmChartConfigs. - HelmChartConfigs(namespace string) HelmChartConfigNamespaceLister - HelmChartConfigListerExpansion -} - -// helmChartConfigLister implements the HelmChartConfigLister interface. -type helmChartConfigLister struct { - indexer cache.Indexer -} - -// NewHelmChartConfigLister returns a new HelmChartConfigLister. -func NewHelmChartConfigLister(indexer cache.Indexer) HelmChartConfigLister { - return &helmChartConfigLister{indexer: indexer} -} - -// List lists all HelmChartConfigs in the indexer. -func (s *helmChartConfigLister) List(selector labels.Selector) (ret []*v1.HelmChartConfig, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.HelmChartConfig)) - }) - return ret, err -} - -// HelmChartConfigs returns an object that can list and get HelmChartConfigs. -func (s *helmChartConfigLister) HelmChartConfigs(namespace string) HelmChartConfigNamespaceLister { - return helmChartConfigNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// HelmChartConfigNamespaceLister helps list and get HelmChartConfigs. -type HelmChartConfigNamespaceLister interface { - // List lists all HelmChartConfigs in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1.HelmChartConfig, err error) - // Get retrieves the HelmChartConfig from the indexer for a given namespace and name. - Get(name string) (*v1.HelmChartConfig, error) - HelmChartConfigNamespaceListerExpansion -} - -// helmChartConfigNamespaceLister implements the HelmChartConfigNamespaceLister -// interface. -type helmChartConfigNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all HelmChartConfigs in the indexer for a given namespace. -func (s helmChartConfigNamespaceLister) List(selector labels.Selector) (ret []*v1.HelmChartConfig, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.HelmChartConfig)) - }) - return ret, err -} - -// Get retrieves the HelmChartConfig from the indexer for a given namespace and name. -func (s helmChartConfigNamespaceLister) Get(name string) (*v1.HelmChartConfig, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1.Resource("helmchartconfig"), name) - } - return obj.(*v1.HelmChartConfig), nil -} diff --git a/vendor/github.com/k3s-io/helm-controller/pkg/helm/controller.go b/vendor/github.com/k3s-io/helm-controller/pkg/helm/controller.go index d82dc10ad6..a3bdd4e213 100644 --- a/vendor/github.com/k3s-io/helm-controller/pkg/helm/controller.go +++ b/vendor/github.com/k3s-io/helm-controller/pkg/helm/controller.go @@ -11,10 +11,10 @@ import ( helmv1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1" helmcontroller "github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1" - batchcontroller "github.com/rancher/wrangler-api/pkg/generated/controllers/batch/v1" - corecontroller "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" - rbaccontroller "github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1" "github.com/rancher/wrangler/pkg/apply" + batchcontroller "github.com/rancher/wrangler/pkg/generated/controllers/batch/v1" + corecontroller "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" + rbaccontroller "github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1" "github.com/rancher/wrangler/pkg/objectset" "github.com/rancher/wrangler/pkg/relatedresource" batch "k8s.io/api/batch/v1" @@ -30,6 +30,7 @@ import ( var ( trueVal = true commaRE = regexp.MustCompile(`\\*,`) + deletePolicy = meta.DeletePropagationForeground DefaultJobImage = "rancher/klipper-helm:v0.6.6-build20211022" ) @@ -64,7 +65,7 @@ func Register(ctx context.Context, apply apply.Apply, apply = apply.WithSetID(Name). WithCacheTypes(helms, confs, jobs, crbs, sas, cm). WithStrictCaching().WithPatcher(batch.SchemeGroupVersion.WithKind("Job"), func(namespace, name string, pt types.PatchType, data []byte) (runtime.Object, error) { - err := jobs.Delete(namespace, name, &meta.DeleteOptions{}) + err := jobs.Delete(namespace, name, &meta.DeleteOptions{PropagationPolicy: &deletePolicy}) if err == nil { return nil, fmt.Errorf("replace job") } diff --git a/vendor/github.com/rancher/dynamiclistener/factory/gen.go b/vendor/github.com/rancher/dynamiclistener/factory/gen.go index ff15a932ac..1f43e67429 100644 --- a/vendor/github.com/rancher/dynamiclistener/factory/gen.go +++ b/vendor/github.com/rancher/dynamiclistener/factory/gen.go @@ -26,7 +26,7 @@ const ( ) var ( - cnRegexp = regexp.MustCompile("^([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$") + cnRegexp = regexp.MustCompile("^([A-Za-z0-9:][-A-Za-z0-9_.:]*)?[A-Za-z0-9:]$") ) type TLS struct { diff --git a/vendor/github.com/rancher/dynamiclistener/go.mod b/vendor/github.com/rancher/dynamiclistener/go.mod index 8eb297f0fa..d0420c1d49 100644 --- a/vendor/github.com/rancher/dynamiclistener/go.mod +++ b/vendor/github.com/rancher/dynamiclistener/go.mod @@ -1,12 +1,11 @@ module github.com/rancher/dynamiclistener -go 1.12 +go 1.16 require ( - github.com/rancher/wrangler v0.1.4 - github.com/rancher/wrangler-api v0.2.0 - github.com/sirupsen/logrus v1.4.1 - golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 - k8s.io/api v0.0.0-20190409021203-6e4e0e4f393b - k8s.io/apimachinery v0.0.0-20190404173353-6a84e37a896d + github.com/rancher/wrangler v0.8.3 + github.com/sirupsen/logrus v1.4.2 + golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 + k8s.io/api v0.18.8 + k8s.io/apimachinery v0.18.8 ) diff --git a/vendor/github.com/rancher/dynamiclistener/go.sum b/vendor/github.com/rancher/dynamiclistener/go.sum index b940275223..9a359c67ae 100644 --- a/vendor/github.com/rancher/dynamiclistener/go.sum +++ b/vendor/github.com/rancher/dynamiclistener/go.sum @@ -1,132 +1,618 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +github.com/360EntSecGroup-Skylar/excelize v1.4.1/go.mod h1:vnax29X2usfl7HHkBrX5EvSCJcmH3dT9luvxzu8iGAE= +github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= +github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= +github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/MakeNowJust/heredoc v0.0.0-20170808103936-bb23615498cd/go.mod h1:64YHyfSL2R96J44Nlwm39UHepQbyR5q10x7iYa1ks2E= github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/PuerkitoBio/goquery v1.5.0/go.mod h1:qD2PgZ9lccMbQlc7eEOjaeRlFQON7xY8kdmcsrnKqMg= github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/purell v1.1.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4RqaHDIsdSBg7lM= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= +github.com/andybalholm/cascadia v1.0.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/asaskevich/govalidator v0.0.0-20180720115003-f9ffefc3facf/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= +github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/blang/semver v3.5.0+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/chai2010/gettext-go v0.0.0-20160711120539-c6fed771bfd5/go.mod h1:/iP1qXHoty45bqomnu2LM+VVyAEdWN+vtSHGlQgyxbw= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= +github.com/coreos/bbolt v1.3.1-coreos.6/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= +github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/etcd v3.3.15+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= +github.com/coreos/go-oidc v2.1.0+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/coreos/pkg v0.0.0-20180108230652-97fdf19511ea/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/davecgh/go-spew v0.0.0-20151105211317-5215b55f46b2/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/daviddengcn/go-colortext v0.0.0-20160507010035-511bcaf42ccd/go.mod h1:dv4zxwHi5C/8AeI+4gX4dCWOIvNi7I6JCSX0HvlKPgE= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= +github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v0.7.3-0.20190327010347-be7ac8be2ae0/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-units v0.3.3/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM= +github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= +github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustmop/soup v1.1.2-0.20190516214245-38228baa104e/go.mod h1:CgNC6SGbT+Xb8wGGvzilttZL1mc5sQ/5KkcxsZttMIk= +github.com/elazarl/goproxy v0.0.0-20170405201442-c4fc26588b6e/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= +github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= +github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/evanphx/json-patch v0.0.0-20200808040245-162e5629780b/go.mod h1:NAJj0yf/KaRKURN6nyi7A9IZydMivZEm9oQLWNjfKDc= github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/evanphx/json-patch v4.5.0+incompatible h1:ouOWdg56aJriqS0huScTkVXPC5IcNrDCXZ6OoTAWu7M= +github.com/evanphx/json-patch v4.5.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d/go.mod h1:ZZMPRZwes7CROmyNKgQzC3XPs6L/G2EJLHddWejkmf4= +github.com/fatih/camelcase v1.0.0/go.mod h1:yN2Sb0lFhZJUdVvtELVWefmrXpuZESvPmqwoZc+/fpc= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/globalsign/mgo v0.0.0-20180905125535-1ca0a4f7cbcb/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q= +github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q= +github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= +github.com/go-logr/zapr v0.1.0/go.mod h1:tabnROwaDl0UNxkVeFRbY8bwB37GwRv0P8lg6aAiEnk= +github.com/go-openapi/analysis v0.0.0-20180825180245-b006789cd277/go.mod h1:k70tL6pCuVxPJOHXQ+wIac1FUrvNkHolPie/cLEU6hI= +github.com/go-openapi/analysis v0.17.0/go.mod h1:IowGgpVeD0vNm45So8nr+IcQ3pxVtpRoBWb8PVZO0ik= +github.com/go-openapi/analysis v0.18.0/go.mod h1:IowGgpVeD0vNm45So8nr+IcQ3pxVtpRoBWb8PVZO0ik= +github.com/go-openapi/analysis v0.19.2/go.mod h1:3P1osvZa9jKjb8ed2TPng3f0i/UY9snX6gxi44djMjk= +github.com/go-openapi/analysis v0.19.5/go.mod h1:hkEAkxagaIvIP7VTn8ygJNkd4kAYON2rCu0v0ObL0AU= +github.com/go-openapi/errors v0.17.0/go.mod h1:LcZQpmvG4wyF5j4IhA73wkLFQg+QJXOQHVjmcZxhka0= +github.com/go-openapi/errors v0.18.0/go.mod h1:LcZQpmvG4wyF5j4IhA73wkLFQg+QJXOQHVjmcZxhka0= +github.com/go-openapi/errors v0.19.2/go.mod h1:qX0BLWsyaKfvhluLejVpVNwNRdXZhEbTA4kxxpKBC94= github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0= +github.com/go-openapi/jsonpointer v0.17.0/go.mod h1:cOnomiV+CVVwFLk0A/MExoFMjwdsUdVpsRhURCKh+3M= +github.com/go-openapi/jsonpointer v0.18.0/go.mod h1:cOnomiV+CVVwFLk0A/MExoFMjwdsUdVpsRhURCKh+3M= +github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg= +github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg= +github.com/go-openapi/jsonreference v0.17.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I= +github.com/go-openapi/jsonreference v0.18.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I= +github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc= +github.com/go-openapi/jsonreference v0.19.3/go.mod h1:rjx6GuL8TTa9VaixXglHmQmIL98+wF9xc8zWvFonSJ8= +github.com/go-openapi/loads v0.17.0/go.mod h1:72tmFy5wsWx89uEVddd0RjRWPZm92WRLhf7AC+0+OOU= +github.com/go-openapi/loads v0.18.0/go.mod h1:72tmFy5wsWx89uEVddd0RjRWPZm92WRLhf7AC+0+OOU= +github.com/go-openapi/loads v0.19.0/go.mod h1:72tmFy5wsWx89uEVddd0RjRWPZm92WRLhf7AC+0+OOU= +github.com/go-openapi/loads v0.19.2/go.mod h1:QAskZPMX5V0C2gvfkGZzJlINuP7Hx/4+ix5jWFxsNPs= +github.com/go-openapi/loads v0.19.4/go.mod h1:zZVHonKd8DXyxyw4yfnVjPzBjIQcLt0CCsn0N0ZrQsk= +github.com/go-openapi/runtime v0.0.0-20180920151709-4f900dc2ade9/go.mod h1:6v9a6LTXWQCdL8k1AO3cvqx5OtZY/Y9wKTgaoP6YRfA= +github.com/go-openapi/runtime v0.19.0/go.mod h1:OwNfisksmmaZse4+gpV3Ne9AyMOlP1lt4sK4FXt0O64= +github.com/go-openapi/runtime v0.19.4/go.mod h1:X277bwSUBxVlCYR3r7xgZZGKVvBd/29gLDlFGtJ8NL4= github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc= +github.com/go-openapi/spec v0.17.0/go.mod h1:XkF/MOi14NmjsfZ8VtAKf8pIlbZzyoTvZsdfssdxcBI= +github.com/go-openapi/spec v0.18.0/go.mod h1:XkF/MOi14NmjsfZ8VtAKf8pIlbZzyoTvZsdfssdxcBI= +github.com/go-openapi/spec v0.19.2/go.mod h1:sCxk3jxKgioEJikev4fgkNmwS+3kuYdJtcsZsD5zxMY= +github.com/go-openapi/spec v0.19.3/go.mod h1:FpwSN1ksY1eteniUU7X0N/BgJ7a4WvBFVA8Lj9mJglo= +github.com/go-openapi/spec v0.19.5/go.mod h1:Hm2Jr4jv8G1ciIAo+frC/Ft+rR2kQDh8JHKHb3gWUSk= +github.com/go-openapi/strfmt v0.17.0/go.mod h1:P82hnJI0CXkErkXi8IKjPbNBM6lV6+5pLP5l494TcyU= +github.com/go-openapi/strfmt v0.18.0/go.mod h1:P82hnJI0CXkErkXi8IKjPbNBM6lV6+5pLP5l494TcyU= +github.com/go-openapi/strfmt v0.19.0/go.mod h1:+uW+93UVvGGq2qGaZxdDeJqSAqBqBdl+ZPMF/cC8nDY= +github.com/go-openapi/strfmt v0.19.3/go.mod h1:0yX7dbo8mKIvc3XSKp7MNfxw4JytCfCD6+bY1AVL9LU= +github.com/go-openapi/strfmt v0.19.5/go.mod h1:eftuHTlB/dI8Uq8JJOyRlieZf+WkkxUuk0dgdHXr2Qk= github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I= -github.com/gogo/protobuf v1.2.1 h1:/s5zKNz0uPFCZ5hddgPdo2TK2TVrUNMn0OOX8/aZMTE= +github.com/go-openapi/swag v0.17.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg= +github.com/go-openapi/swag v0.18.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg= +github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/validate v0.18.0/go.mod h1:Uh4HdOzKt19xGIGm1qHf/ofbX1YQ4Y+MYsct2VUrAJ4= +github.com/go-openapi/validate v0.19.2/go.mod h1:1tRCw7m3jtI8eNWEEliiAqUIcBztB2KDnRCRMUi7GTA= +github.com/go-openapi/validate v0.19.5/go.mod h1:8DJv2CVJQ6kGNpFW6eV9N3JviE1C85nY1c2z52x1Gk4= +github.com/go-openapi/validate v0.19.8/go.mod h1:8DJv2CVJQ6kGNpFW6eV9N3JviE1C85nY1c2z52x1Gk4= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= -github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef h1:veQD95Isof8w9/WXiA+pa3tz3fJXkt5B7QaRBrM62gk= +github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/gogo/protobuf v1.3.1 h1:DqDEcV5aeaTmdFBePNpYsp3FlcVH/2ISVVM9Qf8PSls= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20180513044358-24b0969c4cb7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 h1:ZgQEtGgCBiWRM39fZuwSd1LwSqqSW0hOdXCYYDX0R3I= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v0.0.0-20161109072736-4bd1920723d7/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.0.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golangplus/bytes v0.0.0-20160111154220-45c989fe5450/go.mod h1:Bk6SMAONeMXrxql8uvOKuAZSu8aM5RUGv+1C6IJaEho= +github.com/golangplus/fmt v0.0.0-20150411045040-2a5d6d7d2995/go.mod h1:lJgMEyOkYFkPcDKwRXegd+iM6E7matEszMG5HhwytU8= +github.com/golangplus/testing v0.0.0-20180327235837-af21d9c3145e/go.mod h1:0AA//k/eakGydO4jKRoRL2j92ZKSzTgj9tclaCrvXHk= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-containerregistry v0.0.0-20190617215043-876b8855d23c/go.mod h1:yZAFP63pRshzrEYLXLGPmUt0Ay+2zdjmMN1loCnRLUk= +github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= -github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/googleapis/gnostic v0.0.0-20170426233943-68f4ded48ba9/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= -github.com/googleapis/gnostic v0.2.0 h1:l6N3VoaVzTncYYW+9yOz2LJJammFZGBO13sqgEhpy9g= -github.com/googleapis/gnostic v0.2.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= -github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= +github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= +github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= +github.com/googleapis/gnostic v0.1.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= +github.com/googleapis/gnostic v0.3.1 h1:WeAefnSUHlBb0iJKwxFDZdbfGwkd7xRNuV+IpXMJhYk= +github.com/googleapis/gnostic v0.3.1/go.mod h1:on+2t9HRStVgn95RSsFWFz+6Q0Snyqv1awfrALZdbtU= +github.com/gophercloud/gophercloud v0.1.0/go.mod h1:vxM41WHh5uqHVBMZHzuwNOHh8XEoIEcSTewFxm1c5g8= +github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gregjones/httpcache v0.0.0-20170728041850-787624de3eb7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/grpc-ecosystem/go-grpc-middleware v0.0.0-20190222133341-cfaf5686ec79/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.3.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= +github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/imdario/mergo v0.3.7/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/jetstack/cert-manager v0.7.2/go.mod h1:nbddmhjWxYGt04bxvwVGUSeLhZ2PCyNvd7MpXdq+yWY= +github.com/hashicorp/golang-lru v0.5.3 h1:YPkqC67at8FYaadspW/6uE0COsBxS2656RLEr8Bppgk= +github.com/hashicorp/golang-lru v0.5.3/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/json-iterator/go v0.0.0-20180612202835-f2b4162afba3/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.6 h1:MrUvLMLTMxbqFJ9kzlvat/rYZqZnW3u4wkLzWTaFwKs= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.8 h1:QiWkFLKq0T7mpzwOTu6BzNDbfTE8OLrYhVKYMLF46Ok= +github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= -github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/knative/build v0.6.0/go.mod h1:/sU74ZQkwlYA5FwYDJhYTy61i/Kn+5eWfln2jDbw3Qo= -github.com/knative/pkg v0.0.0-20190514205332-5e4512dcb2ca/go.mod h1:7Ijfhw7rfB+H9VtosIsDYvZQ+qYTz7auK3fHW/5z4ww= -github.com/knative/serving v0.6.1/go.mod h1:ljvMfwQy2qanaM/8xnBSK4Mz3Vv2NawC2fo5kFRJS1A= -github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +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/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= +github.com/lithammer/dedent v1.1.0/go.mod h1:jrXYCQtgg0nJiN+StA2KgR7w6CiQNv9Fd/Z9BP0jIOc= +github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/matryer/moq v0.0.0-20190312154309-6cfb0558e1bd/go.mod h1:9ELz6aaclSIGnZBoaSLZ3NAl1VTufbOrXBPvtcy6WiQ= -github.com/mattbaird/jsonpatch v0.0.0-20171005235357-81af80346b1a/go.mod h1:M1qoD/MqPgTZIk0EWKB38wE28ACRfVcn+cU08jyArI0= +github.com/mailru/easyjson v0.0.0-20180823135443-60711f1a8329/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180320133207-05fbef0ca5da/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.4.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.11.0 h1:JAKSXpt1YjtLA7YpPiqO9ss6sNXEsPfSGdwN0UHqzrw= +github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= +github.com/onsi/gomega v1.3.0/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= +github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.8.1 h1:C5Dqfs/LeauYDX0jJXIe2SWmwCbGzx9yF8C8xy3Lh34= +github.com/onsi/gomega v1.8.1/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= +github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= +github.com/paulmach/orb v0.1.3/go.mod h1:VFlX/8C+IQ1p6FTRRKzKoOPJnvEtA5G0Veuqwbu//Vk= +github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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/rancher/wrangler v0.1.4 h1:bdzBw4H9JKQhXPBPNp4eHbmrkA24+VII865VLiVWcw8= -github.com/rancher/wrangler v0.1.4/go.mod h1:EYP7cqpg42YqElaCm+U9ieSrGQKAXxUH5xsr+XGpWyE= -github.com/rancher/wrangler-api v0.2.0 h1:VR7hLNnDrKykKLqthtwZ58pDDtUa9ijSNToPaJLEkWc= -github.com/rancher/wrangler-api v0.2.0/go.mod h1:zTPdNLZO07KvRaVOx6XQbKBSV55Fnn4s7nqmrMPJqd8= -github.com/sirupsen/logrus v1.4.1 h1:GL2rEmy6nsikmW0r8opw9JIRScdMF5hA8cOYLH7In1k= -github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/pquerna/cachecontrol v0.0.0-20171018203845-0dec1b30a021/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM= +github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= +github.com/qri-io/starlib v0.4.2-0.20200213133954-ff2e8cd5ef8d/go.mod h1:7DPO4domFU579Ga6E61sB9VFNaniPVwJP5C4bBCu3wA= +github.com/rancher/lasso v0.0.0-20210616224652-fc3ebd901c08 h1:NxR8Fh0eE7/5/5Zvlog9B5NVjWKqBSb1WYMUF7/IE5c= +github.com/rancher/lasso v0.0.0-20210616224652-fc3ebd901c08/go.mod h1:9qZd/S8DqWzfKtjKGgSoHqGEByYmUE3qRaBaaAHwfEM= +github.com/rancher/wrangler v0.8.3 h1:m3d5ChOQj2Pdozy6nkGiSzAgQxlQlXRis2zSRwaO83k= +github.com/rancher/wrangler v0.8.3/go.mod h1:dKEaHNB4izxmPUtpq1Hvr3z3Oh+9k5pCZyFO9sUhlaY= +github.com/remyoudompheng/bigfft v0.0.0-20170806203942-52369c62f446/go.mod h1:uYEyJGbgTkfkS4+E/PavXkNJcbFIpEtjt2B0KDQ5+9M= +github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/soheilhy/cmux v0.1.3/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= -github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff h1:VARhShG49tiji6mdRNp7JTNDtJ0FhuprF93GBQ37xGU= +github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= +github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= +github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/testify v0.0.0-20151208002404-e3a8ff8ce365/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= +github.com/stretchr/testify v1.2.3-0.20181224173747-660f15d67dbb/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/tektoncd/pipeline v0.4.0/go.mod h1:IZzJdiX9EqEMuUcgdnElozdYYRh0/ZRC+NKMLj1K3Yw= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= +github.com/vektah/gqlparser v1.1.2/go.mod h1:1ycwN7Ij5njmMkPPAOaRFY4rET2Enx7IkVv3vaXspKw= +github.com/xiang90/probing v0.0.0-20160813154853-07dd2e8dfe18/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xlab/handysort v0.0.0-20150421192137-fb3537ed64a1/go.mod h1:QcJo0QPSfTONNIgpN5RA8prR7fF8nkF6cTWTcNerRO8= +github.com/xlab/treeprint v0.0.0-20181112141820-a009c3971eca/go.mod h1:ce1O1j6UtZfjr22oyGxGLbauSBp2YVXpARAosm7dHBg= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= +go.mongodb.org/mongo-driver v1.0.3/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qLUO4lqsUM= +go.mongodb.org/mongo-driver v1.1.1/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qLUO4lqsUM= +go.mongodb.org/mongo-driver v1.1.2/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qLUO4lqsUM= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.starlark.net v0.0.0-20190528202925-30ae18b8564f/go.mod h1:c1/X6cHgvdXj6pUlmWKMkuqRnW4K8x2vwt6JAaaircg= +go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5/go.mod h1:nmDLcffg48OtT/PSW0Hg7FvpRQsQh5OSqIylirxKC7o= +go.uber.org/atomic v0.0.0-20181018215023-8dc6146f7569/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/multierr v0.0.0-20180122172545-ddea229ff1df/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/zap v0.0.0-20180814183419-67bc79d13d15/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190320223903-b7391e95e576/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190617133340-57b3e21c3d56/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 h1:It14KIkyBFYkHkwZ7k45minvA9aorojkyjGk9KJ5B/w= +golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190312203227-4b39c73a6495/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180112015858-5ccada7d0a7b/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181005035420-146acd28ed58/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/oauth2 v0.0.0-20190402181905-9f3314589c9a h1:tImsplftrFpALCYumobsd0K86vlAs/eXGFms2txfJfA= -golang.org/x/oauth2 v0.0.0-20190402181905-9f3314589c9a/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/net v0.0.0-20190320064053-1272bf9dcd53/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190812203447-cdfb69ac37fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 h1:qWPm9rbaAMKs8Bq/9LRpbMqxWRVUAQwMI9fVrssnTfw= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20170830134202-bb24a47a89ea/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33 h1:I6FyU15t786LL7oL/hn43zqTuEGr4PN7F4XJ1p4E3Y8= +golang.org/x/sys v0.0.0-20180117170059-2c42eef0765b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190209173611-3b5209105503/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190321052220-f7bb7a8bee54/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191002063906-3421d5a6bb1c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20171227012246-e19ae1496984/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190125232054-d66bd3c5d5a6/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190617190820-da514acc4774/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190920225731-5eefd052ad72/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191017205301-920acffc3e65/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 h1:/atklqdjdhuosWIl6AIbOeHJjicWYPqR9bpxqxYG2pA= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gomodules.xyz/jsonpatch/v2 v2.0.1/go.mod h1:IhYNNY4jnS53ZnfE4PAmpKtDpTCj1JFXc+3mwe7XcUU= +gonum.org/v1/gonum v0.0.0-20190331200053-3d26580ed485/go.mod h1:2ltnJ7xHfj0zHS40VVPYEAAMTa3ZGguvHGBSJeRWqE0= +gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= +gonum.org/v1/netlib v0.0.0-20190331212654-76723241ea4e/go.mod h1:kS+toOQn6AQKjmKJ7gzohV1XkqsFehRA2FbsbkopSuQ= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1 h1:QzqyMA1tlu6CgqCDUtU9V+ZKhLFT2dkJuANu5QaxI3I= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.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 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/inf.v0 v0.9.0/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= +gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= +gopkg.in/square/go-jose.v2 v2.2.2/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= +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/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= +gopkg.in/yaml.v2 v2.0.0/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -k8s.io/api v0.0.0-20190409021203-6e4e0e4f393b h1:aBGgKJUM9Hk/3AE8WaZIApnTxG35kbuQba2w+SXqezo= -k8s.io/api v0.0.0-20190409021203-6e4e0e4f393b/go.mod h1:iuAfoD4hCxJ8Onx9kaTIt30j7jUFS00AXQi6QMi99vA= -k8s.io/apiextensions-apiserver v0.0.0-20190409022649-727a075fdec8/go.mod h1:IxkesAMoaCRoLrPJdZNZUQp9NfZnzqaVzLhb2VEQzXE= -k8s.io/apimachinery v0.0.0-20190404173353-6a84e37a896d h1:Jmdtdt1ZnoGfWWIIik61Z7nKYgO3J+swQJtPYsP9wHA= -k8s.io/apimachinery v0.0.0-20190404173353-6a84e37a896d/go.mod h1:ccL7Eh7zubPUSh9A3USN90/OzHNSVN6zxzde07TDCL0= -k8s.io/client-go v11.0.1-0.20190409021438-1a26190bd76a+incompatible h1:U5Bt+dab9K8qaUmXINrkXO135kA11/i5Kg1RUydgaMQ= -k8s.io/client-go v11.0.1-0.20190409021438-1a26190bd76a+incompatible/go.mod h1:7vJpHMYJwNQCWgzmNV+VYUl1zCObLyodBc8nIyt8L5s= -k8s.io/code-generator v0.0.0-20190311093542-50b561225d70/go.mod h1:MYiN+ZJZ9HkETbgVZdWw2AsuAi9PZ4V80cwfuf2axe8= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +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-20191120175047-4206685974f2/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200121175148-a6ecf24a6d71/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +k8s.io/api v0.0.0-20190918155943-95b840bb6a1f/go.mod h1:uWuOHnjmNrtQomJrvEBg0c0HRNyQ+8KTEERVsK0PW48= +k8s.io/api v0.0.0-20191214185829-ca1d04f8b0d3/go.mod h1:itOjKREfmUTvcjantxOsyYU5mbFsU7qUnyUuRfF5+5M= +k8s.io/api v0.17.2/go.mod h1:BS9fjjLc4CMuqfSO8vgbHPKMt5+SF0ET6u/RVDihTo4= +k8s.io/api v0.18.0/go.mod h1:q2HRQkfDzHMBZL9l/y9rH63PkQl4vae0xRT+8prbrK8= +k8s.io/api v0.18.8 h1:aIKUzJPb96f3fKec2lxtY7acZC9gQNDLVhfSGpxBAC4= +k8s.io/api v0.18.8/go.mod h1:d/CXqwWv+Z2XEG1LgceeDmHQwpUJhROPx16SlxJgERY= +k8s.io/apiextensions-apiserver v0.0.0-20190918161926-8f644eb6e783/go.mod h1:xvae1SZB3E17UpV59AWc271W/Ph25N+bjPyR63X6tPY= +k8s.io/apiextensions-apiserver v0.17.2/go.mod h1:4KdMpjkEjjDI2pPfBA15OscyNldHWdBCfsWMDWAmSTs= +k8s.io/apiextensions-apiserver v0.18.0/go.mod h1:18Cwn1Xws4xnWQNC00FLq1E350b9lUF+aOdIWDOZxgo= +k8s.io/apimachinery v0.0.0-20190913080033-27d36303b655/go.mod h1:nL6pwRT8NgfF8TT68DBI8uEePRt89cSvoXUVqbkWHq4= +k8s.io/apimachinery v0.0.0-20191214185652-442f8fb2f03a/go.mod h1:Ng1IY8TS7sC44KJxT/WUR6qFRfWwahYYYpNXyYRKOCY= +k8s.io/apimachinery v0.0.0-20191216025728-0ee8b4573e3a/go.mod h1:Ng1IY8TS7sC44KJxT/WUR6qFRfWwahYYYpNXyYRKOCY= +k8s.io/apimachinery v0.17.2/go.mod h1:b9qmWdKlLuU9EBh+06BtLcSf/Mu89rWL33naRxs1uZg= +k8s.io/apimachinery v0.18.0/go.mod h1:9SnR/e11v5IbyPCGbvJViimtJ0SwHG4nfZFjU77ftcA= +k8s.io/apimachinery v0.18.8 h1:jimPrycCqgx2QPearX3to1JePz7wSbVLq+7PdBTTwQ0= +k8s.io/apimachinery v0.18.8/go.mod h1:6sQd+iHEqmOtALqOFjSWp2KZ9F0wlU/nWm0ZgsYWMig= +k8s.io/apiserver v0.0.0-20190918160949-bfa5e2e684ad/go.mod h1:XPCXEwhjaFN29a8NldXA901ElnKeKLrLtREO9ZhFyhg= +k8s.io/apiserver v0.17.2/go.mod h1:lBmw/TtQdtxvrTk0e2cgtOxHizXI+d0mmGQURIHQZlo= +k8s.io/apiserver v0.18.0/go.mod h1:3S2O6FeBBd6XTo0njUrLxiqk8GNy6wWOftjhJcXYnjw= +k8s.io/cli-runtime v0.0.0-20191214191754-e6dc6d5c8724/go.mod h1:wzlq80lvjgHW9if6MlE4OIGC86MDKsy5jtl9nxz/IYY= +k8s.io/cli-runtime v0.17.2/go.mod h1:aa8t9ziyQdbkuizkNLAw3qe3srSyWh9zlSB7zTqRNPI= +k8s.io/client-go v0.0.0-20190918160344-1fbdaa4c8d90/go.mod h1:J69/JveO6XESwVgG53q3Uz5OSfgsv4uxpScmmyYOOlk= +k8s.io/client-go v0.0.0-20191214190045-a32a6f7a3052/go.mod h1:tAaoc/sYuIL0+njJefSAmE28CIcxyaFV4kbIujBlY2s= +k8s.io/client-go v0.0.0-20191219150334-0b8da7416048/go.mod h1:ZEe8ZASDUAuqVGJ+UN0ka0PfaR+b6a6E1PGsSNZRui8= +k8s.io/client-go v0.17.2/go.mod h1:QAzRgsa0C2xl4/eVpeVAZMvikCn8Nm81yqVx3Kk9XYI= +k8s.io/client-go v0.18.0/go.mod h1:uQSYDYs4WhVZ9i6AIoEZuwUggLVEF64HOD37boKAtF8= +k8s.io/client-go v0.18.8 h1:SdbLpIxk5j5YbFr1b7fq8S7mDgDjYmUxSbszyoesoDM= +k8s.io/client-go v0.18.8/go.mod h1:HqFqMllQ5NnQJNwjro9k5zMyfhZlOwpuTLVrxjkYSxU= +k8s.io/code-generator v0.0.0-20190912054826-cd179ad6a269/go.mod h1:V5BD6M4CyaN5m+VthcclXWsVcT1Hu+glwa1bi3MIsyE= +k8s.io/code-generator v0.0.0-20191214185510-0b9b3c99f9f2/go.mod h1:BjGKcoq1MRUmcssvHiSxodCco1T6nVIt4YeCT5CMSao= +k8s.io/code-generator v0.17.2/go.mod h1:DVmfPQgxQENqDIzVR2ddLXMH34qeszkKSdH/N+s+38s= +k8s.io/code-generator v0.18.0/go.mod h1:+UHX5rSbxmR8kzS+FAv7um6dtYrZokQvjHpDSYRVkTc= +k8s.io/component-base v0.0.0-20190918160511-547f6c5d7090/go.mod h1:933PBGtQFJky3TEwYx4aEPZ4IxqhWh3R6DCmzqIn1hA= +k8s.io/component-base v0.0.0-20191214190519-d868452632e2/go.mod h1:wupxkh1T/oUDqyTtcIjiEfpbmIHGm8By/vqpSKC6z8c= +k8s.io/component-base v0.17.2/go.mod h1:zMPW3g5aH7cHJpKYQ/ZsGMcgbsA/VyhEugF3QT1awLs= +k8s.io/component-base v0.18.0/go.mod h1:u3BCg0z1uskkzrnAKFzulmYaEpZF7XC9Pf/uFyb1v2c= k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= -k8s.io/gengo v0.0.0-20190327210449-e17681d19d3a/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= +k8s.io/gengo v0.0.0-20190822140433-26a664648505/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= +k8s.io/gengo v0.0.0-20200114144118-36b2048a9120/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= -k8s.io/klog v0.3.0 h1:0VPpR+sizsiivjIfIAQH/rl8tan6jvWkS7lU+0di3lE= k8s.io/klog v0.3.0/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= -k8s.io/kube-openapi v0.0.0-20190502190224-411b2483e503/go.mod h1:iU+ZGYsNlvU9XKUSso6SQfKTCCw7lFduMZy26Mgr2Fw= -k8s.io/utils v0.0.0-20190506122338-8fab8cb257d5 h1:VBM/0P5TWxwk+Nw6Z+lAw3DKgO76g90ETOiA6rfLV1Y= -k8s.io/utils v0.0.0-20190506122338-8fab8cb257d5/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= -sigs.k8s.io/structured-merge-diff v0.0.0-20190426204423-ea680f03cc65/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI= -sigs.k8s.io/yaml v1.1.0 h1:4A07+ZFc2wgJwo8YNlQpr1rVlgUDlxXHhPJciaPY5gs= +k8s.io/klog v0.4.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= +k8s.io/klog v1.0.0 h1:Pt+yjF5aB1xDSVbau4VsWe+dQNzA0qv1LlXdC2dF6Q8= +k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= +k8s.io/kube-aggregator v0.18.0/go.mod h1:ateewQ5QbjMZF/dihEFXwaEwoA4v/mayRvzfmvb6eqI= +k8s.io/kube-openapi v0.0.0-20190816220812-743ec37842bf/go.mod h1:1TqjTSzOxsLGIKfj0lK8EeCP7K1iUG65v09OM0/WG5E= +k8s.io/kube-openapi v0.0.0-20191107075043-30be4d16710a/go.mod h1:1TqjTSzOxsLGIKfj0lK8EeCP7K1iUG65v09OM0/WG5E= +k8s.io/kube-openapi v0.0.0-20200121204235-bf4fb3bd569c/go.mod h1:GRQhZsXIAJ1xR0C9bd8UpWHZ5plfAS9fzPjJuQ6JL3E= +k8s.io/kube-openapi v0.0.0-20200410145947-61e04a5be9a6 h1:Oh3Mzx5pJ+yIumsAD0MOECPVeXsVot0UkiaCGVyfGQY= +k8s.io/kube-openapi v0.0.0-20200410145947-61e04a5be9a6/go.mod h1:GRQhZsXIAJ1xR0C9bd8UpWHZ5plfAS9fzPjJuQ6JL3E= +k8s.io/kubectl v0.0.0-20191219154910-1528d4eea6dd/go.mod h1:9ehGcuUGjXVZh0qbYSB0vvofQw2JQe6c6cO0k4wu/Oo= +k8s.io/metrics v0.0.0-20191214191643-6b1944c9f765/go.mod h1:5V7rewilItwK0cz4nomU0b3XCcees2Ka5EBYWS1HBeM= +k8s.io/utils v0.0.0-20190801114015-581e00157fb1/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= +k8s.io/utils v0.0.0-20191114184206-e782cd3c129f/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= +k8s.io/utils v0.0.0-20200324210504-a9aa75ae1b89 h1:d4vVOjXm687F1iLSP2q3lyPPuyvTUt3aVoBpi2DqRsU= +k8s.io/utils v0.0.0-20200324210504-a9aa75ae1b89/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= +modernc.org/cc v1.0.0/go.mod h1:1Sk4//wdnYJiUIxnW8ddKpaOJCF37yAdqYnkxUpaYxw= +modernc.org/golex v1.0.0/go.mod h1:b/QX9oBD/LhixY6NDh+IdGv17hgB+51fET1i2kPSmvk= +modernc.org/mathutil v1.0.0/go.mod h1:wU0vUrJsVWBZ4P6e7xtFJEhFSNsfRLJ8H458uRjg03k= +modernc.org/strutil v1.0.0/go.mod h1:lstksw84oURvj9y3tn8lGvRxyRC1S2+g5uuIzNfIOBs= +modernc.org/xc v1.0.0/go.mod h1:mRNCo0bvLjGhHO9WsyuKVU4q0ceiDDDoEeWDJHrNx8I= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.7/go.mod h1:PHgbrJT7lCHcxMU+mDHEm+nx46H4zuuHZkDP6icnhu0= +sigs.k8s.io/cli-utils v0.16.0/go.mod h1:9Jqm9K2W6ShhCxsEuaz6HSRKKOXigPUx3ZfypGgxBLY= +sigs.k8s.io/controller-runtime v0.4.0/go.mod h1:ApC79lpY3PHW9xj/w9pj+lYkLgwAAUZwfXkME1Lajns= +sigs.k8s.io/kustomize v2.0.3+incompatible/go.mod h1:MkjgH3RdOWrievjo6c9T245dYlB5QeXV4WCbnt/PEpU= +sigs.k8s.io/kustomize/kyaml v0.4.0/go.mod h1:XJL84E6sOFeNrQ7CADiemc1B0EjIxHo3OhW4o1aJYNw= +sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI= +sigs.k8s.io/structured-merge-diff v0.0.0-20190817042607-6149e4549fca/go.mod h1:IIgPezJWb76P0hotTxzDbWsMYB8APh18qZnxkomBpxA= +sigs.k8s.io/structured-merge-diff v1.0.1-0.20191108220359-b1b620dd3f06 h1:zD2IemQ4LmOcAumeiyDWXKUI2SO0NYDe3H6QGvPOVgU= +sigs.k8s.io/structured-merge-diff v1.0.1-0.20191108220359-b1b620dd3f06/go.mod h1:/ULNhyfzRopfcjskuui0cTITekDduZ7ycKN3oUT9R18= +sigs.k8s.io/structured-merge-diff/v3 v3.0.0-20200116222232-67a7b8c61874/go.mod h1:PlARxl6Hbt/+BC80dRLi1qAmnMqwqDg62YvvVkZjemw= +sigs.k8s.io/structured-merge-diff/v3 v3.0.0 h1:dOmIZBMfhcHS09XZkMyUgkq5trg3/jRyJYFZUiaOp8E= +sigs.k8s.io/structured-merge-diff/v3 v3.0.0/go.mod h1:PlARxl6Hbt/+BC80dRLi1qAmnMqwqDg62YvvVkZjemw= +sigs.k8s.io/testing_frameworks v0.1.2/go.mod h1:ToQrwSC3s8Xf/lADdZp3Mktcql9CG0UAmdJG9th5i0w= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= +sigs.k8s.io/yaml v1.2.0 h1:kr/MCeFWJWTwyaHoR9c8EjH9OumOmoF9YGiZd7lFm/Q= +sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= +vbom.ml/util v0.0.0-20160121211510-db5cfe13f5cc/go.mod h1:so/NYdZXCz+E3ZpW0uAoCj6uzU2+8OWDFv/HxUSs7kI= diff --git a/vendor/github.com/rancher/dynamiclistener/storage/kubernetes/ca.go b/vendor/github.com/rancher/dynamiclistener/storage/kubernetes/ca.go index 5d418451b8..d23ac4ff32 100644 --- a/vendor/github.com/rancher/dynamiclistener/storage/kubernetes/ca.go +++ b/vendor/github.com/rancher/dynamiclistener/storage/kubernetes/ca.go @@ -5,7 +5,7 @@ import ( "crypto/x509" "github.com/rancher/dynamiclistener/factory" - v1controller "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + v1controller "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/vendor/github.com/rancher/dynamiclistener/storage/kubernetes/controller.go b/vendor/github.com/rancher/dynamiclistener/storage/kubernetes/controller.go index 70d5d7c44b..2e82e96646 100644 --- a/vendor/github.com/rancher/dynamiclistener/storage/kubernetes/controller.go +++ b/vendor/github.com/rancher/dynamiclistener/storage/kubernetes/controller.go @@ -6,8 +6,8 @@ import ( "time" "github.com/rancher/dynamiclistener" - "github.com/rancher/wrangler-api/pkg/generated/controllers/core" - v1controller "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" + "github.com/rancher/wrangler/pkg/generated/controllers/core" + v1controller "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" "github.com/rancher/wrangler/pkg/start" "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" diff --git a/vendor/github.com/rancher/wrangler-api/LICENSE b/vendor/github.com/rancher/lasso/LICENSE similarity index 99% rename from vendor/github.com/rancher/wrangler-api/LICENSE rename to vendor/github.com/rancher/lasso/LICENSE index f433b1a53f..e454a52586 100644 --- a/vendor/github.com/rancher/wrangler-api/LICENSE +++ b/vendor/github.com/rancher/lasso/LICENSE @@ -175,3 +175,4 @@ of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS + diff --git a/vendor/github.com/rancher/lasso/pkg/cache/cache.go b/vendor/github.com/rancher/lasso/pkg/cache/cache.go new file mode 100644 index 0000000000..a69239a65a --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/cache/cache.go @@ -0,0 +1,125 @@ +package cache + +import ( + "context" + "fmt" + "time" + + "github.com/rancher/lasso/pkg/client" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/client-go/tools/cache" +) + +type Options struct { + Namespace string + Resync time.Duration + TweakList TweakListOptionsFunc + WaitHealthy func(ctx context.Context) +} + +func NewCache(obj, listObj runtime.Object, client *client.Client, opts *Options) cache.SharedIndexInformer { + indexers := cache.Indexers{} + + if client.Namespaced { + indexers[cache.NamespaceIndex] = cache.MetaNamespaceIndexFunc + } + + opts = applyDefaultCacheOptions(opts) + + lw := &deferredListWatcher{ + client: client, + tweakList: opts.TweakList, + namespace: opts.Namespace, + listObj: listObj, + waitHealthy: opts.WaitHealthy, + } + + return &deferredCache{ + SharedIndexInformer: cache.NewSharedIndexInformer( + lw, + obj, + opts.Resync, + indexers, + ), + deferredListWatcher: lw, + } +} + +func applyDefaultCacheOptions(opts *Options) *Options { + var newOpts Options + if opts != nil { + newOpts = *opts + } + if newOpts.Resync == 0 { + newOpts.Resync = 10 * time.Hour + } + if newOpts.TweakList == nil { + newOpts.TweakList = func(*metav1.ListOptions) {} + } + return &newOpts +} + +type deferredCache struct { + cache.SharedIndexInformer + deferredListWatcher *deferredListWatcher +} + +type deferredListWatcher struct { + lw cache.ListerWatcher + client *client.Client + tweakList TweakListOptionsFunc + namespace string + listObj runtime.Object + waitHealthy func(ctx context.Context) +} + +func (d *deferredListWatcher) List(options metav1.ListOptions) (runtime.Object, error) { + if d.lw == nil { + return nil, fmt.Errorf("cache not started") + } + return d.lw.List(options) +} + +func (d *deferredListWatcher) Watch(options metav1.ListOptions) (watch.Interface, error) { + if d.lw == nil { + return nil, fmt.Errorf("cache not started") + } + return d.lw.Watch(options) +} + +func (d *deferredListWatcher) run(stopCh <-chan struct{}) { + ctx, cancel := context.WithCancel(context.Background()) + go func() { + <-stopCh + cancel() + }() + + d.lw = &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + d.tweakList(&options) + // If ResourceVersion is set to 0 then the Limit is ignored on the API side. Usually + // that's not a problem, but with very large counts of a single object type the client will + // hit it's connection timeout + if options.ResourceVersion == "0" { + options.ResourceVersion = "" + } + listObj := d.listObj.DeepCopyObject() + err := d.client.List(ctx, d.namespace, listObj, options) + if err != nil && d.waitHealthy != nil { + d.waitHealthy(ctx) + } + return listObj, err + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + d.tweakList(&options) + return d.client.Watch(ctx, d.namespace, options) + }, + } +} + +func (d *deferredCache) Run(stopCh <-chan struct{}) { + d.deferredListWatcher.run(stopCh) + d.SharedIndexInformer.Run(stopCh) +} diff --git a/vendor/github.com/rancher/lasso/pkg/cache/cancel_collection.go b/vendor/github.com/rancher/lasso/pkg/cache/cancel_collection.go new file mode 100644 index 0000000000..c2ab3589ab --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/cache/cancel_collection.go @@ -0,0 +1,29 @@ +package cache + +import ( + "context" + "sync" + "sync/atomic" +) + +type CancelCollection struct { + id int64 + items sync.Map +} + +func (c *CancelCollection) Add(ctx context.Context, obj interface{}) { + key := atomic.AddInt64(&c.id, 1) + c.items.Store(key, obj) + go func() { + <-ctx.Done() + c.items.Delete(key) + }() +} + +func (c *CancelCollection) List() (result []interface{}) { + c.items.Range(func(key, value interface{}) bool { + result = append(result, value) + return true + }) + return +} diff --git a/vendor/github.com/rancher/lasso/pkg/cache/healthcheck.go b/vendor/github.com/rancher/lasso/pkg/cache/healthcheck.go new file mode 100644 index 0000000000..8d667ed8bc --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/cache/healthcheck.go @@ -0,0 +1,71 @@ +package cache + +import ( + "context" + "sync" + "time" + + "github.com/rancher/lasso/pkg/client" +) + +const ( + defaultTimeout = 15 * time.Second +) + +type healthcheck struct { + lock sync.Mutex + cf client.SharedClientFactory + callback func(bool) +} + +func (h *healthcheck) ping(ctx context.Context) bool { + ctx, cancel := context.WithTimeout(ctx, defaultTimeout) + defer cancel() + return h.cf.IsHealthy(ctx) +} + +func (h *healthcheck) start(ctx context.Context, cf client.SharedClientFactory) error { + first, err := h.initialize(cf) + if err != nil { + return err + } + if first { + h.ensureHealthy(ctx) + } + return nil +} + +func (h *healthcheck) initialize(cf client.SharedClientFactory) (bool, error) { + h.lock.Lock() + defer h.lock.Unlock() + if h.cf != nil { + return false, nil + } + + h.cf = cf + return true, nil +} + +func (h *healthcheck) ensureHealthy(ctx context.Context) { + h.lock.Lock() + defer h.lock.Unlock() + h.pingUntilGood(ctx) +} + +func (h *healthcheck) report(good bool) { + if h.callback != nil { + h.callback(good) + } +} + +func (h *healthcheck) pingUntilGood(ctx context.Context) { + for { + if h.ping(ctx) { + h.report(true) + return + } + + h.report(false) + time.Sleep(defaultTimeout) + } +} diff --git a/vendor/github.com/rancher/lasso/pkg/cache/sharedinformerfactory.go b/vendor/github.com/rancher/lasso/pkg/cache/sharedinformerfactory.go new file mode 100644 index 0000000000..196daace3f --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/cache/sharedinformerfactory.go @@ -0,0 +1,218 @@ +package cache + +import ( + "context" + "sync" + "time" + + "github.com/rancher/lasso/pkg/client" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/tools/cache" +) + +type TweakListOptionsFunc func(*v1.ListOptions) + +type SharedCacheFactoryOptions struct { + DefaultResync time.Duration + DefaultNamespace string + DefaultTweakList TweakListOptionsFunc + + KindResync map[schema.GroupVersionKind]time.Duration + KindNamespace map[schema.GroupVersionKind]string + KindTweakList map[schema.GroupVersionKind]TweakListOptionsFunc + HealthCallback func(healthy bool) +} + +type sharedCacheFactory struct { + lock sync.Mutex + + tweakList TweakListOptionsFunc + defaultResync time.Duration + defaultNamespace string + customResync map[schema.GroupVersionKind]time.Duration + customNamespaces map[schema.GroupVersionKind]string + customTweakList map[schema.GroupVersionKind]TweakListOptionsFunc + sharedClientFactory client.SharedClientFactory + healthcheck healthcheck + + caches map[schema.GroupVersionKind]cache.SharedIndexInformer + startedCaches map[schema.GroupVersionKind]bool +} + +// NewSharedInformerFactoryWithOptions constructs a new instance of a SharedInformerFactory with additional options. +func NewSharedCachedFactory(sharedClientFactory client.SharedClientFactory, opts *SharedCacheFactoryOptions) SharedCacheFactory { + opts = applyDefaults(opts) + + factory := &sharedCacheFactory{ + lock: sync.Mutex{}, + tweakList: opts.DefaultTweakList, + defaultResync: opts.DefaultResync, + defaultNamespace: opts.DefaultNamespace, + customResync: opts.KindResync, + customNamespaces: opts.KindNamespace, + customTweakList: opts.KindTweakList, + caches: map[schema.GroupVersionKind]cache.SharedIndexInformer{}, + startedCaches: map[schema.GroupVersionKind]bool{}, + sharedClientFactory: sharedClientFactory, + healthcheck: healthcheck{ + callback: opts.HealthCallback, + }, + } + + return factory +} + +func applyDefaults(opts *SharedCacheFactoryOptions) *SharedCacheFactoryOptions { + var newOpts SharedCacheFactoryOptions + if opts != nil { + newOpts = *opts + } + + return &newOpts +} + +func (f *sharedCacheFactory) StartGVK(ctx context.Context, gvk schema.GroupVersionKind) error { + f.lock.Lock() + defer f.lock.Unlock() + + informer, ok := f.caches[gvk] + if !ok { + return nil + } + + if !f.startedCaches[gvk] { + go informer.Run(ctx.Done()) + f.startedCaches[gvk] = true + } + + return nil +} + +func (f *sharedCacheFactory) Start(ctx context.Context) error { + f.lock.Lock() + defer f.lock.Unlock() + + if err := f.healthcheck.start(ctx, f.sharedClientFactory); err != nil { + return err + } + + for informerType, informer := range f.caches { + if !f.startedCaches[informerType] { + go informer.Run(ctx.Done()) + f.startedCaches[informerType] = true + } + } + + return nil +} + +func (f *sharedCacheFactory) WaitForCacheSync(ctx context.Context) map[schema.GroupVersionKind]bool { + informers := func() map[schema.GroupVersionKind]cache.SharedIndexInformer { + f.lock.Lock() + defer f.lock.Unlock() + + informers := map[schema.GroupVersionKind]cache.SharedIndexInformer{} + for informerType, informer := range f.caches { + if f.startedCaches[informerType] { + informers[informerType] = informer + } + } + return informers + }() + + res := map[schema.GroupVersionKind]bool{} + for informType, informer := range informers { + res[informType] = cache.WaitForCacheSync(ctx.Done(), informer.HasSynced) + } + return res +} + +func (f *sharedCacheFactory) ForObject(obj runtime.Object) (cache.SharedIndexInformer, error) { + return f.ForKind(obj.GetObjectKind().GroupVersionKind()) +} + +func (f *sharedCacheFactory) ForResource(gvr schema.GroupVersionResource, namespaced bool) (cache.SharedIndexInformer, error) { + return f.ForResourceKind(gvr, "", namespaced) +} + +func (f *sharedCacheFactory) ForKind(gvk schema.GroupVersionKind) (cache.SharedIndexInformer, error) { + gvr, namespaced, err := f.sharedClientFactory.ResourceForGVK(gvk) + if err != nil { + return nil, err + } + return f.ForResourceKind(gvr, gvk.Kind, namespaced) +} + +func (f *sharedCacheFactory) ForResourceKind(gvr schema.GroupVersionResource, kind string, namespaced bool) (cache.SharedIndexInformer, error) { + var ( + gvk schema.GroupVersionKind + err error + ) + + if kind == "" { + gvk, err = f.sharedClientFactory.GVKForResource(gvr) + if err != nil { + return nil, err + } + } else { + gvk = gvr.GroupVersion().WithKind(kind) + } + + f.lock.Lock() + defer f.lock.Unlock() + + informer, ok := f.caches[gvk] + if ok { + return informer, nil + } + + resyncPeriod, ok := f.customResync[gvk] + if !ok { + resyncPeriod = f.defaultResync + } + + namespace, ok := f.customNamespaces[gvk] + if !ok { + namespace = f.defaultNamespace + } + + tweakList, ok := f.customTweakList[gvk] + if !ok { + tweakList = f.tweakList + } + + obj, objList, err := f.sharedClientFactory.NewObjects(gvk) + if err != nil { + return nil, err + } + + client := f.sharedClientFactory.ForResourceKind(gvr, kind, namespaced) + + cache := NewCache(obj, objList, client, &Options{ + Namespace: namespace, + Resync: resyncPeriod, + TweakList: tweakList, + WaitHealthy: f.healthcheck.ensureHealthy, + }) + f.caches[gvk] = cache + + return cache, nil +} + +func (f *sharedCacheFactory) SharedClientFactory() client.SharedClientFactory { + return f.sharedClientFactory +} + +type SharedCacheFactory interface { + Start(ctx context.Context) error + StartGVK(ctx context.Context, gvk schema.GroupVersionKind) error + ForObject(obj runtime.Object) (cache.SharedIndexInformer, error) + ForKind(gvk schema.GroupVersionKind) (cache.SharedIndexInformer, error) + ForResource(gvr schema.GroupVersionResource, namespaced bool) (cache.SharedIndexInformer, error) + ForResourceKind(gvr schema.GroupVersionResource, kind string, namespaced bool) (cache.SharedIndexInformer, error) + WaitForCacheSync(ctx context.Context) map[schema.GroupVersionKind]bool + SharedClientFactory() client.SharedClientFactory +} diff --git a/vendor/github.com/rancher/lasso/pkg/client/client.go b/vendor/github.com/rancher/lasso/pkg/client/client.go new file mode 100644 index 0000000000..8d1d7b5e5f --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/client/client.go @@ -0,0 +1,280 @@ +package client + +import ( + "context" + "time" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/client-go/rest" +) + +type Client struct { + RESTClient rest.Interface + timeout time.Duration + Namespaced bool + GVR schema.GroupVersionResource + resource string + prefix []string + apiVersion string + kind string +} + +func IsNamespaced(gvr schema.GroupVersionResource, mapper meta.RESTMapper) (bool, error) { + kind, err := mapper.KindFor(gvr) + if err != nil { + return false, err + } + + mapping, err := mapper.RESTMapping(kind.GroupKind(), kind.Version) + if err != nil { + return false, err + } + + return mapping.Scope.Name() == meta.RESTScopeNameNamespace, nil +} + +func NewClient(gvr schema.GroupVersionResource, kind string, namespaced bool, client rest.Interface, defaultTimeout time.Duration) *Client { + var ( + prefix []string + ) + + if gvr.Group == "" { + prefix = []string{ + "api", + gvr.Version, + } + } else { + prefix = []string{ + "apis", + gvr.Group, + gvr.Version, + } + } + + c := &Client{ + RESTClient: client, + timeout: defaultTimeout, + Namespaced: namespaced, + GVR: gvr, + prefix: prefix, + resource: gvr.Resource, + } + c.apiVersion, c.kind = gvr.GroupVersion().WithKind(kind).ToAPIVersionAndKind() + return c +} + +func noop() {} + +func (c *Client) setupCtx(ctx context.Context, minTimeout time.Duration) (context.Context, func()) { + if minTimeout == 0 && c.timeout == 0 { + return ctx, noop + } + + timeout := c.timeout + if minTimeout > 0 && timeout < minTimeout { + timeout = minTimeout + } + + return context.WithTimeout(ctx, timeout) +} + +func (c *Client) Get(ctx context.Context, namespace, name string, result runtime.Object, options metav1.GetOptions) (err error) { + defer c.setKind(result) + ctx, cancel := c.setupCtx(ctx, 0) + defer cancel() + err = c.RESTClient.Get(). + Prefix(c.prefix...). + NamespaceIfScoped(namespace, c.Namespaced). + Resource(c.resource). + Name(name). + VersionedParams(&options, metav1.ParameterCodec). + Do(ctx). + Into(result) + return +} + +func (c *Client) List(ctx context.Context, namespace string, result runtime.Object, opts metav1.ListOptions) (err error) { + ctx, cancel := c.setupCtx(ctx, 0) + defer cancel() + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + r := c.RESTClient.Get() + if namespace != "" { + r = r.NamespaceIfScoped(namespace, c.Namespaced) + } + err = r.Resource(c.resource). + Prefix(c.prefix...). + VersionedParams(&opts, metav1.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +func (c *Client) Watch(ctx context.Context, namespace string, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.injectKind(c.RESTClient.Get(). + Prefix(c.prefix...). + NamespaceIfScoped(namespace, c.Namespaced). + Resource(c.resource). + VersionedParams(&opts, metav1.ParameterCodec). + Timeout(timeout). + Watch(ctx)) +} + +func (c *Client) Create(ctx context.Context, namespace string, obj, result runtime.Object, opts metav1.CreateOptions) (err error) { + defer c.setKind(result) + ctx, cancel := c.setupCtx(ctx, 0) + defer cancel() + err = c.RESTClient.Post(). + Prefix(c.prefix...). + NamespaceIfScoped(namespace, c.Namespaced). + Resource(c.resource). + VersionedParams(&opts, metav1.ParameterCodec). + Body(obj). + Do(ctx). + Into(result) + return +} + +func (c *Client) Update(ctx context.Context, namespace string, obj, result runtime.Object, opts metav1.UpdateOptions) (err error) { + defer c.setKind(result) + ctx, cancel := c.setupCtx(ctx, 0) + defer cancel() + m, err := meta.Accessor(obj) + if err != nil { + return err + } + err = c.RESTClient.Put(). + Prefix(c.prefix...). + NamespaceIfScoped(namespace, c.Namespaced). + Resource(c.resource). + Name(m.GetName()). + VersionedParams(&opts, metav1.ParameterCodec). + Body(obj). + Do(ctx). + Into(result) + return +} + +func (c *Client) UpdateStatus(ctx context.Context, namespace string, obj, result runtime.Object, opts metav1.UpdateOptions) (err error) { + defer c.setKind(result) + ctx, cancel := c.setupCtx(ctx, 0) + defer cancel() + m, err := meta.Accessor(obj) + if err != nil { + return err + } + err = c.RESTClient.Put(). + Prefix(c.prefix...). + NamespaceIfScoped(namespace, c.Namespaced). + Resource(c.resource). + Name(m.GetName()). + SubResource("status"). + VersionedParams(&opts, metav1.ParameterCodec). + Body(obj). + Do(ctx). + Into(result) + return +} + +func (c *Client) Delete(ctx context.Context, namespace, name string, opts metav1.DeleteOptions) error { + ctx, cancel := c.setupCtx(ctx, 0) + defer cancel() + return c.RESTClient.Delete(). + Prefix(c.prefix...). + NamespaceIfScoped(namespace, c.Namespaced). + Resource(c.resource). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +func (c *Client) DeleteCollection(ctx context.Context, namespace string, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { + ctx, cancel := c.setupCtx(ctx, 0) + defer cancel() + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.RESTClient.Delete(). + Prefix(c.prefix...). + NamespaceIfScoped(namespace, c.Namespaced). + Resource(c.resource). + VersionedParams(&listOpts, metav1.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +func (c *Client) Patch(ctx context.Context, namespace, name string, pt types.PatchType, data []byte, result runtime.Object, opts metav1.PatchOptions, subresources ...string) (err error) { + defer c.setKind(result) + ctx, cancel := c.setupCtx(ctx, 0) + defer cancel() + err = c.RESTClient.Patch(pt). + Prefix(c.prefix...). + Namespace(namespace). + Resource(c.resource). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, metav1.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} + +func (c *Client) setKind(obj runtime.Object) { + if c.kind == "" { + return + } + if _, ok := obj.(*metav1.Status); !ok { + if meta, err := meta.TypeAccessor(obj); err == nil { + meta.SetKind(c.kind) + meta.SetAPIVersion(c.apiVersion) + } + } +} + +func (c *Client) injectKind(w watch.Interface, err error) (watch.Interface, error) { + if c.kind == "" || err != nil { + return w, err + } + + eventChan := make(chan watch.Event) + + go func() { + defer close(eventChan) + for event := range w.ResultChan() { + c.setKind(event.Object) + eventChan <- event + } + }() + + return &watcher{ + Interface: w, + eventChan: eventChan, + }, nil +} + +type watcher struct { + watch.Interface + eventChan chan watch.Event +} + +func (w *watcher) ResultChan() <-chan watch.Event { + return w.eventChan +} diff --git a/vendor/github.com/rancher/lasso/pkg/client/sharedclientfactory.go b/vendor/github.com/rancher/lasso/pkg/client/sharedclientfactory.go new file mode 100644 index 0000000000..9cea4507a1 --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/client/sharedclientfactory.go @@ -0,0 +1,236 @@ +package client + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/rancher/lasso/pkg/mapper" + "github.com/rancher/lasso/pkg/scheme" + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/runtime/serializer" + "k8s.io/client-go/discovery" + "k8s.io/client-go/rest" +) + +type SharedClientFactoryOptions struct { + Mapper meta.RESTMapper + Scheme *runtime.Scheme +} + +type SharedClientFactory interface { + ForKind(gvk schema.GroupVersionKind) (*Client, error) + ForResource(gvr schema.GroupVersionResource, namespaced bool) (*Client, error) + ForResourceKind(gvr schema.GroupVersionResource, kind string, namespaced bool) *Client + NewObjects(gvk schema.GroupVersionKind) (runtime.Object, runtime.Object, error) + GVKForObject(obj runtime.Object) (schema.GroupVersionKind, error) + GVKForResource(gvr schema.GroupVersionResource) (schema.GroupVersionKind, error) + IsNamespaced(gvk schema.GroupVersionKind) (bool, error) + ResourceForGVK(gvk schema.GroupVersionKind) (schema.GroupVersionResource, bool, error) + IsHealthy(ctx context.Context) bool +} + +type sharedClientFactory struct { + createLock sync.RWMutex + discovery discovery.DiscoveryInterface + clients map[schema.GroupVersionResource]*Client + timeout time.Duration + rest rest.Interface + + Mapper meta.RESTMapper + Scheme *runtime.Scheme +} + +func NewSharedClientFactoryForConfig(config *rest.Config) (SharedClientFactory, error) { + return NewSharedClientFactory(config, nil) +} + +func NewSharedClientFactory(config *rest.Config, opts *SharedClientFactoryOptions) (_ SharedClientFactory, err error) { + opts, err = applyDefaults(config, opts) + if err != nil { + return nil, err + } + + config, timeout := populateConfig(opts.Scheme, config) + rest, err := rest.UnversionedRESTClientFor(config) + if err != nil { + return nil, err + } + + discovery, err := discovery.NewDiscoveryClientForConfig(config) + if err != nil { + return nil, err + } + + return &sharedClientFactory{ + timeout: timeout, + clients: map[schema.GroupVersionResource]*Client{}, + Scheme: opts.Scheme, + Mapper: opts.Mapper, + rest: rest, + discovery: discovery, + }, nil +} + +func applyDefaults(config *rest.Config, opts *SharedClientFactoryOptions) (*SharedClientFactoryOptions, error) { + var newOpts SharedClientFactoryOptions + if opts != nil { + newOpts = *opts + } + + if newOpts.Scheme == nil { + newOpts.Scheme = scheme.All + } + + if newOpts.Mapper == nil { + mapperOpt, err := mapper.New(config) + if err != nil { + return nil, err + } + newOpts.Mapper = mapperOpt + } + + return &newOpts, nil +} + +func (s *sharedClientFactory) GVKForResource(gvr schema.GroupVersionResource) (schema.GroupVersionKind, error) { + return s.Mapper.KindFor(gvr) +} + +func (s *sharedClientFactory) IsHealthy(ctx context.Context) bool { + _, err := s.rest.Get().AbsPath("/version").Do(ctx).Raw() + return err == nil +} + +func (s *sharedClientFactory) IsNamespaced(gvk schema.GroupVersionKind) (bool, error) { + mapping, err := s.Mapper.RESTMapping(gvk.GroupKind(), gvk.Version) + if err != nil { + return false, err + } + + return IsNamespaced(mapping.Resource, s.Mapper) +} + +func (s *sharedClientFactory) ResourceForGVK(gvk schema.GroupVersionKind) (schema.GroupVersionResource, bool, error) { + mapping, err := s.Mapper.RESTMapping(gvk.GroupKind(), gvk.Version) + if err != nil { + return schema.GroupVersionResource{}, false, err + } + + nsed, err := IsNamespaced(mapping.Resource, s.Mapper) + if err != nil { + return schema.GroupVersionResource{}, false, err + } + + return mapping.Resource, nsed, nil +} + +func (s *sharedClientFactory) GVKForObject(obj runtime.Object) (schema.GroupVersionKind, error) { + gvks, _, err := s.Scheme.ObjectKinds(obj) + if err != nil { + return schema.GroupVersionKind{}, err + } + if len(gvks) == 0 { + return schema.GroupVersionKind{}, fmt.Errorf("failed to find schema.GroupVersionKind for %T", obj) + } + return gvks[0], nil +} + +func (s *sharedClientFactory) NewObjects(gvk schema.GroupVersionKind) (runtime.Object, runtime.Object, error) { + obj, err := s.Scheme.New(gvk) + if runtime.IsNotRegisteredError(err) { + return &unstructured.Unstructured{}, &unstructured.UnstructuredList{}, nil + } else if err != nil { + return nil, nil, err + } + + objList, err := s.Scheme.New(schema.GroupVersionKind{ + Group: gvk.Group, + Version: gvk.Version, + Kind: gvk.Kind + "List", + }) + return obj, objList, err +} + +func (s *sharedClientFactory) ForKind(gvk schema.GroupVersionKind) (*Client, error) { + gvr, nsed, err := s.ResourceForGVK(gvk) + if err != nil { + return nil, err + } + + return s.ForResourceKind(gvr, gvk.Kind, nsed), nil +} + +func (s *sharedClientFactory) ForResource(gvr schema.GroupVersionResource, namespaced bool) (*Client, error) { + gvk, err := s.GVKForResource(gvr) + if err != nil { + return nil, err + } + return s.ForResourceKind(gvr, gvk.Kind, namespaced), nil +} + +func (s *sharedClientFactory) ForResourceKind(gvr schema.GroupVersionResource, kind string, namespaced bool) *Client { + client := s.getClient(gvr) + if client != nil { + return client + } + + s.createLock.Lock() + defer s.createLock.Unlock() + + client = s.clients[gvr] + if client != nil { + return client + } + + client = NewClient(gvr, kind, namespaced, s.rest, s.timeout) + + s.clients[gvr] = client + return client +} + +func (s *sharedClientFactory) getClient(gvr schema.GroupVersionResource) *Client { + s.createLock.RLock() + defer s.createLock.RUnlock() + return s.clients[gvr] +} + +func populateConfig(scheme *runtime.Scheme, config *rest.Config) (*rest.Config, time.Duration) { + config = rest.CopyConfig(config) + config.NegotiatedSerializer = unstructuredNegotiator{ + NegotiatedSerializer: serializer.NewCodecFactory(scheme).WithoutConversion(), + } + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } + timeout := config.Timeout + config.Timeout = 0 + return config, timeout +} + +type unstructuredNegotiator struct { + runtime.NegotiatedSerializer +} + +func (u unstructuredNegotiator) DecoderToVersion(serializer runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder { + result := u.NegotiatedSerializer.DecoderToVersion(serializer, gv) + return unstructuredDecoder{ + Decoder: result, + } +} + +type unstructuredDecoder struct { + runtime.Decoder +} + +func (u unstructuredDecoder) Decode(data []byte, defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) { + obj, gvk, err := u.Decoder.Decode(data, defaults, into) + if into == nil && runtime.IsNotRegisteredError(err) { + return u.Decode(data, defaults, &unstructured.Unstructured{}) + } + return obj, gvk, err +} diff --git a/vendor/github.com/rancher/lasso/pkg/controller/controller.go b/vendor/github.com/rancher/lasso/pkg/controller/controller.go new file mode 100644 index 0000000000..597f1c486a --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/controller/controller.go @@ -0,0 +1,293 @@ +package controller + +import ( + "context" + "fmt" + "strings" + "sync" + "time" + + "github.com/rancher/lasso/pkg/log" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/tools/cache" + "k8s.io/client-go/util/workqueue" +) + +const maxTimeout2min = 2 * time.Minute + +type Handler interface { + OnChange(key string, obj runtime.Object) error +} + +type HandlerFunc func(key string, obj runtime.Object) error + +func (h HandlerFunc) OnChange(key string, obj runtime.Object) error { + return h(key, obj) +} + +type Controller interface { + Enqueue(namespace, name string) + EnqueueAfter(namespace, name string, delay time.Duration) + EnqueueKey(key string) + Informer() cache.SharedIndexInformer + Start(ctx context.Context, workers int) error +} + +type controller struct { + startLock sync.Mutex + + name string + workqueue workqueue.RateLimitingInterface + rateLimiter workqueue.RateLimiter + informer cache.SharedIndexInformer + handler Handler + gvk schema.GroupVersionKind + startKeys []startKey + started bool + startCache func(context.Context) error +} + +type startKey struct { + key string + after time.Duration +} + +type Options struct { + RateLimiter workqueue.RateLimiter +} + +func New(name string, informer cache.SharedIndexInformer, startCache func(context.Context) error, handler Handler, opts *Options) Controller { + opts = applyDefaultOptions(opts) + + controller := &controller{ + name: name, + handler: handler, + informer: informer, + rateLimiter: opts.RateLimiter, + startCache: startCache, + } + + informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ + AddFunc: controller.handleObject, + UpdateFunc: func(old, new interface{}) { + controller.handleObject(new) + }, + DeleteFunc: controller.handleObject, + }) + + return controller +} + +func applyDefaultOptions(opts *Options) *Options { + var newOpts Options + if opts != nil { + newOpts = *opts + } + if newOpts.RateLimiter == nil { + newOpts.RateLimiter = workqueue.NewMaxOfRateLimiter( + workqueue.NewItemFastSlowRateLimiter(time.Millisecond, maxTimeout2min, 30), + workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond, 30*time.Second), + ) + } + return &newOpts +} + +func (c *controller) Informer() cache.SharedIndexInformer { + return c.informer +} + +func (c *controller) GroupVersionKind() schema.GroupVersionKind { + return c.gvk +} + +func (c *controller) run(workers int, stopCh <-chan struct{}) { + c.startLock.Lock() + // we have to defer queue creation until we have a stopCh available because a workqueue + // will create a goroutine under the hood. It we instantiate a workqueue we must have + // a mechanism to Shutdown it down. Without the stopCh we don't know when to shutdown + // the queue and release the goroutine + c.workqueue = workqueue.NewNamedRateLimitingQueue(c.rateLimiter, c.name) + for _, start := range c.startKeys { + if start.after == 0 { + c.workqueue.Add(start.key) + } else { + c.workqueue.AddAfter(start.key, start.after) + } + } + c.startKeys = nil + c.startLock.Unlock() + + defer utilruntime.HandleCrash() + defer func() { + c.workqueue.ShutDown() + }() + + // Start the informer factories to begin populating the informer caches + log.Infof("Starting %s controller", c.name) + + // Launch two workers to process Foo resources + for i := 0; i < workers; i++ { + go wait.Until(c.runWorker, time.Second, stopCh) + } + + <-stopCh + log.Infof("Shutting down %s workers", c.name) +} + +func (c *controller) Start(ctx context.Context, workers int) error { + c.startLock.Lock() + defer c.startLock.Unlock() + + if c.started { + return nil + } + + if err := c.startCache(ctx); err != nil { + return err + } + + if ok := cache.WaitForCacheSync(ctx.Done(), c.informer.HasSynced); !ok { + return fmt.Errorf("failed to wait for caches to sync") + } + + go c.run(workers, ctx.Done()) + c.started = true + return nil +} + +func (c *controller) runWorker() { + for c.processNextWorkItem() { + } +} + +func (c *controller) processNextWorkItem() bool { + obj, shutdown := c.workqueue.Get() + + if shutdown { + return false + } + + if err := c.processSingleItem(obj); err != nil { + if !strings.Contains(err.Error(), "please apply your changes to the latest version and try again") { + log.Errorf("%v", err) + } + return true + } + + return true +} + +func (c *controller) processSingleItem(obj interface{}) error { + var ( + key string + ok bool + ) + + defer c.workqueue.Done(obj) + + if key, ok = obj.(string); !ok { + c.workqueue.Forget(obj) + log.Errorf("expected string in workqueue but got %#v", obj) + return nil + } + if err := c.syncHandler(key); err != nil { + c.workqueue.AddRateLimited(key) + return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error()) + } + + c.workqueue.Forget(obj) + return nil +} + +func (c *controller) syncHandler(key string) error { + obj, exists, err := c.informer.GetStore().GetByKey(key) + if err != nil { + return err + } + if !exists { + return c.handler.OnChange(key, nil) + } + + return c.handler.OnChange(key, obj.(runtime.Object)) +} + +func (c *controller) EnqueueKey(key string) { + c.startLock.Lock() + defer c.startLock.Unlock() + + if c.workqueue == nil { + c.startKeys = append(c.startKeys, startKey{key: key}) + } else { + c.workqueue.Add(key) + } +} + +func (c *controller) Enqueue(namespace, name string) { + key := keyFunc(namespace, name) + + c.startLock.Lock() + defer c.startLock.Unlock() + + if c.workqueue == nil { + c.startKeys = append(c.startKeys, startKey{key: key}) + } else { + c.workqueue.AddRateLimited(key) + } +} + +func (c *controller) EnqueueAfter(namespace, name string, duration time.Duration) { + key := keyFunc(namespace, name) + + c.startLock.Lock() + defer c.startLock.Unlock() + + if c.workqueue == nil { + c.startKeys = append(c.startKeys, startKey{key: key, after: duration}) + } else { + c.workqueue.AddAfter(key, duration) + } +} + +func keyFunc(namespace, name string) string { + if namespace == "" { + return name + } + return namespace + "/" + name +} + +func (c *controller) enqueue(obj interface{}) { + var key string + var err error + if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { + log.Errorf("%v", err) + return + } + c.startLock.Lock() + if c.workqueue == nil { + c.startKeys = append(c.startKeys, startKey{key: key}) + } else { + c.workqueue.Add(key) + } + c.startLock.Unlock() +} + +func (c *controller) handleObject(obj interface{}) { + if _, ok := obj.(metav1.Object); !ok { + tombstone, ok := obj.(cache.DeletedFinalStateUnknown) + if !ok { + log.Errorf("error decoding object, invalid type") + return + } + newObj, ok := tombstone.Obj.(metav1.Object) + if !ok { + log.Errorf("error decoding object tombstone, invalid type") + return + } + obj = newObj + } + c.enqueue(obj) +} diff --git a/vendor/github.com/rancher/lasso/pkg/controller/errorcontroller.go b/vendor/github.com/rancher/lasso/pkg/controller/errorcontroller.go new file mode 100644 index 0000000000..f868eb1f32 --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/controller/errorcontroller.go @@ -0,0 +1,35 @@ +package controller + +import ( + "context" + "time" + + "k8s.io/client-go/tools/cache" +) + +type errorController struct { + informer cache.SharedIndexInformer +} + +func newErrorController() *errorController { + return &errorController{ + informer: cache.NewSharedIndexInformer(nil, nil, 0, cache.Indexers{}), + } +} + +func (n *errorController) Enqueue(namespace, name string) { +} + +func (n *errorController) EnqueueAfter(namespace, name string, delay time.Duration) { +} + +func (n *errorController) EnqueueKey(key string) { +} + +func (n *errorController) Informer() cache.SharedIndexInformer { + return n.informer +} + +func (n *errorController) Start(ctx context.Context, workers int) error { + return nil +} diff --git a/vendor/github.com/rancher/lasso/pkg/controller/sharedcontroller.go b/vendor/github.com/rancher/lasso/pkg/controller/sharedcontroller.go new file mode 100644 index 0000000000..7eb3f3c3b6 --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/controller/sharedcontroller.go @@ -0,0 +1,122 @@ +package controller + +import ( + "context" + "sync" + "time" + + "github.com/rancher/lasso/pkg/cache" + "github.com/rancher/lasso/pkg/client" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + cachetools "k8s.io/client-go/tools/cache" +) + +type SharedControllerHandler interface { + OnChange(key string, obj runtime.Object) (runtime.Object, error) +} + +type SharedController interface { + Controller + + RegisterHandler(ctx context.Context, name string, handler SharedControllerHandler) + Client() *client.Client +} + +type SharedControllerHandlerFunc func(key string, obj runtime.Object) (runtime.Object, error) + +func (s SharedControllerHandlerFunc) OnChange(key string, obj runtime.Object) (runtime.Object, error) { + return s(key, obj) +} + +type sharedController struct { + // this allows one to create a sharedcontroller but it will not actually be started + // unless some aspect of the controllers informer is accessed or needed to be used + deferredController func() (Controller, error) + sharedCacheFactory cache.SharedCacheFactory + controller Controller + gvk schema.GroupVersionKind + handler *SharedHandler + startLock sync.Mutex + started bool + startError error + client *client.Client +} + +func (s *sharedController) Enqueue(namespace, name string) { + s.initController().Enqueue(namespace, name) +} + +func (s *sharedController) EnqueueAfter(namespace, name string, delay time.Duration) { + s.initController().EnqueueAfter(namespace, name, delay) +} + +func (s *sharedController) EnqueueKey(key string) { + s.initController().EnqueueKey(key) +} + +func (s *sharedController) Informer() cachetools.SharedIndexInformer { + return s.initController().Informer() +} + +func (s *sharedController) Client() *client.Client { + return s.client +} + +func (s *sharedController) initController() Controller { + s.startLock.Lock() + defer s.startLock.Unlock() + + if s.controller != nil { + return s.controller + } + + controller, err := s.deferredController() + if err != nil { + controller = newErrorController() + } + + s.startError = err + s.controller = controller + return s.controller +} + +func (s *sharedController) Start(ctx context.Context, workers int) error { + s.startLock.Lock() + defer s.startLock.Unlock() + + if s.startError != nil || s.controller == nil { + return s.startError + } + + if err := s.controller.Start(ctx, workers); err != nil { + return err + } + s.started = true + + go func() { + <-ctx.Done() + s.startLock.Lock() + defer s.startLock.Unlock() + s.started = false + }() + + return nil +} + +func (s *sharedController) RegisterHandler(ctx context.Context, name string, handler SharedControllerHandler) { + // Ensure that controller is initialized + c := s.initController() + + getHandlerTransaction(ctx).do(func() { + s.handler.Register(ctx, name, handler) + + s.startLock.Lock() + defer s.startLock.Unlock() + if s.started { + for _, key := range c.Informer().GetStore().ListKeys() { + c.EnqueueKey(key) + } + } + }) +} diff --git a/vendor/github.com/rancher/lasso/pkg/controller/sharedcontrollerfactory.go b/vendor/github.com/rancher/lasso/pkg/controller/sharedcontrollerfactory.go new file mode 100644 index 0000000000..49a2daa18f --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/controller/sharedcontrollerfactory.go @@ -0,0 +1,210 @@ +package controller + +import ( + "context" + "sync" + + "github.com/rancher/lasso/pkg/cache" + "github.com/rancher/lasso/pkg/client" + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/rest" + "k8s.io/client-go/util/workqueue" +) + +type SharedControllerFactory interface { + ForObject(obj runtime.Object) (SharedController, error) + ForKind(gvk schema.GroupVersionKind) (SharedController, error) + ForResource(gvr schema.GroupVersionResource, namespaced bool) SharedController + ForResourceKind(gvr schema.GroupVersionResource, kind string, namespaced bool) SharedController + SharedCacheFactory() cache.SharedCacheFactory + Start(ctx context.Context, workers int) error +} + +type SharedControllerFactoryOptions struct { + DefaultRateLimiter workqueue.RateLimiter + DefaultWorkers int + + KindRateLimiter map[schema.GroupVersionKind]workqueue.RateLimiter + KindWorkers map[schema.GroupVersionKind]int +} + +type sharedControllerFactory struct { + controllerLock sync.RWMutex + + sharedCacheFactory cache.SharedCacheFactory + controllers map[schema.GroupVersionResource]*sharedController + + rateLimiter workqueue.RateLimiter + workers int + kindRateLimiter map[schema.GroupVersionKind]workqueue.RateLimiter + kindWorkers map[schema.GroupVersionKind]int +} + +func NewSharedControllerFactoryFromConfig(config *rest.Config, scheme *runtime.Scheme) (SharedControllerFactory, error) { + cf, err := client.NewSharedClientFactory(config, &client.SharedClientFactoryOptions{ + Scheme: scheme, + }) + if err != nil { + return nil, err + } + return NewSharedControllerFactory(cache.NewSharedCachedFactory(cf, nil), nil), nil +} + +func NewSharedControllerFactory(cacheFactory cache.SharedCacheFactory, opts *SharedControllerFactoryOptions) SharedControllerFactory { + opts = applyDefaultSharedOptions(opts) + return &sharedControllerFactory{ + sharedCacheFactory: cacheFactory, + controllers: map[schema.GroupVersionResource]*sharedController{}, + workers: opts.DefaultWorkers, + kindWorkers: opts.KindWorkers, + rateLimiter: opts.DefaultRateLimiter, + kindRateLimiter: opts.KindRateLimiter, + } +} + +func applyDefaultSharedOptions(opts *SharedControllerFactoryOptions) *SharedControllerFactoryOptions { + var newOpts SharedControllerFactoryOptions + if opts != nil { + newOpts = *opts + } + if newOpts.DefaultWorkers == 0 { + newOpts.DefaultWorkers = 5 + } + return &newOpts +} + +func (s *sharedControllerFactory) Start(ctx context.Context, defaultWorkers int) error { + s.controllerLock.Lock() + defer s.controllerLock.Unlock() + + if err := s.sharedCacheFactory.Start(ctx); err != nil { + return err + } + + s.sharedCacheFactory.WaitForCacheSync(ctx) + + for gvr, controller := range s.controllers { + w, err := s.getWorkers(gvr, defaultWorkers) + if err != nil { + return err + } + if err := controller.Start(ctx, w); err != nil { + return err + } + } + + return nil +} + +func (s *sharedControllerFactory) ForObject(obj runtime.Object) (SharedController, error) { + gvk, err := s.sharedCacheFactory.SharedClientFactory().GVKForObject(obj) + if err != nil { + return nil, err + } + return s.ForKind(gvk) +} + +func (s *sharedControllerFactory) ForKind(gvk schema.GroupVersionKind) (SharedController, error) { + gvr, nsed, err := s.sharedCacheFactory.SharedClientFactory().ResourceForGVK(gvk) + if err != nil { + return nil, err + } + + return s.ForResourceKind(gvr, gvk.Kind, nsed), nil +} + +func (s *sharedControllerFactory) ForResource(gvr schema.GroupVersionResource, namespaced bool) SharedController { + return s.ForResourceKind(gvr, "", namespaced) +} + +func (s *sharedControllerFactory) ForResourceKind(gvr schema.GroupVersionResource, kind string, namespaced bool) SharedController { + controllerResult := s.byResource(gvr) + if controllerResult != nil { + return controllerResult + } + + s.controllerLock.Lock() + defer s.controllerLock.Unlock() + + controllerResult = s.controllers[gvr] + if controllerResult != nil { + return controllerResult + } + + client := s.sharedCacheFactory.SharedClientFactory().ForResourceKind(gvr, kind, namespaced) + + handler := &SharedHandler{} + + controllerResult = &sharedController{ + deferredController: func() (Controller, error) { + var ( + gvk schema.GroupVersionKind + err error + ) + + if kind == "" { + gvk, err = s.sharedCacheFactory.SharedClientFactory().GVKForResource(gvr) + if err != nil { + return nil, err + } + } else { + gvk = gvr.GroupVersion().WithKind(kind) + } + + cache, err := s.sharedCacheFactory.ForResourceKind(gvr, kind, namespaced) + if err != nil { + return nil, err + } + + rateLimiter, ok := s.kindRateLimiter[gvk] + if !ok { + rateLimiter = s.rateLimiter + } + + starter := func(ctx context.Context) error { + return s.sharedCacheFactory.StartGVK(ctx, gvk) + } + + c := New(gvk.String(), cache, starter, handler, &Options{ + RateLimiter: rateLimiter, + }) + + return c, err + }, + handler: handler, + client: client, + } + + s.controllers[gvr] = controllerResult + return controllerResult +} + +func (s *sharedControllerFactory) getWorkers(gvr schema.GroupVersionResource, workers int) (int, error) { + gvk, err := s.sharedCacheFactory.SharedClientFactory().GVKForResource(gvr) + if meta.IsNoMatchError(err) { + return workers, nil + } else if err != nil { + return 0, err + } + + w, ok := s.kindWorkers[gvk] + if ok { + return w, nil + } + if workers > 0 { + return workers, nil + } + return s.workers, nil +} + +func (s *sharedControllerFactory) byResource(gvr schema.GroupVersionResource) *sharedController { + s.controllerLock.RLock() + defer s.controllerLock.RUnlock() + return s.controllers[gvr] +} + +func (s *sharedControllerFactory) SharedCacheFactory() cache.SharedCacheFactory { + return s.sharedCacheFactory +} diff --git a/vendor/github.com/rancher/lasso/pkg/controller/sharedhandler.go b/vendor/github.com/rancher/lasso/pkg/controller/sharedhandler.go new file mode 100644 index 0000000000..a3f9bada2c --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/controller/sharedhandler.go @@ -0,0 +1,133 @@ +package controller + +import ( + "context" + "errors" + "fmt" + "reflect" + "strings" + "sync" + "sync/atomic" + + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/runtime" +) + +var ( + ErrIgnore = errors.New("ignore handler error") +) + +type handlerEntry struct { + id int64 + name string + handler SharedControllerHandler +} + +type SharedHandler struct { + // keep first because arm32 needs atomic.AddInt64 target to be mem aligned + idCounter int64 + + lock sync.RWMutex + handlers []handlerEntry +} + +func (h *SharedHandler) Register(ctx context.Context, name string, handler SharedControllerHandler) { + h.lock.Lock() + defer h.lock.Unlock() + + id := atomic.AddInt64(&h.idCounter, 1) + h.handlers = append(h.handlers, handlerEntry{ + id: id, + name: name, + handler: handler, + }) + + go func() { + <-ctx.Done() + + h.lock.Lock() + defer h.lock.Unlock() + + for i := range h.handlers { + if h.handlers[i].id == id { + h.handlers = append(h.handlers[:i], h.handlers[i+1:]...) + break + } + } + }() +} + +func (h *SharedHandler) OnChange(key string, obj runtime.Object) error { + var ( + errs errorList + ) + h.lock.RLock() + handlers := h.handlers + h.lock.RUnlock() + + for _, handler := range handlers { + newObj, err := handler.handler.OnChange(key, obj) + if err != nil && !errors.Is(err, ErrIgnore) { + errs = append(errs, &handlerError{ + HandlerName: handler.name, + Err: err, + }) + } + if newObj != nil && !reflect.ValueOf(newObj).IsNil() { + meta, err := meta.Accessor(newObj) + if err == nil && meta.GetUID() != "" { + // avoid using an empty object + obj = newObj + } else if err != nil { + // assign if we can't determine metadata + obj = newObj + } + } + } + + return errs.ToErr() +} + +type errorList []error + +func (e errorList) Error() string { + buf := strings.Builder{} + for _, err := range e { + if buf.Len() > 0 { + buf.WriteString(", ") + } + buf.WriteString(err.Error()) + } + return buf.String() +} + +func (e errorList) ToErr() error { + switch len(e) { + case 0: + return nil + case 1: + return e[0] + default: + return e + } +} + +func (e errorList) Cause() error { + if len(e) > 0 { + return e[0] + } + return nil +} + +type handlerError struct { + HandlerName string + Err error +} + +func (h handlerError) Error() string { + return fmt.Sprintf("handler %s: %v", h.HandlerName, h.Err) +} + +func (h handlerError) Cause() error { + return h.Err +} diff --git a/vendor/github.com/rancher/wrangler/pkg/generic/transaction.go b/vendor/github.com/rancher/lasso/pkg/controller/transaction.go similarity index 62% rename from vendor/github.com/rancher/wrangler/pkg/generic/transaction.go rename to vendor/github.com/rancher/lasso/pkg/controller/transaction.go index 23b9847d8d..e00f28a5e7 100644 --- a/vendor/github.com/rancher/wrangler/pkg/generic/transaction.go +++ b/vendor/github.com/rancher/lasso/pkg/controller/transaction.go @@ -1,40 +1,52 @@ -package generic +package controller import ( "context" + "sync" ) type hTransactionKey struct{} type HandlerTransaction struct { context.Context + + lock sync.Mutex parent context.Context - done chan struct{} - result bool + todo []func() } -func (h *HandlerTransaction) shouldContinue() bool { - select { - case <-h.parent.Done(): - return false - case <-h.done: - return h.result +func (h *HandlerTransaction) do(f func()) { + if h == nil { + f() + return } + + h.lock.Lock() + defer h.lock.Unlock() + + h.todo = append(h.todo, f) } func (h *HandlerTransaction) Commit() { - h.result = true - close(h.done) + h.lock.Lock() + fs := h.todo + h.todo = nil + h.lock.Unlock() + + for _, f := range fs { + f() + } } func (h *HandlerTransaction) Rollback() { - close(h.done) + h.lock.Lock() + h.todo = nil + h.lock.Unlock() } func NewHandlerTransaction(ctx context.Context) *HandlerTransaction { ht := &HandlerTransaction{ parent: ctx, - done: make(chan struct{}), } ctx = context.WithValue(ctx, hTransactionKey{}, ht) ht.Context = ctx diff --git a/vendor/github.com/rancher/lasso/pkg/log/log.go b/vendor/github.com/rancher/lasso/pkg/log/log.go new file mode 100644 index 0000000000..a8725e4532 --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/log/log.go @@ -0,0 +1,13 @@ +package log + +import "log" + +var ( + // Stupid log abstraction + Infof = func(message string, obj ...interface{}) { + log.Printf("INFO: "+message+"\n", obj...) + } + Errorf = func(message string, obj ...interface{}) { + log.Printf("ERROR: "+message+"\n", obj...) + } +) diff --git a/vendor/github.com/rancher/lasso/pkg/mapper/mapper.go b/vendor/github.com/rancher/lasso/pkg/mapper/mapper.go new file mode 100644 index 0000000000..3466582484 --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/mapper/mapper.go @@ -0,0 +1,90 @@ +package mapper + +import ( + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/discovery" + "k8s.io/client-go/discovery/cached/memory" + "k8s.io/client-go/rest" + "k8s.io/client-go/restmapper" +) + +func New(config *rest.Config) (meta.RESTMapper, error) { + d, err := discovery.NewDiscoveryClientForConfig(config) + if err != nil { + return nil, err + } + cached := memory.NewMemCacheClient(d) + return &retryMapper{ + target: restmapper.NewDeferredDiscoveryRESTMapper(cached), + cache: cached, + }, nil +} + +type retryMapper struct { + target meta.RESTMapper + cache discovery.CachedDiscoveryInterface +} + +func (r *retryMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { + result, err := r.target.KindFor(resource) + if err != nil { + r.cache.Invalidate() + return r.target.KindFor(resource) + } + return result, err +} + +func (r *retryMapper) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) { + result, err := r.target.KindsFor(resource) + if err != nil { + r.cache.Invalidate() + return r.target.KindsFor(resource) + } + return result, err +} + +func (r *retryMapper) ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error) { + result, err := r.target.ResourceFor(input) + if err != nil { + r.cache.Invalidate() + return r.target.ResourceFor(input) + } + return result, err +} + +func (r *retryMapper) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { + result, err := r.target.ResourcesFor(input) + if err != nil { + r.cache.Invalidate() + return r.target.ResourcesFor(input) + } + return result, err +} + +func (r *retryMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) { + result, err := r.target.RESTMapping(gk, versions...) + if err != nil { + r.cache.Invalidate() + return r.target.RESTMapping(gk, versions...) + } + return result, err +} + +func (r *retryMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*meta.RESTMapping, error) { + result, err := r.target.RESTMappings(gk, versions...) + if err != nil { + r.cache.Invalidate() + return r.target.RESTMappings(gk, versions...) + } + return result, err +} + +func (r *retryMapper) ResourceSingularizer(resource string) (singular string, err error) { + result, err := r.target.ResourceSingularizer(resource) + if err != nil { + r.cache.Invalidate() + return r.target.ResourceSingularizer(resource) + } + return result, err +} diff --git a/vendor/github.com/rancher/lasso/pkg/scheme/all.go b/vendor/github.com/rancher/lasso/pkg/scheme/all.go new file mode 100644 index 0000000000..119766c4ce --- /dev/null +++ b/vendor/github.com/rancher/lasso/pkg/scheme/all.go @@ -0,0 +1,5 @@ +package scheme + +import "k8s.io/apimachinery/pkg/runtime" + +var All = runtime.NewScheme() diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/factory.go b/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/factory.go deleted file mode 100644 index 9c7261ec78..0000000000 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/factory.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package apps - -import ( - "context" - "time" - - "github.com/rancher/wrangler/pkg/generic" - "github.com/rancher/wrangler/pkg/schemes" - "k8s.io/apimachinery/pkg/runtime/schema" - informers "k8s.io/client-go/informers" - clientset "k8s.io/client-go/kubernetes" - scheme "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" -) - -func init() { - scheme.AddToScheme(schemes.All) -} - -type Factory struct { - synced bool - informerFactory informers.SharedInformerFactory - clientset clientset.Interface - controllerManager *generic.ControllerManager - threadiness map[schema.GroupVersionKind]int -} - -func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { - f, err := NewFactoryFromConfig(config) - if err != nil { - panic(err) - } - return f -} - -func NewFactoryFromConfig(config *rest.Config) (*Factory, error) { - return NewFactoryFromConfigWithOptions(config, nil) -} - -func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) { - return NewFactoryFromConfigWithOptions(config, &FactoryOptions{ - Namespace: namespace, - }) -} - -type FactoryOptions struct { - Namespace string - Resync time.Duration -} - -func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { - if opts == nil { - opts = &FactoryOptions{} - } - - cs, err := clientset.NewForConfig(config) - if err != nil { - return nil, err - } - - resync := opts.Resync - if resync == 0 { - resync = 2 * time.Hour - } - - if opts.Namespace == "" { - informerFactory := informers.NewSharedInformerFactory(cs, resync) - return NewFactory(cs, informerFactory), nil - } - - informerFactory := informers.NewSharedInformerFactoryWithOptions(cs, resync, informers.WithNamespace(opts.Namespace)) - return NewFactory(cs, informerFactory), nil -} - -func NewFactory(clientset clientset.Interface, informerFactory informers.SharedInformerFactory) *Factory { - return &Factory{ - threadiness: map[schema.GroupVersionKind]int{}, - controllerManager: &generic.ControllerManager{}, - clientset: clientset, - informerFactory: informerFactory, - } -} - -func (c *Factory) Controllers() map[schema.GroupVersionKind]*generic.Controller { - return c.controllerManager.Controllers() -} - -func (c *Factory) SetThreadiness(gvk schema.GroupVersionKind, threadiness int) { - c.threadiness[gvk] = threadiness -} - -func (c *Factory) Sync(ctx context.Context) error { - c.informerFactory.Start(ctx.Done()) - c.informerFactory.WaitForCacheSync(ctx.Done()) - return nil -} - -func (c *Factory) Start(ctx context.Context, defaultThreadiness int) error { - if err := c.Sync(ctx); err != nil { - return err - } - - return c.controllerManager.Start(ctx, defaultThreadiness, c.threadiness) -} - -func (c *Factory) Apps() Interface { - return New(c.controllerManager, c.informerFactory.Apps(), c.clientset) -} diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/factory.go b/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/factory.go deleted file mode 100644 index c3a8c56498..0000000000 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/factory.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package batch - -import ( - "context" - "time" - - "github.com/rancher/wrangler/pkg/generic" - "github.com/rancher/wrangler/pkg/schemes" - "k8s.io/apimachinery/pkg/runtime/schema" - informers "k8s.io/client-go/informers" - clientset "k8s.io/client-go/kubernetes" - scheme "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" -) - -func init() { - scheme.AddToScheme(schemes.All) -} - -type Factory struct { - synced bool - informerFactory informers.SharedInformerFactory - clientset clientset.Interface - controllerManager *generic.ControllerManager - threadiness map[schema.GroupVersionKind]int -} - -func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { - f, err := NewFactoryFromConfig(config) - if err != nil { - panic(err) - } - return f -} - -func NewFactoryFromConfig(config *rest.Config) (*Factory, error) { - return NewFactoryFromConfigWithOptions(config, nil) -} - -func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) { - return NewFactoryFromConfigWithOptions(config, &FactoryOptions{ - Namespace: namespace, - }) -} - -type FactoryOptions struct { - Namespace string - Resync time.Duration -} - -func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { - if opts == nil { - opts = &FactoryOptions{} - } - - cs, err := clientset.NewForConfig(config) - if err != nil { - return nil, err - } - - resync := opts.Resync - if resync == 0 { - resync = 2 * time.Hour - } - - if opts.Namespace == "" { - informerFactory := informers.NewSharedInformerFactory(cs, resync) - return NewFactory(cs, informerFactory), nil - } - - informerFactory := informers.NewSharedInformerFactoryWithOptions(cs, resync, informers.WithNamespace(opts.Namespace)) - return NewFactory(cs, informerFactory), nil -} - -func NewFactory(clientset clientset.Interface, informerFactory informers.SharedInformerFactory) *Factory { - return &Factory{ - threadiness: map[schema.GroupVersionKind]int{}, - controllerManager: &generic.ControllerManager{}, - clientset: clientset, - informerFactory: informerFactory, - } -} - -func (c *Factory) Controllers() map[schema.GroupVersionKind]*generic.Controller { - return c.controllerManager.Controllers() -} - -func (c *Factory) SetThreadiness(gvk schema.GroupVersionKind, threadiness int) { - c.threadiness[gvk] = threadiness -} - -func (c *Factory) Sync(ctx context.Context) error { - c.informerFactory.Start(ctx.Done()) - c.informerFactory.WaitForCacheSync(ctx.Done()) - return nil -} - -func (c *Factory) Start(ctx context.Context, defaultThreadiness int) error { - if err := c.Sync(ctx); err != nil { - return err - } - - return c.controllerManager.Start(ctx, defaultThreadiness, c.threadiness) -} - -func (c *Factory) Batch() Interface { - return New(c.controllerManager, c.informerFactory.Batch(), c.clientset) -} diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/factory.go b/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/factory.go deleted file mode 100644 index e4d841ea64..0000000000 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/factory.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package core - -import ( - "context" - "time" - - "github.com/rancher/wrangler/pkg/generic" - "github.com/rancher/wrangler/pkg/schemes" - "k8s.io/apimachinery/pkg/runtime/schema" - informers "k8s.io/client-go/informers" - clientset "k8s.io/client-go/kubernetes" - scheme "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" -) - -func init() { - scheme.AddToScheme(schemes.All) -} - -type Factory struct { - synced bool - informerFactory informers.SharedInformerFactory - clientset clientset.Interface - controllerManager *generic.ControllerManager - threadiness map[schema.GroupVersionKind]int -} - -func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { - f, err := NewFactoryFromConfig(config) - if err != nil { - panic(err) - } - return f -} - -func NewFactoryFromConfig(config *rest.Config) (*Factory, error) { - return NewFactoryFromConfigWithOptions(config, nil) -} - -func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) { - return NewFactoryFromConfigWithOptions(config, &FactoryOptions{ - Namespace: namespace, - }) -} - -type FactoryOptions struct { - Namespace string - Resync time.Duration -} - -func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { - if opts == nil { - opts = &FactoryOptions{} - } - - cs, err := clientset.NewForConfig(config) - if err != nil { - return nil, err - } - - resync := opts.Resync - if resync == 0 { - resync = 2 * time.Hour - } - - if opts.Namespace == "" { - informerFactory := informers.NewSharedInformerFactory(cs, resync) - return NewFactory(cs, informerFactory), nil - } - - informerFactory := informers.NewSharedInformerFactoryWithOptions(cs, resync, informers.WithNamespace(opts.Namespace)) - return NewFactory(cs, informerFactory), nil -} - -func NewFactory(clientset clientset.Interface, informerFactory informers.SharedInformerFactory) *Factory { - return &Factory{ - threadiness: map[schema.GroupVersionKind]int{}, - controllerManager: &generic.ControllerManager{}, - clientset: clientset, - informerFactory: informerFactory, - } -} - -func (c *Factory) Controllers() map[schema.GroupVersionKind]*generic.Controller { - return c.controllerManager.Controllers() -} - -func (c *Factory) SetThreadiness(gvk schema.GroupVersionKind, threadiness int) { - c.threadiness[gvk] = threadiness -} - -func (c *Factory) Sync(ctx context.Context) error { - c.informerFactory.Start(ctx.Done()) - c.informerFactory.WaitForCacheSync(ctx.Done()) - return nil -} - -func (c *Factory) Start(ctx context.Context, defaultThreadiness int) error { - if err := c.Sync(ctx); err != nil { - return err - } - - return c.controllerManager.Start(ctx, defaultThreadiness, c.threadiness) -} - -func (c *Factory) Core() Interface { - return New(c.controllerManager, c.informerFactory.Core(), c.clientset) -} diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/interface.go b/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/interface.go deleted file mode 100644 index 92fc1c6ec0..0000000000 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/interface.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package v1 - -import ( - "github.com/rancher/wrangler/pkg/generic" - v1 "k8s.io/api/core/v1" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" -) - -type Interface interface { - ConfigMap() ConfigMapController - Endpoints() EndpointsController - Event() EventController - Namespace() NamespaceController - Node() NodeController - PersistentVolumeClaim() PersistentVolumeClaimController - Pod() PodController - Secret() SecretController - Service() ServiceController - ServiceAccount() ServiceAccountController -} - -func New(controllerManager *generic.ControllerManager, client clientset.CoreV1Interface, - informers informers.Interface) Interface { - return &version{ - controllerManager: controllerManager, - client: client, - informers: informers, - } -} - -type version struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.CoreV1Interface -} - -func (c *version) ConfigMap() ConfigMapController { - return NewConfigMapController(v1.SchemeGroupVersion.WithKind("ConfigMap"), c.controllerManager, c.client, c.informers.ConfigMaps()) -} -func (c *version) Endpoints() EndpointsController { - return NewEndpointsController(v1.SchemeGroupVersion.WithKind("Endpoints"), c.controllerManager, c.client, c.informers.Endpoints()) -} -func (c *version) Event() EventController { - return NewEventController(v1.SchemeGroupVersion.WithKind("Event"), c.controllerManager, c.client, c.informers.Events()) -} -func (c *version) Namespace() NamespaceController { - return NewNamespaceController(v1.SchemeGroupVersion.WithKind("Namespace"), c.controllerManager, c.client, c.informers.Namespaces()) -} -func (c *version) Node() NodeController { - return NewNodeController(v1.SchemeGroupVersion.WithKind("Node"), c.controllerManager, c.client, c.informers.Nodes()) -} -func (c *version) PersistentVolumeClaim() PersistentVolumeClaimController { - return NewPersistentVolumeClaimController(v1.SchemeGroupVersion.WithKind("PersistentVolumeClaim"), c.controllerManager, c.client, c.informers.PersistentVolumeClaims()) -} -func (c *version) Pod() PodController { - return NewPodController(v1.SchemeGroupVersion.WithKind("Pod"), c.controllerManager, c.client, c.informers.Pods()) -} -func (c *version) Secret() SecretController { - return NewSecretController(v1.SchemeGroupVersion.WithKind("Secret"), c.controllerManager, c.client, c.informers.Secrets()) -} -func (c *version) Service() ServiceController { - return NewServiceController(v1.SchemeGroupVersion.WithKind("Service"), c.controllerManager, c.client, c.informers.Services()) -} -func (c *version) ServiceAccount() ServiceAccountController { - return NewServiceAccountController(v1.SchemeGroupVersion.WithKind("ServiceAccount"), c.controllerManager, c.client, c.informers.ServiceAccounts()) -} diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/factory.go b/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/factory.go deleted file mode 100644 index 1ae7c9f52e..0000000000 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/factory.go +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by main. DO NOT EDIT. - -package rbac - -import ( - "context" - "time" - - "github.com/rancher/wrangler/pkg/generic" - "github.com/rancher/wrangler/pkg/schemes" - "k8s.io/apimachinery/pkg/runtime/schema" - informers "k8s.io/client-go/informers" - clientset "k8s.io/client-go/kubernetes" - scheme "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" -) - -func init() { - scheme.AddToScheme(schemes.All) -} - -type Factory struct { - synced bool - informerFactory informers.SharedInformerFactory - clientset clientset.Interface - controllerManager *generic.ControllerManager - threadiness map[schema.GroupVersionKind]int -} - -func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { - f, err := NewFactoryFromConfig(config) - if err != nil { - panic(err) - } - return f -} - -func NewFactoryFromConfig(config *rest.Config) (*Factory, error) { - return NewFactoryFromConfigWithOptions(config, nil) -} - -func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) { - return NewFactoryFromConfigWithOptions(config, &FactoryOptions{ - Namespace: namespace, - }) -} - -type FactoryOptions struct { - Namespace string - Resync time.Duration -} - -func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { - if opts == nil { - opts = &FactoryOptions{} - } - - cs, err := clientset.NewForConfig(config) - if err != nil { - return nil, err - } - - resync := opts.Resync - if resync == 0 { - resync = 2 * time.Hour - } - - if opts.Namespace == "" { - informerFactory := informers.NewSharedInformerFactory(cs, resync) - return NewFactory(cs, informerFactory), nil - } - - informerFactory := informers.NewSharedInformerFactoryWithOptions(cs, resync, informers.WithNamespace(opts.Namespace)) - return NewFactory(cs, informerFactory), nil -} - -func NewFactory(clientset clientset.Interface, informerFactory informers.SharedInformerFactory) *Factory { - return &Factory{ - threadiness: map[schema.GroupVersionKind]int{}, - controllerManager: &generic.ControllerManager{}, - clientset: clientset, - informerFactory: informerFactory, - } -} - -func (c *Factory) Controllers() map[schema.GroupVersionKind]*generic.Controller { - return c.controllerManager.Controllers() -} - -func (c *Factory) SetThreadiness(gvk schema.GroupVersionKind, threadiness int) { - c.threadiness[gvk] = threadiness -} - -func (c *Factory) Sync(ctx context.Context) error { - c.informerFactory.Start(ctx.Done()) - c.informerFactory.WaitForCacheSync(ctx.Done()) - return nil -} - -func (c *Factory) Start(ctx context.Context, defaultThreadiness int) error { - if err := c.Sync(ctx); err != nil { - return err - } - - return c.controllerManager.Start(ctx, defaultThreadiness, c.threadiness) -} - -func (c *Factory) Rbac() Interface { - return New(c.controllerManager, c.informerFactory.Rbac(), c.clientset) -} diff --git a/vendor/github.com/rancher/wrangler/pkg/apply/apply.go b/vendor/github.com/rancher/wrangler/pkg/apply/apply.go index 372cd44e42..2f295a704d 100644 --- a/vendor/github.com/rancher/wrangler/pkg/apply/apply.go +++ b/vendor/github.com/rancher/wrangler/pkg/apply/apply.go @@ -12,7 +12,6 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/discovery" "k8s.io/client-go/dynamic" - "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" ) @@ -78,8 +77,11 @@ type Apply interface { WithListerNamespace(ns string) Apply WithRateLimiting(ratelimitingQps float32) Apply WithNoDelete() Apply + WithNoDeleteGVK(gvks ...schema.GroupVersionKind) Apply WithGVK(gvks ...schema.GroupVersionKind) Apply WithSetOwnerReference(controller, block bool) Apply + WithIgnorePreviousApplied() Apply + WithDiffPatch(gvk schema.GroupVersionKind, namespace, name string, patch []byte) Apply FindOwner(obj runtime.Object) (runtime.Object, error) PurgeOrphan(obj runtime.Object) error @@ -87,12 +89,12 @@ type Apply interface { } func NewForConfig(cfg *rest.Config) (Apply, error) { - k8s, err := kubernetes.NewForConfig(cfg) + discovery, err := discovery.NewDiscoveryClientForConfig(cfg) if err != nil { return nil, err } - return New(k8s.Discovery(), NewClientFactory(cfg)), nil + return New(discovery, NewClientFactory(cfg)), nil } func New(discovery discovery.DiscoveryInterface, cf ClientFactory, igs ...InformerGetter) Apply { @@ -129,10 +131,22 @@ type clients struct { clients map[schema.GroupVersionKind]dynamic.NamespaceableResourceInterface } -func (c *clients) IsNamespaced(gvk schema.GroupVersionKind) bool { +func (c *clients) IsNamespaced(gvk schema.GroupVersionKind) (bool, error) { + c.Lock() + ok, exists := c.namespaced[gvk] + c.Unlock() + + if exists { + return ok, nil + } + _, err := c.client(gvk) + if err != nil { + return false, err + } + c.Lock() defer c.Unlock() - return c.namespaced[gvk] + return c.namespaced[gvk], nil } func (c *clients) gvr(gvk schema.GroupVersionKind) schema.GroupVersionResource { @@ -266,6 +280,10 @@ func (a *apply) WithNoDelete() Apply { return a.newDesiredSet().WithNoDelete() } +func (a *apply) WithNoDeleteGVK(gvks ...schema.GroupVersionKind) Apply { + return a.newDesiredSet().WithNoDeleteGVK(gvks...) +} + func (a *apply) WithSetOwnerReference(controller, block bool) Apply { return a.newDesiredSet().WithSetOwnerReference(controller, block) } @@ -274,6 +292,10 @@ func (a *apply) WithContext(ctx context.Context) Apply { return a.newDesiredSet().WithContext(ctx) } +func (a *apply) WithIgnorePreviousApplied() Apply { + return a.newDesiredSet().WithIgnorePreviousApplied() +} + func (a *apply) FindOwner(obj runtime.Object) (runtime.Object, error) { return a.newDesiredSet().FindOwner(obj) } @@ -281,3 +303,7 @@ func (a *apply) FindOwner(obj runtime.Object) (runtime.Object, error) { func (a *apply) PurgeOrphan(obj runtime.Object) error { return a.newDesiredSet().PurgeOrphan(obj) } + +func (a *apply) WithDiffPatch(gvk schema.GroupVersionKind, namespace, name string, patch []byte) Apply { + return a.newDesiredSet().WithDiffPatch(gvk, namespace, name, patch) +} diff --git a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset.go b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset.go index 8cc6da4cfc..ecdaa9185a 100644 --- a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset.go +++ b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset.go @@ -2,6 +2,7 @@ package apply import ( "context" + "github.com/rancher/wrangler/pkg/apply/injectors" "github.com/rancher/wrangler/pkg/kv" "github.com/rancher/wrangler/pkg/merr" @@ -12,11 +13,17 @@ import ( "k8s.io/client-go/tools/cache" ) +type patchKey struct { + schema.GroupVersionKind + objectset.ObjectKey +} + type desiredSet struct { a *apply ctx context.Context defaultNamespace string listerNamespace string + ignorePreviousApplied bool setOwnerReference bool ownerReferenceController bool ownerReferenceBlock bool @@ -25,9 +32,11 @@ type desiredSet struct { pruneTypes map[schema.GroupVersionKind]cache.SharedIndexInformer patchers map[schema.GroupVersionKind]Patcher reconcilers map[schema.GroupVersionKind]Reconciler + diffPatches map[patchKey][][]byte informerFactory InformerFactory remove bool noDelete bool + noDeleteGVK map[schema.GroupVersionKind]struct{} setID string objs *objectset.ObjectSet codeVersion string @@ -70,6 +79,23 @@ func (o desiredSet) ApplyObjects(objs ...runtime.Object) error { return o.Apply(os) } +func (o desiredSet) WithDiffPatch(gvk schema.GroupVersionKind, namespace, name string, patch []byte) Apply { + patches := map[patchKey][][]byte{} + for k, v := range o.diffPatches { + patches[k] = v + } + key := patchKey{ + GroupVersionKind: gvk, + ObjectKey: objectset.ObjectKey{ + Name: name, + Namespace: namespace, + }, + } + patches[key] = append(patches[key], patch) + o.diffPatches = patches + return o +} + // WithGVK uses a known listing of existing gvks to modify the the prune types to allow for deletion of objects func (o desiredSet) WithGVK(gvks ...schema.GroupVersionKind) Apply { pruneTypes := make(map[schema.GroupVersionKind]cache.SharedIndexInformer, len(gvks)) @@ -123,6 +149,11 @@ func (o desiredSet) WithCacheTypeFactory(factory InformerFactory) Apply { return o } +func (o desiredSet) WithIgnorePreviousApplied() Apply { + o.ignorePreviousApplied = true + return o +} + func (o desiredSet) WithCacheTypes(igs ...InformerGetter) Apply { pruneTypes := make(map[schema.GroupVersionKind]cache.SharedIndexInformer, len(igs)) for k, v := range o.pruneTypes { @@ -195,6 +226,16 @@ func (o desiredSet) WithNoDelete() Apply { return o } +func (o desiredSet) WithNoDeleteGVK(gvks ...schema.GroupVersionKind) Apply { + if o.noDeleteGVK == nil { + o.noDeleteGVK = make(map[schema.GroupVersionKind]struct{}) + } + for _, curr := range gvks { + o.noDeleteGVK[curr] = struct{}{} + } + return o +} + func (o desiredSet) WithContext(ctx context.Context) Apply { o.ctx = ctx return o diff --git a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_apply.go b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_apply.go index e297fc795d..7f335530b4 100644 --- a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_apply.go +++ b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_apply.go @@ -5,13 +5,15 @@ import ( "encoding/hex" "fmt" "sync" + "time" + + "github.com/sirupsen/logrus" gvk2 "github.com/rancher/wrangler/pkg/gvk" "github.com/pkg/errors" "github.com/rancher/wrangler/pkg/apply/injectors" "github.com/rancher/wrangler/pkg/objectset" - errors2 "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" @@ -83,8 +85,12 @@ func (o *desiredSet) apply() error { } rl := o.getRateLimit(labelSet[LabelHash]) - if rl != nil && !rl.TryAccept() { - return errors2.NewConflict(schema.GroupResource{}, o.setID, errors.New("delaying object set")) + if rl != nil { + t := time.Now() + rl.Accept() + if d := time.Now().Sub(t); d.Seconds() > 1 { + logrus.Infof("rate limited %s(%s) %s", o.setID, labelSet, d) + } } objList, err := o.injectLabelsAndAnnotations(labelSet, annotationSet) @@ -171,6 +177,17 @@ func (o *desiredSet) runInjectors(objList []runtime.Object) ([]runtime.Object, e return objList, nil } +// GetSelectorFromOwner returns the label selector for the owner object which is useful +// to list the dependents +func GetSelectorFromOwner(setID string, owner runtime.Object) (labels.Selector, error) { + // Build the labels, we want the hash label for the lister + ownerLabel, _, err := GetLabelsAndAnnotations(setID, owner) + if err != nil { + return nil, err + } + return GetSelector(ownerLabel) +} + func GetSelector(labelSet map[string]string) (labels.Selector, error) { req, err := labels.NewRequirement(LabelHash, selection.Equals, []string{labelSet[LabelHash]}) if err != nil { @@ -180,6 +197,10 @@ func GetSelector(labelSet map[string]string) (labels.Selector, error) { } func GetLabelsAndAnnotations(setID string, owner runtime.Object) (map[string]string, map[string]string, error) { + if setID == "" && owner == nil { + return nil, nil, fmt.Errorf("set ID or owner must be set") + } + annotations := map[string]string{ LabelID: setID, } diff --git a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_compare.go b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_compare.go index 892fc36ede..f59628ced1 100644 --- a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_compare.go +++ b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_compare.go @@ -7,10 +7,11 @@ import ( "io/ioutil" "strings" - data2 "github.com/rancher/wrangler/pkg/data" - + jsonpatch "github.com/evanphx/json-patch" "github.com/pkg/errors" + data2 "github.com/rancher/wrangler/pkg/data" "github.com/rancher/wrangler/pkg/data/convert" + "github.com/rancher/wrangler/pkg/objectset" patch2 "github.com/rancher/wrangler/pkg/patch" "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/api/meta" @@ -29,8 +30,23 @@ const ( LabelApplied = "objectset.rio.cattle.io/applied" ) +var ( + knownListKeys = map[string]bool{ + "apiVersion": true, + "containerPort": true, + "devicePath": true, + "ip": true, + "kind": true, + "mountPath": true, + "name": true, + "port": true, + "topologyKey": true, + "type": true, + } +) + func prepareObjectForCreate(gvk schema.GroupVersionKind, obj runtime.Object) (runtime.Object, error) { - serialized, err := json.Marshal(obj) + serialized, err := serializeApplied(obj) if err != nil { return nil, err } @@ -116,6 +132,11 @@ func sanitizePatch(patch []byte, removeObjectSetAnnotation bool) ([]byte, error) delete(data, "apiVersion") } + if _, ok := data["status"]; ok { + mod = true + delete(data, "status") + } + if deleted := removeCreationTimestamp(data); deleted { mod = true } @@ -148,7 +169,7 @@ func sanitizePatch(patch []byte, removeObjectSetAnnotation bool) ([]byte, error) return json.Marshal(data) } -func applyPatch(gvk schema.GroupVersionKind, reconciler Reconciler, patcher Patcher, debugID string, oldObject, newObject runtime.Object) (bool, error) { +func applyPatch(gvk schema.GroupVersionKind, reconciler Reconciler, patcher Patcher, debugID string, ignoreOriginal bool, oldObject, newObject runtime.Object, diffPatches [][]byte) (bool, error) { oldMetadata, err := meta.Accessor(oldObject) if err != nil { return false, err @@ -158,12 +179,17 @@ func applyPatch(gvk schema.GroupVersionKind, reconciler Reconciler, patcher Patc if err != nil { return false, err } + + if ignoreOriginal { + original = nil + } + current, err := json.Marshal(oldObject) if err != nil { return false, err } - patchType, patch, err := doPatch(gvk, original, modified, current) + patchType, patch, err := doPatch(gvk, original, modified, current, diffPatches) if err != nil { return false, errors.Wrap(err, "patch generation") } @@ -220,7 +246,18 @@ func (o *desiredSet) compareObjects(gvk schema.GroupVersionKind, reconciler Reco o.plan.Objects = append(o.plan.Objects, oldObject) } - if ran, err := applyPatch(gvk, reconciler, patcher, debugID, oldObject, newObject); err != nil { + diffPatches := o.diffPatches[patchKey{ + GroupVersionKind: gvk, + ObjectKey: objectset.ObjectKey{ + Namespace: oldMetadata.GetNamespace(), + Name: oldMetadata.GetName(), + }, + }] + diffPatches = append(diffPatches, o.diffPatches[patchKey{ + GroupVersionKind: gvk, + }]...) + + if ran, err := applyPatch(gvk, reconciler, patcher, debugID, o.ignorePreviousApplied, oldObject, newObject, diffPatches); err != nil { return err } else if !ran { logrus.Debugf("DesiredSet - No change(2) %s %s/%s for %s", gvk, oldMetadata.GetNamespace(), oldMetadata.GetName(), debugID) @@ -296,10 +333,61 @@ func appliedFromAnnotation(str string) []byte { return b } -func appliedToAnnotation(b []byte) string { - if len(b) < 1024 { - return string(b) +func pruneList(data []interface{}) []interface{} { + result := make([]interface{}, 0, len(data)) + for _, v := range data { + switch typed := v.(type) { + case map[string]interface{}: + result = append(result, pruneValues(typed, true)) + case []interface{}: + result = append(result, pruneList(typed)) + default: + result = append(result, v) + } } + return result +} + +func pruneValues(data map[string]interface{}, isList bool) map[string]interface{} { + result := map[string]interface{}{} + for k, v := range data { + switch typed := v.(type) { + case map[string]interface{}: + result[k] = pruneValues(typed, false) + case []interface{}: + result[k] = pruneList(typed) + default: + if isList && knownListKeys[k] { + result[k] = v + } else { + switch x := v.(type) { + case string: + if len(x) > 64 { + result[k] = x[:64] + } else { + result[k] = v + } + case []byte: + result[k] = nil + default: + result[k] = v + } + } + } + } + return result +} + +func serializeApplied(obj runtime.Object) ([]byte, error) { + data, err := convert.EncodeToMap(obj) + if err != nil { + return nil, err + } + data = pruneValues(data, false) + return json.Marshal(data) +} + +func appliedToAnnotation(b []byte) string { buf := &bytes.Buffer{} w := gzip.NewWriter(buf) if _, err := w.Write(b); err != nil { @@ -311,11 +399,42 @@ func appliedToAnnotation(b []byte) string { return base64.RawStdEncoding.EncodeToString(buf.Bytes()) } +func stripIgnores(original, modified, current []byte, patches [][]byte) ([]byte, []byte, []byte, error) { + for _, patch := range patches { + patch, err := jsonpatch.DecodePatch(patch) + if err != nil { + return nil, nil, nil, err + } + if len(original) > 0 { + b, err := patch.Apply(original) + if err == nil { + original = b + } + } + b, err := patch.Apply(modified) + if err == nil { + modified = b + } + b, err = patch.Apply(current) + if err == nil { + current = b + } + } + + return original, modified, current, nil +} + // doPatch is adapted from "kubectl apply" -func doPatch(gvk schema.GroupVersionKind, original, modified, current []byte) (types.PatchType, []byte, error) { - var patchType types.PatchType - var patch []byte - var lookupPatchMeta strategicpatch.LookupPatchMeta +func doPatch(gvk schema.GroupVersionKind, original, modified, current []byte, diffPatch [][]byte) (types.PatchType, []byte, error) { + var ( + patchType types.PatchType + patch []byte + ) + + original, modified, current, err := stripIgnores(original, modified, current, diffPatch) + if err != nil { + return patchType, nil, err + } patchType, lookupPatchMeta, err := patch2.GetMergeStyle(gvk) if err != nil { diff --git a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_crud.go b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_crud.go index 7d74bcc1d4..901650ca69 100644 --- a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_crud.go +++ b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_crud.go @@ -6,6 +6,7 @@ import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/json" "k8s.io/client-go/dynamic" ) @@ -51,9 +52,14 @@ func (o *desiredSet) get(nsed bool, namespace, name string, client dynamic.Names return client.Get(o.ctx, name, v1.GetOptions{}) } -func (o *desiredSet) delete(nsed bool, namespace, name string, client dynamic.NamespaceableResourceInterface, force bool) error { - if o.noDelete && !force { - return nil +func (o *desiredSet) delete(nsed bool, namespace, name string, client dynamic.NamespaceableResourceInterface, force bool, gvk schema.GroupVersionKind) error { + if !force { + if o.noDelete { + return nil + } + if _, ok := o.noDeleteGVK[gvk]; ok { + return nil + } } opts := v1.DeleteOptions{ PropagationPolicy: &deletePolicy, diff --git a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_owner.go b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_owner.go index 126fe02be5..dbe87dad9a 100644 --- a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_owner.go +++ b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_owner.go @@ -20,7 +20,8 @@ import ( ) var ( - ErrOwnerNotFound = errors.New("owner not found") + ErrOwnerNotFound = errors.New("owner not found") + ErrNoInformerFound = errors.New("informer not found") ) func notFound(name string, gvk schema.GroupVersionKind) error { diff --git a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_process.go b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_process.go index 459de8ff8d..d559b710cf 100644 --- a/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_process.go +++ b/vendor/github.com/rancher/wrangler/pkg/apply/desiredset_process.go @@ -46,7 +46,7 @@ func (o *desiredSet) getControllerAndClient(debugID string, gvk schema.GroupVers informer = newInformer } if informer == nil && o.strictCaching { - return nil, nil, fmt.Errorf("failed to find informer for %s for %s", gvk, debugID) + return nil, nil, fmt.Errorf("failed to find informer for %s for %s: %w", gvk, debugID, ErrNoInformerFound) } return informer, client, nil @@ -61,17 +61,29 @@ func (o *desiredSet) assignOwnerReference(gvk schema.GroupVersionKind, objs map[ return err } ownerGVK, err := gvk2.Get(o.owner) - ownerNSed := o.a.clients.IsNamespaced(ownerGVK) + if err != nil { + return err + } + ownerNSed, err := o.a.clients.IsNamespaced(ownerGVK) + if err != nil { + return err + } for k, v := range objs { // can't set owners across boundaries - if ownerNSed && !o.a.clients.IsNamespaced(gvk) { - continue + if ownerNSed { + if nsed, err := o.a.clients.IsNamespaced(gvk); err != nil { + return err + } else if !nsed { + continue + } } assignNS := false assignOwner := true - if o.a.clients.IsNamespaced(gvk) { + if nsed, err := o.a.clients.IsNamespaced(gvk); err != nil { + return err + } else if nsed { if k.Namespace == "" { assignNS = true } else if k.Namespace != ownerMeta.GetNamespace() && ownerNSed { @@ -176,6 +188,21 @@ func (o *desiredSet) createPatcher(client dynamic.NamespaceableResourceInterface } } +func (o *desiredSet) filterCrossVersion(gvk schema.GroupVersionKind, keys []objectset.ObjectKey) []objectset.ObjectKey { + result := make([]objectset.ObjectKey, 0, len(keys)) + gk := gvk.GroupKind() + for _, key := range keys { + if o.objs.Contains(gk, key) { + continue + } + if key.Namespace == o.defaultNamespace && o.objs.Contains(gk, objectset.ObjectKey{Name: key.Name}) { + continue + } + result = append(result, key) + } + return result +} + func (o *desiredSet) process(debugID string, set labels.Selector, gvk schema.GroupVersionKind, objs map[objectset.ObjectKey]runtime.Object) { controller, client, err := o.getControllerAndClient(debugID, gvk) if err != nil { @@ -183,14 +210,18 @@ func (o *desiredSet) process(debugID string, set labels.Selector, gvk schema.Gro return } - nsed := o.a.clients.IsNamespaced(gvk) + nsed, err := o.a.clients.IsNamespaced(gvk) + if err != nil { + o.err(err) + return + } if !nsed && o.restrictClusterScoped { o.err(fmt.Errorf("invalid cluster scoped gvk: %v", gvk)) return } - if o.setOwnerReference { + if o.setOwnerReference && o.owner != nil { if err := o.assignOwnerReference(gvk, objs); err != nil { o.err(err) return @@ -216,7 +247,7 @@ func (o *desiredSet) process(debugID string, set labels.Selector, gvk schema.Gro reconciler := o.reconcilers[gvk] - existing, err := o.list(controller, client, set) + existing, err := o.list(nsed, controller, client, set) if err != nil { o.err(errors.Wrapf(err, "failed to list %s for %s", gvk, debugID)) return @@ -224,6 +255,9 @@ func (o *desiredSet) process(debugID string, set labels.Selector, gvk schema.Gro toCreate, toDelete, toUpdate := compareSets(existing, objs) + // check for resources in the objectset but under a different version of the same group/kind + toDelete = o.filterCrossVersion(gvk, toDelete) + if o.createPlan { o.plan.Create[gvk] = toCreate o.plan.Delete[gvk] = toDelete @@ -270,7 +304,7 @@ func (o *desiredSet) process(debugID string, set labels.Selector, gvk schema.Gro } deleteF := func(k objectset.ObjectKey, force bool) { - if err := o.delete(nsed, k.Namespace, k.Name, client, force); err != nil { + if err := o.delete(nsed, k.Namespace, k.Name, client, force, gvk); err != nil { o.err(errors.Wrapf(err, "failed to delete %s %s for %s", k, gvk, debugID)) return } @@ -300,7 +334,7 @@ func (o *desiredSet) process(debugID string, set labels.Selector, gvk schema.Gro } } -func (o *desiredSet) list(informer cache.SharedIndexInformer, client dynamic.NamespaceableResourceInterface, selector labels.Selector) (map[objectset.ObjectKey]runtime.Object, error) { +func (o *desiredSet) list(namespaced bool, informer cache.SharedIndexInformer, client dynamic.NamespaceableResourceInterface, selector labels.Selector) (map[objectset.ObjectKey]runtime.Object, error) { var ( errs []error objs = map[objectset.ObjectKey]runtime.Object{} @@ -331,7 +365,12 @@ func (o *desiredSet) list(informer cache.SharedIndexInformer, client dynamic.Nam return objs, merr.NewErrors(errs...) } - err := cache.ListAllByNamespace(informer.GetIndexer(), "", selector, func(obj interface{}) { + var namespace string + if namespaced { + namespace = o.listerNamespace + } + + err := cache.ListAllByNamespace(informer.GetIndexer(), namespace, selector, func(obj interface{}) { if err := addObjectToMap(objs, obj); err != nil { errs = append(errs, err) } diff --git a/vendor/github.com/rancher/wrangler/pkg/apply/reconcilers.go b/vendor/github.com/rancher/wrangler/pkg/apply/reconcilers.go index f9c487f741..2fba99a75f 100644 --- a/vendor/github.com/rancher/wrangler/pkg/apply/reconcilers.go +++ b/vendor/github.com/rancher/wrangler/pkg/apply/reconcilers.go @@ -16,6 +16,7 @@ import ( var ( defaultReconcilers = map[schema.GroupVersionKind]Reconciler{ + v1.SchemeGroupVersion.WithKind("Secret"): reconcileSecret, v1.SchemeGroupVersion.WithKind("Service"): reconcileService, batchv1.SchemeGroupVersion.WithKind("Job"): reconcileJob, appsv1.SchemeGroupVersion.WithKind("Deployment"): reconcileDeployment, @@ -69,6 +70,29 @@ func reconcileDeployment(oldObj, newObj runtime.Object) (bool, error) { return false, nil } +func reconcileSecret(oldObj, newObj runtime.Object) (bool, error) { + oldSvc, ok := oldObj.(*v1.Secret) + if !ok { + oldSvc = &v1.Secret{} + if err := convertObj(oldObj, oldSvc); err != nil { + return false, err + } + } + newSvc, ok := newObj.(*v1.Secret) + if !ok { + newSvc = &v1.Secret{} + if err := convertObj(newObj, newSvc); err != nil { + return false, err + } + } + + if newSvc.Type != "" && oldSvc.Type != newSvc.Type { + return false, ErrReplace + } + + return false, nil +} + func reconcileService(oldObj, newObj runtime.Object) (bool, error) { oldSvc, ok := oldObj.(*v1.Service) if !ok { diff --git a/vendor/github.com/rancher/wrangler/pkg/condition/condition.go b/vendor/github.com/rancher/wrangler/pkg/condition/condition.go index 906a4213eb..a994541714 100644 --- a/vendor/github.com/rancher/wrangler/pkg/condition/condition.go +++ b/vendor/github.com/rancher/wrangler/pkg/condition/condition.go @@ -128,7 +128,7 @@ func (c Cond) GetMessage(obj interface{}) string { } func touchTS(value reflect.Value) { - now := time.Now().Format(time.RFC3339) + now := time.Now().UTC().Format(time.RFC3339) getFieldValue(value, "LastUpdateTime").SetString(now) } diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/args/args.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/args/args.go index fc176704ca..f08fc528b9 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/args/args.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/args/args.go @@ -18,11 +18,29 @@ type Options struct { Boilerplate string } +type Type struct { + Version string + Package string + Name string +} + type Group struct { - Types []interface{} - GenerateTypes bool - GenerateClients bool - PackageName string + // Types is a slice of the following types + // Instance of any struct: used for reflection to describe the type + // string: a directory that will be listed (non-recursively) for types + // Type: a description of a type + Types []interface{} + GenerateTypes bool + // Generate clientsets + GenerateClients bool + OutputControllerPackageName string + // Generate listers + GenerateListers bool + // Generate informers + GenerateInformers bool + // The package name of the API types + PackageName string + // Use existing clientset, informer, listers ClientSetPackage string ListersPackage string InformersPackage string diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/args/groupversion.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/args/groupversion.go index becf16f929..40cc78be30 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/args/groupversion.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/args/groupversion.go @@ -1,12 +1,14 @@ package args import ( + gotypes "go/types" "reflect" + "sort" "strings" - "k8s.io/code-generator/cmd/client-gen/generators/util" - + "golang.org/x/tools/go/packages" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/code-generator/cmd/client-gen/generators/util" "k8s.io/code-generator/cmd/client-gen/path" "k8s.io/gengo/types" ) @@ -19,8 +21,26 @@ const ( objectComment = "+k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object" ) -func ObjectsToGroupVersion(group string, objs []interface{}, ret map[schema.GroupVersion][]*types.Name) { +func translate(types []Type, err error) (result []interface{}, _ error) { + for _, v := range types { + result = append(result, v) + } + return result, err +} + +func ObjectsToGroupVersion(group string, objs []interface{}, ret map[schema.GroupVersion][]*types.Name) error { for _, obj := range objs { + if s, ok := obj.(string); ok { + types, err := translate(ScanDirectory(s)) + if err != nil { + return err + } + if err := ObjectsToGroupVersion(group, types, ret); err != nil { + return err + } + continue + } + version, t := toVersionType(obj) gv := schema.GroupVersion{ Group: group, @@ -28,21 +48,40 @@ func ObjectsToGroupVersion(group string, objs []interface{}, ret map[schema.Grou } ret[gv] = append(ret[gv], t) } + + return nil } func toVersionType(obj interface{}) (string, *types.Name) { + switch v := obj.(type) { + case Type: + return v.Version, &types.Name{ + Package: v.Package, + Name: v.Name, + } + case *Type: + return v.Version, &types.Name{ + Package: v.Package, + Name: v.Name, + } + } + t := reflect.TypeOf(obj) if t.Kind() == reflect.Ptr { t = t.Elem() } pkg := path.Vendorless(t.PkgPath()) - parts := strings.Split(pkg, "/") - return parts[len(parts)-1], &types.Name{ + return versionFromPackage(pkg), &types.Name{ Package: pkg, Name: t.Name(), } } +func versionFromPackage(pkg string) string { + parts := strings.Split(pkg, "/") + return parts[len(parts)-1] +} + func CheckType(passedType *types.Type) { tags := util.MustParseClientGenTags(passedType.SecondClosestCommentLines) if !tags.GenerateClient { @@ -58,3 +97,38 @@ func CheckType(passedType *types.Type) { panic("Type " + passedType.String() + " is missing comment " + objectComment) } } + +func ScanDirectory(pkgPath string) (result []Type, err error) { + pkgs, err := packages.Load(&packages.Config{ + Mode: packages.NeedName | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedSyntax, + Dir: pkgPath, + }) + if err != nil { + return nil, err + } + for _, v := range pkgs[0].TypesInfo.Defs { + typeAndName, ok := v.(*gotypes.TypeName) + if !ok { + continue + } + s, ok := typeAndName.Type().Underlying().(*gotypes.Struct) + if !ok { + continue + } + for i := 0; i < s.NumFields(); i++ { + f := s.Field(i) + if f.Embedded() && f.Type().String() == "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta" { + pkgPath := path.Vendorless(pkgs[0].PkgPath) + result = append(result, Type{ + Package: pkgPath, + Version: versionFromPackage(pkgPath), + Name: typeAndName.Name(), + }) + } + } + } + sort.Slice(result, func(i, j int) bool { + return result[i].Name < result[j].Name + }) + return +} diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/client_generator.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/client_generator.go index bf79fa9c36..8eb02cab74 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/client_generator.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/client_generator.go @@ -14,33 +14,20 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package generators has the generators for the client-gen utility. package generators import ( "fmt" "path/filepath" - "regexp" "strings" args2 "github.com/rancher/wrangler/pkg/controller-gen/args" - "golang.org/x/tools/imports" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/gengo/args" "k8s.io/gengo/generator" "k8s.io/gengo/types" ) -var ( - underscoreRegexp = regexp.MustCompile(`([a-z])([A-Z])`) - goImportOpts = &imports.Options{ - TabWidth: 8, - TabIndent: true, - Comments: true, - Fragment: true, - } -) - type ClientGenerator struct { Fakes map[string][]string } @@ -83,7 +70,7 @@ func (cg *ClientGenerator) Packages(context *generator.Context, arguments *args. } } - return generator.Packages(packageList) + return packageList } func (cg *ClientGenerator) typesGroupPackage(name *types.Name, gv schema.GroupVersion, generatorArgs *args.GeneratorArgs, customArgs *args2.CustomArgs) generator.Package { @@ -127,7 +114,7 @@ func (cg *ClientGenerator) typesGroupVersionPackage(name *types.Name, gv schema. } func (cg *ClientGenerator) groupPackage(group string, generatorArgs *args.GeneratorArgs, customArgs *args2.CustomArgs) generator.Package { - packagePath := filepath.Join(customArgs.Package, "controllers", groupPackageName(group, "")) + packagePath := filepath.Join(customArgs.Package, "controllers", groupPackageName(group, customArgs.Options.Groups[group].OutputControllerPackageName)) return Package(generatorArgs, packagePath, func(context *generator.Context) []generator.Generator { return []generator.Generator{ FactoryGo(group, generatorArgs, customArgs), @@ -137,7 +124,7 @@ func (cg *ClientGenerator) groupPackage(group string, generatorArgs *args.Genera } func (cg *ClientGenerator) groupVersionPackage(gv schema.GroupVersion, generatorArgs *args.GeneratorArgs, customArgs *args2.CustomArgs) generator.Package { - packagePath := filepath.Join(customArgs.Package, "controllers", groupPackageName(gv.Group, ""), gv.Version) + packagePath := filepath.Join(customArgs.Package, "controllers", groupPackageName(gv.Group, customArgs.Options.Groups[gv.Group].OutputControllerPackageName), gv.Version) return Package(generatorArgs, packagePath, func(context *generator.Context) []generator.Generator { generators := []generator.Generator{ diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/factory_go.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/factory_go.go index 723f030c33..76e74806a3 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/factory_go.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/factory_go.go @@ -3,7 +3,6 @@ package generators import ( "fmt" "io" - "path/filepath" args2 "github.com/rancher/wrangler/pkg/controller-gen/args" "k8s.io/gengo/args" @@ -31,19 +30,16 @@ type factory struct { } func (f *factory) Imports(*generator.Context) []string { - group := f.customArgs.Options.Groups[f.group] + imports := Imports - return []string{ - "context", - "time", - "k8s.io/apimachinery/pkg/runtime/schema", - "k8s.io/client-go/rest", - GenericPackage, - AllSchemes, - fmt.Sprintf("clientset \"%s\"", group.ClientSetPackage), - fmt.Sprintf("scheme \"%s\"", filepath.Join(group.ClientSetPackage, "scheme")), - fmt.Sprintf("informers \"%s\"", group.InformersPackage), + for gv, types := range f.customArgs.TypesByGroup { + if f.group == gv.Group && len(types) > 0 { + imports = append(imports, + fmt.Sprintf("%s \"%s\"", gv.Version, types[0].Package)) + } } + + return imports } func (f *factory) Init(c *generator.Context, w io.Writer) error { @@ -56,24 +52,16 @@ func (f *factory) Init(c *generator.Context, w io.Writer) error { "groupName": upperLowercase(f.group), } - sw.Do("func (c *Factory) {{.groupName}}() Interface {\n", m) - sw.Do(" return New(c.controllerManager, c.informerFactory.{{.groupName}}(), c.clientset)\n", m) - sw.Do("}\n", m) + sw.Do("\n\nfunc (c *Factory) {{.groupName}}() Interface {\n", m) + sw.Do(" return New(c.ControllerFactory())\n", m) + sw.Do("}\n\n", m) return sw.Error() } var factoryBody = ` -func init() { - scheme.AddToScheme(schemes.All) -} - type Factory struct { - synced bool - informerFactory informers.SharedInformerFactory - clientset clientset.Interface - controllerManager *generic.ControllerManager - threadiness map[schema.GroupVersionKind]int + *generic.Factory } func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { @@ -94,65 +82,21 @@ func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (* }) } -type FactoryOptions struct { - Namespace string - Resync time.Duration -} +type FactoryOptions = generic.FactoryOptions func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { - if opts == nil { - opts = &FactoryOptions{} - } - - cs, err := clientset.NewForConfig(config) - if err != nil { - return nil, err - } - - resync := opts.Resync - if resync == 0 { - resync = 2*time.Hour - } - - if opts.Namespace == "" { - informerFactory := informers.NewSharedInformerFactory(cs, resync) - return NewFactory(cs, informerFactory), nil - } - - informerFactory := informers.NewSharedInformerFactoryWithOptions(cs, resync, informers.WithNamespace(opts.Namespace)) - return NewFactory(cs, informerFactory), nil -} - - -func NewFactory(clientset clientset.Interface, informerFactory informers.SharedInformerFactory) *Factory { + f, err := generic.NewFactoryFromConfigWithOptions(config, opts) return &Factory{ - threadiness: map[schema.GroupVersionKind]int{}, - controllerManager: &generic.ControllerManager{}, - clientset: clientset, - informerFactory: informerFactory, + Factory: f, + }, err +} + +func NewFactoryFromConfigWithOptionsOrDie(config *rest.Config, opts *FactoryOptions) *Factory { + f, err := NewFactoryFromConfigWithOptions(config, opts) + if err != nil { + panic(err) } -} - -func (c *Factory) Controllers() map[schema.GroupVersionKind]*generic.Controller { - return c.controllerManager.Controllers() -} - -func (c *Factory) SetThreadiness(gvk schema.GroupVersionKind, threadiness int) { - c.threadiness[gvk] = threadiness -} - -func (c *Factory) Sync(ctx context.Context) error { - c.informerFactory.Start(ctx.Done()) - c.informerFactory.WaitForCacheSync(ctx.Done()) - return nil -} - -func (c *Factory) Start(ctx context.Context, defaultThreadiness int) error { - if err := c.Sync(ctx); err != nil { - return err - } - - return c.controllerManager.Start(ctx, defaultThreadiness, c.threadiness) + return f } ` diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/group_interface_go.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/group_interface_go.go index 77d4120afa..d682796c10 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/group_interface_go.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/group_interface_go.go @@ -30,21 +30,15 @@ type interfaceGo struct { customArgs *args2.CustomArgs } -func (f *interfaceGo) Imports(*generator.Context) []string { - group := f.customArgs.Options.Groups[f.group] - - packages := []string{ - GenericPackage, - fmt.Sprintf("clientset \"%s\"", group.ClientSetPackage), - fmt.Sprintf("informers \"%s/%s\"", group.InformersPackage, groupPackageName(f.group, group.PackageName)), - } +func (f *interfaceGo) Imports(context *generator.Context) []string { + packages := Imports for gv := range f.customArgs.TypesByGroup { if gv.Group != f.group { continue } - - packages = append(packages, fmt.Sprintf("%s \"%s/controllers/%s/%s\"", gv.Version, f.customArgs.Package, groupPackageName(gv.Group, ""), gv.Version)) + packages = append(packages, fmt.Sprintf("%s \"%s/controllers/%s/%s\"", gv.Version, f.customArgs.Package, + groupPackageName(gv.Group, f.customArgs.Options.Groups[gv.Group].OutputControllerPackageName), gv.Version)) } return packages @@ -80,7 +74,7 @@ func (f *interfaceGo) Init(c *generator.Context, w io.Writer) error { "version": gv.Version, } sw.Do("\nfunc (g *group) {{.upperVersion}}() {{.version}}.Interface {\n", m) - sw.Do("return {{.version}}.New(g.controllerManager, g.client.{{.upperGroup}}{{.upperVersion}}(), g.informers.{{.upperVersion}}())\n", m) + sw.Do("return {{.version}}.New(g.controllerFactory)\n", m) sw.Do("}\n", m) } @@ -89,18 +83,13 @@ func (f *interfaceGo) Init(c *generator.Context, w io.Writer) error { var interfaceBody = ` type group struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.Interface + controllerFactory controller.SharedControllerFactory } // New returns a new Interface. -func New(controllerManager *generic.ControllerManager, informers informers.Interface, - client clientset.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &group{ - controllerManager: controllerManager, - informers: informers, - client: client, + controllerFactory: controllerFactory, } } ` diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/group_version_interface_go.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/group_version_interface_go.go index 379e8d580a..1b2f806cdc 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/group_version_interface_go.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/group_version_interface_go.go @@ -3,6 +3,7 @@ package generators import ( "fmt" "io" + "strings" args2 "github.com/rancher/wrangler/pkg/controller-gen/args" "k8s.io/apimachinery/pkg/runtime/schema" @@ -31,16 +32,11 @@ type groupInterfaceGo struct { customArgs *args2.CustomArgs } -func (f *groupInterfaceGo) Imports(*generator.Context) []string { +func (f *groupInterfaceGo) Imports(context *generator.Context) []string { firstType := f.customArgs.TypesByGroup[f.gv][0] - group := f.customArgs.Options.Groups[f.gv.Group] - packages := []string{ - GenericPackage, - fmt.Sprintf("%s \"%s\"", f.gv.Version, firstType.Package), - fmt.Sprintf("clientset \"%s/typed/%s/%s\"", group.ClientSetPackage, groupPackageName(f.gv.Group, group.PackageName), f.gv.Version), - fmt.Sprintf("informers \"%s/%s/%s\"", group.InformersPackage, groupPackageName(f.gv.Group, group.PackageName), f.gv.Version), - } + packages := append(Imports, + fmt.Sprintf("%s \"%s\"", f.gv.Version, firstType.Package)) return packages } @@ -63,6 +59,10 @@ func (f *groupInterfaceGo) Init(c *generator.Context, w io.Writer) error { } types = orderer.OrderTypes(types) + sw.Do("func init() {\n", nil) + sw.Do("schemes.Register("+f.gv.Version+".AddToScheme)\n", nil) + sw.Do("}\n", nil) + sw.Do("type Interface interface {\n", nil) for _, t := range types { m := map[string]interface{}{ @@ -83,13 +83,16 @@ func (f *groupInterfaceGo) Init(c *generator.Context, w io.Writer) error { m := map[string]interface{}{ "type": t.Name.Name, "plural": plural.Name(t), + "pluralLower": strings.ToLower(plural.Name(t)), "version": f.gv.Version, + "group": f.gv.Group, + "namespaced": namespaced(t), "versionUpper": namer.IC(f.gv.Version), "groupUpper": upperLowercase(f.gv.Group), } sw.Do("func (c *version) {{.type}}() {{.type}}Controller {\n", m) - sw.Do("return New{{.type}}Controller({{.version}}.SchemeGroupVersion.WithKind(\"{{.type}}\"), c.controllerManager, c.client, c.informers.{{.plural}}())\n", m) + sw.Do("return New{{.type}}Controller(schema.GroupVersionKind{Group:\"{{.group}}\",Version:\"{{.version}}\",Kind:\"{{.type}}\"} , \"{{.pluralLower}}\", {{.namespaced}}, c.controllerFactory)\n", m) sw.Do("}\n", m) } @@ -97,19 +100,14 @@ func (f *groupInterfaceGo) Init(c *generator.Context, w io.Writer) error { } var groupInterfaceBody = ` -func New(controllerManager *generic.ControllerManager, client clientset.{{.groupUpper}}{{.versionUpper}}Interface, - informers informers.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &version{ - controllerManager: controllerManager, - client: client, - informers: informers, + controllerFactory: controllerFactory, } } type version struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.{{.groupUpper}}{{.versionUpper}}Interface + controllerFactory controller.SharedControllerFactory } ` diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/list_type_go.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/list_type_go.go index 4968d04ca9..dbef39e58e 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/list_type_go.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/list_type_go.go @@ -29,11 +29,7 @@ type listTypesGo struct { } func (f *listTypesGo) Imports(*generator.Context) []string { - packages := []string{ - "metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"", - } - - return packages + return Imports } func (f *listTypesGo) Init(c *generator.Context, w io.Writer) error { diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/register_group_version_go.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/register_group_version_go.go index 3b7d6c906c..cfd7b42e8b 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/register_group_version_go.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/register_group_version_go.go @@ -37,12 +37,8 @@ func (f *registerGroupVersionGo) Imports(*generator.Context) []string { firstType := f.customArgs.TypesByGroup[f.gv][0] typeGroupPath := strings.TrimSuffix(firstType.Package, "/"+f.gv.Version) - packages := []string{ - "metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"", - "k8s.io/apimachinery/pkg/runtime", - "k8s.io/apimachinery/pkg/runtime/schema", - fmt.Sprintf("%s \"%s\"", groupPath(f.gv.Group), typeGroupPath), - } + packages := append(Imports, + fmt.Sprintf("%s \"%s\"", groupPath(f.gv.Group), typeGroupPath)) return packages } diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/type_go.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/type_go.go index 640cdb033a..e6665daf7b 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/type_go.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/type_go.go @@ -7,7 +7,6 @@ import ( args2 "github.com/rancher/wrangler/pkg/controller-gen/args" "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/code-generator/cmd/client-gen/generators/util" "k8s.io/gengo/args" "k8s.io/gengo/generator" "k8s.io/gengo/namer" @@ -35,29 +34,9 @@ type typeGo struct { customArgs *args2.CustomArgs } -func (f *typeGo) Imports(*generator.Context) []string { - group := f.customArgs.Options.Groups[f.gv.Group] - - packages := []string{ - "metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"", - "k8s.io/apimachinery/pkg/api/errors", - "k8s.io/apimachinery/pkg/labels", - "k8s.io/apimachinery/pkg/runtime", - "k8s.io/apimachinery/pkg/runtime/schema", - "k8s.io/apimachinery/pkg/api/equality", - "k8s.io/apimachinery/pkg/types", - "utilruntime \"k8s.io/apimachinery/pkg/util/runtime\"", - "k8s.io/apimachinery/pkg/watch", - "k8s.io/client-go/tools/cache", - "github.com/rancher/wrangler/pkg/apply", - "github.com/rancher/wrangler/pkg/condition", - "github.com/rancher/wrangler/pkg/kv", - fmt.Sprintf("%s \"%s\"", f.gv.Version, f.name.Package), - GenericPackage, - fmt.Sprintf("clientset \"%s/typed/%s/%s\"", group.ClientSetPackage, groupPackageName(f.gv.Group, group.PackageName), f.gv.Version), - fmt.Sprintf("informers \"%s/%s/%s\"", group.InformersPackage, groupPackageName(f.gv.Group, group.PackageName), f.gv.Version), - fmt.Sprintf("listers \"%s/%s/%s\"", group.ListersPackage, groupPackageName(f.gv.Group, group.PackageName), f.gv.Version), - } +func (f *typeGo) Imports(context *generator.Context) []string { + packages := append(Imports, + fmt.Sprintf("%s \"%s\"", f.gv.Version, f.name.Package)) return packages } @@ -75,7 +54,7 @@ func (f *typeGo) Init(c *generator.Context, w io.Writer) error { "lowerName": namer.IL(f.name.Name), "plural": plural.Name(t), "version": f.gv.Version, - "namespaced": !util.MustParseClientGenTags(t.SecondClosestCommentLines).NonNamespaced, + "namespaced": namespaced(t), "hasStatus": hasStatus(t), "statusType": statusType(t), } @@ -141,18 +120,22 @@ type {{.type}}Cache interface { type {{.type}}Indexer func(obj *{{.version}}.{{.type}}) ([]string, error) type {{.lowerName}}Controller struct { - controllerManager *generic.ControllerManager - clientGetter clientset.{{.plural}}Getter - informer informers.{{.type}}Informer + controller controller.SharedController + client *client.Client gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func New{{.type}}Controller(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.{{.plural}}Getter, informer informers.{{.type}}Informer) {{.type}}Controller { +func New{{.type}}Controller(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) {{.type}}Controller { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &{{.lowerName}}Controller{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -199,12 +182,11 @@ func Update{{.type}}DeepCopyOnChange(client {{.type}}Client, obj *{{.version}}.{ } func (c *{{.lowerName}}Controller) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *{{.lowerName}}Controller) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *{{.lowerName}}Controller) OnChange(ctx context.Context, name string, sync {{.type}}Handler) { @@ -212,20 +194,19 @@ func (c *{{.lowerName}}Controller) OnChange(ctx context.Context, name string, sy } func (c *{{.lowerName}}Controller) OnRemove(ctx context.Context, name string, sync {{.type}}Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), From{{.type}}HandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), From{{.type}}HandlerToHandler(sync))) } func (c *{{.lowerName}}Controller) Enqueue({{ if .namespaced}}namespace, {{end}}name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), {{ if .namespaced }}namespace, {{else}}"", {{end}}name) + c.controller.Enqueue({{ if .namespaced }}namespace, {{else}}"", {{end}}name) } func (c *{{.lowerName}}Controller) EnqueueAfter({{ if .namespaced}}namespace, {{end}}name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), {{ if .namespaced }}namespace, {{else}}"", {{end}}name, duration) + c.controller.EnqueueAfter({{ if .namespaced }}namespace, {{else}}"", {{end}}name, duration) } func (c *{{.lowerName}}Controller) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *{{.lowerName}}Controller) GroupVersionKind() schema.GroupVersionKind { @@ -234,22 +215,25 @@ func (c *{{.lowerName}}Controller) GroupVersionKind() schema.GroupVersionKind { func (c *{{.lowerName}}Controller) Cache() {{.type}}Cache { return &{{.lowerName}}Cache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *{{.lowerName}}Controller) Create(obj *{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) { - return c.clientGetter.{{.plural}}({{ if .namespaced}}obj.Namespace{{end}}).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &{{.version}}.{{.type}}{} + return result, c.client.Create(context.TODO(), {{ if .namespaced}}obj.Namespace,{{else}}"",{{end}} obj, result, metav1.CreateOptions{}) } func (c *{{.lowerName}}Controller) Update(obj *{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) { - return c.clientGetter.{{.plural}}({{ if .namespaced}}obj.Namespace{{end}}).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &{{.version}}.{{.type}}{} + return result, c.client.Update(context.TODO(), {{ if .namespaced}}obj.Namespace,{{else}}"",{{end}} obj, result, metav1.UpdateOptions{}) } {{ if .hasStatus -}} func (c *{{.lowerName}}Controller) UpdateStatus(obj *{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) { - return c.clientGetter.{{.plural}}({{ if .namespaced}}obj.Namespace{{end}}).UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &{{.version}}.{{.type}}{} + return result, c.client.UpdateStatus(context.TODO(), {{ if .namespaced}}obj.Namespace,{{else}}"",{{end}} obj, result, metav1.UpdateOptions{}) } {{- end }} @@ -257,36 +241,55 @@ func (c *{{.lowerName}}Controller) Delete({{ if .namespaced}}namespace, {{end}}n if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.{{.plural}}({{ if .namespaced}}namespace{{end}}).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), {{ if .namespaced}}namespace,{{else}}"",{{end}} name, *options) } func (c *{{.lowerName}}Controller) Get({{ if .namespaced}}namespace, {{end}}name string, options metav1.GetOptions) (*{{.version}}.{{.type}}, error) { - return c.clientGetter.{{.plural}}({{ if .namespaced}}namespace{{end}}).Get(context.TODO(), name, options) + result := &{{.version}}.{{.type}}{} + return result, c.client.Get(context.TODO(), {{ if .namespaced}}namespace,{{else}}"",{{end}} name, result, options) } func (c *{{.lowerName}}Controller) List({{ if .namespaced}}namespace string, {{end}}opts metav1.ListOptions) (*{{.version}}.{{.type}}List, error) { - return c.clientGetter.{{.plural}}({{ if .namespaced}}namespace{{end}}).List(context.TODO(), opts) + result := &{{.version}}.{{.type}}List{} + return result, c.client.List(context.TODO(), {{ if .namespaced}}namespace,{{else}}"",{{end}} result, opts) } func (c *{{.lowerName}}Controller) Watch({{ if .namespaced}}namespace string, {{end}}opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.{{.plural}}({{ if .namespaced}}namespace{{end}}).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), {{ if .namespaced}}namespace,{{else}}"",{{end}} opts) } -func (c *{{.lowerName}}Controller) Patch({{ if .namespaced}}namespace, {{end}}name string, pt types.PatchType, data []byte, subresources ...string) (result *{{.version}}.{{.type}}, err error) { - return c.clientGetter.{{.plural}}({{ if .namespaced}}namespace{{end}}).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *{{.lowerName}}Controller) Patch({{ if .namespaced}}namespace, {{end}}name string, pt types.PatchType, data []byte, subresources ...string) (*{{.version}}.{{.type}}, error) { + result := &{{.version}}.{{.type}}{} + return result, c.client.Patch(context.TODO(), {{ if .namespaced}}namespace,{{else}}"",{{end}} name, pt, data, result, metav1.PatchOptions{}, subresources...) } type {{.lowerName}}Cache struct { - lister listers.{{.type}}Lister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *{{.lowerName}}Cache) Get({{ if .namespaced}}namespace, {{end}}name string) (*{{.version}}.{{.type}}, error) { - return c.lister.{{ if .namespaced}}{{.plural}}(namespace).{{end}}Get(name) + obj, exists, err := c.indexer.GetByKey({{ if .namespaced }}namespace + "/" + {{end}}name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*{{.version}}.{{.type}}), nil } -func (c *{{.lowerName}}Cache) List({{ if .namespaced}}namespace string, {{end}}selector labels.Selector) ([]*{{.version}}.{{.type}}, error) { - return c.lister.{{ if .namespaced}}{{.plural}}(namespace).{{end}}List(selector) +func (c *{{.lowerName}}Cache) List({{ if .namespaced}}namespace string, {{end}}selector labels.Selector) (ret []*{{.version}}.{{.type}}, err error) { + {{ if .namespaced }} + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*{{.version}}.{{.type}})) + }) + {{else}} + err = cache.ListAll(c.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*{{.version}}.{{.type}})) + }) + {{end}} + return ret, err } func (c *{{.lowerName}}Cache) AddIndexer(indexName string, indexer {{.type}}Indexer) { @@ -365,12 +368,20 @@ func (a *{{.lowerName}}StatusHandler) sync(key string, obj *{{.version}}.{{.type } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -399,6 +410,10 @@ func (a *{{.lowerName}}GeneratingHandler) Remove(key string, obj *{{.version}}.{ } func (a *{{.lowerName}}GeneratingHandler) Handle(obj *{{.version}}.{{.type}}, status {{.version}}.{{.statusType}}) ({{.version}}.{{.statusType}}, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.{{.type}}GeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/util.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/util.go index a3ca741cbe..5458b07931 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/util.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/generators/util.go @@ -3,14 +3,54 @@ package generators import ( "strings" + "k8s.io/code-generator/cmd/client-gen/generators/util" "k8s.io/gengo/namer" + "k8s.io/gengo/types" ) -const ( - GenericPackage = "github.com/rancher/wrangler/pkg/generic" - AllSchemes = "github.com/rancher/wrangler/pkg/schemes" +var ( + Imports = []string{ + "context", + "time", + "k8s.io/client-go/rest", + "github.com/rancher/lasso/pkg/client", + "github.com/rancher/lasso/pkg/controller", + "github.com/rancher/wrangler/pkg/apply", + "github.com/rancher/wrangler/pkg/condition", + "github.com/rancher/wrangler/pkg/schemes", + "github.com/rancher/wrangler/pkg/generic", + "github.com/rancher/wrangler/pkg/kv", + "k8s.io/apimachinery/pkg/api/equality", + "k8s.io/apimachinery/pkg/api/errors", + "metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"", + "k8s.io/apimachinery/pkg/labels", + "k8s.io/apimachinery/pkg/runtime", + "k8s.io/apimachinery/pkg/runtime/schema", + "k8s.io/apimachinery/pkg/types", + "utilruntime \"k8s.io/apimachinery/pkg/util/runtime\"", + "k8s.io/apimachinery/pkg/watch", + "k8s.io/client-go/tools/cache", + } ) +func namespaced(t *types.Type) bool { + if util.MustParseClientGenTags(t.SecondClosestCommentLines).NonNamespaced { + return false + } + + kubeBuilder := false + for _, line := range t.SecondClosestCommentLines { + if strings.HasPrefix(line, "+kubebuilder:resource:path=") { + kubeBuilder = true + if strings.Contains(line, "scope=Namespaced") { + return true + } + } + } + + return !kubeBuilder +} + func groupPath(group string) string { g := strings.Replace(strings.Split(group, ".")[0], "-", "", -1) return groupPackageName(g, "") diff --git a/vendor/github.com/rancher/wrangler/pkg/controller-gen/main.go b/vendor/github.com/rancher/wrangler/pkg/controller-gen/main.go index d42b4cdb9c..f74f509c8b 100644 --- a/vendor/github.com/rancher/wrangler/pkg/controller-gen/main.go +++ b/vendor/github.com/rancher/wrangler/pkg/controller-gen/main.go @@ -1,6 +1,7 @@ package controllergen import ( + "fmt" "io" "io/ioutil" "os" @@ -8,6 +9,8 @@ import ( "sort" "strings" + "k8s.io/gengo/generator" + cgargs "github.com/rancher/wrangler/pkg/controller-gen/args" "github.com/rancher/wrangler/pkg/controller-gen/generators" "github.com/sirupsen/logrus" @@ -64,22 +67,28 @@ func Run(opts cgargs.Options) { } groups := map[string]bool{} + listerGroups := map[string]bool{} + informerGroups := map[string]bool{} deepCopygroups := map[string]bool{} for groupName, group := range customArgs.Options.Groups { if group.GenerateTypes { deepCopygroups[groupName] = true - groups[groupName] = true } if group.GenerateClients { groups[groupName] = true } + if group.GenerateListers { + listerGroups[groupName] = true + } + if group.GenerateInformers { + informerGroups[groupName] = true + } } - if len(groups) == 0 { + if len(deepCopygroups) == 0 && len(groups) == 0 && len(listerGroups) == 0 && len(informerGroups) == 0 { if err := copyGoPathToModules(customArgs); err != nil { logrus.Fatalf("go modules copy failed: %v", err) } - return } @@ -95,11 +104,11 @@ func Run(opts cgargs.Options) { logrus.Fatalf("clientset failed: %v", err) } - if err := generateListers(groups, customArgs); err != nil { + if err := generateListers(listerGroups, customArgs); err != nil { logrus.Fatalf("listers failed: %v", err) } - if err := generateInformers(groups, customArgs); err != nil { + if err := generateInformers(informerGroups, customArgs); err != nil { logrus.Fatalf("informers failed: %v", err) } @@ -135,15 +144,11 @@ func copyGoPathToModules(customArgs *cgargs.CustomArgs) error { return filepath.Walk(pkg, func(path string, info os.FileInfo, err error) error { newPath := strings.Replace(path, pkg, ".", 1) - if _, err := os.Stat(newPath); os.IsNotExist(err) { - if info.IsDir() { - return os.Mkdir(newPath, info.Mode()) - } - - return copyFile(path, newPath) + if info.IsDir() { + return os.MkdirAll(newPath, info.Mode()) } - return err + return copyFile(path, newPath) }) } @@ -176,6 +181,10 @@ func copyFile(src, dst string) error { } func generateDeepcopy(groups map[string]bool, customArgs *cgargs.CustomArgs) error { + if len(groups) == 0 { + return nil + } + deepCopyCustomArgs := &dpargs.CustomArgs{} args := args.Default().WithoutDefaultFlagParsing() @@ -198,6 +207,10 @@ func generateDeepcopy(groups map[string]bool, customArgs *cgargs.CustomArgs) err } func generateClientset(groups map[string]bool, customArgs *cgargs.CustomArgs) error { + if len(groups) == 0 { + return nil + } + args, clientSetArgs := csargs.NewDefaults() clientSetArgs.ClientsetName = "versioned" args.OutputBase = customArgs.OutputBase @@ -237,10 +250,69 @@ func generateClientset(groups map[string]bool, customArgs *cgargs.CustomArgs) er return args.Execute(cs.NameSystems(nil), cs.DefaultNameSystem(), - cs.Packages) + setGenClient(groups, customArgs.TypesByGroup, cs.Packages)) +} + +func setGenClient(groups map[string]bool, typesByGroup map[schema.GroupVersion][]*types.Name, f func(*generator.Context, *args.GeneratorArgs) generator.Packages) func(*generator.Context, *args.GeneratorArgs) generator.Packages { + return func(context *generator.Context, generatorArgs *args.GeneratorArgs) generator.Packages { + for gv, names := range typesByGroup { + if !groups[gv.Group] { + continue + } + for _, name := range names { + var ( + p = context.Universe.Package(name.Package) + t = p.Type(name.Name) + status bool + nsed bool + kubebuilder bool + ) + + for _, line := range append(t.SecondClosestCommentLines, t.CommentLines...) { + switch { + case strings.Contains(line, "+kubebuilder:object:root=true"): + kubebuilder = true + t.SecondClosestCommentLines = append(t.SecondClosestCommentLines, "+genclient") + case strings.Contains(line, "+kubebuilder:subresource:status"): + status = true + case strings.Contains(line, "+kubebuilder:resource:") && strings.Contains(line, "scope=Namespaced"): + nsed = true + } + } + + if kubebuilder { + if !nsed { + t.SecondClosestCommentLines = append(t.SecondClosestCommentLines, "+genclient:nonNamespaced") + } + if !status { + t.SecondClosestCommentLines = append(t.SecondClosestCommentLines, "+genclient:noStatus") + } + + foundGroup := false + for _, comment := range p.DocComments { + if strings.Contains(comment, "+groupName=") { + foundGroup = true + break + } + } + + if !foundGroup { + p.DocComments = append(p.DocComments, "+groupName="+gv.Group) + p.Comments = append(p.Comments, "+groupName="+gv.Group) + fmt.Println(gv.Group, p.DocComments, p.Comments, p.Path) + } + } + } + } + return f(context, generatorArgs) + } } func generateInformers(groups map[string]bool, customArgs *cgargs.CustomArgs) error { + if len(groups) == 0 { + return nil + } + args, clientSetArgs := infargs.NewDefaults() clientSetArgs.VersionedClientSetPackage = filepath.Join(customArgs.Package, "clientset/versioned") clientSetArgs.ListersPackage = filepath.Join(customArgs.Package, "listers") @@ -257,10 +329,14 @@ func generateInformers(groups map[string]bool, customArgs *cgargs.CustomArgs) er return args.Execute(inf.NameSystems(nil), inf.DefaultNameSystem(), - inf.Packages) + setGenClient(groups, customArgs.TypesByGroup, inf.Packages)) } func generateListers(groups map[string]bool, customArgs *cgargs.CustomArgs) error { + if len(groups) == 0 { + return nil + } + args, _ := lsargs.NewDefaults() args.OutputBase = customArgs.OutputBase args.OutputPackagePath = filepath.Join(customArgs.Package, "listers") @@ -275,7 +351,7 @@ func generateListers(groups map[string]bool, customArgs *cgargs.CustomArgs) erro return args.Execute(ls.NameSystems(nil), ls.DefaultNameSystem(), - ls.Packages) + setGenClient(groups, customArgs.TypesByGroup, ls.Packages)) } func parseTypes(customArgs *cgargs.CustomArgs) []string { @@ -295,7 +371,10 @@ func parseTypes(customArgs *cgargs.CustomArgs) []string { } for groupName, group := range customArgs.Options.Groups { - cgargs.ObjectsToGroupVersion(groupName, group.Types, customArgs.TypesByGroup) + if err := cgargs.ObjectsToGroupVersion(groupName, group.Types, customArgs.TypesByGroup); err != nil { + // sorry, should really handle this better + panic(err) + } } var inputDirs []string diff --git a/vendor/github.com/rancher/wrangler/pkg/crd/init.go b/vendor/github.com/rancher/wrangler/pkg/crd/init.go index a5c9095282..d5dfb2912b 100644 --- a/vendor/github.com/rancher/wrangler/pkg/crd/init.go +++ b/vendor/github.com/rancher/wrangler/pkg/crd/init.go @@ -2,48 +2,65 @@ package crd import ( "context" + "fmt" + "path/filepath" "reflect" "strconv" "strings" "sync" "time" + "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/data/convert" "github.com/rancher/wrangler/pkg/kv" "github.com/rancher/wrangler/pkg/name" "github.com/rancher/wrangler/pkg/schemas/openapi" "github.com/sirupsen/logrus" - "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" - apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" - "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/rest" + + // Ensure the gvks are loaded so that apply works correctly + _ "github.com/rancher/wrangler/pkg/generated/controllers/apiextensions.k8s.io/v1" ) +const CRDKind = "CustomResourceDefinition" + type Factory struct { wg sync.WaitGroup err error CRDClient clientset.Interface + apply apply.Apply } type CRD struct { GVK schema.GroupVersionKind PluralName string + SingularName string NonNamespace bool - Schema *v1beta1.JSONSchemaProps + Schema *apiextv1.JSONSchemaProps SchemaObject interface{} - Columns []v1beta1.CustomResourceColumnDefinition + Columns []apiextv1.CustomResourceColumnDefinition Status bool Scale bool Categories []string ShortNames []string + Labels map[string]string + Annotations map[string]string + + Override runtime.Object } -func (c CRD) WithSchema(schema *v1beta1.JSONSchemaProps) CRD { +func (c CRD) WithSchema(schema *apiextv1.JSONSchemaProps) CRD { c.Schema = schema return c } @@ -54,7 +71,7 @@ func (c CRD) WithSchemaFromStruct(obj interface{}) CRD { } func (c CRD) WithColumn(name, path string) CRD { - c.Columns = append(c.Columns, v1beta1.CustomResourceColumnDefinition{ + c.Columns = append(c.Columns, apiextv1.CustomResourceColumnDefinition{ Name: name, Type: "string", Priority: 0, @@ -92,8 +109,8 @@ func fieldName(f reflect.StructField) string { return name } -func tagToColumn(f reflect.StructField) (v1beta1.CustomResourceColumnDefinition, bool) { - c := v1beta1.CustomResourceColumnDefinition{ +func tagToColumn(f reflect.StructField) (apiextv1.CustomResourceColumnDefinition, bool) { + c := apiextv1.CustomResourceColumnDefinition{ Name: f.Name, Type: "string", } @@ -124,7 +141,7 @@ func tagToColumn(f reflect.StructField) (v1beta1.CustomResourceColumnDefinition, return c, true } -func readCustomColumns(t reflect.Type, path string) (result []v1beta1.CustomResourceColumnDefinition) { +func readCustomColumns(t reflect.Type, path string) (result []apiextv1.CustomResourceColumnDefinition) { for i := 0; i < t.NumField(); i++ { f := t.Field(i) fieldName := fieldName(f) @@ -152,7 +169,7 @@ func readCustomColumns(t reflect.Type, path string) (result []v1beta1.CustomReso return result } -func (c CRD) WithCustomColumn(columns ...v1beta1.CustomResourceColumnDefinition) CRD { +func (c CRD) WithCustomColumn(columns ...apiextv1.CustomResourceColumnDefinition) CRD { c.Columns = append(c.Columns, columns...) return c } @@ -172,50 +189,75 @@ func (c CRD) WithCategories(categories ...string) CRD { return c } +func (c CRD) WithGroup(group string) CRD { + c.GVK.Group = group + return c +} + func (c CRD) WithShortNames(shortNames ...string) CRD { c.ShortNames = shortNames return c } -func (c CRD) ToCustomResourceDefinition() (apiext.CustomResourceDefinition, error) { +func (c CRD) ToCustomResourceDefinition() (runtime.Object, error) { + if c.Override != nil { + return c.Override, nil + } + if c.SchemaObject != nil && c.GVK.Kind == "" { t := getType(c.SchemaObject) c.GVK.Kind = t.Name() } + if c.SchemaObject != nil && c.GVK.Version == "" { + t := getType(c.SchemaObject) + c.GVK.Version = filepath.Base(t.PkgPath()) + } + + if c.SchemaObject != nil && c.GVK.Group == "" { + t := getType(c.SchemaObject) + c.GVK.Group = filepath.Base(filepath.Dir(t.PkgPath())) + } + plural := c.PluralName if plural == "" { plural = strings.ToLower(name.GuessPluralName(c.GVK.Kind)) } + singular := c.SingularName + if singular == "" { + singular = strings.ToLower(c.GVK.Kind) + } + name := strings.ToLower(plural + "." + c.GVK.Group) - crd := apiext.CustomResourceDefinition{ + crd := apiextv1.CustomResourceDefinition{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, - Spec: apiext.CustomResourceDefinitionSpec{ - AdditionalPrinterColumns: c.Columns, - Group: c.GVK.Group, - Version: c.GVK.Version, - Versions: []apiext.CustomResourceDefinitionVersion{ + Spec: apiextv1.CustomResourceDefinitionSpec{ + Group: c.GVK.Group, + Versions: []apiextv1.CustomResourceDefinitionVersion{ { - Name: c.GVK.Version, - Storage: true, - Served: true, + Name: c.GVK.Version, + Storage: true, + Served: true, + AdditionalPrinterColumns: c.Columns, }, }, - Names: apiext.CustomResourceDefinitionNames{ + Names: apiextv1.CustomResourceDefinitionNames{ Plural: plural, + Singular: singular, Kind: c.GVK.Kind, Categories: c.Categories, ShortNames: c.ShortNames, }, + PreserveUnknownFields: false, }, } if c.Schema != nil { - crd.Spec.Validation = &apiext.CustomResourceValidation{ + crd.Spec.Versions[0].Schema = &apiextv1.CustomResourceValidation{ OpenAPIV3Schema: c.Schema, } } @@ -223,20 +265,37 @@ func (c CRD) ToCustomResourceDefinition() (apiext.CustomResourceDefinition, erro if c.SchemaObject != nil { schema, err := openapi.ToOpenAPIFromStruct(c.SchemaObject) if err != nil { - return apiext.CustomResourceDefinition{}, err + return nil, err } - crd.Spec.Validation = &apiext.CustomResourceValidation{ + crd.Spec.Versions[0].Schema = &apiextv1.CustomResourceValidation{ OpenAPIV3Schema: schema, } } + // add a dummy schema because v1 requires OpenAPIV3Schema to be set + if crd.Spec.Versions[0].Schema == nil { + crd.Spec.Versions[0].Schema = &apiextv1.CustomResourceValidation{ + OpenAPIV3Schema: &apiextv1.JSONSchemaProps{ + Type: "object", + Properties: map[string]apiextv1.JSONSchemaProps{ + "spec": { + XPreserveUnknownFields: &[]bool{true}[0], + }, + "status": { + XPreserveUnknownFields: &[]bool{true}[0], + }, + }, + }, + } + } + if c.Status { - crd.Spec.Subresources = &apiext.CustomResourceSubresources{ - Status: &apiext.CustomResourceSubresourceStatus{}, + crd.Spec.Versions[0].Subresources = &apiextv1.CustomResourceSubresources{ + Status: &apiextv1.CustomResourceSubresourceStatus{}, } if c.Scale { sel := "Spec.Selector" - crd.Spec.Subresources.Scale = &apiext.CustomResourceSubresourceScale{ + crd.Spec.Versions[0].Subresources.Scale = &apiextv1.CustomResourceSubresourceScale{ SpecReplicasPath: "Spec.Replicas", StatusReplicasPath: "Status.Replicas", LabelSelectorPath: &sel, @@ -245,12 +304,61 @@ func (c CRD) ToCustomResourceDefinition() (apiext.CustomResourceDefinition, erro } if c.NonNamespace { - crd.Spec.Scope = apiext.ClusterScoped + crd.Spec.Scope = apiextv1.ClusterScoped } else { - crd.Spec.Scope = apiext.NamespaceScoped + crd.Spec.Scope = apiextv1.NamespaceScoped } - return crd, nil + crd.Labels = c.Labels + crd.Annotations = c.Annotations + + // Convert to unstructured to ensure that PreserveUnknownFields=false is set because the struct will omit false + mapData, err := convert.EncodeToMap(crd) + if err != nil { + return nil, err + } + mapData["kind"] = CRDKind + mapData["apiVersion"] = apiextv1.SchemeGroupVersion.String() + + return &unstructured.Unstructured{ + Object: mapData, + }, unstructured.SetNestedField(mapData, false, "spec", "preserveUnknownFields") +} + +func (c CRD) ToCustomResourceDefinitionV1Beta1() (*apiextv1beta1.CustomResourceDefinition, error) { + toConvertCRD, err := c.ToCustomResourceDefinition() + if err != nil { + return nil, err + } + if toConvertCRD == nil { + return nil, fmt.Errorf("cannot convert empty CRD runtime object to apiextensions v1beta1 CRD object") + } + + unstructuredCRD, ok := toConvertCRD.(*unstructured.Unstructured) + if !ok { + return nil, fmt.Errorf("could not convert CRD runtime object to *unstructured.Unstructured") + } + var v1CRD *apiextv1.CustomResourceDefinition + if err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstructuredCRD.UnstructuredContent(), &v1CRD); err != nil { + return nil, err + } + + internalCRD := &apiext.CustomResourceDefinition{} + if err := apiextv1.Convert_v1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(v1CRD, internalCRD, nil); err != nil { + return nil, err + } + v1beta1CRD := &apiextv1beta1.CustomResourceDefinition{} + if err := apiextv1beta1.Convert_apiextensions_CustomResourceDefinition_To_v1beta1_CustomResourceDefinition(internalCRD, v1beta1CRD, nil); err != nil { + return nil, err + } + + // GVK is dropped during conversion, so we must add it. + v1beta1CRD.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{ + Group: apiextv1beta1.SchemeGroupVersion.Group, + Version: apiextv1beta1.SchemeGroupVersion.Version, + Kind: CRDKind, + }) + return v1beta1CRD, nil } func NamespacedType(name string) CRD { @@ -309,13 +417,12 @@ func FromGV(gv schema.GroupVersion, kind string) CRD { } } -func NewFactoryFromClientGetter(client clientset.Interface) *Factory { - return &Factory{ - CRDClient: client, - } -} - func NewFactoryFromClient(config *rest.Config) (*Factory, error) { + apply, err := apply.NewForConfig(config) + if err != nil { + return nil, err + } + f, err := clientset.NewForConfig(config) if err != nil { return nil, err @@ -323,6 +430,7 @@ func NewFactoryFromClient(config *rest.Config) (*Factory, error) { return &Factory{ CRDClient: f, + apply: apply.WithDynamicLookup().WithNoDelete(), }, nil } @@ -342,7 +450,7 @@ func (f *Factory) BatchCreateCRDs(ctx context.Context, crds ...CRD) *Factory { return f } -func (f *Factory) CreateCRDs(ctx context.Context, crds ...CRD) (map[schema.GroupVersionKind]*apiext.CustomResourceDefinition, error) { +func (f *Factory) CreateCRDs(ctx context.Context, crds ...CRD) (map[schema.GroupVersionKind]*apiextv1.CustomResourceDefinition, error) { if len(crds) == 0 { return nil, nil } @@ -354,7 +462,7 @@ func (f *Factory) CreateCRDs(ctx context.Context, crds ...CRD) (map[schema.Group return nil, err } - crdStatus := map[schema.GroupVersionKind]*apiext.CustomResourceDefinition{} + crdStatus := map[schema.GroupVersionKind]*apiextv1.CustomResourceDefinition{} ready, err := f.getReadyCRDs(ctx) if err != nil { @@ -387,7 +495,7 @@ func (f *Factory) CreateCRDs(ctx context.Context, crds ...CRD) (map[schema.Group return crdStatus, nil } -func (f *Factory) waitCRD(ctx context.Context, crdName string, gvk schema.GroupVersionKind, crdStatus map[schema.GroupVersionKind]*apiext.CustomResourceDefinition) error { +func (f *Factory) waitCRD(ctx context.Context, crdName string, gvk schema.GroupVersionKind, crdStatus map[schema.GroupVersionKind]*apiextv1.CustomResourceDefinition) error { logrus.Infof("Waiting for CRD %s to become available", crdName) defer logrus.Infof("Done waiting for CRD %s to become available", crdName) @@ -398,20 +506,20 @@ func (f *Factory) waitCRD(ctx context.Context, crdName string, gvk schema.GroupV } first = false - crd, err := f.CRDClient.ApiextensionsV1beta1().CustomResourceDefinitions().Get(ctx, crdName, metav1.GetOptions{}) + crd, err := f.CRDClient.ApiextensionsV1().CustomResourceDefinitions().Get(ctx, crdName, metav1.GetOptions{}) if err != nil { return false, err } for _, cond := range crd.Status.Conditions { switch cond.Type { - case apiext.Established: - if cond.Status == apiext.ConditionTrue { + case apiextv1.Established: + if cond.Status == apiextv1.ConditionTrue { crdStatus[gvk] = crd return true, err } - case apiext.NamesAccepted: - if cond.Status == apiext.ConditionFalse { + case apiextv1.NamesAccepted: + if cond.Status == apiextv1.ConditionFalse { logrus.Infof("Name conflict on %s: %v\n", crdName, cond.Reason) } } @@ -421,60 +529,46 @@ func (f *Factory) waitCRD(ctx context.Context, crdName string, gvk schema.GroupV }) } -func (f *Factory) createCRD(ctx context.Context, crdDef CRD, ready map[string]*apiext.CustomResourceDefinition) (*apiext.CustomResourceDefinition, error) { - plural := crdDef.PluralName - if plural == "" { - plural = strings.ToLower(name.GuessPluralName(crdDef.GVK.Kind)) - } - +func (f *Factory) createCRD(ctx context.Context, crdDef CRD, ready map[string]*apiextv1.CustomResourceDefinition) (*apiextv1.CustomResourceDefinition, error) { crd, err := crdDef.ToCustomResourceDefinition() if err != nil { return nil, err } - existing, ok := ready[crd.Name] - if ok { - if !equality.Semantic.DeepEqual(crd.Spec.Subresources, existing.Spec.Subresources) || - !equality.Semantic.DeepEqual(crd.Spec.Validation, existing.Spec.Validation) || - !equality.Semantic.DeepEqual(crd.Spec.Versions, existing.Spec.Versions) { - existing.Spec = crd.Spec - logrus.Infof("Updating CRD %s", crd.Name) - return f.CRDClient.ApiextensionsV1beta1().CustomResourceDefinitions().Update(ctx, existing, metav1.UpdateOptions{}) - } - return existing, nil + meta, err := meta.Accessor(crd) + if err != nil { + return nil, err } - logrus.Infof("Creating CRD %s", crd.Name) - if newCrd, err := f.CRDClient.ApiextensionsV1beta1().CustomResourceDefinitions().Create(ctx, &crd, metav1.CreateOptions{}); apierrors.IsAlreadyExists(err) { - return f.CRDClient.ApiextensionsV1beta1().CustomResourceDefinitions().Get(ctx, crd.Name, metav1.GetOptions{}) - } else if err != nil { + logrus.Infof("Applying CRD %s", meta.GetName()) + if err := f.apply.WithOwner(crd).ApplyObjects(crd); err != nil { return nil, err - } else { - return newCrd, nil } + + return f.CRDClient.ApiextensionsV1().CustomResourceDefinitions().Get(ctx, meta.GetName(), metav1.GetOptions{}) } func (f *Factory) ensureAccess(ctx context.Context) (bool, error) { - _, err := f.CRDClient.ApiextensionsV1beta1().CustomResourceDefinitions().List(ctx, metav1.ListOptions{}) + _, err := f.CRDClient.ApiextensionsV1().CustomResourceDefinitions().List(ctx, metav1.ListOptions{}) if apierrors.IsForbidden(err) { return false, nil } return true, err } -func (f *Factory) getReadyCRDs(ctx context.Context) (map[string]*apiext.CustomResourceDefinition, error) { - list, err := f.CRDClient.ApiextensionsV1beta1().CustomResourceDefinitions().List(ctx, metav1.ListOptions{}) +func (f *Factory) getReadyCRDs(ctx context.Context) (map[string]*apiextv1.CustomResourceDefinition, error) { + list, err := f.CRDClient.ApiextensionsV1().CustomResourceDefinitions().List(ctx, metav1.ListOptions{}) if err != nil { return nil, err } - result := map[string]*apiext.CustomResourceDefinition{} + result := map[string]*apiextv1.CustomResourceDefinition{} for i, crd := range list.Items { for _, cond := range crd.Status.Conditions { switch cond.Type { - case apiext.Established: - if cond.Status == apiext.ConditionTrue { + case apiextv1.Established: + if cond.Status == apiextv1.ConditionTrue { result[crd.Name] = &list.Items[i] } } diff --git a/vendor/github.com/rancher/wrangler/pkg/crd/print.go b/vendor/github.com/rancher/wrangler/pkg/crd/print.go new file mode 100644 index 0000000000..adee2d12ea --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/crd/print.go @@ -0,0 +1,64 @@ +package crd + +import ( + "context" + "io" + "os" + "path/filepath" + + "github.com/rancher/wrangler/pkg/yaml" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" +) + +func WriteFile(filename string, crds []CRD) error { + if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil { + return err + } + f, err := os.Create(filename) + if err != nil { + return err + } + defer f.Close() + + return Print(f, crds) +} + +func Print(out io.Writer, crds []CRD) error { + obj, err := Objects(crds) + if err != nil { + return err + } + + data, err := yaml.Export(obj...) + if err != nil { + return err + } + + _, err = out.Write(data) + return err +} + +func Objects(crds []CRD) (result []runtime.Object, err error) { + for _, crdDef := range crds { + if crdDef.Override == nil { + crd, err := crdDef.ToCustomResourceDefinition() + if err != nil { + return nil, err + } + result = append(result, crd) + } else { + result = append(result, crdDef.Override) + } + } + return +} + +func Create(ctx context.Context, cfg *rest.Config, crds []CRD) error { + factory, err := NewFactoryFromClient(cfg) + if err != nil { + return err + } + + return factory.BatchCreateCRDs(ctx, crds...).BatchWait() +} diff --git a/vendor/github.com/rancher/wrangler/pkg/data/convert/convert.go b/vendor/github.com/rancher/wrangler/pkg/data/convert/convert.go index 47af9bc74a..c87f8b211d 100644 --- a/vendor/github.com/rancher/wrangler/pkg/data/convert/convert.go +++ b/vendor/github.com/rancher/wrangler/pkg/data/convert/convert.go @@ -9,6 +9,8 @@ import ( "strings" "time" "unicode" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) func Singular(value interface{}) interface{} { @@ -197,6 +199,9 @@ func ToStringSlice(data interface{}) []string { } return result } + if v, ok := data.(string); ok { + return []string{v} + } return nil } @@ -213,6 +218,10 @@ func EncodeToMap(obj interface{}) (map[string]interface{}, error) { return m, nil } + if unstr, ok := obj.(*unstructured.Unstructured); ok { + return unstr.Object, nil + } + b, err := json.Marshal(obj) if err != nil { return nil, err @@ -259,3 +268,44 @@ func ToYAMLKey(str string) string { return string(result) } + +func ToArgKey(str string) string { + var ( + result []rune + input = []rune(str) + ) + cap := false + + for i := 0; i < len(input); i++ { + r := input[i] + if i == 0 { + if unicode.IsUpper(r) { + cap = true + } + result = append(result, unicode.ToLower(r)) + continue + } + + if unicode.IsUpper(r) { + if cap { + result = append(result, unicode.ToLower(r)) + } else if len(input) > i+2 && + unicode.IsUpper(input[i]) && + unicode.IsUpper(input[i+1]) && + unicode.IsUpper(input[i+2]) { + result = append(result, '-', + unicode.ToLower(input[i]), + unicode.ToLower(input[i+1]), + unicode.ToLower(input[i+2])) + i += 2 + } else { + result = append(result, '-', unicode.ToLower(r)) + } + } else { + cap = false + result = append(result, r) + } + } + + return "--" + string(result) +} diff --git a/vendor/github.com/rancher/wrangler/pkg/data/data.go b/vendor/github.com/rancher/wrangler/pkg/data/data.go index e279a29924..46a3ccb74f 100644 --- a/vendor/github.com/rancher/wrangler/pkg/data/data.go +++ b/vendor/github.com/rancher/wrangler/pkg/data/data.go @@ -12,6 +12,14 @@ func New() Object { return map[string]interface{}{} } +func Convert(obj interface{}) (Object, error) { + data, err := convert.EncodeToMap(obj) + if err != nil { + return nil, err + } + return data, nil +} + func (o Object) Map(names ...string) Object { v := GetValueN(o, names...) m := convert.ToMapInterface(v) diff --git a/vendor/github.com/rancher/wrangler/pkg/data/merge.go b/vendor/github.com/rancher/wrangler/pkg/data/merge.go index 76970aa0a6..8e5de4c050 100644 --- a/vendor/github.com/rancher/wrangler/pkg/data/merge.go +++ b/vendor/github.com/rancher/wrangler/pkg/data/merge.go @@ -22,3 +22,32 @@ func bothMaps(left, right interface{}) (map[string]interface{}, map[string]inter rightMap, ok := right.(map[string]interface{}) return leftMap, rightMap, ok } + +func bothSlices(left, right interface{}) ([]interface{}, []interface{}, bool) { + leftSlice, ok := left.([]interface{}) + if !ok { + return nil, nil, false + } + rightSlice, ok := right.([]interface{}) + return leftSlice, rightSlice, ok +} + +func MergeMapsConcatSlice(base, overlay map[string]interface{}) map[string]interface{} { + result := map[string]interface{}{} + for k, v := range base { + result[k] = v + } + for k, v := range overlay { + if baseMap, overlayMap, bothMaps := bothMaps(result[k], v); bothMaps { + v = MergeMaps(baseMap, overlayMap) + } else if baseSlice, overlaySlice, bothSlices := bothSlices(result[k], v); bothSlices { + s := make([]interface{}, 0, len(baseSlice)+len(overlaySlice)) + s = append(s, baseSlice...) + s = append(s, overlaySlice...) + v = s + } + result[k] = v + } + return result + +} diff --git a/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apiextensions.k8s.io/v1/customresourcedefinition.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apiextensions.k8s.io/v1/customresourcedefinition.go new file mode 100644 index 0000000000..be7526f8ae --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apiextensions.k8s.io/v1/customresourcedefinition.go @@ -0,0 +1,376 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by main. DO NOT EDIT. + +package v1 + +import ( + "context" + "time" + + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/apply" + "github.com/rancher/wrangler/pkg/condition" + "github.com/rancher/wrangler/pkg/generic" + "github.com/rancher/wrangler/pkg/kv" + v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/client-go/tools/cache" +) + +type CustomResourceDefinitionHandler func(string, *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) + +type CustomResourceDefinitionController interface { + generic.ControllerMeta + CustomResourceDefinitionClient + + OnChange(ctx context.Context, name string, sync CustomResourceDefinitionHandler) + OnRemove(ctx context.Context, name string, sync CustomResourceDefinitionHandler) + Enqueue(name string) + EnqueueAfter(name string, duration time.Duration) + + Cache() CustomResourceDefinitionCache +} + +type CustomResourceDefinitionClient interface { + Create(*v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) + Update(*v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) + UpdateStatus(*v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) + Delete(name string, options *metav1.DeleteOptions) error + Get(name string, options metav1.GetOptions) (*v1.CustomResourceDefinition, error) + List(opts metav1.ListOptions) (*v1.CustomResourceDefinitionList, error) + Watch(opts metav1.ListOptions) (watch.Interface, error) + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.CustomResourceDefinition, err error) +} + +type CustomResourceDefinitionCache interface { + Get(name string) (*v1.CustomResourceDefinition, error) + List(selector labels.Selector) ([]*v1.CustomResourceDefinition, error) + + AddIndexer(indexName string, indexer CustomResourceDefinitionIndexer) + GetByIndex(indexName, key string) ([]*v1.CustomResourceDefinition, error) +} + +type CustomResourceDefinitionIndexer func(obj *v1.CustomResourceDefinition) ([]string, error) + +type customResourceDefinitionController struct { + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource +} + +func NewCustomResourceDefinitionController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) CustomResourceDefinitionController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) + return &customResourceDefinitionController{ + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, + } +} + +func FromCustomResourceDefinitionHandlerToHandler(sync CustomResourceDefinitionHandler) generic.Handler { + return func(key string, obj runtime.Object) (ret runtime.Object, err error) { + var v *v1.CustomResourceDefinition + if obj == nil { + v, err = sync(key, nil) + } else { + v, err = sync(key, obj.(*v1.CustomResourceDefinition)) + } + if v == nil { + return nil, err + } + return v, err + } +} + +func (c *customResourceDefinitionController) Updater() generic.Updater { + return func(obj runtime.Object) (runtime.Object, error) { + newObj, err := c.Update(obj.(*v1.CustomResourceDefinition)) + if newObj == nil { + return nil, err + } + return newObj, err + } +} + +func UpdateCustomResourceDefinitionDeepCopyOnChange(client CustomResourceDefinitionClient, obj *v1.CustomResourceDefinition, handler func(obj *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error)) (*v1.CustomResourceDefinition, error) { + if obj == nil { + return obj, nil + } + + copyObj := obj.DeepCopy() + newObj, err := handler(copyObj) + if newObj != nil { + copyObj = newObj + } + if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { + return client.Update(copyObj) + } + + return copyObj, err +} + +func (c *customResourceDefinitionController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) +} + +func (c *customResourceDefinitionController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) +} + +func (c *customResourceDefinitionController) OnChange(ctx context.Context, name string, sync CustomResourceDefinitionHandler) { + c.AddGenericHandler(ctx, name, FromCustomResourceDefinitionHandlerToHandler(sync)) +} + +func (c *customResourceDefinitionController) OnRemove(ctx context.Context, name string, sync CustomResourceDefinitionHandler) { + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromCustomResourceDefinitionHandlerToHandler(sync))) +} + +func (c *customResourceDefinitionController) Enqueue(name string) { + c.controller.Enqueue("", name) +} + +func (c *customResourceDefinitionController) EnqueueAfter(name string, duration time.Duration) { + c.controller.EnqueueAfter("", name, duration) +} + +func (c *customResourceDefinitionController) Informer() cache.SharedIndexInformer { + return c.controller.Informer() +} + +func (c *customResourceDefinitionController) GroupVersionKind() schema.GroupVersionKind { + return c.gvk +} + +func (c *customResourceDefinitionController) Cache() CustomResourceDefinitionCache { + return &customResourceDefinitionCache{ + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, + } +} + +func (c *customResourceDefinitionController) Create(obj *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) { + result := &v1.CustomResourceDefinition{} + return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) +} + +func (c *customResourceDefinitionController) Update(obj *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) { + result := &v1.CustomResourceDefinition{} + return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) +} + +func (c *customResourceDefinitionController) UpdateStatus(obj *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) { + result := &v1.CustomResourceDefinition{} + return result, c.client.UpdateStatus(context.TODO(), "", obj, result, metav1.UpdateOptions{}) +} + +func (c *customResourceDefinitionController) Delete(name string, options *metav1.DeleteOptions) error { + if options == nil { + options = &metav1.DeleteOptions{} + } + return c.client.Delete(context.TODO(), "", name, *options) +} + +func (c *customResourceDefinitionController) Get(name string, options metav1.GetOptions) (*v1.CustomResourceDefinition, error) { + result := &v1.CustomResourceDefinition{} + return result, c.client.Get(context.TODO(), "", name, result, options) +} + +func (c *customResourceDefinitionController) List(opts metav1.ListOptions) (*v1.CustomResourceDefinitionList, error) { + result := &v1.CustomResourceDefinitionList{} + return result, c.client.List(context.TODO(), "", result, opts) +} + +func (c *customResourceDefinitionController) Watch(opts metav1.ListOptions) (watch.Interface, error) { + return c.client.Watch(context.TODO(), "", opts) +} + +func (c *customResourceDefinitionController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.CustomResourceDefinition, error) { + result := &v1.CustomResourceDefinition{} + return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +} + +type customResourceDefinitionCache struct { + indexer cache.Indexer + resource schema.GroupResource +} + +func (c *customResourceDefinitionCache) Get(name string) (*v1.CustomResourceDefinition, error) { + obj, exists, err := c.indexer.GetByKey(name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.CustomResourceDefinition), nil +} + +func (c *customResourceDefinitionCache) List(selector labels.Selector) (ret []*v1.CustomResourceDefinition, err error) { + + err = cache.ListAll(c.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.CustomResourceDefinition)) + }) + + return ret, err +} + +func (c *customResourceDefinitionCache) AddIndexer(indexName string, indexer CustomResourceDefinitionIndexer) { + utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ + indexName: func(obj interface{}) (strings []string, e error) { + return indexer(obj.(*v1.CustomResourceDefinition)) + }, + })) +} + +func (c *customResourceDefinitionCache) GetByIndex(indexName, key string) (result []*v1.CustomResourceDefinition, err error) { + objs, err := c.indexer.ByIndex(indexName, key) + if err != nil { + return nil, err + } + result = make([]*v1.CustomResourceDefinition, 0, len(objs)) + for _, obj := range objs { + result = append(result, obj.(*v1.CustomResourceDefinition)) + } + return result, nil +} + +type CustomResourceDefinitionStatusHandler func(obj *v1.CustomResourceDefinition, status v1.CustomResourceDefinitionStatus) (v1.CustomResourceDefinitionStatus, error) + +type CustomResourceDefinitionGeneratingHandler func(obj *v1.CustomResourceDefinition, status v1.CustomResourceDefinitionStatus) ([]runtime.Object, v1.CustomResourceDefinitionStatus, error) + +func RegisterCustomResourceDefinitionStatusHandler(ctx context.Context, controller CustomResourceDefinitionController, condition condition.Cond, name string, handler CustomResourceDefinitionStatusHandler) { + statusHandler := &customResourceDefinitionStatusHandler{ + client: controller, + condition: condition, + handler: handler, + } + controller.AddGenericHandler(ctx, name, FromCustomResourceDefinitionHandlerToHandler(statusHandler.sync)) +} + +func RegisterCustomResourceDefinitionGeneratingHandler(ctx context.Context, controller CustomResourceDefinitionController, apply apply.Apply, + condition condition.Cond, name string, handler CustomResourceDefinitionGeneratingHandler, opts *generic.GeneratingHandlerOptions) { + statusHandler := &customResourceDefinitionGeneratingHandler{ + CustomResourceDefinitionGeneratingHandler: handler, + apply: apply, + name: name, + gvk: controller.GroupVersionKind(), + } + if opts != nil { + statusHandler.opts = *opts + } + controller.OnChange(ctx, name, statusHandler.Remove) + RegisterCustomResourceDefinitionStatusHandler(ctx, controller, condition, name, statusHandler.Handle) +} + +type customResourceDefinitionStatusHandler struct { + client CustomResourceDefinitionClient + condition condition.Cond + handler CustomResourceDefinitionStatusHandler +} + +func (a *customResourceDefinitionStatusHandler) sync(key string, obj *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) { + if obj == nil { + return obj, nil + } + + origStatus := obj.Status.DeepCopy() + obj = obj.DeepCopy() + newStatus, err := a.handler(obj, obj.Status) + if err != nil { + // Revert to old status on error + newStatus = *origStatus.DeepCopy() + } + + if a.condition != "" { + if errors.IsConflict(err) { + a.condition.SetError(&newStatus, "", nil) + } else { + a.condition.SetError(&newStatus, "", err) + } + } + if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + + var newErr error + obj.Status = newStatus + newObj, newErr := a.client.UpdateStatus(obj) + if err == nil { + err = newErr + } + if newErr == nil { + obj = newObj + } + } + return obj, err +} + +type customResourceDefinitionGeneratingHandler struct { + CustomResourceDefinitionGeneratingHandler + apply apply.Apply + opts generic.GeneratingHandlerOptions + gvk schema.GroupVersionKind + name string +} + +func (a *customResourceDefinitionGeneratingHandler) Remove(key string, obj *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) { + if obj != nil { + return obj, nil + } + + obj = &v1.CustomResourceDefinition{} + obj.Namespace, obj.Name = kv.RSplit(key, "/") + obj.SetGroupVersionKind(a.gvk) + + return nil, generic.ConfigureApplyForObject(a.apply, obj, &a.opts). + WithOwner(obj). + WithSetID(a.name). + ApplyObjects() +} + +func (a *customResourceDefinitionGeneratingHandler) Handle(obj *v1.CustomResourceDefinition, status v1.CustomResourceDefinitionStatus) (v1.CustomResourceDefinitionStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + + objs, newStatus, err := a.CustomResourceDefinitionGeneratingHandler(obj, status) + if err != nil { + return newStatus, err + } + + return newStatus, generic.ConfigureApplyForObject(a.apply, obj, &a.opts). + WithOwner(obj). + WithSetID(a.name). + ApplyObjects(objs...) +} diff --git a/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apiextensions.k8s.io/v1/interface.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apiextensions.k8s.io/v1/interface.go new file mode 100644 index 0000000000..ba505b6b73 --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apiextensions.k8s.io/v1/interface.go @@ -0,0 +1,48 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by main. DO NOT EDIT. + +package v1 + +import ( + "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/schemes" + v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +func init() { + schemes.Register(v1.AddToScheme) +} + +type Interface interface { + CustomResourceDefinition() CustomResourceDefinitionController +} + +func New(controllerFactory controller.SharedControllerFactory) Interface { + return &version{ + controllerFactory: controllerFactory, + } +} + +type version struct { + controllerFactory controller.SharedControllerFactory +} + +func (c *version) CustomResourceDefinition() CustomResourceDefinitionController { + return NewCustomResourceDefinitionController(schema.GroupVersionKind{Group: "apiextensions.k8s.io", Version: "v1", Kind: "CustomResourceDefinition"}, "customresourcedefinitions", false, c.controllerFactory) +} diff --git a/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/factory.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/factory.go new file mode 100644 index 0000000000..3679d03175 --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/factory.go @@ -0,0 +1,67 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by main. DO NOT EDIT. + +package apps + +import ( + "github.com/rancher/wrangler/pkg/generic" + "k8s.io/client-go/rest" +) + +type Factory struct { + *generic.Factory +} + +func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { + f, err := NewFactoryFromConfig(config) + if err != nil { + panic(err) + } + return f +} + +func NewFactoryFromConfig(config *rest.Config) (*Factory, error) { + return NewFactoryFromConfigWithOptions(config, nil) +} + +func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) { + return NewFactoryFromConfigWithOptions(config, &FactoryOptions{ + Namespace: namespace, + }) +} + +type FactoryOptions = generic.FactoryOptions + +func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { + f, err := generic.NewFactoryFromConfigWithOptions(config, opts) + return &Factory{ + Factory: f, + }, err +} + +func NewFactoryFromConfigWithOptionsOrDie(config *rest.Config, opts *FactoryOptions) *Factory { + f, err := NewFactoryFromConfigWithOptions(config, opts) + if err != nil { + panic(err) + } + return f +} + +func (c *Factory) Apps() Interface { + return New(c.ControllerFactory()) +} diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/interface.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/interface.go similarity index 56% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/interface.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/interface.go index 40179e4c76..4f91f157d9 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/interface.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/interface.go @@ -19,10 +19,8 @@ limitations under the License. package apps import ( - v1 "github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1" - "github.com/rancher/wrangler/pkg/generic" - informers "k8s.io/client-go/informers/apps" - clientset "k8s.io/client-go/kubernetes" + "github.com/rancher/lasso/pkg/controller" + v1 "github.com/rancher/wrangler/pkg/generated/controllers/apps/v1" ) type Interface interface { @@ -30,21 +28,16 @@ type Interface interface { } type group struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.Interface + controllerFactory controller.SharedControllerFactory } // New returns a new Interface. -func New(controllerManager *generic.ControllerManager, informers informers.Interface, - client clientset.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &group{ - controllerManager: controllerManager, - informers: informers, - client: client, + controllerFactory: controllerFactory, } } func (g *group) V1() v1.Interface { - return v1.New(g.controllerManager, g.client.AppsV1(), g.informers.V1()) + return v1.New(g.controllerFactory) } diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/daemonset.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/daemonset.go similarity index 76% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/daemonset.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/daemonset.go index c7c5378a6e..039d680dd9 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/daemonset.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/daemonset.go @@ -22,6 +22,8 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,9 +38,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/apps/v1" - clientset "k8s.io/client-go/kubernetes/typed/apps/v1" - listers "k8s.io/client-go/listers/apps/v1" "k8s.io/client-go/tools/cache" ) @@ -78,18 +77,22 @@ type DaemonSetCache interface { type DaemonSetIndexer func(obj *v1.DaemonSet) ([]string, error) type daemonSetController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.DaemonSetsGetter - informer informers.DaemonSetInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewDaemonSetController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.DaemonSetsGetter, informer informers.DaemonSetInformer) DaemonSetController { +func NewDaemonSetController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) DaemonSetController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &daemonSetController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdateDaemonSetDeepCopyOnChange(client DaemonSetClient, obj *v1.DaemonSet, } func (c *daemonSetController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *daemonSetController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *daemonSetController) OnChange(ctx context.Context, name string, sync DaemonSetHandler) { @@ -149,20 +151,19 @@ func (c *daemonSetController) OnChange(ctx context.Context, name string, sync Da } func (c *daemonSetController) OnRemove(ctx context.Context, name string, sync DaemonSetHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromDaemonSetHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromDaemonSetHandlerToHandler(sync))) } func (c *daemonSetController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *daemonSetController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *daemonSetController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *daemonSetController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *daemonSetController) GroupVersionKind() schema.GroupVersionKind { func (c *daemonSetController) Cache() DaemonSetCache { return &daemonSetCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *daemonSetController) Create(obj *v1.DaemonSet) (*v1.DaemonSet, error) { - return c.clientGetter.DaemonSets(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.DaemonSet{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *daemonSetController) Update(obj *v1.DaemonSet) (*v1.DaemonSet, error) { - return c.clientGetter.DaemonSets(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.DaemonSet{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *daemonSetController) UpdateStatus(obj *v1.DaemonSet) (*v1.DaemonSet, error) { - return c.clientGetter.DaemonSets(obj.Namespace).UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.DaemonSet{} + return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *daemonSetController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.DaemonSets(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *daemonSetController) Get(namespace, name string, options metav1.GetOptions) (*v1.DaemonSet, error) { - return c.clientGetter.DaemonSets(namespace).Get(context.TODO(), name, options) + result := &v1.DaemonSet{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *daemonSetController) List(namespace string, opts metav1.ListOptions) (*v1.DaemonSetList, error) { - return c.clientGetter.DaemonSets(namespace).List(context.TODO(), opts) + result := &v1.DaemonSetList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *daemonSetController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.DaemonSets(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *daemonSetController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.DaemonSet, err error) { - return c.clientGetter.DaemonSets(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *daemonSetController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.DaemonSet, error) { + result := &v1.DaemonSet{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type daemonSetCache struct { - lister listers.DaemonSetLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *daemonSetCache) Get(namespace, name string) (*v1.DaemonSet, error) { - return c.lister.DaemonSets(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.DaemonSet), nil } -func (c *daemonSetCache) List(namespace string, selector labels.Selector) ([]*v1.DaemonSet, error) { - return c.lister.DaemonSets(namespace).List(selector) +func (c *daemonSetCache) List(namespace string, selector labels.Selector) (ret []*v1.DaemonSet, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.DaemonSet)) + }) + + return ret, err } func (c *daemonSetCache) AddIndexer(indexName string, indexer DaemonSetIndexer) { @@ -299,12 +318,20 @@ func (a *daemonSetStatusHandler) sync(key string, obj *v1.DaemonSet) (*v1.Daemon } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *daemonSetGeneratingHandler) Remove(key string, obj *v1.DaemonSet) (*v1. } func (a *daemonSetGeneratingHandler) Handle(obj *v1.DaemonSet, status v1.DaemonSetStatus) (v1.DaemonSetStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.DaemonSetGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/deployment.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/deployment.go similarity index 76% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/deployment.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/deployment.go index 4f405391eb..2adb321e99 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/deployment.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/deployment.go @@ -22,6 +22,8 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,9 +38,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/apps/v1" - clientset "k8s.io/client-go/kubernetes/typed/apps/v1" - listers "k8s.io/client-go/listers/apps/v1" "k8s.io/client-go/tools/cache" ) @@ -78,18 +77,22 @@ type DeploymentCache interface { type DeploymentIndexer func(obj *v1.Deployment) ([]string, error) type deploymentController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.DeploymentsGetter - informer informers.DeploymentInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewDeploymentController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.DeploymentsGetter, informer informers.DeploymentInformer) DeploymentController { +func NewDeploymentController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) DeploymentController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &deploymentController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdateDeploymentDeepCopyOnChange(client DeploymentClient, obj *v1.Deploymen } func (c *deploymentController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *deploymentController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *deploymentController) OnChange(ctx context.Context, name string, sync DeploymentHandler) { @@ -149,20 +151,19 @@ func (c *deploymentController) OnChange(ctx context.Context, name string, sync D } func (c *deploymentController) OnRemove(ctx context.Context, name string, sync DeploymentHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromDeploymentHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromDeploymentHandlerToHandler(sync))) } func (c *deploymentController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *deploymentController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *deploymentController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *deploymentController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *deploymentController) GroupVersionKind() schema.GroupVersionKind { func (c *deploymentController) Cache() DeploymentCache { return &deploymentCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *deploymentController) Create(obj *v1.Deployment) (*v1.Deployment, error) { - return c.clientGetter.Deployments(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Deployment{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *deploymentController) Update(obj *v1.Deployment) (*v1.Deployment, error) { - return c.clientGetter.Deployments(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Deployment{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *deploymentController) UpdateStatus(obj *v1.Deployment) (*v1.Deployment, error) { - return c.clientGetter.Deployments(obj.Namespace).UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Deployment{} + return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *deploymentController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Deployments(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *deploymentController) Get(namespace, name string, options metav1.GetOptions) (*v1.Deployment, error) { - return c.clientGetter.Deployments(namespace).Get(context.TODO(), name, options) + result := &v1.Deployment{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *deploymentController) List(namespace string, opts metav1.ListOptions) (*v1.DeploymentList, error) { - return c.clientGetter.Deployments(namespace).List(context.TODO(), opts) + result := &v1.DeploymentList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *deploymentController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Deployments(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *deploymentController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Deployment, err error) { - return c.clientGetter.Deployments(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *deploymentController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Deployment, error) { + result := &v1.Deployment{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type deploymentCache struct { - lister listers.DeploymentLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *deploymentCache) Get(namespace, name string) (*v1.Deployment, error) { - return c.lister.Deployments(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Deployment), nil } -func (c *deploymentCache) List(namespace string, selector labels.Selector) ([]*v1.Deployment, error) { - return c.lister.Deployments(namespace).List(selector) +func (c *deploymentCache) List(namespace string, selector labels.Selector) (ret []*v1.Deployment, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Deployment)) + }) + + return ret, err } func (c *deploymentCache) AddIndexer(indexName string, indexer DeploymentIndexer) { @@ -299,12 +318,20 @@ func (a *deploymentStatusHandler) sync(key string, obj *v1.Deployment) (*v1.Depl } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *deploymentGeneratingHandler) Remove(key string, obj *v1.Deployment) (*v } func (a *deploymentGeneratingHandler) Handle(obj *v1.Deployment, status v1.DeploymentStatus) (v1.DeploymentStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.DeploymentGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/interface.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/interface.go similarity index 52% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/interface.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/interface.go index 1436dddd23..c08a4c7efc 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/interface.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/interface.go @@ -19,39 +19,38 @@ limitations under the License. package v1 import ( - "github.com/rancher/wrangler/pkg/generic" + "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/apps/v1" - informers "k8s.io/client-go/informers/apps/v1" - clientset "k8s.io/client-go/kubernetes/typed/apps/v1" + "k8s.io/apimachinery/pkg/runtime/schema" ) +func init() { + schemes.Register(v1.AddToScheme) +} + type Interface interface { DaemonSet() DaemonSetController Deployment() DeploymentController StatefulSet() StatefulSetController } -func New(controllerManager *generic.ControllerManager, client clientset.AppsV1Interface, - informers informers.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &version{ - controllerManager: controllerManager, - client: client, - informers: informers, + controllerFactory: controllerFactory, } } type version struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.AppsV1Interface + controllerFactory controller.SharedControllerFactory } func (c *version) DaemonSet() DaemonSetController { - return NewDaemonSetController(v1.SchemeGroupVersion.WithKind("DaemonSet"), c.controllerManager, c.client, c.informers.DaemonSets()) + return NewDaemonSetController(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "DaemonSet"}, "daemonsets", true, c.controllerFactory) } func (c *version) Deployment() DeploymentController { - return NewDeploymentController(v1.SchemeGroupVersion.WithKind("Deployment"), c.controllerManager, c.client, c.informers.Deployments()) + return NewDeploymentController(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}, "deployments", true, c.controllerFactory) } func (c *version) StatefulSet() StatefulSetController { - return NewStatefulSetController(v1.SchemeGroupVersion.WithKind("StatefulSet"), c.controllerManager, c.client, c.informers.StatefulSets()) + return NewStatefulSetController(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "StatefulSet"}, "statefulsets", true, c.controllerFactory) } diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/statefulset.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/statefulset.go similarity index 76% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/statefulset.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/statefulset.go index 5b1b403635..a573f7c541 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1/statefulset.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/apps/v1/statefulset.go @@ -22,6 +22,8 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,9 +38,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/apps/v1" - clientset "k8s.io/client-go/kubernetes/typed/apps/v1" - listers "k8s.io/client-go/listers/apps/v1" "k8s.io/client-go/tools/cache" ) @@ -78,18 +77,22 @@ type StatefulSetCache interface { type StatefulSetIndexer func(obj *v1.StatefulSet) ([]string, error) type statefulSetController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.StatefulSetsGetter - informer informers.StatefulSetInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewStatefulSetController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.StatefulSetsGetter, informer informers.StatefulSetInformer) StatefulSetController { +func NewStatefulSetController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) StatefulSetController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &statefulSetController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdateStatefulSetDeepCopyOnChange(client StatefulSetClient, obj *v1.Statefu } func (c *statefulSetController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *statefulSetController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *statefulSetController) OnChange(ctx context.Context, name string, sync StatefulSetHandler) { @@ -149,20 +151,19 @@ func (c *statefulSetController) OnChange(ctx context.Context, name string, sync } func (c *statefulSetController) OnRemove(ctx context.Context, name string, sync StatefulSetHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromStatefulSetHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromStatefulSetHandlerToHandler(sync))) } func (c *statefulSetController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *statefulSetController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *statefulSetController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *statefulSetController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *statefulSetController) GroupVersionKind() schema.GroupVersionKind { func (c *statefulSetController) Cache() StatefulSetCache { return &statefulSetCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *statefulSetController) Create(obj *v1.StatefulSet) (*v1.StatefulSet, error) { - return c.clientGetter.StatefulSets(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.StatefulSet{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *statefulSetController) Update(obj *v1.StatefulSet) (*v1.StatefulSet, error) { - return c.clientGetter.StatefulSets(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.StatefulSet{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *statefulSetController) UpdateStatus(obj *v1.StatefulSet) (*v1.StatefulSet, error) { - return c.clientGetter.StatefulSets(obj.Namespace).UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.StatefulSet{} + return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *statefulSetController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.StatefulSets(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *statefulSetController) Get(namespace, name string, options metav1.GetOptions) (*v1.StatefulSet, error) { - return c.clientGetter.StatefulSets(namespace).Get(context.TODO(), name, options) + result := &v1.StatefulSet{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *statefulSetController) List(namespace string, opts metav1.ListOptions) (*v1.StatefulSetList, error) { - return c.clientGetter.StatefulSets(namespace).List(context.TODO(), opts) + result := &v1.StatefulSetList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *statefulSetController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.StatefulSets(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *statefulSetController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.StatefulSet, err error) { - return c.clientGetter.StatefulSets(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *statefulSetController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.StatefulSet, error) { + result := &v1.StatefulSet{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type statefulSetCache struct { - lister listers.StatefulSetLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *statefulSetCache) Get(namespace, name string) (*v1.StatefulSet, error) { - return c.lister.StatefulSets(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.StatefulSet), nil } -func (c *statefulSetCache) List(namespace string, selector labels.Selector) ([]*v1.StatefulSet, error) { - return c.lister.StatefulSets(namespace).List(selector) +func (c *statefulSetCache) List(namespace string, selector labels.Selector) (ret []*v1.StatefulSet, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.StatefulSet)) + }) + + return ret, err } func (c *statefulSetCache) AddIndexer(indexName string, indexer StatefulSetIndexer) { @@ -299,12 +318,20 @@ func (a *statefulSetStatusHandler) sync(key string, obj *v1.StatefulSet) (*v1.St } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *statefulSetGeneratingHandler) Remove(key string, obj *v1.StatefulSet) ( } func (a *statefulSetGeneratingHandler) Handle(obj *v1.StatefulSet, status v1.StatefulSetStatus) (v1.StatefulSetStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.StatefulSetGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/factory.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/factory.go new file mode 100644 index 0000000000..6558b8d0ae --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/factory.go @@ -0,0 +1,67 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by main. DO NOT EDIT. + +package batch + +import ( + "github.com/rancher/wrangler/pkg/generic" + "k8s.io/client-go/rest" +) + +type Factory struct { + *generic.Factory +} + +func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { + f, err := NewFactoryFromConfig(config) + if err != nil { + panic(err) + } + return f +} + +func NewFactoryFromConfig(config *rest.Config) (*Factory, error) { + return NewFactoryFromConfigWithOptions(config, nil) +} + +func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) { + return NewFactoryFromConfigWithOptions(config, &FactoryOptions{ + Namespace: namespace, + }) +} + +type FactoryOptions = generic.FactoryOptions + +func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { + f, err := generic.NewFactoryFromConfigWithOptions(config, opts) + return &Factory{ + Factory: f, + }, err +} + +func NewFactoryFromConfigWithOptionsOrDie(config *rest.Config, opts *FactoryOptions) *Factory { + f, err := NewFactoryFromConfigWithOptions(config, opts) + if err != nil { + panic(err) + } + return f +} + +func (c *Factory) Batch() Interface { + return New(c.ControllerFactory()) +} diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/interface.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/interface.go similarity index 55% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/interface.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/interface.go index 77da90250d..a078bf8e5e 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/interface.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/interface.go @@ -19,10 +19,8 @@ limitations under the License. package batch import ( - v1 "github.com/rancher/wrangler-api/pkg/generated/controllers/batch/v1" - "github.com/rancher/wrangler/pkg/generic" - informers "k8s.io/client-go/informers/batch" - clientset "k8s.io/client-go/kubernetes" + "github.com/rancher/lasso/pkg/controller" + v1 "github.com/rancher/wrangler/pkg/generated/controllers/batch/v1" ) type Interface interface { @@ -30,21 +28,16 @@ type Interface interface { } type group struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.Interface + controllerFactory controller.SharedControllerFactory } // New returns a new Interface. -func New(controllerManager *generic.ControllerManager, informers informers.Interface, - client clientset.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &group{ - controllerManager: controllerManager, - informers: informers, - client: client, + controllerFactory: controllerFactory, } } func (g *group) V1() v1.Interface { - return v1.New(g.controllerManager, g.client.BatchV1(), g.informers.V1()) + return v1.New(g.controllerFactory) } diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/v1/interface.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/v1/interface.go similarity index 55% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/v1/interface.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/v1/interface.go index 27edcfb5de..abaf5ad5c8 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/v1/interface.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/v1/interface.go @@ -19,31 +19,30 @@ limitations under the License. package v1 import ( - "github.com/rancher/wrangler/pkg/generic" + "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/batch/v1" - informers "k8s.io/client-go/informers/batch/v1" - clientset "k8s.io/client-go/kubernetes/typed/batch/v1" + "k8s.io/apimachinery/pkg/runtime/schema" ) +func init() { + schemes.Register(v1.AddToScheme) +} + type Interface interface { Job() JobController } -func New(controllerManager *generic.ControllerManager, client clientset.BatchV1Interface, - informers informers.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &version{ - controllerManager: controllerManager, - client: client, - informers: informers, + controllerFactory: controllerFactory, } } type version struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.BatchV1Interface + controllerFactory controller.SharedControllerFactory } func (c *version) Job() JobController { - return NewJobController(v1.SchemeGroupVersion.WithKind("Job"), c.controllerManager, c.client, c.informers.Jobs()) + return NewJobController(schema.GroupVersionKind{Group: "batch", Version: "v1", Kind: "Job"}, "jobs", true, c.controllerFactory) } diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/v1/job.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/v1/job.go similarity index 75% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/v1/job.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/v1/job.go index 09b1e3ac75..ca5b9355f7 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/batch/v1/job.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/batch/v1/job.go @@ -22,6 +22,8 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,9 +38,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/batch/v1" - clientset "k8s.io/client-go/kubernetes/typed/batch/v1" - listers "k8s.io/client-go/listers/batch/v1" "k8s.io/client-go/tools/cache" ) @@ -78,18 +77,22 @@ type JobCache interface { type JobIndexer func(obj *v1.Job) ([]string, error) type jobController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.JobsGetter - informer informers.JobInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewJobController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.JobsGetter, informer informers.JobInformer) JobController { +func NewJobController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) JobController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &jobController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdateJobDeepCopyOnChange(client JobClient, obj *v1.Job, handler func(obj * } func (c *jobController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *jobController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *jobController) OnChange(ctx context.Context, name string, sync JobHandler) { @@ -149,20 +151,19 @@ func (c *jobController) OnChange(ctx context.Context, name string, sync JobHandl } func (c *jobController) OnRemove(ctx context.Context, name string, sync JobHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromJobHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromJobHandlerToHandler(sync))) } func (c *jobController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *jobController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *jobController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *jobController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *jobController) GroupVersionKind() schema.GroupVersionKind { func (c *jobController) Cache() JobCache { return &jobCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *jobController) Create(obj *v1.Job) (*v1.Job, error) { - return c.clientGetter.Jobs(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Job{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *jobController) Update(obj *v1.Job) (*v1.Job, error) { - return c.clientGetter.Jobs(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Job{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *jobController) UpdateStatus(obj *v1.Job) (*v1.Job, error) { - return c.clientGetter.Jobs(obj.Namespace).UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Job{} + return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *jobController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Jobs(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *jobController) Get(namespace, name string, options metav1.GetOptions) (*v1.Job, error) { - return c.clientGetter.Jobs(namespace).Get(context.TODO(), name, options) + result := &v1.Job{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *jobController) List(namespace string, opts metav1.ListOptions) (*v1.JobList, error) { - return c.clientGetter.Jobs(namespace).List(context.TODO(), opts) + result := &v1.JobList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *jobController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Jobs(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *jobController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Job, err error) { - return c.clientGetter.Jobs(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *jobController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Job, error) { + result := &v1.Job{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type jobCache struct { - lister listers.JobLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *jobCache) Get(namespace, name string) (*v1.Job, error) { - return c.lister.Jobs(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Job), nil } -func (c *jobCache) List(namespace string, selector labels.Selector) ([]*v1.Job, error) { - return c.lister.Jobs(namespace).List(selector) +func (c *jobCache) List(namespace string, selector labels.Selector) (ret []*v1.Job, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Job)) + }) + + return ret, err } func (c *jobCache) AddIndexer(indexName string, indexer JobIndexer) { @@ -299,12 +318,20 @@ func (a *jobStatusHandler) sync(key string, obj *v1.Job) (*v1.Job, error) { } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *jobGeneratingHandler) Remove(key string, obj *v1.Job) (*v1.Job, error) } func (a *jobGeneratingHandler) Handle(obj *v1.Job, status v1.JobStatus) (v1.JobStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.JobGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/factory.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/factory.go new file mode 100644 index 0000000000..8a8ad7f6f4 --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/factory.go @@ -0,0 +1,67 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by main. DO NOT EDIT. + +package core + +import ( + "github.com/rancher/wrangler/pkg/generic" + "k8s.io/client-go/rest" +) + +type Factory struct { + *generic.Factory +} + +func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { + f, err := NewFactoryFromConfig(config) + if err != nil { + panic(err) + } + return f +} + +func NewFactoryFromConfig(config *rest.Config) (*Factory, error) { + return NewFactoryFromConfigWithOptions(config, nil) +} + +func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) { + return NewFactoryFromConfigWithOptions(config, &FactoryOptions{ + Namespace: namespace, + }) +} + +type FactoryOptions = generic.FactoryOptions + +func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { + f, err := generic.NewFactoryFromConfigWithOptions(config, opts) + return &Factory{ + Factory: f, + }, err +} + +func NewFactoryFromConfigWithOptionsOrDie(config *rest.Config, opts *FactoryOptions) *Factory { + f, err := NewFactoryFromConfigWithOptions(config, opts) + if err != nil { + panic(err) + } + return f +} + +func (c *Factory) Core() Interface { + return New(c.ControllerFactory()) +} diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/interface.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/interface.go similarity index 56% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/interface.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/interface.go index 51d1216ed9..689915f184 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/interface.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/interface.go @@ -19,10 +19,8 @@ limitations under the License. package core import ( - v1 "github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1" - "github.com/rancher/wrangler/pkg/generic" - informers "k8s.io/client-go/informers/core" - clientset "k8s.io/client-go/kubernetes" + "github.com/rancher/lasso/pkg/controller" + v1 "github.com/rancher/wrangler/pkg/generated/controllers/core/v1" ) type Interface interface { @@ -30,21 +28,16 @@ type Interface interface { } type group struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.Interface + controllerFactory controller.SharedControllerFactory } // New returns a new Interface. -func New(controllerManager *generic.ControllerManager, informers informers.Interface, - client clientset.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &group{ - controllerManager: controllerManager, - informers: informers, - client: client, + controllerFactory: controllerFactory, } } func (g *group) V1() v1.Interface { - return v1.New(g.controllerManager, g.client.CoreV1(), g.informers.V1()) + return v1.New(g.controllerFactory) } diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/configmap.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/configmap.go similarity index 70% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/configmap.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/configmap.go index 334ad0a861..d56e1d87b4 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/configmap.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/configmap.go @@ -22,9 +22,12 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -32,9 +35,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" - listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" ) @@ -74,18 +74,22 @@ type ConfigMapCache interface { type ConfigMapIndexer func(obj *v1.ConfigMap) ([]string, error) type configMapController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.ConfigMapsGetter - informer informers.ConfigMapInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewConfigMapController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.ConfigMapsGetter, informer informers.ConfigMapInformer) ConfigMapController { +func NewConfigMapController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ConfigMapController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &configMapController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -132,12 +136,11 @@ func UpdateConfigMapDeepCopyOnChange(client ConfigMapClient, obj *v1.ConfigMap, } func (c *configMapController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *configMapController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *configMapController) OnChange(ctx context.Context, name string, sync ConfigMapHandler) { @@ -145,20 +148,19 @@ func (c *configMapController) OnChange(ctx context.Context, name string, sync Co } func (c *configMapController) OnRemove(ctx context.Context, name string, sync ConfigMapHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromConfigMapHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromConfigMapHandlerToHandler(sync))) } func (c *configMapController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *configMapController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *configMapController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *configMapController) GroupVersionKind() schema.GroupVersionKind { @@ -167,53 +169,70 @@ func (c *configMapController) GroupVersionKind() schema.GroupVersionKind { func (c *configMapController) Cache() ConfigMapCache { return &configMapCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *configMapController) Create(obj *v1.ConfigMap) (*v1.ConfigMap, error) { - return c.clientGetter.ConfigMaps(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.ConfigMap{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *configMapController) Update(obj *v1.ConfigMap) (*v1.ConfigMap, error) { - return c.clientGetter.ConfigMaps(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.ConfigMap{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *configMapController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.ConfigMaps(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *configMapController) Get(namespace, name string, options metav1.GetOptions) (*v1.ConfigMap, error) { - return c.clientGetter.ConfigMaps(namespace).Get(context.TODO(), name, options) + result := &v1.ConfigMap{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *configMapController) List(namespace string, opts metav1.ListOptions) (*v1.ConfigMapList, error) { - return c.clientGetter.ConfigMaps(namespace).List(context.TODO(), opts) + result := &v1.ConfigMapList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *configMapController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.ConfigMaps(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *configMapController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.ConfigMap, err error) { - return c.clientGetter.ConfigMaps(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *configMapController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.ConfigMap, error) { + result := &v1.ConfigMap{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type configMapCache struct { - lister listers.ConfigMapLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *configMapCache) Get(namespace, name string) (*v1.ConfigMap, error) { - return c.lister.ConfigMaps(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.ConfigMap), nil } -func (c *configMapCache) List(namespace string, selector labels.Selector) ([]*v1.ConfigMap, error) { - return c.lister.ConfigMaps(namespace).List(selector) +func (c *configMapCache) List(namespace string, selector labels.Selector) (ret []*v1.ConfigMap, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.ConfigMap)) + }) + + return ret, err } func (c *configMapCache) AddIndexer(indexName string, indexer ConfigMapIndexer) { diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/endpoints.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/endpoints.go similarity index 70% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/endpoints.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/endpoints.go index bbd7cf4b24..742c38be00 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/endpoints.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/endpoints.go @@ -22,9 +22,12 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -32,9 +35,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" - listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" ) @@ -74,18 +74,22 @@ type EndpointsCache interface { type EndpointsIndexer func(obj *v1.Endpoints) ([]string, error) type endpointsController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.EndpointsGetter - informer informers.EndpointsInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewEndpointsController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.EndpointsGetter, informer informers.EndpointsInformer) EndpointsController { +func NewEndpointsController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) EndpointsController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &endpointsController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -132,12 +136,11 @@ func UpdateEndpointsDeepCopyOnChange(client EndpointsClient, obj *v1.Endpoints, } func (c *endpointsController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *endpointsController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *endpointsController) OnChange(ctx context.Context, name string, sync EndpointsHandler) { @@ -145,20 +148,19 @@ func (c *endpointsController) OnChange(ctx context.Context, name string, sync En } func (c *endpointsController) OnRemove(ctx context.Context, name string, sync EndpointsHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromEndpointsHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromEndpointsHandlerToHandler(sync))) } func (c *endpointsController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *endpointsController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *endpointsController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *endpointsController) GroupVersionKind() schema.GroupVersionKind { @@ -167,53 +169,70 @@ func (c *endpointsController) GroupVersionKind() schema.GroupVersionKind { func (c *endpointsController) Cache() EndpointsCache { return &endpointsCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *endpointsController) Create(obj *v1.Endpoints) (*v1.Endpoints, error) { - return c.clientGetter.Endpoints(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Endpoints{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *endpointsController) Update(obj *v1.Endpoints) (*v1.Endpoints, error) { - return c.clientGetter.Endpoints(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Endpoints{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *endpointsController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Endpoints(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *endpointsController) Get(namespace, name string, options metav1.GetOptions) (*v1.Endpoints, error) { - return c.clientGetter.Endpoints(namespace).Get(context.TODO(), name, options) + result := &v1.Endpoints{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *endpointsController) List(namespace string, opts metav1.ListOptions) (*v1.EndpointsList, error) { - return c.clientGetter.Endpoints(namespace).List(context.TODO(), opts) + result := &v1.EndpointsList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *endpointsController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Endpoints(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *endpointsController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Endpoints, err error) { - return c.clientGetter.Endpoints(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *endpointsController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Endpoints, error) { + result := &v1.Endpoints{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type endpointsCache struct { - lister listers.EndpointsLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *endpointsCache) Get(namespace, name string) (*v1.Endpoints, error) { - return c.lister.Endpoints(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Endpoints), nil } -func (c *endpointsCache) List(namespace string, selector labels.Selector) ([]*v1.Endpoints, error) { - return c.lister.Endpoints(namespace).List(selector) +func (c *endpointsCache) List(namespace string, selector labels.Selector) (ret []*v1.Endpoints, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Endpoints)) + }) + + return ret, err } func (c *endpointsCache) AddIndexer(indexName string, indexer EndpointsIndexer) { diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/event.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/event.go similarity index 70% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/event.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/event.go index 7f1387661b..b052ef91ac 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/event.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/event.go @@ -22,9 +22,12 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -32,9 +35,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" - listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" ) @@ -74,18 +74,22 @@ type EventCache interface { type EventIndexer func(obj *v1.Event) ([]string, error) type eventController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.EventsGetter - informer informers.EventInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewEventController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.EventsGetter, informer informers.EventInformer) EventController { +func NewEventController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) EventController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &eventController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -132,12 +136,11 @@ func UpdateEventDeepCopyOnChange(client EventClient, obj *v1.Event, handler func } func (c *eventController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *eventController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *eventController) OnChange(ctx context.Context, name string, sync EventHandler) { @@ -145,20 +148,19 @@ func (c *eventController) OnChange(ctx context.Context, name string, sync EventH } func (c *eventController) OnRemove(ctx context.Context, name string, sync EventHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromEventHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromEventHandlerToHandler(sync))) } func (c *eventController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *eventController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *eventController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *eventController) GroupVersionKind() schema.GroupVersionKind { @@ -167,53 +169,70 @@ func (c *eventController) GroupVersionKind() schema.GroupVersionKind { func (c *eventController) Cache() EventCache { return &eventCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *eventController) Create(obj *v1.Event) (*v1.Event, error) { - return c.clientGetter.Events(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Event{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *eventController) Update(obj *v1.Event) (*v1.Event, error) { - return c.clientGetter.Events(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Event{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *eventController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Events(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *eventController) Get(namespace, name string, options metav1.GetOptions) (*v1.Event, error) { - return c.clientGetter.Events(namespace).Get(context.TODO(), name, options) + result := &v1.Event{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *eventController) List(namespace string, opts metav1.ListOptions) (*v1.EventList, error) { - return c.clientGetter.Events(namespace).List(context.TODO(), opts) + result := &v1.EventList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *eventController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Events(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *eventController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Event, err error) { - return c.clientGetter.Events(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *eventController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Event, error) { + result := &v1.Event{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type eventCache struct { - lister listers.EventLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *eventCache) Get(namespace, name string) (*v1.Event, error) { - return c.lister.Events(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Event), nil } -func (c *eventCache) List(namespace string, selector labels.Selector) ([]*v1.Event, error) { - return c.lister.Events(namespace).List(selector) +func (c *eventCache) List(namespace string, selector labels.Selector) (ret []*v1.Event, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Event)) + }) + + return ret, err } func (c *eventCache) AddIndexer(indexName string, indexer EventIndexer) { diff --git a/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/interface.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/interface.go new file mode 100644 index 0000000000..8439e33977 --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/interface.go @@ -0,0 +1,84 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by main. DO NOT EDIT. + +package v1 + +import ( + "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/schemes" + v1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +func init() { + schemes.Register(v1.AddToScheme) +} + +type Interface interface { + ConfigMap() ConfigMapController + Endpoints() EndpointsController + Event() EventController + Namespace() NamespaceController + Node() NodeController + PersistentVolumeClaim() PersistentVolumeClaimController + Pod() PodController + Secret() SecretController + Service() ServiceController + ServiceAccount() ServiceAccountController +} + +func New(controllerFactory controller.SharedControllerFactory) Interface { + return &version{ + controllerFactory: controllerFactory, + } +} + +type version struct { + controllerFactory controller.SharedControllerFactory +} + +func (c *version) ConfigMap() ConfigMapController { + return NewConfigMapController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMap"}, "configmaps", true, c.controllerFactory) +} +func (c *version) Endpoints() EndpointsController { + return NewEndpointsController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Endpoints"}, "endpoints", true, c.controllerFactory) +} +func (c *version) Event() EventController { + return NewEventController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Event"}, "events", true, c.controllerFactory) +} +func (c *version) Namespace() NamespaceController { + return NewNamespaceController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Namespace"}, "namespaces", false, c.controllerFactory) +} +func (c *version) Node() NodeController { + return NewNodeController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Node"}, "nodes", false, c.controllerFactory) +} +func (c *version) PersistentVolumeClaim() PersistentVolumeClaimController { + return NewPersistentVolumeClaimController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PersistentVolumeClaim"}, "persistentvolumeclaims", true, c.controllerFactory) +} +func (c *version) Pod() PodController { + return NewPodController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"}, "pods", true, c.controllerFactory) +} +func (c *version) Secret() SecretController { + return NewSecretController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Secret"}, "secrets", true, c.controllerFactory) +} +func (c *version) Service() ServiceController { + return NewServiceController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Service"}, "services", true, c.controllerFactory) +} +func (c *version) ServiceAccount() ServiceAccountController { + return NewServiceAccountController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ServiceAccount"}, "serviceaccounts", true, c.controllerFactory) +} diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/namespace.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/namespace.go similarity index 76% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/namespace.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/namespace.go index 14f4a090dd..83d04ac6b9 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/namespace.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/namespace.go @@ -22,6 +22,8 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,9 +38,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" - listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" ) @@ -78,18 +77,22 @@ type NamespaceCache interface { type NamespaceIndexer func(obj *v1.Namespace) ([]string, error) type namespaceController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.NamespacesGetter - informer informers.NamespaceInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewNamespaceController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.NamespacesGetter, informer informers.NamespaceInformer) NamespaceController { +func NewNamespaceController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) NamespaceController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &namespaceController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdateNamespaceDeepCopyOnChange(client NamespaceClient, obj *v1.Namespace, } func (c *namespaceController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *namespaceController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *namespaceController) OnChange(ctx context.Context, name string, sync NamespaceHandler) { @@ -149,20 +151,19 @@ func (c *namespaceController) OnChange(ctx context.Context, name string, sync Na } func (c *namespaceController) OnRemove(ctx context.Context, name string, sync NamespaceHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromNamespaceHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromNamespaceHandlerToHandler(sync))) } func (c *namespaceController) Enqueue(name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), "", name) + c.controller.Enqueue("", name) } func (c *namespaceController) EnqueueAfter(name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), "", name, duration) + c.controller.EnqueueAfter("", name, duration) } func (c *namespaceController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *namespaceController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *namespaceController) GroupVersionKind() schema.GroupVersionKind { func (c *namespaceController) Cache() NamespaceCache { return &namespaceCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *namespaceController) Create(obj *v1.Namespace) (*v1.Namespace, error) { - return c.clientGetter.Namespaces().Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Namespace{} + return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) } func (c *namespaceController) Update(obj *v1.Namespace) (*v1.Namespace, error) { - return c.clientGetter.Namespaces().Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Namespace{} + return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) } func (c *namespaceController) UpdateStatus(obj *v1.Namespace) (*v1.Namespace, error) { - return c.clientGetter.Namespaces().UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Namespace{} + return result, c.client.UpdateStatus(context.TODO(), "", obj, result, metav1.UpdateOptions{}) } func (c *namespaceController) Delete(name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Namespaces().Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), "", name, *options) } func (c *namespaceController) Get(name string, options metav1.GetOptions) (*v1.Namespace, error) { - return c.clientGetter.Namespaces().Get(context.TODO(), name, options) + result := &v1.Namespace{} + return result, c.client.Get(context.TODO(), "", name, result, options) } func (c *namespaceController) List(opts metav1.ListOptions) (*v1.NamespaceList, error) { - return c.clientGetter.Namespaces().List(context.TODO(), opts) + result := &v1.NamespaceList{} + return result, c.client.List(context.TODO(), "", result, opts) } func (c *namespaceController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Namespaces().Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), "", opts) } -func (c *namespaceController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Namespace, err error) { - return c.clientGetter.Namespaces().Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *namespaceController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Namespace, error) { + result := &v1.Namespace{} + return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) } type namespaceCache struct { - lister listers.NamespaceLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *namespaceCache) Get(name string) (*v1.Namespace, error) { - return c.lister.Get(name) + obj, exists, err := c.indexer.GetByKey(name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Namespace), nil } -func (c *namespaceCache) List(selector labels.Selector) ([]*v1.Namespace, error) { - return c.lister.List(selector) +func (c *namespaceCache) List(selector labels.Selector) (ret []*v1.Namespace, err error) { + + err = cache.ListAll(c.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Namespace)) + }) + + return ret, err } func (c *namespaceCache) AddIndexer(indexName string, indexer NamespaceIndexer) { @@ -299,12 +318,20 @@ func (a *namespaceStatusHandler) sync(key string, obj *v1.Namespace) (*v1.Namesp } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *namespaceGeneratingHandler) Remove(key string, obj *v1.Namespace) (*v1. } func (a *namespaceGeneratingHandler) Handle(obj *v1.Namespace, status v1.NamespaceStatus) (v1.NamespaceStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.NamespaceGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/node.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/node.go similarity index 75% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/node.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/node.go index 1ef583d47d..b444b33c3c 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/node.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/node.go @@ -22,6 +22,8 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,9 +38,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" - listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" ) @@ -78,18 +77,22 @@ type NodeCache interface { type NodeIndexer func(obj *v1.Node) ([]string, error) type nodeController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.NodesGetter - informer informers.NodeInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewNodeController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.NodesGetter, informer informers.NodeInformer) NodeController { +func NewNodeController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) NodeController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &nodeController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdateNodeDeepCopyOnChange(client NodeClient, obj *v1.Node, handler func(ob } func (c *nodeController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *nodeController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *nodeController) OnChange(ctx context.Context, name string, sync NodeHandler) { @@ -149,20 +151,19 @@ func (c *nodeController) OnChange(ctx context.Context, name string, sync NodeHan } func (c *nodeController) OnRemove(ctx context.Context, name string, sync NodeHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromNodeHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromNodeHandlerToHandler(sync))) } func (c *nodeController) Enqueue(name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), "", name) + c.controller.Enqueue("", name) } func (c *nodeController) EnqueueAfter(name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), "", name, duration) + c.controller.EnqueueAfter("", name, duration) } func (c *nodeController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *nodeController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *nodeController) GroupVersionKind() schema.GroupVersionKind { func (c *nodeController) Cache() NodeCache { return &nodeCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *nodeController) Create(obj *v1.Node) (*v1.Node, error) { - return c.clientGetter.Nodes().Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Node{} + return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) } func (c *nodeController) Update(obj *v1.Node) (*v1.Node, error) { - return c.clientGetter.Nodes().Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Node{} + return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) } func (c *nodeController) UpdateStatus(obj *v1.Node) (*v1.Node, error) { - return c.clientGetter.Nodes().UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Node{} + return result, c.client.UpdateStatus(context.TODO(), "", obj, result, metav1.UpdateOptions{}) } func (c *nodeController) Delete(name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Nodes().Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), "", name, *options) } func (c *nodeController) Get(name string, options metav1.GetOptions) (*v1.Node, error) { - return c.clientGetter.Nodes().Get(context.TODO(), name, options) + result := &v1.Node{} + return result, c.client.Get(context.TODO(), "", name, result, options) } func (c *nodeController) List(opts metav1.ListOptions) (*v1.NodeList, error) { - return c.clientGetter.Nodes().List(context.TODO(), opts) + result := &v1.NodeList{} + return result, c.client.List(context.TODO(), "", result, opts) } func (c *nodeController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Nodes().Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), "", opts) } -func (c *nodeController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Node, err error) { - return c.clientGetter.Nodes().Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *nodeController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Node, error) { + result := &v1.Node{} + return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) } type nodeCache struct { - lister listers.NodeLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *nodeCache) Get(name string) (*v1.Node, error) { - return c.lister.Get(name) + obj, exists, err := c.indexer.GetByKey(name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Node), nil } -func (c *nodeCache) List(selector labels.Selector) ([]*v1.Node, error) { - return c.lister.List(selector) +func (c *nodeCache) List(selector labels.Selector) (ret []*v1.Node, err error) { + + err = cache.ListAll(c.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Node)) + }) + + return ret, err } func (c *nodeCache) AddIndexer(indexName string, indexer NodeIndexer) { @@ -299,12 +318,20 @@ func (a *nodeStatusHandler) sync(key string, obj *v1.Node) (*v1.Node, error) { } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *nodeGeneratingHandler) Remove(key string, obj *v1.Node) (*v1.Node, erro } func (a *nodeGeneratingHandler) Handle(obj *v1.Node, status v1.NodeStatus) (v1.NodeStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.NodeGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/persistentvolumeclaim.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/persistentvolumeclaim.go similarity index 78% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/persistentvolumeclaim.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/persistentvolumeclaim.go index be41b9acd1..5fbce6d885 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/persistentvolumeclaim.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/persistentvolumeclaim.go @@ -22,6 +22,8 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,9 +38,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" - listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" ) @@ -78,18 +77,22 @@ type PersistentVolumeClaimCache interface { type PersistentVolumeClaimIndexer func(obj *v1.PersistentVolumeClaim) ([]string, error) type persistentVolumeClaimController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.PersistentVolumeClaimsGetter - informer informers.PersistentVolumeClaimInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewPersistentVolumeClaimController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.PersistentVolumeClaimsGetter, informer informers.PersistentVolumeClaimInformer) PersistentVolumeClaimController { +func NewPersistentVolumeClaimController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) PersistentVolumeClaimController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &persistentVolumeClaimController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdatePersistentVolumeClaimDeepCopyOnChange(client PersistentVolumeClaimCli } func (c *persistentVolumeClaimController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *persistentVolumeClaimController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *persistentVolumeClaimController) OnChange(ctx context.Context, name string, sync PersistentVolumeClaimHandler) { @@ -149,20 +151,19 @@ func (c *persistentVolumeClaimController) OnChange(ctx context.Context, name str } func (c *persistentVolumeClaimController) OnRemove(ctx context.Context, name string, sync PersistentVolumeClaimHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromPersistentVolumeClaimHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromPersistentVolumeClaimHandlerToHandler(sync))) } func (c *persistentVolumeClaimController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *persistentVolumeClaimController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *persistentVolumeClaimController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *persistentVolumeClaimController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *persistentVolumeClaimController) GroupVersionKind() schema.GroupVersion func (c *persistentVolumeClaimController) Cache() PersistentVolumeClaimCache { return &persistentVolumeClaimCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *persistentVolumeClaimController) Create(obj *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) { - return c.clientGetter.PersistentVolumeClaims(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.PersistentVolumeClaim{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *persistentVolumeClaimController) Update(obj *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) { - return c.clientGetter.PersistentVolumeClaims(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.PersistentVolumeClaim{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *persistentVolumeClaimController) UpdateStatus(obj *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) { - return c.clientGetter.PersistentVolumeClaims(obj.Namespace).UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.PersistentVolumeClaim{} + return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *persistentVolumeClaimController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.PersistentVolumeClaims(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *persistentVolumeClaimController) Get(namespace, name string, options metav1.GetOptions) (*v1.PersistentVolumeClaim, error) { - return c.clientGetter.PersistentVolumeClaims(namespace).Get(context.TODO(), name, options) + result := &v1.PersistentVolumeClaim{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *persistentVolumeClaimController) List(namespace string, opts metav1.ListOptions) (*v1.PersistentVolumeClaimList, error) { - return c.clientGetter.PersistentVolumeClaims(namespace).List(context.TODO(), opts) + result := &v1.PersistentVolumeClaimList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *persistentVolumeClaimController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.PersistentVolumeClaims(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *persistentVolumeClaimController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.PersistentVolumeClaim, err error) { - return c.clientGetter.PersistentVolumeClaims(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *persistentVolumeClaimController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.PersistentVolumeClaim, error) { + result := &v1.PersistentVolumeClaim{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type persistentVolumeClaimCache struct { - lister listers.PersistentVolumeClaimLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *persistentVolumeClaimCache) Get(namespace, name string) (*v1.PersistentVolumeClaim, error) { - return c.lister.PersistentVolumeClaims(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.PersistentVolumeClaim), nil } -func (c *persistentVolumeClaimCache) List(namespace string, selector labels.Selector) ([]*v1.PersistentVolumeClaim, error) { - return c.lister.PersistentVolumeClaims(namespace).List(selector) +func (c *persistentVolumeClaimCache) List(namespace string, selector labels.Selector) (ret []*v1.PersistentVolumeClaim, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.PersistentVolumeClaim)) + }) + + return ret, err } func (c *persistentVolumeClaimCache) AddIndexer(indexName string, indexer PersistentVolumeClaimIndexer) { @@ -299,12 +318,20 @@ func (a *persistentVolumeClaimStatusHandler) sync(key string, obj *v1.Persistent } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *persistentVolumeClaimGeneratingHandler) Remove(key string, obj *v1.Pers } func (a *persistentVolumeClaimGeneratingHandler) Handle(obj *v1.PersistentVolumeClaim, status v1.PersistentVolumeClaimStatus) (v1.PersistentVolumeClaimStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.PersistentVolumeClaimGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/pod.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/pod.go similarity index 75% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/pod.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/pod.go index e808414d49..4286bcf56e 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/pod.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/pod.go @@ -22,6 +22,8 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,9 +38,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" - listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" ) @@ -78,18 +77,22 @@ type PodCache interface { type PodIndexer func(obj *v1.Pod) ([]string, error) type podController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.PodsGetter - informer informers.PodInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewPodController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.PodsGetter, informer informers.PodInformer) PodController { +func NewPodController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) PodController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &podController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdatePodDeepCopyOnChange(client PodClient, obj *v1.Pod, handler func(obj * } func (c *podController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *podController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *podController) OnChange(ctx context.Context, name string, sync PodHandler) { @@ -149,20 +151,19 @@ func (c *podController) OnChange(ctx context.Context, name string, sync PodHandl } func (c *podController) OnRemove(ctx context.Context, name string, sync PodHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromPodHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromPodHandlerToHandler(sync))) } func (c *podController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *podController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *podController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *podController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *podController) GroupVersionKind() schema.GroupVersionKind { func (c *podController) Cache() PodCache { return &podCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *podController) Create(obj *v1.Pod) (*v1.Pod, error) { - return c.clientGetter.Pods(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Pod{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *podController) Update(obj *v1.Pod) (*v1.Pod, error) { - return c.clientGetter.Pods(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Pod{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *podController) UpdateStatus(obj *v1.Pod) (*v1.Pod, error) { - return c.clientGetter.Pods(obj.Namespace).UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Pod{} + return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *podController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Pods(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *podController) Get(namespace, name string, options metav1.GetOptions) (*v1.Pod, error) { - return c.clientGetter.Pods(namespace).Get(context.TODO(), name, options) + result := &v1.Pod{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *podController) List(namespace string, opts metav1.ListOptions) (*v1.PodList, error) { - return c.clientGetter.Pods(namespace).List(context.TODO(), opts) + result := &v1.PodList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *podController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Pods(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *podController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Pod, err error) { - return c.clientGetter.Pods(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *podController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Pod, error) { + result := &v1.Pod{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type podCache struct { - lister listers.PodLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *podCache) Get(namespace, name string) (*v1.Pod, error) { - return c.lister.Pods(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Pod), nil } -func (c *podCache) List(namespace string, selector labels.Selector) ([]*v1.Pod, error) { - return c.lister.Pods(namespace).List(selector) +func (c *podCache) List(namespace string, selector labels.Selector) (ret []*v1.Pod, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Pod)) + }) + + return ret, err } func (c *podCache) AddIndexer(indexName string, indexer PodIndexer) { @@ -299,12 +318,20 @@ func (a *podStatusHandler) sync(key string, obj *v1.Pod) (*v1.Pod, error) { } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *podGeneratingHandler) Remove(key string, obj *v1.Pod) (*v1.Pod, error) } func (a *podGeneratingHandler) Handle(obj *v1.Pod, status v1.PodStatus) (v1.PodStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.PodGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/secret.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/secret.go similarity index 70% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/secret.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/secret.go index c91479a5c8..55cc637076 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/secret.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/secret.go @@ -22,9 +22,12 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -32,9 +35,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" - listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" ) @@ -74,18 +74,22 @@ type SecretCache interface { type SecretIndexer func(obj *v1.Secret) ([]string, error) type secretController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.SecretsGetter - informer informers.SecretInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewSecretController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.SecretsGetter, informer informers.SecretInformer) SecretController { +func NewSecretController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) SecretController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &secretController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -132,12 +136,11 @@ func UpdateSecretDeepCopyOnChange(client SecretClient, obj *v1.Secret, handler f } func (c *secretController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *secretController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *secretController) OnChange(ctx context.Context, name string, sync SecretHandler) { @@ -145,20 +148,19 @@ func (c *secretController) OnChange(ctx context.Context, name string, sync Secre } func (c *secretController) OnRemove(ctx context.Context, name string, sync SecretHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromSecretHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromSecretHandlerToHandler(sync))) } func (c *secretController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *secretController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *secretController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *secretController) GroupVersionKind() schema.GroupVersionKind { @@ -167,53 +169,70 @@ func (c *secretController) GroupVersionKind() schema.GroupVersionKind { func (c *secretController) Cache() SecretCache { return &secretCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *secretController) Create(obj *v1.Secret) (*v1.Secret, error) { - return c.clientGetter.Secrets(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Secret{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *secretController) Update(obj *v1.Secret) (*v1.Secret, error) { - return c.clientGetter.Secrets(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Secret{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *secretController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Secrets(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *secretController) Get(namespace, name string, options metav1.GetOptions) (*v1.Secret, error) { - return c.clientGetter.Secrets(namespace).Get(context.TODO(), name, options) + result := &v1.Secret{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *secretController) List(namespace string, opts metav1.ListOptions) (*v1.SecretList, error) { - return c.clientGetter.Secrets(namespace).List(context.TODO(), opts) + result := &v1.SecretList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *secretController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Secrets(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *secretController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Secret, err error) { - return c.clientGetter.Secrets(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *secretController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Secret, error) { + result := &v1.Secret{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type secretCache struct { - lister listers.SecretLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *secretCache) Get(namespace, name string) (*v1.Secret, error) { - return c.lister.Secrets(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Secret), nil } -func (c *secretCache) List(namespace string, selector labels.Selector) ([]*v1.Secret, error) { - return c.lister.Secrets(namespace).List(selector) +func (c *secretCache) List(namespace string, selector labels.Selector) (ret []*v1.Secret, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Secret)) + }) + + return ret, err } func (c *secretCache) AddIndexer(indexName string, indexer SecretIndexer) { diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/service.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/service.go similarity index 76% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/service.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/service.go index 28fba8f794..4802feb6ba 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/service.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/service.go @@ -22,6 +22,8 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,9 +38,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" - listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" ) @@ -78,18 +77,22 @@ type ServiceCache interface { type ServiceIndexer func(obj *v1.Service) ([]string, error) type serviceController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.ServicesGetter - informer informers.ServiceInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewServiceController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.ServicesGetter, informer informers.ServiceInformer) ServiceController { +func NewServiceController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ServiceController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &serviceController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -136,12 +139,11 @@ func UpdateServiceDeepCopyOnChange(client ServiceClient, obj *v1.Service, handle } func (c *serviceController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *serviceController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *serviceController) OnChange(ctx context.Context, name string, sync ServiceHandler) { @@ -149,20 +151,19 @@ func (c *serviceController) OnChange(ctx context.Context, name string, sync Serv } func (c *serviceController) OnRemove(ctx context.Context, name string, sync ServiceHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromServiceHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromServiceHandlerToHandler(sync))) } func (c *serviceController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *serviceController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *serviceController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *serviceController) GroupVersionKind() schema.GroupVersionKind { @@ -171,57 +172,75 @@ func (c *serviceController) GroupVersionKind() schema.GroupVersionKind { func (c *serviceController) Cache() ServiceCache { return &serviceCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *serviceController) Create(obj *v1.Service) (*v1.Service, error) { - return c.clientGetter.Services(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Service{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *serviceController) Update(obj *v1.Service) (*v1.Service, error) { - return c.clientGetter.Services(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Service{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *serviceController) UpdateStatus(obj *v1.Service) (*v1.Service, error) { - return c.clientGetter.Services(obj.Namespace).UpdateStatus(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Service{} + return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *serviceController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Services(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *serviceController) Get(namespace, name string, options metav1.GetOptions) (*v1.Service, error) { - return c.clientGetter.Services(namespace).Get(context.TODO(), name, options) + result := &v1.Service{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *serviceController) List(namespace string, opts metav1.ListOptions) (*v1.ServiceList, error) { - return c.clientGetter.Services(namespace).List(context.TODO(), opts) + result := &v1.ServiceList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *serviceController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Services(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *serviceController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Service, err error) { - return c.clientGetter.Services(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *serviceController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Service, error) { + result := &v1.Service{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type serviceCache struct { - lister listers.ServiceLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *serviceCache) Get(namespace, name string) (*v1.Service, error) { - return c.lister.Services(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Service), nil } -func (c *serviceCache) List(namespace string, selector labels.Selector) ([]*v1.Service, error) { - return c.lister.Services(namespace).List(selector) +func (c *serviceCache) List(namespace string, selector labels.Selector) (ret []*v1.Service, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Service)) + }) + + return ret, err } func (c *serviceCache) AddIndexer(indexName string, indexer ServiceIndexer) { @@ -299,12 +318,20 @@ func (a *serviceStatusHandler) sync(key string, obj *v1.Service) (*v1.Service, e } } if !equality.Semantic.DeepEqual(origStatus, &newStatus) { + if a.condition != "" { + // Since status has changed, update the lastUpdatedTime + a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339)) + } + var newErr error obj.Status = newStatus - obj, newErr = a.client.UpdateStatus(obj) + newObj, newErr := a.client.UpdateStatus(obj) if err == nil { err = newErr } + if newErr == nil { + obj = newObj + } } return obj, err } @@ -333,6 +360,10 @@ func (a *serviceGeneratingHandler) Remove(key string, obj *v1.Service) (*v1.Serv } func (a *serviceGeneratingHandler) Handle(obj *v1.Service, status v1.ServiceStatus) (v1.ServiceStatus, error) { + if !obj.DeletionTimestamp.IsZero() { + return status, nil + } + objs, newStatus, err := a.ServiceGeneratingHandler(obj, status) if err != nil { return newStatus, err diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/serviceaccount.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/serviceaccount.go similarity index 71% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/serviceaccount.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/serviceaccount.go index abfb22f450..f9a81cc8fa 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1/serviceaccount.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/core/v1/serviceaccount.go @@ -22,9 +22,12 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -32,9 +35,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/core/v1" - clientset "k8s.io/client-go/kubernetes/typed/core/v1" - listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" ) @@ -74,18 +74,22 @@ type ServiceAccountCache interface { type ServiceAccountIndexer func(obj *v1.ServiceAccount) ([]string, error) type serviceAccountController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.ServiceAccountsGetter - informer informers.ServiceAccountInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewServiceAccountController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.ServiceAccountsGetter, informer informers.ServiceAccountInformer) ServiceAccountController { +func NewServiceAccountController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ServiceAccountController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &serviceAccountController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -132,12 +136,11 @@ func UpdateServiceAccountDeepCopyOnChange(client ServiceAccountClient, obj *v1.S } func (c *serviceAccountController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *serviceAccountController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *serviceAccountController) OnChange(ctx context.Context, name string, sync ServiceAccountHandler) { @@ -145,20 +148,19 @@ func (c *serviceAccountController) OnChange(ctx context.Context, name string, sy } func (c *serviceAccountController) OnRemove(ctx context.Context, name string, sync ServiceAccountHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromServiceAccountHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromServiceAccountHandlerToHandler(sync))) } func (c *serviceAccountController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *serviceAccountController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *serviceAccountController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *serviceAccountController) GroupVersionKind() schema.GroupVersionKind { @@ -167,53 +169,70 @@ func (c *serviceAccountController) GroupVersionKind() schema.GroupVersionKind { func (c *serviceAccountController) Cache() ServiceAccountCache { return &serviceAccountCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *serviceAccountController) Create(obj *v1.ServiceAccount) (*v1.ServiceAccount, error) { - return c.clientGetter.ServiceAccounts(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.ServiceAccount{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *serviceAccountController) Update(obj *v1.ServiceAccount) (*v1.ServiceAccount, error) { - return c.clientGetter.ServiceAccounts(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.ServiceAccount{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *serviceAccountController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.ServiceAccounts(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *serviceAccountController) Get(namespace, name string, options metav1.GetOptions) (*v1.ServiceAccount, error) { - return c.clientGetter.ServiceAccounts(namespace).Get(context.TODO(), name, options) + result := &v1.ServiceAccount{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *serviceAccountController) List(namespace string, opts metav1.ListOptions) (*v1.ServiceAccountList, error) { - return c.clientGetter.ServiceAccounts(namespace).List(context.TODO(), opts) + result := &v1.ServiceAccountList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *serviceAccountController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.ServiceAccounts(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *serviceAccountController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.ServiceAccount, err error) { - return c.clientGetter.ServiceAccounts(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *serviceAccountController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.ServiceAccount, error) { + result := &v1.ServiceAccount{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type serviceAccountCache struct { - lister listers.ServiceAccountLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *serviceAccountCache) Get(namespace, name string) (*v1.ServiceAccount, error) { - return c.lister.ServiceAccounts(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.ServiceAccount), nil } -func (c *serviceAccountCache) List(namespace string, selector labels.Selector) ([]*v1.ServiceAccount, error) { - return c.lister.ServiceAccounts(namespace).List(selector) +func (c *serviceAccountCache) List(namespace string, selector labels.Selector) (ret []*v1.ServiceAccount, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.ServiceAccount)) + }) + + return ret, err } func (c *serviceAccountCache) AddIndexer(indexName string, indexer ServiceAccountIndexer) { diff --git a/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/factory.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/factory.go new file mode 100644 index 0000000000..52a114505c --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/factory.go @@ -0,0 +1,67 @@ +/* +Copyright The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Code generated by main. DO NOT EDIT. + +package rbac + +import ( + "github.com/rancher/wrangler/pkg/generic" + "k8s.io/client-go/rest" +) + +type Factory struct { + *generic.Factory +} + +func NewFactoryFromConfigOrDie(config *rest.Config) *Factory { + f, err := NewFactoryFromConfig(config) + if err != nil { + panic(err) + } + return f +} + +func NewFactoryFromConfig(config *rest.Config) (*Factory, error) { + return NewFactoryFromConfigWithOptions(config, nil) +} + +func NewFactoryFromConfigWithNamespace(config *rest.Config, namespace string) (*Factory, error) { + return NewFactoryFromConfigWithOptions(config, &FactoryOptions{ + Namespace: namespace, + }) +} + +type FactoryOptions = generic.FactoryOptions + +func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { + f, err := generic.NewFactoryFromConfigWithOptions(config, opts) + return &Factory{ + Factory: f, + }, err +} + +func NewFactoryFromConfigWithOptionsOrDie(config *rest.Config, opts *FactoryOptions) *Factory { + f, err := NewFactoryFromConfigWithOptions(config, opts) + if err != nil { + panic(err) + } + return f +} + +func (c *Factory) Rbac() Interface { + return New(c.ControllerFactory()) +} diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/interface.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/interface.go similarity index 56% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/interface.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/interface.go index 572969acfb..f4bb1f982f 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/interface.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/interface.go @@ -19,10 +19,8 @@ limitations under the License. package rbac import ( - v1 "github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1" - "github.com/rancher/wrangler/pkg/generic" - informers "k8s.io/client-go/informers/rbac" - clientset "k8s.io/client-go/kubernetes" + "github.com/rancher/lasso/pkg/controller" + v1 "github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1" ) type Interface interface { @@ -30,21 +28,16 @@ type Interface interface { } type group struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.Interface + controllerFactory controller.SharedControllerFactory } // New returns a new Interface. -func New(controllerManager *generic.ControllerManager, informers informers.Interface, - client clientset.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &group{ - controllerManager: controllerManager, - informers: informers, - client: client, + controllerFactory: controllerFactory, } } func (g *group) V1() v1.Interface { - return v1.New(g.controllerManager, g.client.RbacV1(), g.informers.V1()) + return v1.New(g.controllerFactory) } diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/clusterrole.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/clusterrole.go similarity index 70% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/clusterrole.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/clusterrole.go index 8716a3e693..1c192736d5 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/clusterrole.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/clusterrole.go @@ -22,9 +22,12 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -32,9 +35,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/rbac/v1" - clientset "k8s.io/client-go/kubernetes/typed/rbac/v1" - listers "k8s.io/client-go/listers/rbac/v1" "k8s.io/client-go/tools/cache" ) @@ -74,18 +74,22 @@ type ClusterRoleCache interface { type ClusterRoleIndexer func(obj *v1.ClusterRole) ([]string, error) type clusterRoleController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.ClusterRolesGetter - informer informers.ClusterRoleInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewClusterRoleController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.ClusterRolesGetter, informer informers.ClusterRoleInformer) ClusterRoleController { +func NewClusterRoleController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ClusterRoleController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &clusterRoleController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -132,12 +136,11 @@ func UpdateClusterRoleDeepCopyOnChange(client ClusterRoleClient, obj *v1.Cluster } func (c *clusterRoleController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *clusterRoleController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *clusterRoleController) OnChange(ctx context.Context, name string, sync ClusterRoleHandler) { @@ -145,20 +148,19 @@ func (c *clusterRoleController) OnChange(ctx context.Context, name string, sync } func (c *clusterRoleController) OnRemove(ctx context.Context, name string, sync ClusterRoleHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromClusterRoleHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromClusterRoleHandlerToHandler(sync))) } func (c *clusterRoleController) Enqueue(name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), "", name) + c.controller.Enqueue("", name) } func (c *clusterRoleController) EnqueueAfter(name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), "", name, duration) + c.controller.EnqueueAfter("", name, duration) } func (c *clusterRoleController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *clusterRoleController) GroupVersionKind() schema.GroupVersionKind { @@ -167,53 +169,70 @@ func (c *clusterRoleController) GroupVersionKind() schema.GroupVersionKind { func (c *clusterRoleController) Cache() ClusterRoleCache { return &clusterRoleCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *clusterRoleController) Create(obj *v1.ClusterRole) (*v1.ClusterRole, error) { - return c.clientGetter.ClusterRoles().Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.ClusterRole{} + return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) } func (c *clusterRoleController) Update(obj *v1.ClusterRole) (*v1.ClusterRole, error) { - return c.clientGetter.ClusterRoles().Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.ClusterRole{} + return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) } func (c *clusterRoleController) Delete(name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.ClusterRoles().Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), "", name, *options) } func (c *clusterRoleController) Get(name string, options metav1.GetOptions) (*v1.ClusterRole, error) { - return c.clientGetter.ClusterRoles().Get(context.TODO(), name, options) + result := &v1.ClusterRole{} + return result, c.client.Get(context.TODO(), "", name, result, options) } func (c *clusterRoleController) List(opts metav1.ListOptions) (*v1.ClusterRoleList, error) { - return c.clientGetter.ClusterRoles().List(context.TODO(), opts) + result := &v1.ClusterRoleList{} + return result, c.client.List(context.TODO(), "", result, opts) } func (c *clusterRoleController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.ClusterRoles().Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), "", opts) } -func (c *clusterRoleController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.ClusterRole, err error) { - return c.clientGetter.ClusterRoles().Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *clusterRoleController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.ClusterRole, error) { + result := &v1.ClusterRole{} + return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) } type clusterRoleCache struct { - lister listers.ClusterRoleLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *clusterRoleCache) Get(name string) (*v1.ClusterRole, error) { - return c.lister.Get(name) + obj, exists, err := c.indexer.GetByKey(name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.ClusterRole), nil } -func (c *clusterRoleCache) List(selector labels.Selector) ([]*v1.ClusterRole, error) { - return c.lister.List(selector) +func (c *clusterRoleCache) List(selector labels.Selector) (ret []*v1.ClusterRole, err error) { + + err = cache.ListAll(c.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.ClusterRole)) + }) + + return ret, err } func (c *clusterRoleCache) AddIndexer(indexName string, indexer ClusterRoleIndexer) { diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/clusterrolebinding.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/clusterrolebinding.go similarity index 73% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/clusterrolebinding.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/clusterrolebinding.go index ceb7047651..8673b6a201 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/clusterrolebinding.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/clusterrolebinding.go @@ -22,9 +22,12 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -32,9 +35,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/rbac/v1" - clientset "k8s.io/client-go/kubernetes/typed/rbac/v1" - listers "k8s.io/client-go/listers/rbac/v1" "k8s.io/client-go/tools/cache" ) @@ -74,18 +74,22 @@ type ClusterRoleBindingCache interface { type ClusterRoleBindingIndexer func(obj *v1.ClusterRoleBinding) ([]string, error) type clusterRoleBindingController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.ClusterRoleBindingsGetter - informer informers.ClusterRoleBindingInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewClusterRoleBindingController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.ClusterRoleBindingsGetter, informer informers.ClusterRoleBindingInformer) ClusterRoleBindingController { +func NewClusterRoleBindingController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ClusterRoleBindingController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &clusterRoleBindingController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -132,12 +136,11 @@ func UpdateClusterRoleBindingDeepCopyOnChange(client ClusterRoleBindingClient, o } func (c *clusterRoleBindingController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *clusterRoleBindingController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *clusterRoleBindingController) OnChange(ctx context.Context, name string, sync ClusterRoleBindingHandler) { @@ -145,20 +148,19 @@ func (c *clusterRoleBindingController) OnChange(ctx context.Context, name string } func (c *clusterRoleBindingController) OnRemove(ctx context.Context, name string, sync ClusterRoleBindingHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromClusterRoleBindingHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromClusterRoleBindingHandlerToHandler(sync))) } func (c *clusterRoleBindingController) Enqueue(name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), "", name) + c.controller.Enqueue("", name) } func (c *clusterRoleBindingController) EnqueueAfter(name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), "", name, duration) + c.controller.EnqueueAfter("", name, duration) } func (c *clusterRoleBindingController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *clusterRoleBindingController) GroupVersionKind() schema.GroupVersionKind { @@ -167,53 +169,70 @@ func (c *clusterRoleBindingController) GroupVersionKind() schema.GroupVersionKin func (c *clusterRoleBindingController) Cache() ClusterRoleBindingCache { return &clusterRoleBindingCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *clusterRoleBindingController) Create(obj *v1.ClusterRoleBinding) (*v1.ClusterRoleBinding, error) { - return c.clientGetter.ClusterRoleBindings().Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.ClusterRoleBinding{} + return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) } func (c *clusterRoleBindingController) Update(obj *v1.ClusterRoleBinding) (*v1.ClusterRoleBinding, error) { - return c.clientGetter.ClusterRoleBindings().Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.ClusterRoleBinding{} + return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) } func (c *clusterRoleBindingController) Delete(name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.ClusterRoleBindings().Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), "", name, *options) } func (c *clusterRoleBindingController) Get(name string, options metav1.GetOptions) (*v1.ClusterRoleBinding, error) { - return c.clientGetter.ClusterRoleBindings().Get(context.TODO(), name, options) + result := &v1.ClusterRoleBinding{} + return result, c.client.Get(context.TODO(), "", name, result, options) } func (c *clusterRoleBindingController) List(opts metav1.ListOptions) (*v1.ClusterRoleBindingList, error) { - return c.clientGetter.ClusterRoleBindings().List(context.TODO(), opts) + result := &v1.ClusterRoleBindingList{} + return result, c.client.List(context.TODO(), "", result, opts) } func (c *clusterRoleBindingController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.ClusterRoleBindings().Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), "", opts) } -func (c *clusterRoleBindingController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.ClusterRoleBinding, err error) { - return c.clientGetter.ClusterRoleBindings().Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *clusterRoleBindingController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.ClusterRoleBinding, error) { + result := &v1.ClusterRoleBinding{} + return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) } type clusterRoleBindingCache struct { - lister listers.ClusterRoleBindingLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *clusterRoleBindingCache) Get(name string) (*v1.ClusterRoleBinding, error) { - return c.lister.Get(name) + obj, exists, err := c.indexer.GetByKey(name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.ClusterRoleBinding), nil } -func (c *clusterRoleBindingCache) List(selector labels.Selector) ([]*v1.ClusterRoleBinding, error) { - return c.lister.List(selector) +func (c *clusterRoleBindingCache) List(selector labels.Selector) (ret []*v1.ClusterRoleBinding, err error) { + + err = cache.ListAll(c.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.ClusterRoleBinding)) + }) + + return ret, err } func (c *clusterRoleBindingCache) AddIndexer(indexName string, indexer ClusterRoleBindingIndexer) { diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/interface.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/interface.go similarity index 51% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/interface.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/interface.go index 8c62786369..1dbb1045a0 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/interface.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/interface.go @@ -19,12 +19,16 @@ limitations under the License. package v1 import ( - "github.com/rancher/wrangler/pkg/generic" + "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/rbac/v1" - informers "k8s.io/client-go/informers/rbac/v1" - clientset "k8s.io/client-go/kubernetes/typed/rbac/v1" + "k8s.io/apimachinery/pkg/runtime/schema" ) +func init() { + schemes.Register(v1.AddToScheme) +} + type Interface interface { ClusterRole() ClusterRoleController ClusterRoleBinding() ClusterRoleBindingController @@ -32,30 +36,25 @@ type Interface interface { RoleBinding() RoleBindingController } -func New(controllerManager *generic.ControllerManager, client clientset.RbacV1Interface, - informers informers.Interface) Interface { +func New(controllerFactory controller.SharedControllerFactory) Interface { return &version{ - controllerManager: controllerManager, - client: client, - informers: informers, + controllerFactory: controllerFactory, } } type version struct { - controllerManager *generic.ControllerManager - informers informers.Interface - client clientset.RbacV1Interface + controllerFactory controller.SharedControllerFactory } func (c *version) ClusterRole() ClusterRoleController { - return NewClusterRoleController(v1.SchemeGroupVersion.WithKind("ClusterRole"), c.controllerManager, c.client, c.informers.ClusterRoles()) + return NewClusterRoleController(schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRole"}, "clusterroles", false, c.controllerFactory) } func (c *version) ClusterRoleBinding() ClusterRoleBindingController { - return NewClusterRoleBindingController(v1.SchemeGroupVersion.WithKind("ClusterRoleBinding"), c.controllerManager, c.client, c.informers.ClusterRoleBindings()) + return NewClusterRoleBindingController(schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRoleBinding"}, "clusterrolebindings", false, c.controllerFactory) } func (c *version) Role() RoleController { - return NewRoleController(v1.SchemeGroupVersion.WithKind("Role"), c.controllerManager, c.client, c.informers.Roles()) + return NewRoleController(schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "Role"}, "roles", true, c.controllerFactory) } func (c *version) RoleBinding() RoleBindingController { - return NewRoleBindingController(v1.SchemeGroupVersion.WithKind("RoleBinding"), c.controllerManager, c.client, c.informers.RoleBindings()) + return NewRoleBindingController(schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "RoleBinding"}, "rolebindings", true, c.controllerFactory) } diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/role.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/role.go similarity index 70% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/role.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/role.go index 8229c45924..a3b113eae6 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/role.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/role.go @@ -22,9 +22,12 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -32,9 +35,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/rbac/v1" - clientset "k8s.io/client-go/kubernetes/typed/rbac/v1" - listers "k8s.io/client-go/listers/rbac/v1" "k8s.io/client-go/tools/cache" ) @@ -74,18 +74,22 @@ type RoleCache interface { type RoleIndexer func(obj *v1.Role) ([]string, error) type roleController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.RolesGetter - informer informers.RoleInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewRoleController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.RolesGetter, informer informers.RoleInformer) RoleController { +func NewRoleController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) RoleController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &roleController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -132,12 +136,11 @@ func UpdateRoleDeepCopyOnChange(client RoleClient, obj *v1.Role, handler func(ob } func (c *roleController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *roleController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *roleController) OnChange(ctx context.Context, name string, sync RoleHandler) { @@ -145,20 +148,19 @@ func (c *roleController) OnChange(ctx context.Context, name string, sync RoleHan } func (c *roleController) OnRemove(ctx context.Context, name string, sync RoleHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromRoleHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromRoleHandlerToHandler(sync))) } func (c *roleController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *roleController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *roleController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *roleController) GroupVersionKind() schema.GroupVersionKind { @@ -167,53 +169,70 @@ func (c *roleController) GroupVersionKind() schema.GroupVersionKind { func (c *roleController) Cache() RoleCache { return &roleCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *roleController) Create(obj *v1.Role) (*v1.Role, error) { - return c.clientGetter.Roles(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.Role{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *roleController) Update(obj *v1.Role) (*v1.Role, error) { - return c.clientGetter.Roles(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.Role{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *roleController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.Roles(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *roleController) Get(namespace, name string, options metav1.GetOptions) (*v1.Role, error) { - return c.clientGetter.Roles(namespace).Get(context.TODO(), name, options) + result := &v1.Role{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *roleController) List(namespace string, opts metav1.ListOptions) (*v1.RoleList, error) { - return c.clientGetter.Roles(namespace).List(context.TODO(), opts) + result := &v1.RoleList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *roleController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.Roles(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *roleController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Role, err error) { - return c.clientGetter.Roles(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *roleController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Role, error) { + result := &v1.Role{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type roleCache struct { - lister listers.RoleLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *roleCache) Get(namespace, name string) (*v1.Role, error) { - return c.lister.Roles(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.Role), nil } -func (c *roleCache) List(namespace string, selector labels.Selector) ([]*v1.Role, error) { - return c.lister.Roles(namespace).List(selector) +func (c *roleCache) List(namespace string, selector labels.Selector) (ret []*v1.Role, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.Role)) + }) + + return ret, err } func (c *roleCache) AddIndexer(indexName string, indexer RoleIndexer) { diff --git a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/rolebinding.go b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/rolebinding.go similarity index 71% rename from vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/rolebinding.go rename to vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/rolebinding.go index 0ef3f1077a..383ffa15d8 100644 --- a/vendor/github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1/rolebinding.go +++ b/vendor/github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1/rolebinding.go @@ -22,9 +22,12 @@ import ( "context" "time" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/equality" + "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" @@ -32,9 +35,6 @@ import ( "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - informers "k8s.io/client-go/informers/rbac/v1" - clientset "k8s.io/client-go/kubernetes/typed/rbac/v1" - listers "k8s.io/client-go/listers/rbac/v1" "k8s.io/client-go/tools/cache" ) @@ -74,18 +74,22 @@ type RoleBindingCache interface { type RoleBindingIndexer func(obj *v1.RoleBinding) ([]string, error) type roleBindingController struct { - controllerManager *generic.ControllerManager - clientGetter clientset.RoleBindingsGetter - informer informers.RoleBindingInformer - gvk schema.GroupVersionKind + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource } -func NewRoleBindingController(gvk schema.GroupVersionKind, controllerManager *generic.ControllerManager, clientGetter clientset.RoleBindingsGetter, informer informers.RoleBindingInformer) RoleBindingController { +func NewRoleBindingController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) RoleBindingController { + c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) return &roleBindingController{ - controllerManager: controllerManager, - clientGetter: clientGetter, - informer: informer, - gvk: gvk, + controller: c, + client: c.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, } } @@ -132,12 +136,11 @@ func UpdateRoleBindingDeepCopyOnChange(client RoleBindingClient, obj *v1.RoleBin } func (c *roleBindingController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, handler) + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) } func (c *roleBindingController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), handler) - c.controllerManager.AddHandler(ctx, c.gvk, c.informer.Informer(), name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) } func (c *roleBindingController) OnChange(ctx context.Context, name string, sync RoleBindingHandler) { @@ -145,20 +148,19 @@ func (c *roleBindingController) OnChange(ctx context.Context, name string, sync } func (c *roleBindingController) OnRemove(ctx context.Context, name string, sync RoleBindingHandler) { - removeHandler := generic.NewRemoveHandler(name, c.Updater(), FromRoleBindingHandlerToHandler(sync)) - c.AddGenericHandler(ctx, name, removeHandler) + c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromRoleBindingHandlerToHandler(sync))) } func (c *roleBindingController) Enqueue(namespace, name string) { - c.controllerManager.Enqueue(c.gvk, c.informer.Informer(), namespace, name) + c.controller.Enqueue(namespace, name) } func (c *roleBindingController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controllerManager.EnqueueAfter(c.gvk, c.informer.Informer(), namespace, name, duration) + c.controller.EnqueueAfter(namespace, name, duration) } func (c *roleBindingController) Informer() cache.SharedIndexInformer { - return c.informer.Informer() + return c.controller.Informer() } func (c *roleBindingController) GroupVersionKind() schema.GroupVersionKind { @@ -167,53 +169,70 @@ func (c *roleBindingController) GroupVersionKind() schema.GroupVersionKind { func (c *roleBindingController) Cache() RoleBindingCache { return &roleBindingCache{ - lister: c.informer.Lister(), - indexer: c.informer.Informer().GetIndexer(), + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, } } func (c *roleBindingController) Create(obj *v1.RoleBinding) (*v1.RoleBinding, error) { - return c.clientGetter.RoleBindings(obj.Namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) + result := &v1.RoleBinding{} + return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) } func (c *roleBindingController) Update(obj *v1.RoleBinding) (*v1.RoleBinding, error) { - return c.clientGetter.RoleBindings(obj.Namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) + result := &v1.RoleBinding{} + return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) } func (c *roleBindingController) Delete(namespace, name string, options *metav1.DeleteOptions) error { if options == nil { options = &metav1.DeleteOptions{} } - return c.clientGetter.RoleBindings(namespace).Delete(context.TODO(), name, *options) + return c.client.Delete(context.TODO(), namespace, name, *options) } func (c *roleBindingController) Get(namespace, name string, options metav1.GetOptions) (*v1.RoleBinding, error) { - return c.clientGetter.RoleBindings(namespace).Get(context.TODO(), name, options) + result := &v1.RoleBinding{} + return result, c.client.Get(context.TODO(), namespace, name, result, options) } func (c *roleBindingController) List(namespace string, opts metav1.ListOptions) (*v1.RoleBindingList, error) { - return c.clientGetter.RoleBindings(namespace).List(context.TODO(), opts) + result := &v1.RoleBindingList{} + return result, c.client.List(context.TODO(), namespace, result, opts) } func (c *roleBindingController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.clientGetter.RoleBindings(namespace).Watch(context.TODO(), opts) + return c.client.Watch(context.TODO(), namespace, opts) } -func (c *roleBindingController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.RoleBinding, err error) { - return c.clientGetter.RoleBindings(namespace).Patch(context.TODO(), name, pt, data, metav1.PatchOptions{}, subresources...) +func (c *roleBindingController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.RoleBinding, error) { + result := &v1.RoleBinding{} + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) } type roleBindingCache struct { - lister listers.RoleBindingLister - indexer cache.Indexer + indexer cache.Indexer + resource schema.GroupResource } func (c *roleBindingCache) Get(namespace, name string) (*v1.RoleBinding, error) { - return c.lister.RoleBindings(namespace).Get(name) + obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(c.resource, name) + } + return obj.(*v1.RoleBinding), nil } -func (c *roleBindingCache) List(namespace string, selector labels.Selector) ([]*v1.RoleBinding, error) { - return c.lister.RoleBindings(namespace).List(selector) +func (c *roleBindingCache) List(namespace string, selector labels.Selector) (ret []*v1.RoleBinding, err error) { + + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.RoleBinding)) + }) + + return ret, err } func (c *roleBindingCache) AddIndexer(indexName string, indexer RoleBindingIndexer) { diff --git a/vendor/github.com/rancher/wrangler/pkg/generic/controller.go b/vendor/github.com/rancher/wrangler/pkg/generic/controller.go index 4608875e44..d713e0f2be 100644 --- a/vendor/github.com/rancher/wrangler/pkg/generic/controller.go +++ b/vendor/github.com/rancher/wrangler/pkg/generic/controller.go @@ -1,53 +1,19 @@ -/* -Copyright 2017 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - package generic import ( "context" - errors2 "errors" - "fmt" - "strings" - "time" - errors3 "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "github.com/rancher/lasso/pkg/controller" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" ) -var ErrSkip = errors2.New("skip processing") +var ErrSkip = controller.ErrIgnore type Handler func(key string, obj runtime.Object) (runtime.Object, error) -// Controller is the controller implementation for Foo resources -type Controller struct { - name string - workqueue workqueue.RateLimitingInterface - informer cache.SharedIndexInformer - handler Handler - gvk schema.GroupVersionKind -} - type ControllerMeta interface { Informer() cache.SharedIndexInformer GroupVersionKind() schema.GroupVersionKind @@ -56,164 +22,3 @@ type ControllerMeta interface { AddGenericRemoveHandler(ctx context.Context, name string, handler Handler) Updater() Updater } - -// NewController returns a new sample controller -func NewController(gvk schema.GroupVersionKind, informer cache.SharedIndexInformer, workqueue workqueue.RateLimitingInterface, handler Handler) *Controller { - controller := &Controller{ - name: gvk.String(), - handler: handler, - informer: informer, - workqueue: workqueue, - } - - informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: controller.handleObject, - UpdateFunc: func(old, new interface{}) { - newMeta, err := meta.Accessor(new) - utilruntime.Must(err) - oldMeta, err := meta.Accessor(old) - utilruntime.Must(err) - if newMeta.GetResourceVersion() == oldMeta.GetResourceVersion() { - return - } - controller.handleObject(new) - }, - DeleteFunc: controller.handleObject, - }) - - return controller -} - -func (c *Controller) Informer() cache.SharedIndexInformer { - return c.informer -} - -func (c *Controller) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *Controller) run(threadiness int, stopCh <-chan struct{}) { - defer utilruntime.HandleCrash() - defer c.workqueue.ShutDown() - - // Start the informer factories to begin populating the informer caches - logrus.Infof("Starting %s controller", c.name) - - // Launch two workers to process Foo resources - for i := 0; i < threadiness; i++ { - go wait.Until(c.runWorker, time.Second, stopCh) - } - - <-stopCh - logrus.Infof("Shutting down %s workers", c.name) -} - -func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error { - if ok := cache.WaitForCacheSync(stopCh, c.informer.HasSynced); !ok { - c.workqueue.ShutDown() - return fmt.Errorf("failed to wait for caches to sync") - } - - go c.run(threadiness, stopCh) - return nil -} - -func (c *Controller) runWorker() { - for c.processNextWorkItem() { - } -} - -func (c *Controller) processNextWorkItem() bool { - obj, shutdown := c.workqueue.Get() - - if shutdown { - return false - } - - if err := c.processSingleItem(obj); err != nil { - if !strings.Contains(err.Error(), "please apply your changes to the latest version and try again") { - utilruntime.HandleError(err) - } - return true - } - - return true -} - -func (c *Controller) processSingleItem(obj interface{}) error { - var ( - key string - ok bool - ) - - defer c.workqueue.Done(obj) - - if key, ok = obj.(string); !ok { - c.workqueue.Forget(obj) - utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj)) - return nil - } - if err := c.syncHandler(key); err != nil && errors3.Cause(err) != ErrSkip { - c.workqueue.AddRateLimited(key) - return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error()) - } - - c.workqueue.Forget(obj) - return nil -} - -func (c *Controller) syncHandler(key string) error { - obj, exists, err := c.informer.GetStore().GetByKey(key) - if err != nil { - return err - } - if !exists { - _, err := c.handler(key, nil) - return err - } - - _, err = c.handler(key, obj.(runtime.Object)) - return err -} - -func (c *Controller) Enqueue(namespace, name string) { - if namespace == "" { - c.workqueue.AddRateLimited(name) - } else { - c.workqueue.AddRateLimited(namespace + "/" + name) - } -} - -func (c *Controller) EnqueueAfter(namespace, name string, duration time.Duration) { - if namespace == "" { - c.workqueue.AddAfter(name, duration) - } else { - c.workqueue.AddAfter(namespace+"/"+name, duration) - } -} - -func (c *Controller) enqueue(obj interface{}) { - var key string - var err error - if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { - utilruntime.HandleError(err) - return - } - c.workqueue.Add(key) -} - -func (c *Controller) handleObject(obj interface{}) { - if _, ok := obj.(metav1.Object); !ok { - tombstone, ok := obj.(cache.DeletedFinalStateUnknown) - if !ok { - utilruntime.HandleError(fmt.Errorf("error decoding object, invalid type")) - return - } - _, ok = tombstone.Obj.(metav1.Object) - if !ok { - utilruntime.HandleError(fmt.Errorf("error decoding object tombstone, invalid type")) - return - } - } - c.enqueue(obj) -} diff --git a/vendor/github.com/rancher/wrangler/pkg/generic/controllerfactory.go b/vendor/github.com/rancher/wrangler/pkg/generic/controllerfactory.go deleted file mode 100644 index 9c490ec02c..0000000000 --- a/vendor/github.com/rancher/wrangler/pkg/generic/controllerfactory.go +++ /dev/null @@ -1,195 +0,0 @@ -package generic - -import ( - "context" - "strings" - "sync" - "time" - - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/util/workqueue" -) - -type ControllerManager struct { - lock sync.Mutex - generation int - started map[schema.GroupVersionKind]bool - controllers map[schema.GroupVersionKind]*Controller - handlers map[schema.GroupVersionKind]*Handlers -} - -func (g *ControllerManager) Controllers() map[schema.GroupVersionKind]*Controller { - return g.controllers -} - -func (g *ControllerManager) EnsureStart(ctx context.Context, gvk schema.GroupVersionKind, threadiness int) error { - g.lock.Lock() - defer g.lock.Unlock() - - return g.startController(ctx, gvk, threadiness) -} - -func (g *ControllerManager) startController(ctx context.Context, gvk schema.GroupVersionKind, threadiness int) error { - if g.started[gvk] { - return nil - } - - controller, ok := g.controllers[gvk] - if !ok { - return nil - } - - if err := controller.Run(threadiness, ctx.Done()); err != nil { - return err - } - - if g.started == nil { - g.started = map[schema.GroupVersionKind]bool{} - } - g.started[gvk] = true - - go func() { - <-ctx.Done() - g.lock.Lock() - defer g.lock.Unlock() - - delete(g.started, gvk) - delete(g.controllers, gvk) - }() - - return nil -} - -func (g *ControllerManager) Start(ctx context.Context, defaultThreadiness int, threadiness map[schema.GroupVersionKind]int) error { - g.lock.Lock() - defer g.lock.Unlock() - - for gvk := range g.controllers { - threadiness, ok := threadiness[gvk] - if !ok { - threadiness = defaultThreadiness - } - if err := g.startController(ctx, gvk, threadiness); err != nil { - return err - } - } - - return nil -} - -func (g *ControllerManager) Enqueue(gvk schema.GroupVersionKind, informer cache.SharedIndexInformer, namespace, name string) { - _, controller, _ := g.getController(gvk, informer, true) - - if namespace == "*" || name == "*" { - for _, key := range informer.GetStore().ListKeys() { - if namespace != "" && namespace != "*" && !strings.HasPrefix(key, namespace+"/") { - continue - } - if name != "*" && !nameMatches(key, name) { - continue - } - controller.workqueue.AddRateLimited(key) - } - } else { - controller.Enqueue(namespace, name) - } -} - -func nameMatches(key, name string) bool { - return key == name || strings.HasSuffix(key, "/"+name) -} - -func (g *ControllerManager) EnqueueAfter(gvk schema.GroupVersionKind, informer cache.SharedIndexInformer, namespace, name string, duration time.Duration) { - _, controller, _ := g.getController(gvk, informer, true) - controller.EnqueueAfter(namespace, name, duration) -} - -func (g *ControllerManager) removeHandler(gvk schema.GroupVersionKind, generation int) { - g.lock.Lock() - defer g.lock.Unlock() - - handlers, ok := g.handlers[gvk] - if !ok { - return - } - - var newHandlers []handlerEntry - for _, h := range handlers.handlers { - if h.generation == generation { - continue - } - newHandlers = append(newHandlers, h) - } - - handlers.handlers = newHandlers -} - -func (g *ControllerManager) getController(gvk schema.GroupVersionKind, informer cache.SharedIndexInformer, lock bool) (*Handlers, *Controller, bool) { - if lock { - g.lock.Lock() - defer g.lock.Unlock() - } - - if controller, ok := g.controllers[gvk]; ok { - return g.handlers[gvk], controller, true - } - - handlers := &Handlers{} - - queue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), gvk.String()) - controller := NewController(gvk, informer, queue, handlers.Handle) - - if g.handlers == nil { - g.handlers = map[schema.GroupVersionKind]*Handlers{} - } - - if g.controllers == nil { - g.controllers = map[schema.GroupVersionKind]*Controller{} - } - - g.handlers[gvk] = handlers - g.controllers[gvk] = controller - - return handlers, controller, false -} - -func (g *ControllerManager) AddHandler(ctx context.Context, gvk schema.GroupVersionKind, informer cache.SharedIndexInformer, name string, handler Handler) { - t := getHandlerTransaction(ctx) - if t == nil { - g.addHandler(ctx, gvk, informer, name, handler) - return - } - - go func() { - if t.shouldContinue() { - g.addHandler(ctx, gvk, informer, name, handler) - } - }() -} - -func (g *ControllerManager) addHandler(ctx context.Context, gvk schema.GroupVersionKind, informer cache.SharedIndexInformer, name string, handler Handler) { - g.lock.Lock() - defer g.lock.Unlock() - - g.generation++ - entry := handlerEntry{ - generation: g.generation, - name: name, - handler: handler, - } - - go func() { - <-ctx.Done() - g.removeHandler(gvk, entry.generation) - }() - - handlers, controller, ok := g.getController(gvk, informer, false) - handlers.handlers = append(handlers.handlers, entry) - - if ok { - for _, key := range controller.informer.GetStore().ListKeys() { - controller.workqueue.Add(key) - } - } -} diff --git a/vendor/github.com/rancher/wrangler/pkg/generic/factory.go b/vendor/github.com/rancher/wrangler/pkg/generic/factory.go new file mode 100644 index 0000000000..946af86582 --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/generic/factory.go @@ -0,0 +1,122 @@ +package generic + +import ( + "context" + "sync" + "time" + + "github.com/rancher/lasso/pkg/log" + "github.com/sirupsen/logrus" + + "github.com/rancher/lasso/pkg/cache" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/schemes" + "k8s.io/apimachinery/pkg/runtime/schema" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/client-go/rest" +) + +func init() { + log.Infof = logrus.Infof + log.Errorf = logrus.Errorf +} + +type Factory struct { + lock sync.Mutex + cacheFactory cache.SharedCacheFactory + controllerFactory controller.SharedControllerFactory + threadiness map[schema.GroupVersionKind]int + config *rest.Config + opts FactoryOptions +} + +type FactoryOptions struct { + Namespace string + Resync time.Duration + SharedCacheFactory cache.SharedCacheFactory + SharedControllerFactory controller.SharedControllerFactory + HealthCallback func(bool) +} + +func NewFactoryFromConfigWithOptions(config *rest.Config, opts *FactoryOptions) (*Factory, error) { + if opts == nil { + opts = &FactoryOptions{} + } + + f := &Factory{ + config: config, + threadiness: map[schema.GroupVersionKind]int{}, + cacheFactory: opts.SharedCacheFactory, + controllerFactory: opts.SharedControllerFactory, + opts: *opts, + } + + if f.cacheFactory == nil && f.controllerFactory != nil { + f.cacheFactory = f.controllerFactory.SharedCacheFactory() + } + + return f, nil +} + +func (c *Factory) SetThreadiness(gvk schema.GroupVersionKind, threadiness int) { + c.threadiness[gvk] = threadiness +} + +func (c *Factory) ControllerFactory() controller.SharedControllerFactory { + err := c.setControllerFactoryWithLock() + utilruntime.Must(err) + return c.controllerFactory +} + +func (c *Factory) setControllerFactoryWithLock() error { + c.lock.Lock() + defer c.lock.Unlock() + + if c.controllerFactory != nil { + return nil + } + + cacheFactory := c.cacheFactory + if cacheFactory == nil { + client, err := client.NewSharedClientFactory(c.config, &client.SharedClientFactoryOptions{ + Scheme: schemes.All, + }) + if err != nil { + return err + } + + cacheFactory = cache.NewSharedCachedFactory(client, &cache.SharedCacheFactoryOptions{ + DefaultNamespace: c.opts.Namespace, + DefaultResync: c.opts.Resync, + HealthCallback: c.opts.HealthCallback, + }) + } + + c.cacheFactory = cacheFactory + c.controllerFactory = controller.NewSharedControllerFactory(cacheFactory, &controller.SharedControllerFactoryOptions{ + KindWorkers: c.threadiness, + }) + + return nil +} + +func (c *Factory) Sync(ctx context.Context) error { + if c.cacheFactory != nil { + c.cacheFactory.Start(ctx) + c.cacheFactory.WaitForCacheSync(ctx) + } + return nil +} + +func (c *Factory) Start(ctx context.Context, defaultThreadiness int) error { + if err := c.Sync(ctx); err != nil { + return err + } + + if c.controllerFactory != nil { + return c.controllerFactory.Start(ctx, defaultThreadiness) + } + + return nil +} diff --git a/vendor/github.com/rancher/wrangler/pkg/generic/handlers.go b/vendor/github.com/rancher/wrangler/pkg/generic/handlers.go deleted file mode 100644 index 9af89ae45e..0000000000 --- a/vendor/github.com/rancher/wrangler/pkg/generic/handlers.go +++ /dev/null @@ -1,96 +0,0 @@ -package generic - -import ( - "fmt" - "reflect" - "strings" - - errors2 "github.com/pkg/errors" - "k8s.io/apimachinery/pkg/runtime" -) - -type handlerEntry struct { - generation int - name string - handler Handler -} - -type Handlers struct { - handlers []handlerEntry -} - -func (h *Handlers) Handle(key string, obj runtime.Object) (runtime.Object, error) { - var ( - errs errors - ) - - for _, handler := range h.handlers { - newObj, err := handler.handler(key, obj) - if err != nil && errors2.Cause(err) != ErrSkip { - errs = append(errs, &handlerError{ - HandlerName: handler.name, - Err: err, - }) - } - if newObj != nil { - obj = newObj - } - } - - return obj, errs.ToErr() -} - -type errors []error - -func (e errors) Error() string { - buf := strings.Builder{} - for _, err := range e { - if buf.Len() > 0 { - buf.WriteString(", ") - } - buf.WriteString(err.Error()) - } - return buf.String() -} - -func (e errors) ToErr() error { - switch len(e) { - case 0: - return nil - case 1: - return e[0] - default: - return e - } -} - -func (e errors) Cause() error { - if len(e) > 0 { - return e[0] - } - return nil -} - -type handlerError struct { - HandlerName string - Err error -} - -func (h handlerError) Error() string { - return fmt.Sprintf("handler %s: %v", h.HandlerName, h.Err) -} - -func (h handlerError) Cause() error { - return h.Err -} - -func ToName(h interface{}) string { - if str, ok := h.(fmt.Stringer); ok { - return str.String() - } - s := reflect.ValueOf(h).Type().String() - if len(s) > 1 && s[0] == '*' { - return s[1:] - } - return s -} diff --git a/vendor/github.com/rancher/wrangler/pkg/leader/manager.go b/vendor/github.com/rancher/wrangler/pkg/leader/manager.go new file mode 100644 index 0000000000..5bb2fdd4dc --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/leader/manager.go @@ -0,0 +1,59 @@ +package leader + +import ( + "context" + "sync" + "time" + + "github.com/sirupsen/logrus" + "k8s.io/client-go/kubernetes" +) + +type Manager struct { + sync.Mutex + leaderChan chan struct{} + leaderStarted bool + leaderCTX context.Context + namespace string + name string + k8s kubernetes.Interface +} + +func NewManager(namespace, name string, k8s kubernetes.Interface) *Manager { + return &Manager{ + leaderChan: make(chan struct{}), + namespace: namespace, + name: name, + k8s: k8s, + } +} + +func (m *Manager) Start(ctx context.Context) { + m.Lock() + defer m.Unlock() + + if m.leaderStarted { + return + } + + m.leaderStarted = true + go RunOrDie(ctx, m.namespace, m.name, m.k8s, func(ctx context.Context) { + m.leaderCTX = ctx + close(m.leaderChan) + }) +} + +// OnLeader this function will be called when leadership is acquired. +func (m *Manager) OnLeader(f func(ctx context.Context) error) { + go func() { + <-m.leaderChan + for { + if err := f(m.leaderCTX); err != nil { + logrus.Errorf("failed to call leader func: %v", err) + time.Sleep(5 * time.Second) + continue + } + break + } + }() +} diff --git a/vendor/github.com/rancher/wrangler/pkg/name/name.go b/vendor/github.com/rancher/wrangler/pkg/name/name.go index c75507044c..b9a01beff5 100644 --- a/vendor/github.com/rancher/wrangler/pkg/name/name.go +++ b/vendor/github.com/rancher/wrangler/pkg/name/name.go @@ -51,9 +51,16 @@ func Hex(s string, length int) string { func SafeConcatName(name ...string) string { fullPath := strings.Join(name, "-") - if len(fullPath) > 63 { - digest := sha256.Sum256([]byte(fullPath)) + if len(fullPath) < 64 { + return fullPath + } + digest := sha256.Sum256([]byte(fullPath)) + // since we cut the string in the middle, the last char may not be compatible with what is expected in k8s + // we are checking and if necessary removing the last char + c := fullPath[56] + if 'a' <= c && c <= 'z' || '0' <= c && c <= '9' { return fullPath[0:57] + "-" + hex.EncodeToString(digest[0:])[0:5] } - return fullPath + + return fullPath[0:56] + "-" + hex.EncodeToString(digest[0:])[0:6] } diff --git a/vendor/github.com/rancher/wrangler/pkg/objectset/objectset.go b/vendor/github.com/rancher/wrangler/pkg/objectset/objectset.go index f8703dfd91..5c041dadf3 100644 --- a/vendor/github.com/rancher/wrangler/pkg/objectset/objectset.go +++ b/vendor/github.com/rancher/wrangler/pkg/objectset/objectset.go @@ -64,17 +64,19 @@ func (o ObjectByGVK) Add(obj runtime.Object) (schema.GroupVersionKind, error) { } type ObjectSet struct { - errs []error - objects ObjectByGVK - order []runtime.Object - gvkOrder []schema.GroupVersionKind - gvkSeen map[schema.GroupVersionKind]bool + errs []error + objects ObjectByGVK + objectsByGK ObjectByGK + order []runtime.Object + gvkOrder []schema.GroupVersionKind + gvkSeen map[schema.GroupVersionKind]bool } func NewObjectSet(objs ...runtime.Object) *ObjectSet { os := &ObjectSet{ - objects: ObjectByGVK{}, - gvkSeen: map[schema.GroupVersionKind]bool{}, + objects: ObjectByGVK{}, + objectsByGK: ObjectByGK{}, + gvkSeen: map[schema.GroupVersionKind]bool{}, } os.Add(objs...) return os @@ -87,6 +89,11 @@ func (o *ObjectSet) ObjectsByGVK() ObjectByGVK { return o.objects } +func (o *ObjectSet) Contains(gk schema.GroupKind, key ObjectKey) bool { + _, ok := o.objectsByGK[gk][key] + return ok +} + func (o *ObjectSet) All() []runtime.Object { return o.order } @@ -109,6 +116,12 @@ func (o *ObjectSet) add(obj runtime.Object) { return } + _, err = o.objectsByGK.Add(obj) + if err != nil { + o.err(errors.Wrapf(err, "failed to add %T", obj)) + return + } + o.order = append(o.order, obj) if !o.gvkSeen[gvk] { o.gvkSeen[gvk] = true @@ -153,3 +166,32 @@ func (o *ObjectSet) GVKOrder(known ...schema.GroupVersionKind) []schema.GroupVer return append(o.gvkOrder, rest...) } + +type ObjectByGK map[schema.GroupKind]map[ObjectKey]runtime.Object + +func (o ObjectByGK) Add(obj runtime.Object) (schema.GroupKind, error) { + metadata, err := meta.Accessor(obj) + if err != nil { + return schema.GroupKind{}, err + } + + gvk, err := gvk.Get(obj) + if err != nil { + return schema.GroupKind{}, err + } + + gk := gvk.GroupKind() + + objs := o[gk] + if objs == nil { + objs = map[ObjectKey]runtime.Object{} + o[gk] = objs + } + + objs[ObjectKey{ + Namespace: metadata.GetNamespace(), + Name: metadata.GetName(), + }] = obj + + return gk, nil +} diff --git a/vendor/github.com/rancher/wrangler/pkg/patch/style.go b/vendor/github.com/rancher/wrangler/pkg/patch/style.go index eaa8d2120a..88135c8d54 100644 --- a/vendor/github.com/rancher/wrangler/pkg/patch/style.go +++ b/vendor/github.com/rancher/wrangler/pkg/patch/style.go @@ -56,7 +56,7 @@ func GetMergeStyle(gvk schema.GroupVersionKind) (types.PatchType, strategicpatch versionedObject, err := scheme.Scheme.New(gvk) - if runtime.IsNotRegisteredError(err) { + if runtime.IsNotRegisteredError(err) || gvk.Kind == "CustomResourceDefinition" { patchType = types.MergePatchType } else if err != nil { return patchType, nil, err diff --git a/vendor/github.com/rancher/wrangler/pkg/relatedresource/all.go b/vendor/github.com/rancher/wrangler/pkg/relatedresource/all.go new file mode 100644 index 0000000000..c8def937cc --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/relatedresource/all.go @@ -0,0 +1,16 @@ +package relatedresource + +import "k8s.io/apimachinery/pkg/runtime" + +const ( + AllKey = "_all_" +) + +func TriggerAllKey(namespace, name string, obj runtime.Object) ([]Key, error) { + if name != AllKey { + return []Key{{ + Name: AllKey, + }}, nil + } + return nil, nil +} diff --git a/vendor/github.com/rancher/wrangler/pkg/relatedresource/changeset.go b/vendor/github.com/rancher/wrangler/pkg/relatedresource/changeset.go index 8bb1e214ee..991d010d19 100644 --- a/vendor/github.com/rancher/wrangler/pkg/relatedresource/changeset.go +++ b/vendor/github.com/rancher/wrangler/pkg/relatedresource/changeset.go @@ -2,6 +2,7 @@ package relatedresource import ( "context" + "time" "k8s.io/apimachinery/pkg/api/meta" @@ -23,6 +24,10 @@ func NewKey(namespace, name string) Key { } } +func FromString(key string) Key { + return NewKey(kv.RSplit(key, "/")) +} + type ControllerWrapper interface { Informer() cache.SharedIndexInformer AddGenericHandler(ctx context.Context, name string, handler generic.Handler) @@ -76,12 +81,15 @@ func watch(ctx context.Context, name string, enq Enqueuer, resolve Resolver, con return } - runResolve(meta.GetNamespace(), meta.GetName(), ro) + go func() { + time.Sleep(time.Second) + runResolve(meta.GetNamespace(), meta.GetName(), ro) + }() }, }) controller.AddGenericHandler(ctx, name, func(key string, obj runtime.Object) (runtime.Object, error) { - ns, name := kv.Split(key, "/") + ns, name := kv.RSplit(key, "/") return obj, runResolve(ns, name, obj) }) } diff --git a/vendor/github.com/rancher/wrangler/pkg/relatedresource/owner.go b/vendor/github.com/rancher/wrangler/pkg/relatedresource/owner.go new file mode 100644 index 0000000000..236bd99188 --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/relatedresource/owner.go @@ -0,0 +1,38 @@ +package relatedresource + +import ( + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/runtime" +) + +// OwnerResolver Look for owner references that match the apiVersion and kind and resolve to the namespace and +// name of the parent. The namespaced flag is whether the apiVersion/kind referenced is expected to be namespaced +func OwnerResolver(namespaced bool, apiVersion, kind string) Resolver { + return func(namespace, name string, obj runtime.Object) ([]Key, error) { + if obj == nil { + return nil, nil + } + + meta, err := meta.Accessor(obj) + if err != nil { + // ignore err + return nil, nil + } + + var result []Key + for _, owner := range meta.GetOwnerReferences() { + if owner.Kind == kind && owner.APIVersion == apiVersion { + ns := "" + if namespaced { + ns = meta.GetNamespace() + } + result = append(result, Key{ + Namespace: ns, + Name: owner.Name, + }) + } + } + + return result, nil + } +} diff --git a/vendor/github.com/rancher/wrangler/pkg/schemas/openapi/generate.go b/vendor/github.com/rancher/wrangler/pkg/schemas/openapi/generate.go index 5f64e6632e..4d647a77ea 100644 --- a/vendor/github.com/rancher/wrangler/pkg/schemas/openapi/generate.go +++ b/vendor/github.com/rancher/wrangler/pkg/schemas/openapi/generate.go @@ -3,21 +3,15 @@ package openapi import ( "encoding/json" "fmt" + "sort" + "strings" types "github.com/rancher/wrangler/pkg/schemas" "github.com/rancher/wrangler/pkg/schemas/definition" - "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" + v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" ) -var ( - blacklistFields = map[string]bool{ - "kind": true, - "apiVersion": true, - "metadata": true, - } -) - -func MustGenerate(obj interface{}) *v1beta1.JSONSchemaProps { +func MustGenerate(obj interface{}) *v1.JSONSchemaProps { if obj == nil { return nil } @@ -28,17 +22,17 @@ func MustGenerate(obj interface{}) *v1beta1.JSONSchemaProps { return result } -func ToOpenAPIFromStruct(obj interface{}) (*v1beta1.JSONSchemaProps, error) { +func ToOpenAPIFromStruct(obj interface{}) (*v1.JSONSchemaProps, error) { schemas := types.EmptySchemas() schema, err := schemas.Import(obj) if err != nil { return nil, err } - return toOpenAPI(schema.ID, schemas) + return ToOpenAPI(schema.ID, schemas) } -func toOpenAPI(name string, schemas *types.Schemas) (*v1beta1.JSONSchemaProps, error) { +func ToOpenAPI(name string, schemas *types.Schemas) (*v1.JSONSchemaProps, error) { schema := schemas.Schema(name) if schema == nil { return nil, fmt.Errorf("failed to find schema: %s", name) @@ -55,7 +49,7 @@ func toOpenAPI(name string, schemas *types.Schemas) (*v1beta1.JSONSchemaProps, e return schemaToProps(newSchema, schemas, map[string]bool{}) } -func populateField(fieldJSP *v1beta1.JSONSchemaProps, f *types.Field) error { +func populateField(fieldJSP *v1.JSONSchemaProps, f *types.Field) error { fieldJSP.Description = f.Description // don't reset this to not nullable if f.Nullable { @@ -70,7 +64,7 @@ func populateField(fieldJSP *v1beta1.JSONSchemaProps, f *types.Field) error { if err != nil { return err } - fieldJSP.Enum = append(fieldJSP.Enum, v1beta1.JSON{ + fieldJSP.Enum = append(fieldJSP.Enum, v1.JSON{ Raw: bytes, }) } @@ -94,10 +88,20 @@ func populateField(fieldJSP *v1beta1.JSONSchemaProps, f *types.Field) error { fieldJSP.Maximum = &fl } + if f.Default != nil { + bytes, err := json.Marshal(f.Default) + if err != nil { + return err + } + fieldJSP.Default = &v1.JSON{ + Raw: bytes, + } + } + return nil } -func typeToProps(typeName string, schemas *types.Schemas, inflight map[string]bool) (*v1beta1.JSONSchemaProps, error) { +func typeToProps(typeName string, schemas *types.Schemas, inflight map[string]bool) (*v1.JSONSchemaProps, error) { t, subType, schema, err := typeAndSchema(typeName, schemas) if err != nil { return nil, err @@ -107,7 +111,7 @@ func typeToProps(typeName string, schemas *types.Schemas, inflight map[string]bo return schemaToProps(schema, schemas, inflight) } - jsp := &v1beta1.JSONSchemaProps{} + jsp := &v1.JSONSchemaProps{} switch t { case "map": @@ -117,8 +121,11 @@ func typeToProps(typeName string, schemas *types.Schemas, inflight map[string]bo } jsp.Type = "object" jsp.Nullable = true - jsp.AdditionalProperties = &v1beta1.JSONSchemaPropsOrBool{ - Schema: additionalProps, + if subType != "json" { + jsp.AdditionalProperties = &v1.JSONSchemaPropsOrBool{ + Allows: true, + Schema: additionalProps, + } } case "array": items, err := typeToProps(subType, schemas, inflight) @@ -127,18 +134,25 @@ func typeToProps(typeName string, schemas *types.Schemas, inflight map[string]bo } jsp.Type = "array" jsp.Nullable = true - jsp.Items = &v1beta1.JSONSchemaPropsOrArray{ + jsp.Items = &v1.JSONSchemaPropsOrArray{ Schema: items, } + case "string": + jsp.Type = t + jsp.Nullable = true default: jsp.Type = t } + if jsp.Type == "object" && jsp.AdditionalProperties == nil { + jsp.XPreserveUnknownFields = &[]bool{true}[0] + } + return jsp, nil } -func schemaToProps(schema *types.Schema, schemas *types.Schemas, inflight map[string]bool) (*v1beta1.JSONSchemaProps, error) { - jsp := &v1beta1.JSONSchemaProps{ +func schemaToProps(schema *types.Schema, schemas *types.Schemas, inflight map[string]bool) (*v1.JSONSchemaProps, error) { + jsp := &v1.JSONSchemaProps{ Description: schema.Description, Type: "object", } @@ -150,7 +164,7 @@ func schemaToProps(schema *types.Schema, schemas *types.Schemas, inflight map[st inflight[schema.ID] = true defer delete(inflight, schema.ID) - jsp.Properties = map[string]v1beta1.JSONSchemaProps{} + jsp.Properties = map[string]v1.JSONSchemaProps{} for name, f := range schema.ResourceFields { fieldJSP, err := typeToProps(f.Type, schemas, inflight) @@ -166,6 +180,10 @@ func schemaToProps(schema *types.Schema, schemas *types.Schemas, inflight map[st jsp.Properties[name] = *fieldJSP } + sort.Strings(jsp.Required) + if len(jsp.Properties) == 0 && strings.HasSuffix(strings.ToLower(schema.ID), "map") { + jsp.XPreserveUnknownFields = &[]bool{true}[0] + } return jsp, nil } diff --git a/vendor/github.com/rancher/wrangler/pkg/schemas/reflection.go b/vendor/github.com/rancher/wrangler/pkg/schemas/reflection.go index d1efeaa83f..d296baa1ae 100644 --- a/vendor/github.com/rancher/wrangler/pkg/schemas/reflection.go +++ b/vendor/github.com/rancher/wrangler/pkg/schemas/reflection.go @@ -12,7 +12,7 @@ import ( ) var ( - blacklistNames = map[string]bool{ + skippedNames = map[string]bool{ "links": true, "actions": true, } @@ -168,7 +168,7 @@ func (s *Schemas) importType(t reflect.Type, overrides ...reflect.Type) (*Schema return s, nil } - logrus.Debugf("Inspecting schema %s for %v", typeName, t) + logrus.Tracef("Inspecting schema %s for %v", typeName, t) schema, err := s.newSchemaFromType(t, typeName) if err != nil { @@ -249,12 +249,12 @@ func (s *Schemas) readFields(schema *Schema, t reflect.Type) error { } } - if blacklistNames[fieldName] { - logrus.Debugf("Ignoring blacklisted field %s.%s for %v", schema.ID, fieldName, field) + if skippedNames[fieldName] { + logrus.Debugf("Ignoring skip field %s.%s for %v", schema.ID, fieldName, field) continue } - logrus.Debugf("Inspecting field %s.%s for %v", schema.ID, fieldName, field) + logrus.Tracef("Inspecting field %s.%s for %v", schema.ID, fieldName, field) schemaField := Field{ CodeName: field.Name, @@ -268,7 +268,6 @@ func (s *Schemas) readFields(schema *Schema, t reflect.Type) error { fieldType = fieldType.Elem() } else if fieldType.Kind() == reflect.Bool { schemaField.Nullable = false - schemaField.Default = false } else if fieldType.Kind() == reflect.Int || fieldType.Kind() == reflect.Uint32 || fieldType.Kind() == reflect.Int32 || @@ -277,7 +276,6 @@ func (s *Schemas) readFields(schema *Schema, t reflect.Type) error { fieldType.Kind() == reflect.Float32 || fieldType.Kind() == reflect.Float64 { schemaField.Nullable = false - schemaField.Default = 0 } if err := applyTag(&field, &schemaField); err != nil { @@ -317,7 +315,7 @@ func (s *Schemas) readFields(schema *Schema, t reflect.Type) error { } } - logrus.Debugf("Setting field %s.%s: %#v", schema.ID, fieldName, schemaField) + logrus.Tracef("Setting field %s.%s: %#v", schema.ID, fieldName, schemaField) schema.ResourceFields[fieldName] = schemaField } @@ -362,10 +360,7 @@ func (s *Schemas) processFieldsMappers(t reflect.Type, fieldName string, schema } func applyTag(structField *reflect.StructField, field *Field) error { - t, ok := structField.Tag.Lookup("wrangler") - if !ok { - t = structField.Tag.Get("norman") - } + t := structField.Tag.Get("wrangler") for _, part := range strings.Split(t, ",") { if part == "" { continue diff --git a/vendor/github.com/rancher/wrangler/pkg/schemes/all.go b/vendor/github.com/rancher/wrangler/pkg/schemes/all.go index 8e64b5ca9f..0b87075c3f 100644 --- a/vendor/github.com/rancher/wrangler/pkg/schemes/all.go +++ b/vendor/github.com/rancher/wrangler/pkg/schemes/all.go @@ -1,7 +1,20 @@ package schemes import ( + "github.com/rancher/lasso/pkg/scheme" "k8s.io/apimachinery/pkg/runtime" ) -var All = runtime.NewScheme() +var ( + All = scheme.All + localSchemeBuilder = runtime.NewSchemeBuilder() +) + +func Register(addToScheme func(*runtime.Scheme) error) error { + localSchemeBuilder = append(localSchemeBuilder, addToScheme) + return addToScheme(All) +} + +func AddToScheme(scheme *runtime.Scheme) error { + return localSchemeBuilder.AddToScheme(scheme) +} diff --git a/vendor/github.com/rancher/wrangler/pkg/yaml/yaml.go b/vendor/github.com/rancher/wrangler/pkg/yaml/yaml.go new file mode 100644 index 0000000000..ae71a3f10a --- /dev/null +++ b/vendor/github.com/rancher/wrangler/pkg/yaml/yaml.go @@ -0,0 +1,225 @@ +package yaml + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "io" + "strings" + + "github.com/ghodss/yaml" + "github.com/pkg/errors" + "github.com/rancher/wrangler/pkg/data/convert" + "github.com/rancher/wrangler/pkg/gvk" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + yamlDecoder "k8s.io/apimachinery/pkg/util/yaml" +) + +var ( + cleanPrefix = []string{ + "kubectl.kubernetes.io/", + } + cleanContains = []string{ + "cattle.io/", + } +) + +func Unmarshal(data []byte, v interface{}) error { + return yamlDecoder.NewYAMLToJSONDecoder(bytes.NewBuffer(data)).Decode(v) +} + +func ToObjects(in io.Reader) ([]runtime.Object, error) { + var result []runtime.Object + reader := yamlDecoder.NewYAMLReader(bufio.NewReaderSize(in, 4096)) + for { + raw, err := reader.Read() + if err == io.EOF { + break + } + if err != nil { + return nil, err + } + + obj, err := toObjects(raw) + if err != nil { + return nil, err + } + + result = append(result, obj...) + } + + return result, nil +} + +func toObjects(bytes []byte) ([]runtime.Object, error) { + bytes, err := yamlDecoder.ToJSON(bytes) + if err != nil { + return nil, err + } + + check := map[string]interface{}{} + if err := json.Unmarshal(bytes, &check); err != nil || len(check) == 0 { + return nil, err + } + + obj, _, err := unstructured.UnstructuredJSONScheme.Decode(bytes, nil, nil) + if err != nil { + return nil, err + } + + if l, ok := obj.(*unstructured.UnstructuredList); ok { + var result []runtime.Object + for _, obj := range l.Items { + copy := obj + result = append(result, ©) + } + return result, nil + } + + return []runtime.Object{obj}, nil +} + +// Export will attempt to clean up the objects a bit before +// rendering to yaml so that they can easily be imported into another +// cluster +func Export(objects ...runtime.Object) ([]byte, error) { + if len(objects) == 0 { + return nil, nil + } + + buffer := &bytes.Buffer{} + for i, obj := range objects { + if i > 0 { + buffer.WriteString("\n---\n") + } + + obj, err := CleanObjectForExport(obj) + if err != nil { + return nil, err + } + + bytes, err := yaml.Marshal(obj) + if err != nil { + return nil, errors.Wrapf(err, "failed to encode %s", obj.GetObjectKind().GroupVersionKind()) + } + buffer.Write(bytes) + } + + return buffer.Bytes(), nil +} + +func CleanObjectForExport(obj runtime.Object) (runtime.Object, error) { + obj = obj.DeepCopyObject() + if obj.GetObjectKind().GroupVersionKind().Kind == "" { + if gvk, err := gvk.Get(obj); err == nil { + obj.GetObjectKind().SetGroupVersionKind(gvk) + } else if err != nil { + return nil, errors.Wrapf(err, "kind and/or apiVersion is not set on input object: %v", obj) + } + } + + data, err := convert.EncodeToMap(obj) + if err != nil { + return nil, err + } + + unstr := &unstructured.Unstructured{ + Object: data, + } + + metadata := map[string]interface{}{} + + if name := unstr.GetName(); len(name) > 0 { + metadata["name"] = name + } else if generated := unstr.GetGenerateName(); len(generated) > 0 { + metadata["generateName"] = generated + } else { + return nil, fmt.Errorf("either name or generateName must be set on obj: %v", obj) + } + + if unstr.GetNamespace() != "" { + metadata["namespace"] = unstr.GetNamespace() + } + if annotations := unstr.GetAnnotations(); len(annotations) > 0 { + cleanMap(annotations) + if len(annotations) > 0 { + metadata["annotations"] = annotations + } else { + delete(metadata, "annotations") + } + } + if labels := unstr.GetLabels(); len(labels) > 0 { + cleanMap(labels) + if len(labels) > 0 { + metadata["labels"] = labels + } else { + delete(metadata, "labels") + } + } + + if spec, ok := data["spec"]; ok { + if spec == nil { + delete(data, "spec") + } else if m, ok := spec.(map[string]interface{}); ok && len(m) == 0 { + delete(data, "spec") + } + } + + data["metadata"] = metadata + delete(data, "status") + + return unstr, nil +} + +func CleanAnnotationsForExport(annotations map[string]string) map[string]string { + result := make(map[string]string, len(annotations)) + +outer: + for k := range annotations { + for _, prefix := range cleanPrefix { + if strings.HasPrefix(k, prefix) { + continue outer + } + } + for _, contains := range cleanContains { + if strings.Contains(k, contains) { + continue outer + } + } + result[k] = annotations[k] + } + return result +} + +func cleanMap(annoLabels map[string]string) { + for k := range annoLabels { + for _, prefix := range cleanPrefix { + if strings.HasPrefix(k, prefix) { + delete(annoLabels, k) + } + } + } +} + +func ToBytes(objects []runtime.Object) ([]byte, error) { + if len(objects) == 0 { + return nil, nil + } + + buffer := &bytes.Buffer{} + for i, obj := range objects { + if i > 0 { + buffer.WriteString("\n---\n") + } + + bytes, err := yaml.Marshal(obj) + if err != nil { + return nil, errors.Wrapf(err, "failed to encode %s", obj.GetObjectKind().GroupVersionKind()) + } + buffer.Write(bytes) + } + + return buffer.Bytes(), nil +} diff --git a/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go b/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go new file mode 100644 index 0000000000..f8363d8faa --- /dev/null +++ b/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go @@ -0,0 +1,109 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package gcexportdata provides functions for locating, reading, and +// writing export data files containing type information produced by the +// gc compiler. This package supports go1.7 export data format and all +// later versions. +// +// Although it might seem convenient for this package to live alongside +// go/types in the standard library, this would cause version skew +// problems for developer tools that use it, since they must be able to +// consume the outputs of the gc compiler both before and after a Go +// update such as from Go 1.7 to Go 1.8. Because this package lives in +// golang.org/x/tools, sites can update their version of this repo some +// time before the Go 1.8 release and rebuild and redeploy their +// developer tools, which will then be able to consume both Go 1.7 and +// Go 1.8 export data files, so they will work before and after the +// Go update. (See discussion at https://golang.org/issue/15651.) +// +package gcexportdata // import "golang.org/x/tools/go/gcexportdata" + +import ( + "bufio" + "bytes" + "fmt" + "go/token" + "go/types" + "io" + "io/ioutil" + + "golang.org/x/tools/go/internal/gcimporter" +) + +// Find returns the name of an object (.o) or archive (.a) file +// containing type information for the specified import path, +// using the workspace layout conventions of go/build. +// If no file was found, an empty filename is returned. +// +// A relative srcDir is interpreted relative to the current working directory. +// +// Find also returns the package's resolved (canonical) import path, +// reflecting the effects of srcDir and vendoring on importPath. +func Find(importPath, srcDir string) (filename, path string) { + return gcimporter.FindPkg(importPath, srcDir) +} + +// NewReader returns a reader for the export data section of an object +// (.o) or archive (.a) file read from r. The new reader may provide +// additional trailing data beyond the end of the export data. +func NewReader(r io.Reader) (io.Reader, error) { + buf := bufio.NewReader(r) + _, err := gcimporter.FindExportData(buf) + // If we ever switch to a zip-like archive format with the ToC + // at the end, we can return the correct portion of export data, + // but for now we must return the entire rest of the file. + return buf, err +} + +// Read reads export data from in, decodes it, and returns type +// information for the package. +// The package name is specified by path. +// File position information is added to fset. +// +// Read may inspect and add to the imports map to ensure that references +// within the export data to other packages are consistent. The caller +// must ensure that imports[path] does not exist, or exists but is +// incomplete (see types.Package.Complete), and Read inserts the +// resulting package into this map entry. +// +// On return, the state of the reader is undefined. +func Read(in io.Reader, fset *token.FileSet, imports map[string]*types.Package, path string) (*types.Package, error) { + data, err := ioutil.ReadAll(in) + if err != nil { + return nil, fmt.Errorf("reading export data for %q: %v", path, err) + } + + if bytes.HasPrefix(data, []byte("!")) { + return nil, fmt.Errorf("can't read export data for %q directly from an archive file (call gcexportdata.NewReader first to extract export data)", path) + } + + // The App Engine Go runtime v1.6 uses the old export data format. + // TODO(adonovan): delete once v1.7 has been around for a while. + if bytes.HasPrefix(data, []byte("package ")) { + return gcimporter.ImportData(imports, path, path, bytes.NewReader(data)) + } + + // The indexed export format starts with an 'i'; the older + // binary export format starts with a 'c', 'd', or 'v' + // (from "version"). Select appropriate importer. + if len(data) > 0 && data[0] == 'i' { + _, pkg, err := gcimporter.IImportData(fset, imports, data[1:], path) + return pkg, err + } + + _, pkg, err := gcimporter.BImportData(fset, imports, data, path) + return pkg, err +} + +// Write writes encoded type information for the specified package to out. +// The FileSet provides file position information for named objects. +func Write(out io.Writer, fset *token.FileSet, pkg *types.Package) error { + b, err := gcimporter.IExportData(fset, pkg) + if err != nil { + return err + } + _, err = out.Write(b) + return err +} diff --git a/vendor/golang.org/x/tools/go/gcexportdata/importer.go b/vendor/golang.org/x/tools/go/gcexportdata/importer.go new file mode 100644 index 0000000000..efe221e7e1 --- /dev/null +++ b/vendor/golang.org/x/tools/go/gcexportdata/importer.go @@ -0,0 +1,73 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gcexportdata + +import ( + "fmt" + "go/token" + "go/types" + "os" +) + +// NewImporter returns a new instance of the types.Importer interface +// that reads type information from export data files written by gc. +// The Importer also satisfies types.ImporterFrom. +// +// Export data files are located using "go build" workspace conventions +// and the build.Default context. +// +// Use this importer instead of go/importer.For("gc", ...) to avoid the +// version-skew problems described in the documentation of this package, +// or to control the FileSet or access the imports map populated during +// package loading. +// +func NewImporter(fset *token.FileSet, imports map[string]*types.Package) types.ImporterFrom { + return importer{fset, imports} +} + +type importer struct { + fset *token.FileSet + imports map[string]*types.Package +} + +func (imp importer) Import(importPath string) (*types.Package, error) { + return imp.ImportFrom(importPath, "", 0) +} + +func (imp importer) ImportFrom(importPath, srcDir string, mode types.ImportMode) (_ *types.Package, err error) { + filename, path := Find(importPath, srcDir) + if filename == "" { + if importPath == "unsafe" { + // Even for unsafe, call Find first in case + // the package was vendored. + return types.Unsafe, nil + } + return nil, fmt.Errorf("can't find import: %s", importPath) + } + + if pkg, ok := imp.imports[path]; ok && pkg.Complete() { + return pkg, nil // cache hit + } + + // open file + f, err := os.Open(filename) + if err != nil { + return nil, err + } + defer func() { + f.Close() + if err != nil { + // add file name to error + err = fmt.Errorf("reading export data: %s: %v", filename, err) + } + }() + + r, err := NewReader(f) + if err != nil { + return nil, err + } + + return Read(r, imp.fset, imp.imports, path) +} diff --git a/vendor/golang.org/x/tools/go/internal/gcimporter/bexport.go b/vendor/golang.org/x/tools/go/internal/gcimporter/bexport.go new file mode 100644 index 0000000000..a807d0aaa2 --- /dev/null +++ b/vendor/golang.org/x/tools/go/internal/gcimporter/bexport.go @@ -0,0 +1,852 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Binary package export. +// This file was derived from $GOROOT/src/cmd/compile/internal/gc/bexport.go; +// see that file for specification of the format. + +package gcimporter + +import ( + "bytes" + "encoding/binary" + "fmt" + "go/ast" + "go/constant" + "go/token" + "go/types" + "math" + "math/big" + "sort" + "strings" +) + +// If debugFormat is set, each integer and string value is preceded by a marker +// and position information in the encoding. This mechanism permits an importer +// to recognize immediately when it is out of sync. The importer recognizes this +// mode automatically (i.e., it can import export data produced with debugging +// support even if debugFormat is not set at the time of import). This mode will +// lead to massively larger export data (by a factor of 2 to 3) and should only +// be enabled during development and debugging. +// +// NOTE: This flag is the first flag to enable if importing dies because of +// (suspected) format errors, and whenever a change is made to the format. +const debugFormat = false // default: false + +// If trace is set, debugging output is printed to std out. +const trace = false // default: false + +// Current export format version. Increase with each format change. +// Note: The latest binary (non-indexed) export format is at version 6. +// This exporter is still at level 4, but it doesn't matter since +// the binary importer can handle older versions just fine. +// 6: package height (CL 105038) -- NOT IMPLEMENTED HERE +// 5: improved position encoding efficiency (issue 20080, CL 41619) -- NOT IMPLEMEMTED HERE +// 4: type name objects support type aliases, uses aliasTag +// 3: Go1.8 encoding (same as version 2, aliasTag defined but never used) +// 2: removed unused bool in ODCL export (compiler only) +// 1: header format change (more regular), export package for _ struct fields +// 0: Go1.7 encoding +const exportVersion = 4 + +// trackAllTypes enables cycle tracking for all types, not just named +// types. The existing compiler invariants assume that unnamed types +// that are not completely set up are not used, or else there are spurious +// errors. +// If disabled, only named types are tracked, possibly leading to slightly +// less efficient encoding in rare cases. It also prevents the export of +// some corner-case type declarations (but those are not handled correctly +// with with the textual export format either). +// TODO(gri) enable and remove once issues caused by it are fixed +const trackAllTypes = false + +type exporter struct { + fset *token.FileSet + out bytes.Buffer + + // object -> index maps, indexed in order of serialization + strIndex map[string]int + pkgIndex map[*types.Package]int + typIndex map[types.Type]int + + // position encoding + posInfoFormat bool + prevFile string + prevLine int + + // debugging support + written int // bytes written + indent int // for trace +} + +// internalError represents an error generated inside this package. +type internalError string + +func (e internalError) Error() string { return "gcimporter: " + string(e) } + +func internalErrorf(format string, args ...interface{}) error { + return internalError(fmt.Sprintf(format, args...)) +} + +// BExportData returns binary export data for pkg. +// If no file set is provided, position info will be missing. +func BExportData(fset *token.FileSet, pkg *types.Package) (b []byte, err error) { + defer func() { + if e := recover(); e != nil { + if ierr, ok := e.(internalError); ok { + err = ierr + return + } + // Not an internal error; panic again. + panic(e) + } + }() + + p := exporter{ + fset: fset, + strIndex: map[string]int{"": 0}, // empty string is mapped to 0 + pkgIndex: make(map[*types.Package]int), + typIndex: make(map[types.Type]int), + posInfoFormat: true, // TODO(gri) might become a flag, eventually + } + + // write version info + // The version string must start with "version %d" where %d is the version + // number. Additional debugging information may follow after a blank; that + // text is ignored by the importer. + p.rawStringln(fmt.Sprintf("version %d", exportVersion)) + var debug string + if debugFormat { + debug = "debug" + } + p.rawStringln(debug) // cannot use p.bool since it's affected by debugFormat; also want to see this clearly + p.bool(trackAllTypes) + p.bool(p.posInfoFormat) + + // --- generic export data --- + + // populate type map with predeclared "known" types + for index, typ := range predeclared() { + p.typIndex[typ] = index + } + if len(p.typIndex) != len(predeclared()) { + return nil, internalError("duplicate entries in type map?") + } + + // write package data + p.pkg(pkg, true) + if trace { + p.tracef("\n") + } + + // write objects + objcount := 0 + scope := pkg.Scope() + for _, name := range scope.Names() { + if !ast.IsExported(name) { + continue + } + if trace { + p.tracef("\n") + } + p.obj(scope.Lookup(name)) + objcount++ + } + + // indicate end of list + if trace { + p.tracef("\n") + } + p.tag(endTag) + + // for self-verification only (redundant) + p.int(objcount) + + if trace { + p.tracef("\n") + } + + // --- end of export data --- + + return p.out.Bytes(), nil +} + +func (p *exporter) pkg(pkg *types.Package, emptypath bool) { + if pkg == nil { + panic(internalError("unexpected nil pkg")) + } + + // if we saw the package before, write its index (>= 0) + if i, ok := p.pkgIndex[pkg]; ok { + p.index('P', i) + return + } + + // otherwise, remember the package, write the package tag (< 0) and package data + if trace { + p.tracef("P%d = { ", len(p.pkgIndex)) + defer p.tracef("} ") + } + p.pkgIndex[pkg] = len(p.pkgIndex) + + p.tag(packageTag) + p.string(pkg.Name()) + if emptypath { + p.string("") + } else { + p.string(pkg.Path()) + } +} + +func (p *exporter) obj(obj types.Object) { + switch obj := obj.(type) { + case *types.Const: + p.tag(constTag) + p.pos(obj) + p.qualifiedName(obj) + p.typ(obj.Type()) + p.value(obj.Val()) + + case *types.TypeName: + if obj.IsAlias() { + p.tag(aliasTag) + p.pos(obj) + p.qualifiedName(obj) + } else { + p.tag(typeTag) + } + p.typ(obj.Type()) + + case *types.Var: + p.tag(varTag) + p.pos(obj) + p.qualifiedName(obj) + p.typ(obj.Type()) + + case *types.Func: + p.tag(funcTag) + p.pos(obj) + p.qualifiedName(obj) + sig := obj.Type().(*types.Signature) + p.paramList(sig.Params(), sig.Variadic()) + p.paramList(sig.Results(), false) + + default: + panic(internalErrorf("unexpected object %v (%T)", obj, obj)) + } +} + +func (p *exporter) pos(obj types.Object) { + if !p.posInfoFormat { + return + } + + file, line := p.fileLine(obj) + if file == p.prevFile { + // common case: write line delta + // delta == 0 means different file or no line change + delta := line - p.prevLine + p.int(delta) + if delta == 0 { + p.int(-1) // -1 means no file change + } + } else { + // different file + p.int(0) + // Encode filename as length of common prefix with previous + // filename, followed by (possibly empty) suffix. Filenames + // frequently share path prefixes, so this can save a lot + // of space and make export data size less dependent on file + // path length. The suffix is unlikely to be empty because + // file names tend to end in ".go". + n := commonPrefixLen(p.prevFile, file) + p.int(n) // n >= 0 + p.string(file[n:]) // write suffix only + p.prevFile = file + p.int(line) + } + p.prevLine = line +} + +func (p *exporter) fileLine(obj types.Object) (file string, line int) { + if p.fset != nil { + pos := p.fset.Position(obj.Pos()) + file = pos.Filename + line = pos.Line + } + return +} + +func commonPrefixLen(a, b string) int { + if len(a) > len(b) { + a, b = b, a + } + // len(a) <= len(b) + i := 0 + for i < len(a) && a[i] == b[i] { + i++ + } + return i +} + +func (p *exporter) qualifiedName(obj types.Object) { + p.string(obj.Name()) + p.pkg(obj.Pkg(), false) +} + +func (p *exporter) typ(t types.Type) { + if t == nil { + panic(internalError("nil type")) + } + + // Possible optimization: Anonymous pointer types *T where + // T is a named type are common. We could canonicalize all + // such types *T to a single type PT = *T. This would lead + // to at most one *T entry in typIndex, and all future *T's + // would be encoded as the respective index directly. Would + // save 1 byte (pointerTag) per *T and reduce the typIndex + // size (at the cost of a canonicalization map). We can do + // this later, without encoding format change. + + // if we saw the type before, write its index (>= 0) + if i, ok := p.typIndex[t]; ok { + p.index('T', i) + return + } + + // otherwise, remember the type, write the type tag (< 0) and type data + if trackAllTypes { + if trace { + p.tracef("T%d = {>\n", len(p.typIndex)) + defer p.tracef("<\n} ") + } + p.typIndex[t] = len(p.typIndex) + } + + switch t := t.(type) { + case *types.Named: + if !trackAllTypes { + // if we don't track all types, track named types now + p.typIndex[t] = len(p.typIndex) + } + + p.tag(namedTag) + p.pos(t.Obj()) + p.qualifiedName(t.Obj()) + p.typ(t.Underlying()) + if !types.IsInterface(t) { + p.assocMethods(t) + } + + case *types.Array: + p.tag(arrayTag) + p.int64(t.Len()) + p.typ(t.Elem()) + + case *types.Slice: + p.tag(sliceTag) + p.typ(t.Elem()) + + case *dddSlice: + p.tag(dddTag) + p.typ(t.elem) + + case *types.Struct: + p.tag(structTag) + p.fieldList(t) + + case *types.Pointer: + p.tag(pointerTag) + p.typ(t.Elem()) + + case *types.Signature: + p.tag(signatureTag) + p.paramList(t.Params(), t.Variadic()) + p.paramList(t.Results(), false) + + case *types.Interface: + p.tag(interfaceTag) + p.iface(t) + + case *types.Map: + p.tag(mapTag) + p.typ(t.Key()) + p.typ(t.Elem()) + + case *types.Chan: + p.tag(chanTag) + p.int(int(3 - t.Dir())) // hack + p.typ(t.Elem()) + + default: + panic(internalErrorf("unexpected type %T: %s", t, t)) + } +} + +func (p *exporter) assocMethods(named *types.Named) { + // Sort methods (for determinism). + var methods []*types.Func + for i := 0; i < named.NumMethods(); i++ { + methods = append(methods, named.Method(i)) + } + sort.Sort(methodsByName(methods)) + + p.int(len(methods)) + + if trace && methods != nil { + p.tracef("associated methods {>\n") + } + + for i, m := range methods { + if trace && i > 0 { + p.tracef("\n") + } + + p.pos(m) + name := m.Name() + p.string(name) + if !exported(name) { + p.pkg(m.Pkg(), false) + } + + sig := m.Type().(*types.Signature) + p.paramList(types.NewTuple(sig.Recv()), false) + p.paramList(sig.Params(), sig.Variadic()) + p.paramList(sig.Results(), false) + p.int(0) // dummy value for go:nointerface pragma - ignored by importer + } + + if trace && methods != nil { + p.tracef("<\n} ") + } +} + +type methodsByName []*types.Func + +func (x methodsByName) Len() int { return len(x) } +func (x methodsByName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } +func (x methodsByName) Less(i, j int) bool { return x[i].Name() < x[j].Name() } + +func (p *exporter) fieldList(t *types.Struct) { + if trace && t.NumFields() > 0 { + p.tracef("fields {>\n") + defer p.tracef("<\n} ") + } + + p.int(t.NumFields()) + for i := 0; i < t.NumFields(); i++ { + if trace && i > 0 { + p.tracef("\n") + } + p.field(t.Field(i)) + p.string(t.Tag(i)) + } +} + +func (p *exporter) field(f *types.Var) { + if !f.IsField() { + panic(internalError("field expected")) + } + + p.pos(f) + p.fieldName(f) + p.typ(f.Type()) +} + +func (p *exporter) iface(t *types.Interface) { + // TODO(gri): enable importer to load embedded interfaces, + // then emit Embeddeds and ExplicitMethods separately here. + p.int(0) + + n := t.NumMethods() + if trace && n > 0 { + p.tracef("methods {>\n") + defer p.tracef("<\n} ") + } + p.int(n) + for i := 0; i < n; i++ { + if trace && i > 0 { + p.tracef("\n") + } + p.method(t.Method(i)) + } +} + +func (p *exporter) method(m *types.Func) { + sig := m.Type().(*types.Signature) + if sig.Recv() == nil { + panic(internalError("method expected")) + } + + p.pos(m) + p.string(m.Name()) + if m.Name() != "_" && !ast.IsExported(m.Name()) { + p.pkg(m.Pkg(), false) + } + + // interface method; no need to encode receiver. + p.paramList(sig.Params(), sig.Variadic()) + p.paramList(sig.Results(), false) +} + +func (p *exporter) fieldName(f *types.Var) { + name := f.Name() + + if f.Anonymous() { + // anonymous field - we distinguish between 3 cases: + // 1) field name matches base type name and is exported + // 2) field name matches base type name and is not exported + // 3) field name doesn't match base type name (alias name) + bname := basetypeName(f.Type()) + if name == bname { + if ast.IsExported(name) { + name = "" // 1) we don't need to know the field name or package + } else { + name = "?" // 2) use unexported name "?" to force package export + } + } else { + // 3) indicate alias and export name as is + // (this requires an extra "@" but this is a rare case) + p.string("@") + } + } + + p.string(name) + if name != "" && !ast.IsExported(name) { + p.pkg(f.Pkg(), false) + } +} + +func basetypeName(typ types.Type) string { + switch typ := deref(typ).(type) { + case *types.Basic: + return typ.Name() + case *types.Named: + return typ.Obj().Name() + default: + return "" // unnamed type + } +} + +func (p *exporter) paramList(params *types.Tuple, variadic bool) { + // use negative length to indicate unnamed parameters + // (look at the first parameter only since either all + // names are present or all are absent) + n := params.Len() + if n > 0 && params.At(0).Name() == "" { + n = -n + } + p.int(n) + for i := 0; i < params.Len(); i++ { + q := params.At(i) + t := q.Type() + if variadic && i == params.Len()-1 { + t = &dddSlice{t.(*types.Slice).Elem()} + } + p.typ(t) + if n > 0 { + name := q.Name() + p.string(name) + if name != "_" { + p.pkg(q.Pkg(), false) + } + } + p.string("") // no compiler-specific info + } +} + +func (p *exporter) value(x constant.Value) { + if trace { + p.tracef("= ") + } + + switch x.Kind() { + case constant.Bool: + tag := falseTag + if constant.BoolVal(x) { + tag = trueTag + } + p.tag(tag) + + case constant.Int: + if v, exact := constant.Int64Val(x); exact { + // common case: x fits into an int64 - use compact encoding + p.tag(int64Tag) + p.int64(v) + return + } + // uncommon case: large x - use float encoding + // (powers of 2 will be encoded efficiently with exponent) + p.tag(floatTag) + p.float(constant.ToFloat(x)) + + case constant.Float: + p.tag(floatTag) + p.float(x) + + case constant.Complex: + p.tag(complexTag) + p.float(constant.Real(x)) + p.float(constant.Imag(x)) + + case constant.String: + p.tag(stringTag) + p.string(constant.StringVal(x)) + + case constant.Unknown: + // package contains type errors + p.tag(unknownTag) + + default: + panic(internalErrorf("unexpected value %v (%T)", x, x)) + } +} + +func (p *exporter) float(x constant.Value) { + if x.Kind() != constant.Float { + panic(internalErrorf("unexpected constant %v, want float", x)) + } + // extract sign (there is no -0) + sign := constant.Sign(x) + if sign == 0 { + // x == 0 + p.int(0) + return + } + // x != 0 + + var f big.Float + if v, exact := constant.Float64Val(x); exact { + // float64 + f.SetFloat64(v) + } else if num, denom := constant.Num(x), constant.Denom(x); num.Kind() == constant.Int { + // TODO(gri): add big.Rat accessor to constant.Value. + r := valueToRat(num) + f.SetRat(r.Quo(r, valueToRat(denom))) + } else { + // Value too large to represent as a fraction => inaccessible. + // TODO(gri): add big.Float accessor to constant.Value. + f.SetFloat64(math.MaxFloat64) // FIXME + } + + // extract exponent such that 0.5 <= m < 1.0 + var m big.Float + exp := f.MantExp(&m) + + // extract mantissa as *big.Int + // - set exponent large enough so mant satisfies mant.IsInt() + // - get *big.Int from mant + m.SetMantExp(&m, int(m.MinPrec())) + mant, acc := m.Int(nil) + if acc != big.Exact { + panic(internalError("internal error")) + } + + p.int(sign) + p.int(exp) + p.string(string(mant.Bytes())) +} + +func valueToRat(x constant.Value) *big.Rat { + // Convert little-endian to big-endian. + // I can't believe this is necessary. + bytes := constant.Bytes(x) + for i := 0; i < len(bytes)/2; i++ { + bytes[i], bytes[len(bytes)-1-i] = bytes[len(bytes)-1-i], bytes[i] + } + return new(big.Rat).SetInt(new(big.Int).SetBytes(bytes)) +} + +func (p *exporter) bool(b bool) bool { + if trace { + p.tracef("[") + defer p.tracef("= %v] ", b) + } + + x := 0 + if b { + x = 1 + } + p.int(x) + return b +} + +// ---------------------------------------------------------------------------- +// Low-level encoders + +func (p *exporter) index(marker byte, index int) { + if index < 0 { + panic(internalError("invalid index < 0")) + } + if debugFormat { + p.marker('t') + } + if trace { + p.tracef("%c%d ", marker, index) + } + p.rawInt64(int64(index)) +} + +func (p *exporter) tag(tag int) { + if tag >= 0 { + panic(internalError("invalid tag >= 0")) + } + if debugFormat { + p.marker('t') + } + if trace { + p.tracef("%s ", tagString[-tag]) + } + p.rawInt64(int64(tag)) +} + +func (p *exporter) int(x int) { + p.int64(int64(x)) +} + +func (p *exporter) int64(x int64) { + if debugFormat { + p.marker('i') + } + if trace { + p.tracef("%d ", x) + } + p.rawInt64(x) +} + +func (p *exporter) string(s string) { + if debugFormat { + p.marker('s') + } + if trace { + p.tracef("%q ", s) + } + // if we saw the string before, write its index (>= 0) + // (the empty string is mapped to 0) + if i, ok := p.strIndex[s]; ok { + p.rawInt64(int64(i)) + return + } + // otherwise, remember string and write its negative length and bytes + p.strIndex[s] = len(p.strIndex) + p.rawInt64(-int64(len(s))) + for i := 0; i < len(s); i++ { + p.rawByte(s[i]) + } +} + +// marker emits a marker byte and position information which makes +// it easy for a reader to detect if it is "out of sync". Used for +// debugFormat format only. +func (p *exporter) marker(m byte) { + p.rawByte(m) + // Enable this for help tracking down the location + // of an incorrect marker when running in debugFormat. + if false && trace { + p.tracef("#%d ", p.written) + } + p.rawInt64(int64(p.written)) +} + +// rawInt64 should only be used by low-level encoders. +func (p *exporter) rawInt64(x int64) { + var tmp [binary.MaxVarintLen64]byte + n := binary.PutVarint(tmp[:], x) + for i := 0; i < n; i++ { + p.rawByte(tmp[i]) + } +} + +// rawStringln should only be used to emit the initial version string. +func (p *exporter) rawStringln(s string) { + for i := 0; i < len(s); i++ { + p.rawByte(s[i]) + } + p.rawByte('\n') +} + +// rawByte is the bottleneck interface to write to p.out. +// rawByte escapes b as follows (any encoding does that +// hides '$'): +// +// '$' => '|' 'S' +// '|' => '|' '|' +// +// Necessary so other tools can find the end of the +// export data by searching for "$$". +// rawByte should only be used by low-level encoders. +func (p *exporter) rawByte(b byte) { + switch b { + case '$': + // write '$' as '|' 'S' + b = 'S' + fallthrough + case '|': + // write '|' as '|' '|' + p.out.WriteByte('|') + p.written++ + } + p.out.WriteByte(b) + p.written++ +} + +// tracef is like fmt.Printf but it rewrites the format string +// to take care of indentation. +func (p *exporter) tracef(format string, args ...interface{}) { + if strings.ContainsAny(format, "<>\n") { + var buf bytes.Buffer + for i := 0; i < len(format); i++ { + // no need to deal with runes + ch := format[i] + switch ch { + case '>': + p.indent++ + continue + case '<': + p.indent-- + continue + } + buf.WriteByte(ch) + if ch == '\n' { + for j := p.indent; j > 0; j-- { + buf.WriteString(". ") + } + } + } + format = buf.String() + } + fmt.Printf(format, args...) +} + +// Debugging support. +// (tagString is only used when tracing is enabled) +var tagString = [...]string{ + // Packages + -packageTag: "package", + + // Types + -namedTag: "named type", + -arrayTag: "array", + -sliceTag: "slice", + -dddTag: "ddd", + -structTag: "struct", + -pointerTag: "pointer", + -signatureTag: "signature", + -interfaceTag: "interface", + -mapTag: "map", + -chanTag: "chan", + + // Values + -falseTag: "false", + -trueTag: "true", + -int64Tag: "int64", + -floatTag: "float", + -fractionTag: "fraction", + -complexTag: "complex", + -stringTag: "string", + -unknownTag: "unknown", + + // Type aliases + -aliasTag: "alias", +} diff --git a/vendor/golang.org/x/tools/go/internal/gcimporter/bimport.go b/vendor/golang.org/x/tools/go/internal/gcimporter/bimport.go new file mode 100644 index 0000000000..e9f73d14a1 --- /dev/null +++ b/vendor/golang.org/x/tools/go/internal/gcimporter/bimport.go @@ -0,0 +1,1039 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file is a copy of $GOROOT/src/go/internal/gcimporter/bimport.go. + +package gcimporter + +import ( + "encoding/binary" + "fmt" + "go/constant" + "go/token" + "go/types" + "sort" + "strconv" + "strings" + "sync" + "unicode" + "unicode/utf8" +) + +type importer struct { + imports map[string]*types.Package + data []byte + importpath string + buf []byte // for reading strings + version int // export format version + + // object lists + strList []string // in order of appearance + pathList []string // in order of appearance + pkgList []*types.Package // in order of appearance + typList []types.Type // in order of appearance + interfaceList []*types.Interface // for delayed completion only + trackAllTypes bool + + // position encoding + posInfoFormat bool + prevFile string + prevLine int + fake fakeFileSet + + // debugging support + debugFormat bool + read int // bytes read +} + +// BImportData imports a package from the serialized package data +// and returns the number of bytes consumed and a reference to the package. +// If the export data version is not recognized or the format is otherwise +// compromised, an error is returned. +func BImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) { + // catch panics and return them as errors + const currentVersion = 6 + version := -1 // unknown version + defer func() { + if e := recover(); e != nil { + // Return a (possibly nil or incomplete) package unchanged (see #16088). + if version > currentVersion { + err = fmt.Errorf("cannot import %q (%v), export data is newer version - update tool", path, e) + } else { + err = fmt.Errorf("cannot import %q (%v), possibly version skew - reinstall package", path, e) + } + } + }() + + p := importer{ + imports: imports, + data: data, + importpath: path, + version: version, + strList: []string{""}, // empty string is mapped to 0 + pathList: []string{""}, // empty string is mapped to 0 + fake: fakeFileSet{ + fset: fset, + files: make(map[string]*token.File), + }, + } + + // read version info + var versionstr string + if b := p.rawByte(); b == 'c' || b == 'd' { + // Go1.7 encoding; first byte encodes low-level + // encoding format (compact vs debug). + // For backward-compatibility only (avoid problems with + // old installed packages). Newly compiled packages use + // the extensible format string. + // TODO(gri) Remove this support eventually; after Go1.8. + if b == 'd' { + p.debugFormat = true + } + p.trackAllTypes = p.rawByte() == 'a' + p.posInfoFormat = p.int() != 0 + versionstr = p.string() + if versionstr == "v1" { + version = 0 + } + } else { + // Go1.8 extensible encoding + // read version string and extract version number (ignore anything after the version number) + versionstr = p.rawStringln(b) + if s := strings.SplitN(versionstr, " ", 3); len(s) >= 2 && s[0] == "version" { + if v, err := strconv.Atoi(s[1]); err == nil && v > 0 { + version = v + } + } + } + p.version = version + + // read version specific flags - extend as necessary + switch p.version { + // case currentVersion: + // ... + // fallthrough + case currentVersion, 5, 4, 3, 2, 1: + p.debugFormat = p.rawStringln(p.rawByte()) == "debug" + p.trackAllTypes = p.int() != 0 + p.posInfoFormat = p.int() != 0 + case 0: + // Go1.7 encoding format - nothing to do here + default: + errorf("unknown bexport format version %d (%q)", p.version, versionstr) + } + + // --- generic export data --- + + // populate typList with predeclared "known" types + p.typList = append(p.typList, predeclared()...) + + // read package data + pkg = p.pkg() + + // read objects of phase 1 only (see cmd/compile/internal/gc/bexport.go) + objcount := 0 + for { + tag := p.tagOrIndex() + if tag == endTag { + break + } + p.obj(tag) + objcount++ + } + + // self-verification + if count := p.int(); count != objcount { + errorf("got %d objects; want %d", objcount, count) + } + + // ignore compiler-specific import data + + // complete interfaces + // TODO(gri) re-investigate if we still need to do this in a delayed fashion + for _, typ := range p.interfaceList { + typ.Complete() + } + + // record all referenced packages as imports + list := append(([]*types.Package)(nil), p.pkgList[1:]...) + sort.Sort(byPath(list)) + pkg.SetImports(list) + + // package was imported completely and without errors + pkg.MarkComplete() + + return p.read, pkg, nil +} + +func errorf(format string, args ...interface{}) { + panic(fmt.Sprintf(format, args...)) +} + +func (p *importer) pkg() *types.Package { + // if the package was seen before, i is its index (>= 0) + i := p.tagOrIndex() + if i >= 0 { + return p.pkgList[i] + } + + // otherwise, i is the package tag (< 0) + if i != packageTag { + errorf("unexpected package tag %d version %d", i, p.version) + } + + // read package data + name := p.string() + var path string + if p.version >= 5 { + path = p.path() + } else { + path = p.string() + } + if p.version >= 6 { + p.int() // package height; unused by go/types + } + + // we should never see an empty package name + if name == "" { + errorf("empty package name in import") + } + + // an empty path denotes the package we are currently importing; + // it must be the first package we see + if (path == "") != (len(p.pkgList) == 0) { + errorf("package path %q for pkg index %d", path, len(p.pkgList)) + } + + // if the package was imported before, use that one; otherwise create a new one + if path == "" { + path = p.importpath + } + pkg := p.imports[path] + if pkg == nil { + pkg = types.NewPackage(path, name) + p.imports[path] = pkg + } else if pkg.Name() != name { + errorf("conflicting names %s and %s for package %q", pkg.Name(), name, path) + } + p.pkgList = append(p.pkgList, pkg) + + return pkg +} + +// objTag returns the tag value for each object kind. +func objTag(obj types.Object) int { + switch obj.(type) { + case *types.Const: + return constTag + case *types.TypeName: + return typeTag + case *types.Var: + return varTag + case *types.Func: + return funcTag + default: + errorf("unexpected object: %v (%T)", obj, obj) // panics + panic("unreachable") + } +} + +func sameObj(a, b types.Object) bool { + // Because unnamed types are not canonicalized, we cannot simply compare types for + // (pointer) identity. + // Ideally we'd check equality of constant values as well, but this is good enough. + return objTag(a) == objTag(b) && types.Identical(a.Type(), b.Type()) +} + +func (p *importer) declare(obj types.Object) { + pkg := obj.Pkg() + if alt := pkg.Scope().Insert(obj); alt != nil { + // This can only trigger if we import a (non-type) object a second time. + // Excluding type aliases, this cannot happen because 1) we only import a package + // once; and b) we ignore compiler-specific export data which may contain + // functions whose inlined function bodies refer to other functions that + // were already imported. + // However, type aliases require reexporting the original type, so we need + // to allow it (see also the comment in cmd/compile/internal/gc/bimport.go, + // method importer.obj, switch case importing functions). + // TODO(gri) review/update this comment once the gc compiler handles type aliases. + if !sameObj(obj, alt) { + errorf("inconsistent import:\n\t%v\npreviously imported as:\n\t%v\n", obj, alt) + } + } +} + +func (p *importer) obj(tag int) { + switch tag { + case constTag: + pos := p.pos() + pkg, name := p.qualifiedName() + typ := p.typ(nil, nil) + val := p.value() + p.declare(types.NewConst(pos, pkg, name, typ, val)) + + case aliasTag: + // TODO(gri) verify type alias hookup is correct + pos := p.pos() + pkg, name := p.qualifiedName() + typ := p.typ(nil, nil) + p.declare(types.NewTypeName(pos, pkg, name, typ)) + + case typeTag: + p.typ(nil, nil) + + case varTag: + pos := p.pos() + pkg, name := p.qualifiedName() + typ := p.typ(nil, nil) + p.declare(types.NewVar(pos, pkg, name, typ)) + + case funcTag: + pos := p.pos() + pkg, name := p.qualifiedName() + params, isddd := p.paramList() + result, _ := p.paramList() + sig := types.NewSignature(nil, params, result, isddd) + p.declare(types.NewFunc(pos, pkg, name, sig)) + + default: + errorf("unexpected object tag %d", tag) + } +} + +const deltaNewFile = -64 // see cmd/compile/internal/gc/bexport.go + +func (p *importer) pos() token.Pos { + if !p.posInfoFormat { + return token.NoPos + } + + file := p.prevFile + line := p.prevLine + delta := p.int() + line += delta + if p.version >= 5 { + if delta == deltaNewFile { + if n := p.int(); n >= 0 { + // file changed + file = p.path() + line = n + } + } + } else { + if delta == 0 { + if n := p.int(); n >= 0 { + // file changed + file = p.prevFile[:n] + p.string() + line = p.int() + } + } + } + p.prevFile = file + p.prevLine = line + + return p.fake.pos(file, line, 0) +} + +// Synthesize a token.Pos +type fakeFileSet struct { + fset *token.FileSet + files map[string]*token.File +} + +func (s *fakeFileSet) pos(file string, line, column int) token.Pos { + // TODO(mdempsky): Make use of column. + + // Since we don't know the set of needed file positions, we + // reserve maxlines positions per file. + const maxlines = 64 * 1024 + f := s.files[file] + if f == nil { + f = s.fset.AddFile(file, -1, maxlines) + s.files[file] = f + // Allocate the fake linebreak indices on first use. + // TODO(adonovan): opt: save ~512KB using a more complex scheme? + fakeLinesOnce.Do(func() { + fakeLines = make([]int, maxlines) + for i := range fakeLines { + fakeLines[i] = i + } + }) + f.SetLines(fakeLines) + } + + if line > maxlines { + line = 1 + } + + // Treat the file as if it contained only newlines + // and column=1: use the line number as the offset. + return f.Pos(line - 1) +} + +var ( + fakeLines []int + fakeLinesOnce sync.Once +) + +func (p *importer) qualifiedName() (pkg *types.Package, name string) { + name = p.string() + pkg = p.pkg() + return +} + +func (p *importer) record(t types.Type) { + p.typList = append(p.typList, t) +} + +// A dddSlice is a types.Type representing ...T parameters. +// It only appears for parameter types and does not escape +// the importer. +type dddSlice struct { + elem types.Type +} + +func (t *dddSlice) Underlying() types.Type { return t } +func (t *dddSlice) String() string { return "..." + t.elem.String() } + +// parent is the package which declared the type; parent == nil means +// the package currently imported. The parent package is needed for +// exported struct fields and interface methods which don't contain +// explicit package information in the export data. +// +// A non-nil tname is used as the "owner" of the result type; i.e., +// the result type is the underlying type of tname. tname is used +// to give interface methods a named receiver type where possible. +func (p *importer) typ(parent *types.Package, tname *types.Named) types.Type { + // if the type was seen before, i is its index (>= 0) + i := p.tagOrIndex() + if i >= 0 { + return p.typList[i] + } + + // otherwise, i is the type tag (< 0) + switch i { + case namedTag: + // read type object + pos := p.pos() + parent, name := p.qualifiedName() + scope := parent.Scope() + obj := scope.Lookup(name) + + // if the object doesn't exist yet, create and insert it + if obj == nil { + obj = types.NewTypeName(pos, parent, name, nil) + scope.Insert(obj) + } + + if _, ok := obj.(*types.TypeName); !ok { + errorf("pkg = %s, name = %s => %s", parent, name, obj) + } + + // associate new named type with obj if it doesn't exist yet + t0 := types.NewNamed(obj.(*types.TypeName), nil, nil) + + // but record the existing type, if any + tname := obj.Type().(*types.Named) // tname is either t0 or the existing type + p.record(tname) + + // read underlying type + t0.SetUnderlying(p.typ(parent, t0)) + + // interfaces don't have associated methods + if types.IsInterface(t0) { + return tname + } + + // read associated methods + for i := p.int(); i > 0; i-- { + // TODO(gri) replace this with something closer to fieldName + pos := p.pos() + name := p.string() + if !exported(name) { + p.pkg() + } + + recv, _ := p.paramList() // TODO(gri) do we need a full param list for the receiver? + params, isddd := p.paramList() + result, _ := p.paramList() + p.int() // go:nointerface pragma - discarded + + sig := types.NewSignature(recv.At(0), params, result, isddd) + t0.AddMethod(types.NewFunc(pos, parent, name, sig)) + } + + return tname + + case arrayTag: + t := new(types.Array) + if p.trackAllTypes { + p.record(t) + } + + n := p.int64() + *t = *types.NewArray(p.typ(parent, nil), n) + return t + + case sliceTag: + t := new(types.Slice) + if p.trackAllTypes { + p.record(t) + } + + *t = *types.NewSlice(p.typ(parent, nil)) + return t + + case dddTag: + t := new(dddSlice) + if p.trackAllTypes { + p.record(t) + } + + t.elem = p.typ(parent, nil) + return t + + case structTag: + t := new(types.Struct) + if p.trackAllTypes { + p.record(t) + } + + *t = *types.NewStruct(p.fieldList(parent)) + return t + + case pointerTag: + t := new(types.Pointer) + if p.trackAllTypes { + p.record(t) + } + + *t = *types.NewPointer(p.typ(parent, nil)) + return t + + case signatureTag: + t := new(types.Signature) + if p.trackAllTypes { + p.record(t) + } + + params, isddd := p.paramList() + result, _ := p.paramList() + *t = *types.NewSignature(nil, params, result, isddd) + return t + + case interfaceTag: + // Create a dummy entry in the type list. This is safe because we + // cannot expect the interface type to appear in a cycle, as any + // such cycle must contain a named type which would have been + // first defined earlier. + // TODO(gri) Is this still true now that we have type aliases? + // See issue #23225. + n := len(p.typList) + if p.trackAllTypes { + p.record(nil) + } + + var embeddeds []types.Type + for n := p.int(); n > 0; n-- { + p.pos() + embeddeds = append(embeddeds, p.typ(parent, nil)) + } + + t := newInterface(p.methodList(parent, tname), embeddeds) + p.interfaceList = append(p.interfaceList, t) + if p.trackAllTypes { + p.typList[n] = t + } + return t + + case mapTag: + t := new(types.Map) + if p.trackAllTypes { + p.record(t) + } + + key := p.typ(parent, nil) + val := p.typ(parent, nil) + *t = *types.NewMap(key, val) + return t + + case chanTag: + t := new(types.Chan) + if p.trackAllTypes { + p.record(t) + } + + dir := chanDir(p.int()) + val := p.typ(parent, nil) + *t = *types.NewChan(dir, val) + return t + + default: + errorf("unexpected type tag %d", i) // panics + panic("unreachable") + } +} + +func chanDir(d int) types.ChanDir { + // tag values must match the constants in cmd/compile/internal/gc/go.go + switch d { + case 1 /* Crecv */ : + return types.RecvOnly + case 2 /* Csend */ : + return types.SendOnly + case 3 /* Cboth */ : + return types.SendRecv + default: + errorf("unexpected channel dir %d", d) + return 0 + } +} + +func (p *importer) fieldList(parent *types.Package) (fields []*types.Var, tags []string) { + if n := p.int(); n > 0 { + fields = make([]*types.Var, n) + tags = make([]string, n) + for i := range fields { + fields[i], tags[i] = p.field(parent) + } + } + return +} + +func (p *importer) field(parent *types.Package) (*types.Var, string) { + pos := p.pos() + pkg, name, alias := p.fieldName(parent) + typ := p.typ(parent, nil) + tag := p.string() + + anonymous := false + if name == "" { + // anonymous field - typ must be T or *T and T must be a type name + switch typ := deref(typ).(type) { + case *types.Basic: // basic types are named types + pkg = nil // // objects defined in Universe scope have no package + name = typ.Name() + case *types.Named: + name = typ.Obj().Name() + default: + errorf("named base type expected") + } + anonymous = true + } else if alias { + // anonymous field: we have an explicit name because it's an alias + anonymous = true + } + + return types.NewField(pos, pkg, name, typ, anonymous), tag +} + +func (p *importer) methodList(parent *types.Package, baseType *types.Named) (methods []*types.Func) { + if n := p.int(); n > 0 { + methods = make([]*types.Func, n) + for i := range methods { + methods[i] = p.method(parent, baseType) + } + } + return +} + +func (p *importer) method(parent *types.Package, baseType *types.Named) *types.Func { + pos := p.pos() + pkg, name, _ := p.fieldName(parent) + // If we don't have a baseType, use a nil receiver. + // A receiver using the actual interface type (which + // we don't know yet) will be filled in when we call + // types.Interface.Complete. + var recv *types.Var + if baseType != nil { + recv = types.NewVar(token.NoPos, parent, "", baseType) + } + params, isddd := p.paramList() + result, _ := p.paramList() + sig := types.NewSignature(recv, params, result, isddd) + return types.NewFunc(pos, pkg, name, sig) +} + +func (p *importer) fieldName(parent *types.Package) (pkg *types.Package, name string, alias bool) { + name = p.string() + pkg = parent + if pkg == nil { + // use the imported package instead + pkg = p.pkgList[0] + } + if p.version == 0 && name == "_" { + // version 0 didn't export a package for _ fields + return + } + switch name { + case "": + // 1) field name matches base type name and is exported: nothing to do + case "?": + // 2) field name matches base type name and is not exported: need package + name = "" + pkg = p.pkg() + case "@": + // 3) field name doesn't match type name (alias) + name = p.string() + alias = true + fallthrough + default: + if !exported(name) { + pkg = p.pkg() + } + } + return +} + +func (p *importer) paramList() (*types.Tuple, bool) { + n := p.int() + if n == 0 { + return nil, false + } + // negative length indicates unnamed parameters + named := true + if n < 0 { + n = -n + named = false + } + // n > 0 + params := make([]*types.Var, n) + isddd := false + for i := range params { + params[i], isddd = p.param(named) + } + return types.NewTuple(params...), isddd +} + +func (p *importer) param(named bool) (*types.Var, bool) { + t := p.typ(nil, nil) + td, isddd := t.(*dddSlice) + if isddd { + t = types.NewSlice(td.elem) + } + + var pkg *types.Package + var name string + if named { + name = p.string() + if name == "" { + errorf("expected named parameter") + } + if name != "_" { + pkg = p.pkg() + } + if i := strings.Index(name, "·"); i > 0 { + name = name[:i] // cut off gc-specific parameter numbering + } + } + + // read and discard compiler-specific info + p.string() + + return types.NewVar(token.NoPos, pkg, name, t), isddd +} + +func exported(name string) bool { + ch, _ := utf8.DecodeRuneInString(name) + return unicode.IsUpper(ch) +} + +func (p *importer) value() constant.Value { + switch tag := p.tagOrIndex(); tag { + case falseTag: + return constant.MakeBool(false) + case trueTag: + return constant.MakeBool(true) + case int64Tag: + return constant.MakeInt64(p.int64()) + case floatTag: + return p.float() + case complexTag: + re := p.float() + im := p.float() + return constant.BinaryOp(re, token.ADD, constant.MakeImag(im)) + case stringTag: + return constant.MakeString(p.string()) + case unknownTag: + return constant.MakeUnknown() + default: + errorf("unexpected value tag %d", tag) // panics + panic("unreachable") + } +} + +func (p *importer) float() constant.Value { + sign := p.int() + if sign == 0 { + return constant.MakeInt64(0) + } + + exp := p.int() + mant := []byte(p.string()) // big endian + + // remove leading 0's if any + for len(mant) > 0 && mant[0] == 0 { + mant = mant[1:] + } + + // convert to little endian + // TODO(gri) go/constant should have a more direct conversion function + // (e.g., once it supports a big.Float based implementation) + for i, j := 0, len(mant)-1; i < j; i, j = i+1, j-1 { + mant[i], mant[j] = mant[j], mant[i] + } + + // adjust exponent (constant.MakeFromBytes creates an integer value, + // but mant represents the mantissa bits such that 0.5 <= mant < 1.0) + exp -= len(mant) << 3 + if len(mant) > 0 { + for msd := mant[len(mant)-1]; msd&0x80 == 0; msd <<= 1 { + exp++ + } + } + + x := constant.MakeFromBytes(mant) + switch { + case exp < 0: + d := constant.Shift(constant.MakeInt64(1), token.SHL, uint(-exp)) + x = constant.BinaryOp(x, token.QUO, d) + case exp > 0: + x = constant.Shift(x, token.SHL, uint(exp)) + } + + if sign < 0 { + x = constant.UnaryOp(token.SUB, x, 0) + } + return x +} + +// ---------------------------------------------------------------------------- +// Low-level decoders + +func (p *importer) tagOrIndex() int { + if p.debugFormat { + p.marker('t') + } + + return int(p.rawInt64()) +} + +func (p *importer) int() int { + x := p.int64() + if int64(int(x)) != x { + errorf("exported integer too large") + } + return int(x) +} + +func (p *importer) int64() int64 { + if p.debugFormat { + p.marker('i') + } + + return p.rawInt64() +} + +func (p *importer) path() string { + if p.debugFormat { + p.marker('p') + } + // if the path was seen before, i is its index (>= 0) + // (the empty string is at index 0) + i := p.rawInt64() + if i >= 0 { + return p.pathList[i] + } + // otherwise, i is the negative path length (< 0) + a := make([]string, -i) + for n := range a { + a[n] = p.string() + } + s := strings.Join(a, "/") + p.pathList = append(p.pathList, s) + return s +} + +func (p *importer) string() string { + if p.debugFormat { + p.marker('s') + } + // if the string was seen before, i is its index (>= 0) + // (the empty string is at index 0) + i := p.rawInt64() + if i >= 0 { + return p.strList[i] + } + // otherwise, i is the negative string length (< 0) + if n := int(-i); n <= cap(p.buf) { + p.buf = p.buf[:n] + } else { + p.buf = make([]byte, n) + } + for i := range p.buf { + p.buf[i] = p.rawByte() + } + s := string(p.buf) + p.strList = append(p.strList, s) + return s +} + +func (p *importer) marker(want byte) { + if got := p.rawByte(); got != want { + errorf("incorrect marker: got %c; want %c (pos = %d)", got, want, p.read) + } + + pos := p.read + if n := int(p.rawInt64()); n != pos { + errorf("incorrect position: got %d; want %d", n, pos) + } +} + +// rawInt64 should only be used by low-level decoders. +func (p *importer) rawInt64() int64 { + i, err := binary.ReadVarint(p) + if err != nil { + errorf("read error: %v", err) + } + return i +} + +// rawStringln should only be used to read the initial version string. +func (p *importer) rawStringln(b byte) string { + p.buf = p.buf[:0] + for b != '\n' { + p.buf = append(p.buf, b) + b = p.rawByte() + } + return string(p.buf) +} + +// needed for binary.ReadVarint in rawInt64 +func (p *importer) ReadByte() (byte, error) { + return p.rawByte(), nil +} + +// byte is the bottleneck interface for reading p.data. +// It unescapes '|' 'S' to '$' and '|' '|' to '|'. +// rawByte should only be used by low-level decoders. +func (p *importer) rawByte() byte { + b := p.data[0] + r := 1 + if b == '|' { + b = p.data[1] + r = 2 + switch b { + case 'S': + b = '$' + case '|': + // nothing to do + default: + errorf("unexpected escape sequence in export data") + } + } + p.data = p.data[r:] + p.read += r + return b + +} + +// ---------------------------------------------------------------------------- +// Export format + +// Tags. Must be < 0. +const ( + // Objects + packageTag = -(iota + 1) + constTag + typeTag + varTag + funcTag + endTag + + // Types + namedTag + arrayTag + sliceTag + dddTag + structTag + pointerTag + signatureTag + interfaceTag + mapTag + chanTag + + // Values + falseTag + trueTag + int64Tag + floatTag + fractionTag // not used by gc + complexTag + stringTag + nilTag // only used by gc (appears in exported inlined function bodies) + unknownTag // not used by gc (only appears in packages with errors) + + // Type aliases + aliasTag +) + +var predeclOnce sync.Once +var predecl []types.Type // initialized lazily + +func predeclared() []types.Type { + predeclOnce.Do(func() { + // initialize lazily to be sure that all + // elements have been initialized before + predecl = []types.Type{ // basic types + types.Typ[types.Bool], + types.Typ[types.Int], + types.Typ[types.Int8], + types.Typ[types.Int16], + types.Typ[types.Int32], + types.Typ[types.Int64], + types.Typ[types.Uint], + types.Typ[types.Uint8], + types.Typ[types.Uint16], + types.Typ[types.Uint32], + types.Typ[types.Uint64], + types.Typ[types.Uintptr], + types.Typ[types.Float32], + types.Typ[types.Float64], + types.Typ[types.Complex64], + types.Typ[types.Complex128], + types.Typ[types.String], + + // basic type aliases + types.Universe.Lookup("byte").Type(), + types.Universe.Lookup("rune").Type(), + + // error + types.Universe.Lookup("error").Type(), + + // untyped types + types.Typ[types.UntypedBool], + types.Typ[types.UntypedInt], + types.Typ[types.UntypedRune], + types.Typ[types.UntypedFloat], + types.Typ[types.UntypedComplex], + types.Typ[types.UntypedString], + types.Typ[types.UntypedNil], + + // package unsafe + types.Typ[types.UnsafePointer], + + // invalid type + types.Typ[types.Invalid], // only appears in packages with errors + + // used internally by gc; never used by this package or in .a files + anyType{}, + } + }) + return predecl +} + +type anyType struct{} + +func (t anyType) Underlying() types.Type { return t } +func (t anyType) String() string { return "any" } diff --git a/vendor/golang.org/x/tools/go/internal/gcimporter/exportdata.go b/vendor/golang.org/x/tools/go/internal/gcimporter/exportdata.go new file mode 100644 index 0000000000..f33dc5613e --- /dev/null +++ b/vendor/golang.org/x/tools/go/internal/gcimporter/exportdata.go @@ -0,0 +1,93 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file is a copy of $GOROOT/src/go/internal/gcimporter/exportdata.go. + +// This file implements FindExportData. + +package gcimporter + +import ( + "bufio" + "fmt" + "io" + "strconv" + "strings" +) + +func readGopackHeader(r *bufio.Reader) (name string, size int, err error) { + // See $GOROOT/include/ar.h. + hdr := make([]byte, 16+12+6+6+8+10+2) + _, err = io.ReadFull(r, hdr) + if err != nil { + return + } + // leave for debugging + if false { + fmt.Printf("header: %s", hdr) + } + s := strings.TrimSpace(string(hdr[16+12+6+6+8:][:10])) + size, err = strconv.Atoi(s) + if err != nil || hdr[len(hdr)-2] != '`' || hdr[len(hdr)-1] != '\n' { + err = fmt.Errorf("invalid archive header") + return + } + name = strings.TrimSpace(string(hdr[:16])) + return +} + +// FindExportData positions the reader r at the beginning of the +// export data section of an underlying GC-created object/archive +// file by reading from it. The reader must be positioned at the +// start of the file before calling this function. The hdr result +// is the string before the export data, either "$$" or "$$B". +// +func FindExportData(r *bufio.Reader) (hdr string, err error) { + // Read first line to make sure this is an object file. + line, err := r.ReadSlice('\n') + if err != nil { + err = fmt.Errorf("can't find export data (%v)", err) + return + } + + if string(line) == "!\n" { + // Archive file. Scan to __.PKGDEF. + var name string + if name, _, err = readGopackHeader(r); err != nil { + return + } + + // First entry should be __.PKGDEF. + if name != "__.PKGDEF" { + err = fmt.Errorf("go archive is missing __.PKGDEF") + return + } + + // Read first line of __.PKGDEF data, so that line + // is once again the first line of the input. + if line, err = r.ReadSlice('\n'); err != nil { + err = fmt.Errorf("can't find export data (%v)", err) + return + } + } + + // Now at __.PKGDEF in archive or still at beginning of file. + // Either way, line should begin with "go object ". + if !strings.HasPrefix(string(line), "go object ") { + err = fmt.Errorf("not a Go object file") + return + } + + // Skip over object header to export data. + // Begins after first line starting with $$. + for line[0] != '$' { + if line, err = r.ReadSlice('\n'); err != nil { + err = fmt.Errorf("can't find export data (%v)", err) + return + } + } + hdr = string(line) + + return +} diff --git a/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go b/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go new file mode 100644 index 0000000000..e8cba6b237 --- /dev/null +++ b/vendor/golang.org/x/tools/go/internal/gcimporter/gcimporter.go @@ -0,0 +1,1078 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file is a modified copy of $GOROOT/src/go/internal/gcimporter/gcimporter.go, +// but it also contains the original source-based importer code for Go1.6. +// Once we stop supporting 1.6, we can remove that code. + +// Package gcimporter provides various functions for reading +// gc-generated object files that can be used to implement the +// Importer interface defined by the Go 1.5 standard library package. +package gcimporter // import "golang.org/x/tools/go/internal/gcimporter" + +import ( + "bufio" + "errors" + "fmt" + "go/build" + "go/constant" + "go/token" + "go/types" + "io" + "io/ioutil" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "text/scanner" +) + +// debugging/development support +const debug = false + +var pkgExts = [...]string{".a", ".o"} + +// FindPkg returns the filename and unique package id for an import +// path based on package information provided by build.Import (using +// the build.Default build.Context). A relative srcDir is interpreted +// relative to the current working directory. +// If no file was found, an empty filename is returned. +// +func FindPkg(path, srcDir string) (filename, id string) { + if path == "" { + return + } + + var noext string + switch { + default: + // "x" -> "$GOPATH/pkg/$GOOS_$GOARCH/x.ext", "x" + // Don't require the source files to be present. + if abs, err := filepath.Abs(srcDir); err == nil { // see issue 14282 + srcDir = abs + } + bp, _ := build.Import(path, srcDir, build.FindOnly|build.AllowBinary) + if bp.PkgObj == "" { + id = path // make sure we have an id to print in error message + return + } + noext = strings.TrimSuffix(bp.PkgObj, ".a") + id = bp.ImportPath + + case build.IsLocalImport(path): + // "./x" -> "/this/directory/x.ext", "/this/directory/x" + noext = filepath.Join(srcDir, path) + id = noext + + case filepath.IsAbs(path): + // for completeness only - go/build.Import + // does not support absolute imports + // "/x" -> "/x.ext", "/x" + noext = path + id = path + } + + if false { // for debugging + if path != id { + fmt.Printf("%s -> %s\n", path, id) + } + } + + // try extensions + for _, ext := range pkgExts { + filename = noext + ext + if f, err := os.Stat(filename); err == nil && !f.IsDir() { + return + } + } + + filename = "" // not found + return +} + +// ImportData imports a package by reading the gc-generated export data, +// adds the corresponding package object to the packages map indexed by id, +// and returns the object. +// +// The packages map must contains all packages already imported. The data +// reader position must be the beginning of the export data section. The +// filename is only used in error messages. +// +// If packages[id] contains the completely imported package, that package +// can be used directly, and there is no need to call this function (but +// there is also no harm but for extra time used). +// +func ImportData(packages map[string]*types.Package, filename, id string, data io.Reader) (pkg *types.Package, err error) { + // support for parser error handling + defer func() { + switch r := recover().(type) { + case nil: + // nothing to do + case importError: + err = r + default: + panic(r) // internal error + } + }() + + var p parser + p.init(filename, id, data, packages) + pkg = p.parseExport() + + return +} + +// Import imports a gc-generated package given its import path and srcDir, adds +// the corresponding package object to the packages map, and returns the object. +// The packages map must contain all packages already imported. +// +func Import(packages map[string]*types.Package, path, srcDir string, lookup func(path string) (io.ReadCloser, error)) (pkg *types.Package, err error) { + var rc io.ReadCloser + var filename, id string + if lookup != nil { + // With custom lookup specified, assume that caller has + // converted path to a canonical import path for use in the map. + if path == "unsafe" { + return types.Unsafe, nil + } + id = path + + // No need to re-import if the package was imported completely before. + if pkg = packages[id]; pkg != nil && pkg.Complete() { + return + } + f, err := lookup(path) + if err != nil { + return nil, err + } + rc = f + } else { + filename, id = FindPkg(path, srcDir) + if filename == "" { + if path == "unsafe" { + return types.Unsafe, nil + } + return nil, fmt.Errorf("can't find import: %q", id) + } + + // no need to re-import if the package was imported completely before + if pkg = packages[id]; pkg != nil && pkg.Complete() { + return + } + + // open file + f, err := os.Open(filename) + if err != nil { + return nil, err + } + defer func() { + if err != nil { + // add file name to error + err = fmt.Errorf("%s: %v", filename, err) + } + }() + rc = f + } + defer rc.Close() + + var hdr string + buf := bufio.NewReader(rc) + if hdr, err = FindExportData(buf); err != nil { + return + } + + switch hdr { + case "$$\n": + // Work-around if we don't have a filename; happens only if lookup != nil. + // Either way, the filename is only needed for importer error messages, so + // this is fine. + if filename == "" { + filename = path + } + return ImportData(packages, filename, id, buf) + + case "$$B\n": + var data []byte + data, err = ioutil.ReadAll(buf) + if err != nil { + break + } + + // TODO(gri): allow clients of go/importer to provide a FileSet. + // Or, define a new standard go/types/gcexportdata package. + fset := token.NewFileSet() + + // The indexed export format starts with an 'i'; the older + // binary export format starts with a 'c', 'd', or 'v' + // (from "version"). Select appropriate importer. + if len(data) > 0 && data[0] == 'i' { + _, pkg, err = IImportData(fset, packages, data[1:], id) + } else { + _, pkg, err = BImportData(fset, packages, data, id) + } + + default: + err = fmt.Errorf("unknown export data header: %q", hdr) + } + + return +} + +// ---------------------------------------------------------------------------- +// Parser + +// TODO(gri) Imported objects don't have position information. +// Ideally use the debug table line info; alternatively +// create some fake position (or the position of the +// import). That way error messages referring to imported +// objects can print meaningful information. + +// parser parses the exports inside a gc compiler-produced +// object/archive file and populates its scope with the results. +type parser struct { + scanner scanner.Scanner + tok rune // current token + lit string // literal string; only valid for Ident, Int, String tokens + id string // package id of imported package + sharedPkgs map[string]*types.Package // package id -> package object (across importer) + localPkgs map[string]*types.Package // package id -> package object (just this package) +} + +func (p *parser) init(filename, id string, src io.Reader, packages map[string]*types.Package) { + p.scanner.Init(src) + p.scanner.Error = func(_ *scanner.Scanner, msg string) { p.error(msg) } + p.scanner.Mode = scanner.ScanIdents | scanner.ScanInts | scanner.ScanChars | scanner.ScanStrings | scanner.ScanComments | scanner.SkipComments + p.scanner.Whitespace = 1<<'\t' | 1<<' ' + p.scanner.Filename = filename // for good error messages + p.next() + p.id = id + p.sharedPkgs = packages + if debug { + // check consistency of packages map + for _, pkg := range packages { + if pkg.Name() == "" { + fmt.Printf("no package name for %s\n", pkg.Path()) + } + } + } +} + +func (p *parser) next() { + p.tok = p.scanner.Scan() + switch p.tok { + case scanner.Ident, scanner.Int, scanner.Char, scanner.String, '·': + p.lit = p.scanner.TokenText() + default: + p.lit = "" + } + if debug { + fmt.Printf("%s: %q -> %q\n", scanner.TokenString(p.tok), p.scanner.TokenText(), p.lit) + } +} + +func declTypeName(pkg *types.Package, name string) *types.TypeName { + scope := pkg.Scope() + if obj := scope.Lookup(name); obj != nil { + return obj.(*types.TypeName) + } + obj := types.NewTypeName(token.NoPos, pkg, name, nil) + // a named type may be referred to before the underlying type + // is known - set it up + types.NewNamed(obj, nil, nil) + scope.Insert(obj) + return obj +} + +// ---------------------------------------------------------------------------- +// Error handling + +// Internal errors are boxed as importErrors. +type importError struct { + pos scanner.Position + err error +} + +func (e importError) Error() string { + return fmt.Sprintf("import error %s (byte offset = %d): %s", e.pos, e.pos.Offset, e.err) +} + +func (p *parser) error(err interface{}) { + if s, ok := err.(string); ok { + err = errors.New(s) + } + // panic with a runtime.Error if err is not an error + panic(importError{p.scanner.Pos(), err.(error)}) +} + +func (p *parser) errorf(format string, args ...interface{}) { + p.error(fmt.Sprintf(format, args...)) +} + +func (p *parser) expect(tok rune) string { + lit := p.lit + if p.tok != tok { + p.errorf("expected %s, got %s (%s)", scanner.TokenString(tok), scanner.TokenString(p.tok), lit) + } + p.next() + return lit +} + +func (p *parser) expectSpecial(tok string) { + sep := 'x' // not white space + i := 0 + for i < len(tok) && p.tok == rune(tok[i]) && sep > ' ' { + sep = p.scanner.Peek() // if sep <= ' ', there is white space before the next token + p.next() + i++ + } + if i < len(tok) { + p.errorf("expected %q, got %q", tok, tok[0:i]) + } +} + +func (p *parser) expectKeyword(keyword string) { + lit := p.expect(scanner.Ident) + if lit != keyword { + p.errorf("expected keyword %s, got %q", keyword, lit) + } +} + +// ---------------------------------------------------------------------------- +// Qualified and unqualified names + +// PackageId = string_lit . +// +func (p *parser) parsePackageID() string { + id, err := strconv.Unquote(p.expect(scanner.String)) + if err != nil { + p.error(err) + } + // id == "" stands for the imported package id + // (only known at time of package installation) + if id == "" { + id = p.id + } + return id +} + +// PackageName = ident . +// +func (p *parser) parsePackageName() string { + return p.expect(scanner.Ident) +} + +// dotIdentifier = ( ident | '·' ) { ident | int | '·' } . +func (p *parser) parseDotIdent() string { + ident := "" + if p.tok != scanner.Int { + sep := 'x' // not white space + for (p.tok == scanner.Ident || p.tok == scanner.Int || p.tok == '·') && sep > ' ' { + ident += p.lit + sep = p.scanner.Peek() // if sep <= ' ', there is white space before the next token + p.next() + } + } + if ident == "" { + p.expect(scanner.Ident) // use expect() for error handling + } + return ident +} + +// QualifiedName = "@" PackageId "." ( "?" | dotIdentifier ) . +// +func (p *parser) parseQualifiedName() (id, name string) { + p.expect('@') + id = p.parsePackageID() + p.expect('.') + // Per rev f280b8a485fd (10/2/2013), qualified names may be used for anonymous fields. + if p.tok == '?' { + p.next() + } else { + name = p.parseDotIdent() + } + return +} + +// getPkg returns the package for a given id. If the package is +// not found, create the package and add it to the p.localPkgs +// and p.sharedPkgs maps. name is the (expected) name of the +// package. If name == "", the package name is expected to be +// set later via an import clause in the export data. +// +// id identifies a package, usually by a canonical package path like +// "encoding/json" but possibly by a non-canonical import path like +// "./json". +// +func (p *parser) getPkg(id, name string) *types.Package { + // package unsafe is not in the packages maps - handle explicitly + if id == "unsafe" { + return types.Unsafe + } + + pkg := p.localPkgs[id] + if pkg == nil { + // first import of id from this package + pkg = p.sharedPkgs[id] + if pkg == nil { + // first import of id by this importer; + // add (possibly unnamed) pkg to shared packages + pkg = types.NewPackage(id, name) + p.sharedPkgs[id] = pkg + } + // add (possibly unnamed) pkg to local packages + if p.localPkgs == nil { + p.localPkgs = make(map[string]*types.Package) + } + p.localPkgs[id] = pkg + } else if name != "" { + // package exists already and we have an expected package name; + // make sure names match or set package name if necessary + if pname := pkg.Name(); pname == "" { + pkg.SetName(name) + } else if pname != name { + p.errorf("%s package name mismatch: %s (given) vs %s (expected)", id, pname, name) + } + } + return pkg +} + +// parseExportedName is like parseQualifiedName, but +// the package id is resolved to an imported *types.Package. +// +func (p *parser) parseExportedName() (pkg *types.Package, name string) { + id, name := p.parseQualifiedName() + pkg = p.getPkg(id, "") + return +} + +// ---------------------------------------------------------------------------- +// Types + +// BasicType = identifier . +// +func (p *parser) parseBasicType() types.Type { + id := p.expect(scanner.Ident) + obj := types.Universe.Lookup(id) + if obj, ok := obj.(*types.TypeName); ok { + return obj.Type() + } + p.errorf("not a basic type: %s", id) + return nil +} + +// ArrayType = "[" int_lit "]" Type . +// +func (p *parser) parseArrayType(parent *types.Package) types.Type { + // "[" already consumed and lookahead known not to be "]" + lit := p.expect(scanner.Int) + p.expect(']') + elem := p.parseType(parent) + n, err := strconv.ParseInt(lit, 10, 64) + if err != nil { + p.error(err) + } + return types.NewArray(elem, n) +} + +// MapType = "map" "[" Type "]" Type . +// +func (p *parser) parseMapType(parent *types.Package) types.Type { + p.expectKeyword("map") + p.expect('[') + key := p.parseType(parent) + p.expect(']') + elem := p.parseType(parent) + return types.NewMap(key, elem) +} + +// Name = identifier | "?" | QualifiedName . +// +// For unqualified and anonymous names, the returned package is the parent +// package unless parent == nil, in which case the returned package is the +// package being imported. (The parent package is not nil if the name +// is an unqualified struct field or interface method name belonging to a +// type declared in another package.) +// +// For qualified names, the returned package is nil (and not created if +// it doesn't exist yet) unless materializePkg is set (which creates an +// unnamed package with valid package path). In the latter case, a +// subsequent import clause is expected to provide a name for the package. +// +func (p *parser) parseName(parent *types.Package, materializePkg bool) (pkg *types.Package, name string) { + pkg = parent + if pkg == nil { + pkg = p.sharedPkgs[p.id] + } + switch p.tok { + case scanner.Ident: + name = p.lit + p.next() + case '?': + // anonymous + p.next() + case '@': + // exported name prefixed with package path + pkg = nil + var id string + id, name = p.parseQualifiedName() + if materializePkg { + pkg = p.getPkg(id, "") + } + default: + p.error("name expected") + } + return +} + +func deref(typ types.Type) types.Type { + if p, _ := typ.(*types.Pointer); p != nil { + return p.Elem() + } + return typ +} + +// Field = Name Type [ string_lit ] . +// +func (p *parser) parseField(parent *types.Package) (*types.Var, string) { + pkg, name := p.parseName(parent, true) + + if name == "_" { + // Blank fields should be package-qualified because they + // are unexported identifiers, but gc does not qualify them. + // Assuming that the ident belongs to the current package + // causes types to change during re-exporting, leading + // to spurious "can't assign A to B" errors from go/types. + // As a workaround, pretend all blank fields belong + // to the same unique dummy package. + const blankpkg = "<_>" + pkg = p.getPkg(blankpkg, blankpkg) + } + + typ := p.parseType(parent) + anonymous := false + if name == "" { + // anonymous field - typ must be T or *T and T must be a type name + switch typ := deref(typ).(type) { + case *types.Basic: // basic types are named types + pkg = nil // objects defined in Universe scope have no package + name = typ.Name() + case *types.Named: + name = typ.Obj().Name() + default: + p.errorf("anonymous field expected") + } + anonymous = true + } + tag := "" + if p.tok == scanner.String { + s := p.expect(scanner.String) + var err error + tag, err = strconv.Unquote(s) + if err != nil { + p.errorf("invalid struct tag %s: %s", s, err) + } + } + return types.NewField(token.NoPos, pkg, name, typ, anonymous), tag +} + +// StructType = "struct" "{" [ FieldList ] "}" . +// FieldList = Field { ";" Field } . +// +func (p *parser) parseStructType(parent *types.Package) types.Type { + var fields []*types.Var + var tags []string + + p.expectKeyword("struct") + p.expect('{') + for i := 0; p.tok != '}' && p.tok != scanner.EOF; i++ { + if i > 0 { + p.expect(';') + } + fld, tag := p.parseField(parent) + if tag != "" && tags == nil { + tags = make([]string, i) + } + if tags != nil { + tags = append(tags, tag) + } + fields = append(fields, fld) + } + p.expect('}') + + return types.NewStruct(fields, tags) +} + +// Parameter = ( identifier | "?" ) [ "..." ] Type [ string_lit ] . +// +func (p *parser) parseParameter() (par *types.Var, isVariadic bool) { + _, name := p.parseName(nil, false) + // remove gc-specific parameter numbering + if i := strings.Index(name, "·"); i >= 0 { + name = name[:i] + } + if p.tok == '.' { + p.expectSpecial("...") + isVariadic = true + } + typ := p.parseType(nil) + if isVariadic { + typ = types.NewSlice(typ) + } + // ignore argument tag (e.g. "noescape") + if p.tok == scanner.String { + p.next() + } + // TODO(gri) should we provide a package? + par = types.NewVar(token.NoPos, nil, name, typ) + return +} + +// Parameters = "(" [ ParameterList ] ")" . +// ParameterList = { Parameter "," } Parameter . +// +func (p *parser) parseParameters() (list []*types.Var, isVariadic bool) { + p.expect('(') + for p.tok != ')' && p.tok != scanner.EOF { + if len(list) > 0 { + p.expect(',') + } + par, variadic := p.parseParameter() + list = append(list, par) + if variadic { + if isVariadic { + p.error("... not on final argument") + } + isVariadic = true + } + } + p.expect(')') + + return +} + +// Signature = Parameters [ Result ] . +// Result = Type | Parameters . +// +func (p *parser) parseSignature(recv *types.Var) *types.Signature { + params, isVariadic := p.parseParameters() + + // optional result type + var results []*types.Var + if p.tok == '(' { + var variadic bool + results, variadic = p.parseParameters() + if variadic { + p.error("... not permitted on result type") + } + } + + return types.NewSignature(recv, types.NewTuple(params...), types.NewTuple(results...), isVariadic) +} + +// InterfaceType = "interface" "{" [ MethodList ] "}" . +// MethodList = Method { ";" Method } . +// Method = Name Signature . +// +// The methods of embedded interfaces are always "inlined" +// by the compiler and thus embedded interfaces are never +// visible in the export data. +// +func (p *parser) parseInterfaceType(parent *types.Package) types.Type { + var methods []*types.Func + + p.expectKeyword("interface") + p.expect('{') + for i := 0; p.tok != '}' && p.tok != scanner.EOF; i++ { + if i > 0 { + p.expect(';') + } + pkg, name := p.parseName(parent, true) + sig := p.parseSignature(nil) + methods = append(methods, types.NewFunc(token.NoPos, pkg, name, sig)) + } + p.expect('}') + + // Complete requires the type's embedded interfaces to be fully defined, + // but we do not define any + return newInterface(methods, nil).Complete() +} + +// ChanType = ( "chan" [ "<-" ] | "<-" "chan" ) Type . +// +func (p *parser) parseChanType(parent *types.Package) types.Type { + dir := types.SendRecv + if p.tok == scanner.Ident { + p.expectKeyword("chan") + if p.tok == '<' { + p.expectSpecial("<-") + dir = types.SendOnly + } + } else { + p.expectSpecial("<-") + p.expectKeyword("chan") + dir = types.RecvOnly + } + elem := p.parseType(parent) + return types.NewChan(dir, elem) +} + +// Type = +// BasicType | TypeName | ArrayType | SliceType | StructType | +// PointerType | FuncType | InterfaceType | MapType | ChanType | +// "(" Type ")" . +// +// BasicType = ident . +// TypeName = ExportedName . +// SliceType = "[" "]" Type . +// PointerType = "*" Type . +// FuncType = "func" Signature . +// +func (p *parser) parseType(parent *types.Package) types.Type { + switch p.tok { + case scanner.Ident: + switch p.lit { + default: + return p.parseBasicType() + case "struct": + return p.parseStructType(parent) + case "func": + // FuncType + p.next() + return p.parseSignature(nil) + case "interface": + return p.parseInterfaceType(parent) + case "map": + return p.parseMapType(parent) + case "chan": + return p.parseChanType(parent) + } + case '@': + // TypeName + pkg, name := p.parseExportedName() + return declTypeName(pkg, name).Type() + case '[': + p.next() // look ahead + if p.tok == ']' { + // SliceType + p.next() + return types.NewSlice(p.parseType(parent)) + } + return p.parseArrayType(parent) + case '*': + // PointerType + p.next() + return types.NewPointer(p.parseType(parent)) + case '<': + return p.parseChanType(parent) + case '(': + // "(" Type ")" + p.next() + typ := p.parseType(parent) + p.expect(')') + return typ + } + p.errorf("expected type, got %s (%q)", scanner.TokenString(p.tok), p.lit) + return nil +} + +// ---------------------------------------------------------------------------- +// Declarations + +// ImportDecl = "import" PackageName PackageId . +// +func (p *parser) parseImportDecl() { + p.expectKeyword("import") + name := p.parsePackageName() + p.getPkg(p.parsePackageID(), name) +} + +// int_lit = [ "+" | "-" ] { "0" ... "9" } . +// +func (p *parser) parseInt() string { + s := "" + switch p.tok { + case '-': + s = "-" + p.next() + case '+': + p.next() + } + return s + p.expect(scanner.Int) +} + +// number = int_lit [ "p" int_lit ] . +// +func (p *parser) parseNumber() (typ *types.Basic, val constant.Value) { + // mantissa + mant := constant.MakeFromLiteral(p.parseInt(), token.INT, 0) + if mant == nil { + panic("invalid mantissa") + } + + if p.lit == "p" { + // exponent (base 2) + p.next() + exp, err := strconv.ParseInt(p.parseInt(), 10, 0) + if err != nil { + p.error(err) + } + if exp < 0 { + denom := constant.MakeInt64(1) + denom = constant.Shift(denom, token.SHL, uint(-exp)) + typ = types.Typ[types.UntypedFloat] + val = constant.BinaryOp(mant, token.QUO, denom) + return + } + if exp > 0 { + mant = constant.Shift(mant, token.SHL, uint(exp)) + } + typ = types.Typ[types.UntypedFloat] + val = mant + return + } + + typ = types.Typ[types.UntypedInt] + val = mant + return +} + +// ConstDecl = "const" ExportedName [ Type ] "=" Literal . +// Literal = bool_lit | int_lit | float_lit | complex_lit | rune_lit | string_lit . +// bool_lit = "true" | "false" . +// complex_lit = "(" float_lit "+" float_lit "i" ")" . +// rune_lit = "(" int_lit "+" int_lit ")" . +// string_lit = `"` { unicode_char } `"` . +// +func (p *parser) parseConstDecl() { + p.expectKeyword("const") + pkg, name := p.parseExportedName() + + var typ0 types.Type + if p.tok != '=' { + // constant types are never structured - no need for parent type + typ0 = p.parseType(nil) + } + + p.expect('=') + var typ types.Type + var val constant.Value + switch p.tok { + case scanner.Ident: + // bool_lit + if p.lit != "true" && p.lit != "false" { + p.error("expected true or false") + } + typ = types.Typ[types.UntypedBool] + val = constant.MakeBool(p.lit == "true") + p.next() + + case '-', scanner.Int: + // int_lit + typ, val = p.parseNumber() + + case '(': + // complex_lit or rune_lit + p.next() + if p.tok == scanner.Char { + p.next() + p.expect('+') + typ = types.Typ[types.UntypedRune] + _, val = p.parseNumber() + p.expect(')') + break + } + _, re := p.parseNumber() + p.expect('+') + _, im := p.parseNumber() + p.expectKeyword("i") + p.expect(')') + typ = types.Typ[types.UntypedComplex] + val = constant.BinaryOp(re, token.ADD, constant.MakeImag(im)) + + case scanner.Char: + // rune_lit + typ = types.Typ[types.UntypedRune] + val = constant.MakeFromLiteral(p.lit, token.CHAR, 0) + p.next() + + case scanner.String: + // string_lit + typ = types.Typ[types.UntypedString] + val = constant.MakeFromLiteral(p.lit, token.STRING, 0) + p.next() + + default: + p.errorf("expected literal got %s", scanner.TokenString(p.tok)) + } + + if typ0 == nil { + typ0 = typ + } + + pkg.Scope().Insert(types.NewConst(token.NoPos, pkg, name, typ0, val)) +} + +// TypeDecl = "type" ExportedName Type . +// +func (p *parser) parseTypeDecl() { + p.expectKeyword("type") + pkg, name := p.parseExportedName() + obj := declTypeName(pkg, name) + + // The type object may have been imported before and thus already + // have a type associated with it. We still need to parse the type + // structure, but throw it away if the object already has a type. + // This ensures that all imports refer to the same type object for + // a given type declaration. + typ := p.parseType(pkg) + + if name := obj.Type().(*types.Named); name.Underlying() == nil { + name.SetUnderlying(typ) + } +} + +// VarDecl = "var" ExportedName Type . +// +func (p *parser) parseVarDecl() { + p.expectKeyword("var") + pkg, name := p.parseExportedName() + typ := p.parseType(pkg) + pkg.Scope().Insert(types.NewVar(token.NoPos, pkg, name, typ)) +} + +// Func = Signature [ Body ] . +// Body = "{" ... "}" . +// +func (p *parser) parseFunc(recv *types.Var) *types.Signature { + sig := p.parseSignature(recv) + if p.tok == '{' { + p.next() + for i := 1; i > 0; p.next() { + switch p.tok { + case '{': + i++ + case '}': + i-- + } + } + } + return sig +} + +// MethodDecl = "func" Receiver Name Func . +// Receiver = "(" ( identifier | "?" ) [ "*" ] ExportedName ")" . +// +func (p *parser) parseMethodDecl() { + // "func" already consumed + p.expect('(') + recv, _ := p.parseParameter() // receiver + p.expect(')') + + // determine receiver base type object + base := deref(recv.Type()).(*types.Named) + + // parse method name, signature, and possibly inlined body + _, name := p.parseName(nil, false) + sig := p.parseFunc(recv) + + // methods always belong to the same package as the base type object + pkg := base.Obj().Pkg() + + // add method to type unless type was imported before + // and method exists already + // TODO(gri) This leads to a quadratic algorithm - ok for now because method counts are small. + base.AddMethod(types.NewFunc(token.NoPos, pkg, name, sig)) +} + +// FuncDecl = "func" ExportedName Func . +// +func (p *parser) parseFuncDecl() { + // "func" already consumed + pkg, name := p.parseExportedName() + typ := p.parseFunc(nil) + pkg.Scope().Insert(types.NewFunc(token.NoPos, pkg, name, typ)) +} + +// Decl = [ ImportDecl | ConstDecl | TypeDecl | VarDecl | FuncDecl | MethodDecl ] "\n" . +// +func (p *parser) parseDecl() { + if p.tok == scanner.Ident { + switch p.lit { + case "import": + p.parseImportDecl() + case "const": + p.parseConstDecl() + case "type": + p.parseTypeDecl() + case "var": + p.parseVarDecl() + case "func": + p.next() // look ahead + if p.tok == '(' { + p.parseMethodDecl() + } else { + p.parseFuncDecl() + } + } + } + p.expect('\n') +} + +// ---------------------------------------------------------------------------- +// Export + +// Export = "PackageClause { Decl } "$$" . +// PackageClause = "package" PackageName [ "safe" ] "\n" . +// +func (p *parser) parseExport() *types.Package { + p.expectKeyword("package") + name := p.parsePackageName() + if p.tok == scanner.Ident && p.lit == "safe" { + // package was compiled with -u option - ignore + p.next() + } + p.expect('\n') + + pkg := p.getPkg(p.id, name) + + for p.tok != '$' && p.tok != scanner.EOF { + p.parseDecl() + } + + if ch := p.scanner.Peek(); p.tok != '$' || ch != '$' { + // don't call next()/expect() since reading past the + // export data may cause scanner errors (e.g. NUL chars) + p.errorf("expected '$$', got %s %c", scanner.TokenString(p.tok), ch) + } + + if n := p.scanner.ErrorCount; n != 0 { + p.errorf("expected no scanner errors, got %d", n) + } + + // Record all locally referenced packages as imports. + var imports []*types.Package + for id, pkg2 := range p.localPkgs { + if pkg2.Name() == "" { + p.errorf("%s package has no name", id) + } + if id == p.id { + continue // avoid self-edge + } + imports = append(imports, pkg2) + } + sort.Sort(byPath(imports)) + pkg.SetImports(imports) + + // package was imported completely and without errors + pkg.MarkComplete() + + return pkg +} + +type byPath []*types.Package + +func (a byPath) Len() int { return len(a) } +func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a byPath) Less(i, j int) bool { return a[i].Path() < a[j].Path() } diff --git a/vendor/golang.org/x/tools/go/internal/gcimporter/iexport.go b/vendor/golang.org/x/tools/go/internal/gcimporter/iexport.go new file mode 100644 index 0000000000..4be32a2e55 --- /dev/null +++ b/vendor/golang.org/x/tools/go/internal/gcimporter/iexport.go @@ -0,0 +1,739 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Indexed binary package export. +// This file was derived from $GOROOT/src/cmd/compile/internal/gc/iexport.go; +// see that file for specification of the format. + +package gcimporter + +import ( + "bytes" + "encoding/binary" + "go/ast" + "go/constant" + "go/token" + "go/types" + "io" + "math/big" + "reflect" + "sort" +) + +// Current indexed export format version. Increase with each format change. +// 0: Go1.11 encoding +const iexportVersion = 0 + +// IExportData returns the binary export data for pkg. +// +// If no file set is provided, position info will be missing. +// The package path of the top-level package will not be recorded, +// so that calls to IImportData can override with a provided package path. +func IExportData(fset *token.FileSet, pkg *types.Package) (b []byte, err error) { + defer func() { + if e := recover(); e != nil { + if ierr, ok := e.(internalError); ok { + err = ierr + return + } + // Not an internal error; panic again. + panic(e) + } + }() + + p := iexporter{ + out: bytes.NewBuffer(nil), + fset: fset, + allPkgs: map[*types.Package]bool{}, + stringIndex: map[string]uint64{}, + declIndex: map[types.Object]uint64{}, + typIndex: map[types.Type]uint64{}, + localpkg: pkg, + } + + for i, pt := range predeclared() { + p.typIndex[pt] = uint64(i) + } + if len(p.typIndex) > predeclReserved { + panic(internalErrorf("too many predeclared types: %d > %d", len(p.typIndex), predeclReserved)) + } + + // Initialize work queue with exported declarations. + scope := pkg.Scope() + for _, name := range scope.Names() { + if ast.IsExported(name) { + p.pushDecl(scope.Lookup(name)) + } + } + + // Loop until no more work. + for !p.declTodo.empty() { + p.doDecl(p.declTodo.popHead()) + } + + // Append indices to data0 section. + dataLen := uint64(p.data0.Len()) + w := p.newWriter() + w.writeIndex(p.declIndex) + w.flush() + + // Assemble header. + var hdr intWriter + hdr.WriteByte('i') + hdr.uint64(iexportVersion) + hdr.uint64(uint64(p.strings.Len())) + hdr.uint64(dataLen) + + // Flush output. + io.Copy(p.out, &hdr) + io.Copy(p.out, &p.strings) + io.Copy(p.out, &p.data0) + + return p.out.Bytes(), nil +} + +// writeIndex writes out an object index. mainIndex indicates whether +// we're writing out the main index, which is also read by +// non-compiler tools and includes a complete package description +// (i.e., name and height). +func (w *exportWriter) writeIndex(index map[types.Object]uint64) { + // Build a map from packages to objects from that package. + pkgObjs := map[*types.Package][]types.Object{} + + // For the main index, make sure to include every package that + // we reference, even if we're not exporting (or reexporting) + // any symbols from it. + pkgObjs[w.p.localpkg] = nil + for pkg := range w.p.allPkgs { + pkgObjs[pkg] = nil + } + + for obj := range index { + pkgObjs[obj.Pkg()] = append(pkgObjs[obj.Pkg()], obj) + } + + var pkgs []*types.Package + for pkg, objs := range pkgObjs { + pkgs = append(pkgs, pkg) + + sort.Slice(objs, func(i, j int) bool { + return objs[i].Name() < objs[j].Name() + }) + } + + sort.Slice(pkgs, func(i, j int) bool { + return w.exportPath(pkgs[i]) < w.exportPath(pkgs[j]) + }) + + w.uint64(uint64(len(pkgs))) + for _, pkg := range pkgs { + w.string(w.exportPath(pkg)) + w.string(pkg.Name()) + w.uint64(uint64(0)) // package height is not needed for go/types + + objs := pkgObjs[pkg] + w.uint64(uint64(len(objs))) + for _, obj := range objs { + w.string(obj.Name()) + w.uint64(index[obj]) + } + } +} + +type iexporter struct { + fset *token.FileSet + out *bytes.Buffer + + localpkg *types.Package + + // allPkgs tracks all packages that have been referenced by + // the export data, so we can ensure to include them in the + // main index. + allPkgs map[*types.Package]bool + + declTodo objQueue + + strings intWriter + stringIndex map[string]uint64 + + data0 intWriter + declIndex map[types.Object]uint64 + typIndex map[types.Type]uint64 +} + +// stringOff returns the offset of s within the string section. +// If not already present, it's added to the end. +func (p *iexporter) stringOff(s string) uint64 { + off, ok := p.stringIndex[s] + if !ok { + off = uint64(p.strings.Len()) + p.stringIndex[s] = off + + p.strings.uint64(uint64(len(s))) + p.strings.WriteString(s) + } + return off +} + +// pushDecl adds n to the declaration work queue, if not already present. +func (p *iexporter) pushDecl(obj types.Object) { + // Package unsafe is known to the compiler and predeclared. + assert(obj.Pkg() != types.Unsafe) + + if _, ok := p.declIndex[obj]; ok { + return + } + + p.declIndex[obj] = ^uint64(0) // mark n present in work queue + p.declTodo.pushTail(obj) +} + +// exportWriter handles writing out individual data section chunks. +type exportWriter struct { + p *iexporter + + data intWriter + currPkg *types.Package + prevFile string + prevLine int64 +} + +func (w *exportWriter) exportPath(pkg *types.Package) string { + if pkg == w.p.localpkg { + return "" + } + return pkg.Path() +} + +func (p *iexporter) doDecl(obj types.Object) { + w := p.newWriter() + w.setPkg(obj.Pkg(), false) + + switch obj := obj.(type) { + case *types.Var: + w.tag('V') + w.pos(obj.Pos()) + w.typ(obj.Type(), obj.Pkg()) + + case *types.Func: + sig, _ := obj.Type().(*types.Signature) + if sig.Recv() != nil { + panic(internalErrorf("unexpected method: %v", sig)) + } + w.tag('F') + w.pos(obj.Pos()) + w.signature(sig) + + case *types.Const: + w.tag('C') + w.pos(obj.Pos()) + w.value(obj.Type(), obj.Val()) + + case *types.TypeName: + if obj.IsAlias() { + w.tag('A') + w.pos(obj.Pos()) + w.typ(obj.Type(), obj.Pkg()) + break + } + + // Defined type. + w.tag('T') + w.pos(obj.Pos()) + + underlying := obj.Type().Underlying() + w.typ(underlying, obj.Pkg()) + + t := obj.Type() + if types.IsInterface(t) { + break + } + + named, ok := t.(*types.Named) + if !ok { + panic(internalErrorf("%s is not a defined type", t)) + } + + n := named.NumMethods() + w.uint64(uint64(n)) + for i := 0; i < n; i++ { + m := named.Method(i) + w.pos(m.Pos()) + w.string(m.Name()) + sig, _ := m.Type().(*types.Signature) + w.param(sig.Recv()) + w.signature(sig) + } + + default: + panic(internalErrorf("unexpected object: %v", obj)) + } + + p.declIndex[obj] = w.flush() +} + +func (w *exportWriter) tag(tag byte) { + w.data.WriteByte(tag) +} + +func (w *exportWriter) pos(pos token.Pos) { + if w.p.fset == nil { + w.int64(0) + return + } + + p := w.p.fset.Position(pos) + file := p.Filename + line := int64(p.Line) + + // When file is the same as the last position (common case), + // we can save a few bytes by delta encoding just the line + // number. + // + // Note: Because data objects may be read out of order (or not + // at all), we can only apply delta encoding within a single + // object. This is handled implicitly by tracking prevFile and + // prevLine as fields of exportWriter. + + if file == w.prevFile { + delta := line - w.prevLine + w.int64(delta) + if delta == deltaNewFile { + w.int64(-1) + } + } else { + w.int64(deltaNewFile) + w.int64(line) // line >= 0 + w.string(file) + w.prevFile = file + } + w.prevLine = line +} + +func (w *exportWriter) pkg(pkg *types.Package) { + // Ensure any referenced packages are declared in the main index. + w.p.allPkgs[pkg] = true + + w.string(w.exportPath(pkg)) +} + +func (w *exportWriter) qualifiedIdent(obj types.Object) { + // Ensure any referenced declarations are written out too. + w.p.pushDecl(obj) + + w.string(obj.Name()) + w.pkg(obj.Pkg()) +} + +func (w *exportWriter) typ(t types.Type, pkg *types.Package) { + w.data.uint64(w.p.typOff(t, pkg)) +} + +func (p *iexporter) newWriter() *exportWriter { + return &exportWriter{p: p} +} + +func (w *exportWriter) flush() uint64 { + off := uint64(w.p.data0.Len()) + io.Copy(&w.p.data0, &w.data) + return off +} + +func (p *iexporter) typOff(t types.Type, pkg *types.Package) uint64 { + off, ok := p.typIndex[t] + if !ok { + w := p.newWriter() + w.doTyp(t, pkg) + off = predeclReserved + w.flush() + p.typIndex[t] = off + } + return off +} + +func (w *exportWriter) startType(k itag) { + w.data.uint64(uint64(k)) +} + +func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) { + switch t := t.(type) { + case *types.Named: + w.startType(definedType) + w.qualifiedIdent(t.Obj()) + + case *types.Pointer: + w.startType(pointerType) + w.typ(t.Elem(), pkg) + + case *types.Slice: + w.startType(sliceType) + w.typ(t.Elem(), pkg) + + case *types.Array: + w.startType(arrayType) + w.uint64(uint64(t.Len())) + w.typ(t.Elem(), pkg) + + case *types.Chan: + w.startType(chanType) + // 1 RecvOnly; 2 SendOnly; 3 SendRecv + var dir uint64 + switch t.Dir() { + case types.RecvOnly: + dir = 1 + case types.SendOnly: + dir = 2 + case types.SendRecv: + dir = 3 + } + w.uint64(dir) + w.typ(t.Elem(), pkg) + + case *types.Map: + w.startType(mapType) + w.typ(t.Key(), pkg) + w.typ(t.Elem(), pkg) + + case *types.Signature: + w.startType(signatureType) + w.setPkg(pkg, true) + w.signature(t) + + case *types.Struct: + w.startType(structType) + w.setPkg(pkg, true) + + n := t.NumFields() + w.uint64(uint64(n)) + for i := 0; i < n; i++ { + f := t.Field(i) + w.pos(f.Pos()) + w.string(f.Name()) + w.typ(f.Type(), pkg) + w.bool(f.Anonymous()) + w.string(t.Tag(i)) // note (or tag) + } + + case *types.Interface: + w.startType(interfaceType) + w.setPkg(pkg, true) + + n := t.NumEmbeddeds() + w.uint64(uint64(n)) + for i := 0; i < n; i++ { + f := t.Embedded(i) + w.pos(f.Obj().Pos()) + w.typ(f.Obj().Type(), f.Obj().Pkg()) + } + + n = t.NumExplicitMethods() + w.uint64(uint64(n)) + for i := 0; i < n; i++ { + m := t.ExplicitMethod(i) + w.pos(m.Pos()) + w.string(m.Name()) + sig, _ := m.Type().(*types.Signature) + w.signature(sig) + } + + default: + panic(internalErrorf("unexpected type: %v, %v", t, reflect.TypeOf(t))) + } +} + +func (w *exportWriter) setPkg(pkg *types.Package, write bool) { + if write { + w.pkg(pkg) + } + + w.currPkg = pkg +} + +func (w *exportWriter) signature(sig *types.Signature) { + w.paramList(sig.Params()) + w.paramList(sig.Results()) + if sig.Params().Len() > 0 { + w.bool(sig.Variadic()) + } +} + +func (w *exportWriter) paramList(tup *types.Tuple) { + n := tup.Len() + w.uint64(uint64(n)) + for i := 0; i < n; i++ { + w.param(tup.At(i)) + } +} + +func (w *exportWriter) param(obj types.Object) { + w.pos(obj.Pos()) + w.localIdent(obj) + w.typ(obj.Type(), obj.Pkg()) +} + +func (w *exportWriter) value(typ types.Type, v constant.Value) { + w.typ(typ, nil) + + switch v.Kind() { + case constant.Bool: + w.bool(constant.BoolVal(v)) + case constant.Int: + var i big.Int + if i64, exact := constant.Int64Val(v); exact { + i.SetInt64(i64) + } else if ui64, exact := constant.Uint64Val(v); exact { + i.SetUint64(ui64) + } else { + i.SetString(v.ExactString(), 10) + } + w.mpint(&i, typ) + case constant.Float: + f := constantToFloat(v) + w.mpfloat(f, typ) + case constant.Complex: + w.mpfloat(constantToFloat(constant.Real(v)), typ) + w.mpfloat(constantToFloat(constant.Imag(v)), typ) + case constant.String: + w.string(constant.StringVal(v)) + case constant.Unknown: + // package contains type errors + default: + panic(internalErrorf("unexpected value %v (%T)", v, v)) + } +} + +// constantToFloat converts a constant.Value with kind constant.Float to a +// big.Float. +func constantToFloat(x constant.Value) *big.Float { + assert(x.Kind() == constant.Float) + // Use the same floating-point precision (512) as cmd/compile + // (see Mpprec in cmd/compile/internal/gc/mpfloat.go). + const mpprec = 512 + var f big.Float + f.SetPrec(mpprec) + if v, exact := constant.Float64Val(x); exact { + // float64 + f.SetFloat64(v) + } else if num, denom := constant.Num(x), constant.Denom(x); num.Kind() == constant.Int { + // TODO(gri): add big.Rat accessor to constant.Value. + n := valueToRat(num) + d := valueToRat(denom) + f.SetRat(n.Quo(n, d)) + } else { + // Value too large to represent as a fraction => inaccessible. + // TODO(gri): add big.Float accessor to constant.Value. + _, ok := f.SetString(x.ExactString()) + assert(ok) + } + return &f +} + +// mpint exports a multi-precision integer. +// +// For unsigned types, small values are written out as a single +// byte. Larger values are written out as a length-prefixed big-endian +// byte string, where the length prefix is encoded as its complement. +// For example, bytes 0, 1, and 2 directly represent the integer +// values 0, 1, and 2; while bytes 255, 254, and 253 indicate a 1-, +// 2-, and 3-byte big-endian string follow. +// +// Encoding for signed types use the same general approach as for +// unsigned types, except small values use zig-zag encoding and the +// bottom bit of length prefix byte for large values is reserved as a +// sign bit. +// +// The exact boundary between small and large encodings varies +// according to the maximum number of bytes needed to encode a value +// of type typ. As a special case, 8-bit types are always encoded as a +// single byte. +// +// TODO(mdempsky): Is this level of complexity really worthwhile? +func (w *exportWriter) mpint(x *big.Int, typ types.Type) { + basic, ok := typ.Underlying().(*types.Basic) + if !ok { + panic(internalErrorf("unexpected type %v (%T)", typ.Underlying(), typ.Underlying())) + } + + signed, maxBytes := intSize(basic) + + negative := x.Sign() < 0 + if !signed && negative { + panic(internalErrorf("negative unsigned integer; type %v, value %v", typ, x)) + } + + b := x.Bytes() + if len(b) > 0 && b[0] == 0 { + panic(internalErrorf("leading zeros")) + } + if uint(len(b)) > maxBytes { + panic(internalErrorf("bad mpint length: %d > %d (type %v, value %v)", len(b), maxBytes, typ, x)) + } + + maxSmall := 256 - maxBytes + if signed { + maxSmall = 256 - 2*maxBytes + } + if maxBytes == 1 { + maxSmall = 256 + } + + // Check if x can use small value encoding. + if len(b) <= 1 { + var ux uint + if len(b) == 1 { + ux = uint(b[0]) + } + if signed { + ux <<= 1 + if negative { + ux-- + } + } + if ux < maxSmall { + w.data.WriteByte(byte(ux)) + return + } + } + + n := 256 - uint(len(b)) + if signed { + n = 256 - 2*uint(len(b)) + if negative { + n |= 1 + } + } + if n < maxSmall || n >= 256 { + panic(internalErrorf("encoding mistake: %d, %v, %v => %d", len(b), signed, negative, n)) + } + + w.data.WriteByte(byte(n)) + w.data.Write(b) +} + +// mpfloat exports a multi-precision floating point number. +// +// The number's value is decomposed into mantissa × 2**exponent, where +// mantissa is an integer. The value is written out as mantissa (as a +// multi-precision integer) and then the exponent, except exponent is +// omitted if mantissa is zero. +func (w *exportWriter) mpfloat(f *big.Float, typ types.Type) { + if f.IsInf() { + panic("infinite constant") + } + + // Break into f = mant × 2**exp, with 0.5 <= mant < 1. + var mant big.Float + exp := int64(f.MantExp(&mant)) + + // Scale so that mant is an integer. + prec := mant.MinPrec() + mant.SetMantExp(&mant, int(prec)) + exp -= int64(prec) + + manti, acc := mant.Int(nil) + if acc != big.Exact { + panic(internalErrorf("mantissa scaling failed for %f (%s)", f, acc)) + } + w.mpint(manti, typ) + if manti.Sign() != 0 { + w.int64(exp) + } +} + +func (w *exportWriter) bool(b bool) bool { + var x uint64 + if b { + x = 1 + } + w.uint64(x) + return b +} + +func (w *exportWriter) int64(x int64) { w.data.int64(x) } +func (w *exportWriter) uint64(x uint64) { w.data.uint64(x) } +func (w *exportWriter) string(s string) { w.uint64(w.p.stringOff(s)) } + +func (w *exportWriter) localIdent(obj types.Object) { + // Anonymous parameters. + if obj == nil { + w.string("") + return + } + + name := obj.Name() + if name == "_" { + w.string("_") + return + } + + w.string(name) +} + +type intWriter struct { + bytes.Buffer +} + +func (w *intWriter) int64(x int64) { + var buf [binary.MaxVarintLen64]byte + n := binary.PutVarint(buf[:], x) + w.Write(buf[:n]) +} + +func (w *intWriter) uint64(x uint64) { + var buf [binary.MaxVarintLen64]byte + n := binary.PutUvarint(buf[:], x) + w.Write(buf[:n]) +} + +func assert(cond bool) { + if !cond { + panic("internal error: assertion failed") + } +} + +// The below is copied from go/src/cmd/compile/internal/gc/syntax.go. + +// objQueue is a FIFO queue of types.Object. The zero value of objQueue is +// a ready-to-use empty queue. +type objQueue struct { + ring []types.Object + head, tail int +} + +// empty returns true if q contains no Nodes. +func (q *objQueue) empty() bool { + return q.head == q.tail +} + +// pushTail appends n to the tail of the queue. +func (q *objQueue) pushTail(obj types.Object) { + if len(q.ring) == 0 { + q.ring = make([]types.Object, 16) + } else if q.head+len(q.ring) == q.tail { + // Grow the ring. + nring := make([]types.Object, len(q.ring)*2) + // Copy the old elements. + part := q.ring[q.head%len(q.ring):] + if q.tail-q.head <= len(part) { + part = part[:q.tail-q.head] + copy(nring, part) + } else { + pos := copy(nring, part) + copy(nring[pos:], q.ring[:q.tail%len(q.ring)]) + } + q.ring, q.head, q.tail = nring, 0, q.tail-q.head + } + + q.ring[q.tail%len(q.ring)] = obj + q.tail++ +} + +// popHead pops a node from the head of the queue. It panics if q is empty. +func (q *objQueue) popHead() types.Object { + if q.empty() { + panic("dequeue empty") + } + obj := q.ring[q.head%len(q.ring)] + q.head++ + return obj +} diff --git a/vendor/golang.org/x/tools/go/internal/gcimporter/iimport.go b/vendor/golang.org/x/tools/go/internal/gcimporter/iimport.go new file mode 100644 index 0000000000..a31a880263 --- /dev/null +++ b/vendor/golang.org/x/tools/go/internal/gcimporter/iimport.go @@ -0,0 +1,630 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Indexed package import. +// See cmd/compile/internal/gc/iexport.go for the export data format. + +// This file is a copy of $GOROOT/src/go/internal/gcimporter/iimport.go. + +package gcimporter + +import ( + "bytes" + "encoding/binary" + "fmt" + "go/constant" + "go/token" + "go/types" + "io" + "sort" +) + +type intReader struct { + *bytes.Reader + path string +} + +func (r *intReader) int64() int64 { + i, err := binary.ReadVarint(r.Reader) + if err != nil { + errorf("import %q: read varint error: %v", r.path, err) + } + return i +} + +func (r *intReader) uint64() uint64 { + i, err := binary.ReadUvarint(r.Reader) + if err != nil { + errorf("import %q: read varint error: %v", r.path, err) + } + return i +} + +const predeclReserved = 32 + +type itag uint64 + +const ( + // Types + definedType itag = iota + pointerType + sliceType + arrayType + chanType + mapType + signatureType + structType + interfaceType +) + +// IImportData imports a package from the serialized package data +// and returns the number of bytes consumed and a reference to the package. +// If the export data version is not recognized or the format is otherwise +// compromised, an error is returned. +func IImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) { + const currentVersion = 1 + version := int64(-1) + defer func() { + if e := recover(); e != nil { + if version > currentVersion { + err = fmt.Errorf("cannot import %q (%v), export data is newer version - update tool", path, e) + } else { + err = fmt.Errorf("cannot import %q (%v), possibly version skew - reinstall package", path, e) + } + } + }() + + r := &intReader{bytes.NewReader(data), path} + + version = int64(r.uint64()) + switch version { + case currentVersion, 0: + default: + errorf("unknown iexport format version %d", version) + } + + sLen := int64(r.uint64()) + dLen := int64(r.uint64()) + + whence, _ := r.Seek(0, io.SeekCurrent) + stringData := data[whence : whence+sLen] + declData := data[whence+sLen : whence+sLen+dLen] + r.Seek(sLen+dLen, io.SeekCurrent) + + p := iimporter{ + ipath: path, + version: int(version), + + stringData: stringData, + stringCache: make(map[uint64]string), + pkgCache: make(map[uint64]*types.Package), + + declData: declData, + pkgIndex: make(map[*types.Package]map[string]uint64), + typCache: make(map[uint64]types.Type), + + fake: fakeFileSet{ + fset: fset, + files: make(map[string]*token.File), + }, + } + + for i, pt := range predeclared() { + p.typCache[uint64(i)] = pt + } + + pkgList := make([]*types.Package, r.uint64()) + for i := range pkgList { + pkgPathOff := r.uint64() + pkgPath := p.stringAt(pkgPathOff) + pkgName := p.stringAt(r.uint64()) + _ = r.uint64() // package height; unused by go/types + + if pkgPath == "" { + pkgPath = path + } + pkg := imports[pkgPath] + if pkg == nil { + pkg = types.NewPackage(pkgPath, pkgName) + imports[pkgPath] = pkg + } else if pkg.Name() != pkgName { + errorf("conflicting names %s and %s for package %q", pkg.Name(), pkgName, path) + } + + p.pkgCache[pkgPathOff] = pkg + + nameIndex := make(map[string]uint64) + for nSyms := r.uint64(); nSyms > 0; nSyms-- { + name := p.stringAt(r.uint64()) + nameIndex[name] = r.uint64() + } + + p.pkgIndex[pkg] = nameIndex + pkgList[i] = pkg + } + if len(pkgList) == 0 { + errorf("no packages found for %s", path) + panic("unreachable") + } + p.ipkg = pkgList[0] + names := make([]string, 0, len(p.pkgIndex[p.ipkg])) + for name := range p.pkgIndex[p.ipkg] { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + p.doDecl(p.ipkg, name) + } + + for _, typ := range p.interfaceList { + typ.Complete() + } + + // record all referenced packages as imports + list := append(([]*types.Package)(nil), pkgList[1:]...) + sort.Sort(byPath(list)) + p.ipkg.SetImports(list) + + // package was imported completely and without errors + p.ipkg.MarkComplete() + + consumed, _ := r.Seek(0, io.SeekCurrent) + return int(consumed), p.ipkg, nil +} + +type iimporter struct { + ipath string + ipkg *types.Package + version int + + stringData []byte + stringCache map[uint64]string + pkgCache map[uint64]*types.Package + + declData []byte + pkgIndex map[*types.Package]map[string]uint64 + typCache map[uint64]types.Type + + fake fakeFileSet + interfaceList []*types.Interface +} + +func (p *iimporter) doDecl(pkg *types.Package, name string) { + // See if we've already imported this declaration. + if obj := pkg.Scope().Lookup(name); obj != nil { + return + } + + off, ok := p.pkgIndex[pkg][name] + if !ok { + errorf("%v.%v not in index", pkg, name) + } + + r := &importReader{p: p, currPkg: pkg} + r.declReader.Reset(p.declData[off:]) + + r.obj(name) +} + +func (p *iimporter) stringAt(off uint64) string { + if s, ok := p.stringCache[off]; ok { + return s + } + + slen, n := binary.Uvarint(p.stringData[off:]) + if n <= 0 { + errorf("varint failed") + } + spos := off + uint64(n) + s := string(p.stringData[spos : spos+slen]) + p.stringCache[off] = s + return s +} + +func (p *iimporter) pkgAt(off uint64) *types.Package { + if pkg, ok := p.pkgCache[off]; ok { + return pkg + } + path := p.stringAt(off) + if path == p.ipath { + return p.ipkg + } + errorf("missing package %q in %q", path, p.ipath) + return nil +} + +func (p *iimporter) typAt(off uint64, base *types.Named) types.Type { + if t, ok := p.typCache[off]; ok && (base == nil || !isInterface(t)) { + return t + } + + if off < predeclReserved { + errorf("predeclared type missing from cache: %v", off) + } + + r := &importReader{p: p} + r.declReader.Reset(p.declData[off-predeclReserved:]) + t := r.doType(base) + + if base == nil || !isInterface(t) { + p.typCache[off] = t + } + return t +} + +type importReader struct { + p *iimporter + declReader bytes.Reader + currPkg *types.Package + prevFile string + prevLine int64 + prevColumn int64 +} + +func (r *importReader) obj(name string) { + tag := r.byte() + pos := r.pos() + + switch tag { + case 'A': + typ := r.typ() + + r.declare(types.NewTypeName(pos, r.currPkg, name, typ)) + + case 'C': + typ, val := r.value() + + r.declare(types.NewConst(pos, r.currPkg, name, typ, val)) + + case 'F': + sig := r.signature(nil) + + r.declare(types.NewFunc(pos, r.currPkg, name, sig)) + + case 'T': + // Types can be recursive. We need to setup a stub + // declaration before recursing. + obj := types.NewTypeName(pos, r.currPkg, name, nil) + named := types.NewNamed(obj, nil, nil) + r.declare(obj) + + underlying := r.p.typAt(r.uint64(), named).Underlying() + named.SetUnderlying(underlying) + + if !isInterface(underlying) { + for n := r.uint64(); n > 0; n-- { + mpos := r.pos() + mname := r.ident() + recv := r.param() + msig := r.signature(recv) + + named.AddMethod(types.NewFunc(mpos, r.currPkg, mname, msig)) + } + } + + case 'V': + typ := r.typ() + + r.declare(types.NewVar(pos, r.currPkg, name, typ)) + + default: + errorf("unexpected tag: %v", tag) + } +} + +func (r *importReader) declare(obj types.Object) { + obj.Pkg().Scope().Insert(obj) +} + +func (r *importReader) value() (typ types.Type, val constant.Value) { + typ = r.typ() + + switch b := typ.Underlying().(*types.Basic); b.Info() & types.IsConstType { + case types.IsBoolean: + val = constant.MakeBool(r.bool()) + + case types.IsString: + val = constant.MakeString(r.string()) + + case types.IsInteger: + val = r.mpint(b) + + case types.IsFloat: + val = r.mpfloat(b) + + case types.IsComplex: + re := r.mpfloat(b) + im := r.mpfloat(b) + val = constant.BinaryOp(re, token.ADD, constant.MakeImag(im)) + + default: + if b.Kind() == types.Invalid { + val = constant.MakeUnknown() + return + } + errorf("unexpected type %v", typ) // panics + panic("unreachable") + } + + return +} + +func intSize(b *types.Basic) (signed bool, maxBytes uint) { + if (b.Info() & types.IsUntyped) != 0 { + return true, 64 + } + + switch b.Kind() { + case types.Float32, types.Complex64: + return true, 3 + case types.Float64, types.Complex128: + return true, 7 + } + + signed = (b.Info() & types.IsUnsigned) == 0 + switch b.Kind() { + case types.Int8, types.Uint8: + maxBytes = 1 + case types.Int16, types.Uint16: + maxBytes = 2 + case types.Int32, types.Uint32: + maxBytes = 4 + default: + maxBytes = 8 + } + + return +} + +func (r *importReader) mpint(b *types.Basic) constant.Value { + signed, maxBytes := intSize(b) + + maxSmall := 256 - maxBytes + if signed { + maxSmall = 256 - 2*maxBytes + } + if maxBytes == 1 { + maxSmall = 256 + } + + n, _ := r.declReader.ReadByte() + if uint(n) < maxSmall { + v := int64(n) + if signed { + v >>= 1 + if n&1 != 0 { + v = ^v + } + } + return constant.MakeInt64(v) + } + + v := -n + if signed { + v = -(n &^ 1) >> 1 + } + if v < 1 || uint(v) > maxBytes { + errorf("weird decoding: %v, %v => %v", n, signed, v) + } + + buf := make([]byte, v) + io.ReadFull(&r.declReader, buf) + + // convert to little endian + // TODO(gri) go/constant should have a more direct conversion function + // (e.g., once it supports a big.Float based implementation) + for i, j := 0, len(buf)-1; i < j; i, j = i+1, j-1 { + buf[i], buf[j] = buf[j], buf[i] + } + + x := constant.MakeFromBytes(buf) + if signed && n&1 != 0 { + x = constant.UnaryOp(token.SUB, x, 0) + } + return x +} + +func (r *importReader) mpfloat(b *types.Basic) constant.Value { + x := r.mpint(b) + if constant.Sign(x) == 0 { + return x + } + + exp := r.int64() + switch { + case exp > 0: + x = constant.Shift(x, token.SHL, uint(exp)) + case exp < 0: + d := constant.Shift(constant.MakeInt64(1), token.SHL, uint(-exp)) + x = constant.BinaryOp(x, token.QUO, d) + } + return x +} + +func (r *importReader) ident() string { + return r.string() +} + +func (r *importReader) qualifiedIdent() (*types.Package, string) { + name := r.string() + pkg := r.pkg() + return pkg, name +} + +func (r *importReader) pos() token.Pos { + if r.p.version >= 1 { + r.posv1() + } else { + r.posv0() + } + + if r.prevFile == "" && r.prevLine == 0 && r.prevColumn == 0 { + return token.NoPos + } + return r.p.fake.pos(r.prevFile, int(r.prevLine), int(r.prevColumn)) +} + +func (r *importReader) posv0() { + delta := r.int64() + if delta != deltaNewFile { + r.prevLine += delta + } else if l := r.int64(); l == -1 { + r.prevLine += deltaNewFile + } else { + r.prevFile = r.string() + r.prevLine = l + } +} + +func (r *importReader) posv1() { + delta := r.int64() + r.prevColumn += delta >> 1 + if delta&1 != 0 { + delta = r.int64() + r.prevLine += delta >> 1 + if delta&1 != 0 { + r.prevFile = r.string() + } + } +} + +func (r *importReader) typ() types.Type { + return r.p.typAt(r.uint64(), nil) +} + +func isInterface(t types.Type) bool { + _, ok := t.(*types.Interface) + return ok +} + +func (r *importReader) pkg() *types.Package { return r.p.pkgAt(r.uint64()) } +func (r *importReader) string() string { return r.p.stringAt(r.uint64()) } + +func (r *importReader) doType(base *types.Named) types.Type { + switch k := r.kind(); k { + default: + errorf("unexpected kind tag in %q: %v", r.p.ipath, k) + return nil + + case definedType: + pkg, name := r.qualifiedIdent() + r.p.doDecl(pkg, name) + return pkg.Scope().Lookup(name).(*types.TypeName).Type() + case pointerType: + return types.NewPointer(r.typ()) + case sliceType: + return types.NewSlice(r.typ()) + case arrayType: + n := r.uint64() + return types.NewArray(r.typ(), int64(n)) + case chanType: + dir := chanDir(int(r.uint64())) + return types.NewChan(dir, r.typ()) + case mapType: + return types.NewMap(r.typ(), r.typ()) + case signatureType: + r.currPkg = r.pkg() + return r.signature(nil) + + case structType: + r.currPkg = r.pkg() + + fields := make([]*types.Var, r.uint64()) + tags := make([]string, len(fields)) + for i := range fields { + fpos := r.pos() + fname := r.ident() + ftyp := r.typ() + emb := r.bool() + tag := r.string() + + fields[i] = types.NewField(fpos, r.currPkg, fname, ftyp, emb) + tags[i] = tag + } + return types.NewStruct(fields, tags) + + case interfaceType: + r.currPkg = r.pkg() + + embeddeds := make([]types.Type, r.uint64()) + for i := range embeddeds { + _ = r.pos() + embeddeds[i] = r.typ() + } + + methods := make([]*types.Func, r.uint64()) + for i := range methods { + mpos := r.pos() + mname := r.ident() + + // TODO(mdempsky): Matches bimport.go, but I + // don't agree with this. + var recv *types.Var + if base != nil { + recv = types.NewVar(token.NoPos, r.currPkg, "", base) + } + + msig := r.signature(recv) + methods[i] = types.NewFunc(mpos, r.currPkg, mname, msig) + } + + typ := newInterface(methods, embeddeds) + r.p.interfaceList = append(r.p.interfaceList, typ) + return typ + } +} + +func (r *importReader) kind() itag { + return itag(r.uint64()) +} + +func (r *importReader) signature(recv *types.Var) *types.Signature { + params := r.paramList() + results := r.paramList() + variadic := params.Len() > 0 && r.bool() + return types.NewSignature(recv, params, results, variadic) +} + +func (r *importReader) paramList() *types.Tuple { + xs := make([]*types.Var, r.uint64()) + for i := range xs { + xs[i] = r.param() + } + return types.NewTuple(xs...) +} + +func (r *importReader) param() *types.Var { + pos := r.pos() + name := r.ident() + typ := r.typ() + return types.NewParam(pos, r.currPkg, name, typ) +} + +func (r *importReader) bool() bool { + return r.uint64() != 0 +} + +func (r *importReader) int64() int64 { + n, err := binary.ReadVarint(&r.declReader) + if err != nil { + errorf("readVarint: %v", err) + } + return n +} + +func (r *importReader) uint64() uint64 { + n, err := binary.ReadUvarint(&r.declReader) + if err != nil { + errorf("readUvarint: %v", err) + } + return n +} + +func (r *importReader) byte() byte { + x, err := r.declReader.ReadByte() + if err != nil { + errorf("declReader.ReadByte: %v", err) + } + return x +} diff --git a/vendor/golang.org/x/tools/go/internal/gcimporter/newInterface10.go b/vendor/golang.org/x/tools/go/internal/gcimporter/newInterface10.go new file mode 100644 index 0000000000..463f252271 --- /dev/null +++ b/vendor/golang.org/x/tools/go/internal/gcimporter/newInterface10.go @@ -0,0 +1,21 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.11 + +package gcimporter + +import "go/types" + +func newInterface(methods []*types.Func, embeddeds []types.Type) *types.Interface { + named := make([]*types.Named, len(embeddeds)) + for i, e := range embeddeds { + var ok bool + named[i], ok = e.(*types.Named) + if !ok { + panic("embedding of non-defined interfaces in interfaces is not supported before Go 1.11") + } + } + return types.NewInterface(methods, named) +} diff --git a/vendor/golang.org/x/tools/go/internal/gcimporter/newInterface11.go b/vendor/golang.org/x/tools/go/internal/gcimporter/newInterface11.go new file mode 100644 index 0000000000..ab28b95cbb --- /dev/null +++ b/vendor/golang.org/x/tools/go/internal/gcimporter/newInterface11.go @@ -0,0 +1,13 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.11 + +package gcimporter + +import "go/types" + +func newInterface(methods []*types.Func, embeddeds []types.Type) *types.Interface { + return types.NewInterfaceType(methods, embeddeds) +} diff --git a/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go b/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go new file mode 100644 index 0000000000..f4d73b2339 --- /dev/null +++ b/vendor/golang.org/x/tools/go/internal/packagesdriver/sizes.go @@ -0,0 +1,49 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package packagesdriver fetches type sizes for go/packages and go/analysis. +package packagesdriver + +import ( + "context" + "fmt" + "go/types" + "strings" + + "golang.org/x/tools/internal/gocommand" +) + +var debug = false + +func GetSizesGolist(ctx context.Context, inv gocommand.Invocation, gocmdRunner *gocommand.Runner) (types.Sizes, error) { + inv.Verb = "list" + inv.Args = []string{"-f", "{{context.GOARCH}} {{context.Compiler}}", "--", "unsafe"} + stdout, stderr, friendlyErr, rawErr := gocmdRunner.RunRaw(ctx, inv) + var goarch, compiler string + if rawErr != nil { + if strings.Contains(rawErr.Error(), "cannot find main module") { + // User's running outside of a module. All bets are off. Get GOARCH and guess compiler is gc. + // TODO(matloob): Is this a problem in practice? + inv.Verb = "env" + inv.Args = []string{"GOARCH"} + envout, enverr := gocmdRunner.Run(ctx, inv) + if enverr != nil { + return nil, enverr + } + goarch = strings.TrimSpace(envout.String()) + compiler = "gc" + } else { + return nil, friendlyErr + } + } else { + fields := strings.Fields(stdout.String()) + if len(fields) < 2 { + return nil, fmt.Errorf("could not parse GOARCH and Go compiler in format \" \":\nstdout: <<%s>>\nstderr: <<%s>>", + stdout.String(), stderr.String()) + } + goarch = fields[0] + compiler = fields[1] + } + return types.SizesFor(compiler, goarch), nil +} diff --git a/vendor/golang.org/x/tools/go/packages/doc.go b/vendor/golang.org/x/tools/go/packages/doc.go new file mode 100644 index 0000000000..4bfe28a51f --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/doc.go @@ -0,0 +1,221 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package packages loads Go packages for inspection and analysis. + +The Load function takes as input a list of patterns and return a list of Package +structs describing individual packages matched by those patterns. +The LoadMode controls the amount of detail in the loaded packages. + +Load passes most patterns directly to the underlying build tool, +but all patterns with the prefix "query=", where query is a +non-empty string of letters from [a-z], are reserved and may be +interpreted as query operators. + +Two query operators are currently supported: "file" and "pattern". + +The query "file=path/to/file.go" matches the package or packages enclosing +the Go source file path/to/file.go. For example "file=~/go/src/fmt/print.go" +might return the packages "fmt" and "fmt [fmt.test]". + +The query "pattern=string" causes "string" to be passed directly to +the underlying build tool. In most cases this is unnecessary, +but an application can use Load("pattern=" + x) as an escaping mechanism +to ensure that x is not interpreted as a query operator if it contains '='. + +All other query operators are reserved for future use and currently +cause Load to report an error. + +The Package struct provides basic information about the package, including + + - ID, a unique identifier for the package in the returned set; + - GoFiles, the names of the package's Go source files; + - Imports, a map from source import strings to the Packages they name; + - Types, the type information for the package's exported symbols; + - Syntax, the parsed syntax trees for the package's source code; and + - TypeInfo, the result of a complete type-check of the package syntax trees. + +(See the documentation for type Package for the complete list of fields +and more detailed descriptions.) + +For example, + + Load(nil, "bytes", "unicode...") + +returns four Package structs describing the standard library packages +bytes, unicode, unicode/utf16, and unicode/utf8. Note that one pattern +can match multiple packages and that a package might be matched by +multiple patterns: in general it is not possible to determine which +packages correspond to which patterns. + +Note that the list returned by Load contains only the packages matched +by the patterns. Their dependencies can be found by walking the import +graph using the Imports fields. + +The Load function can be configured by passing a pointer to a Config as +the first argument. A nil Config is equivalent to the zero Config, which +causes Load to run in LoadFiles mode, collecting minimal information. +See the documentation for type Config for details. + +As noted earlier, the Config.Mode controls the amount of detail +reported about the loaded packages. See the documentation for type LoadMode +for details. + +Most tools should pass their command-line arguments (after any flags) +uninterpreted to the loader, so that the loader can interpret them +according to the conventions of the underlying build system. +See the Example function for typical usage. + +*/ +package packages // import "golang.org/x/tools/go/packages" + +/* + +Motivation and design considerations + +The new package's design solves problems addressed by two existing +packages: go/build, which locates and describes packages, and +golang.org/x/tools/go/loader, which loads, parses and type-checks them. +The go/build.Package structure encodes too much of the 'go build' way +of organizing projects, leaving us in need of a data type that describes a +package of Go source code independent of the underlying build system. +We wanted something that works equally well with go build and vgo, and +also other build systems such as Bazel and Blaze, making it possible to +construct analysis tools that work in all these environments. +Tools such as errcheck and staticcheck were essentially unavailable to +the Go community at Google, and some of Google's internal tools for Go +are unavailable externally. +This new package provides a uniform way to obtain package metadata by +querying each of these build systems, optionally supporting their +preferred command-line notations for packages, so that tools integrate +neatly with users' build environments. The Metadata query function +executes an external query tool appropriate to the current workspace. + +Loading packages always returns the complete import graph "all the way down", +even if all you want is information about a single package, because the query +mechanisms of all the build systems we currently support ({go,vgo} list, and +blaze/bazel aspect-based query) cannot provide detailed information +about one package without visiting all its dependencies too, so there is +no additional asymptotic cost to providing transitive information. +(This property might not be true of a hypothetical 5th build system.) + +In calls to TypeCheck, all initial packages, and any package that +transitively depends on one of them, must be loaded from source. +Consider A->B->C->D->E: if A,C are initial, A,B,C must be loaded from +source; D may be loaded from export data, and E may not be loaded at all +(though it's possible that D's export data mentions it, so a +types.Package may be created for it and exposed.) + +The old loader had a feature to suppress type-checking of function +bodies on a per-package basis, primarily intended to reduce the work of +obtaining type information for imported packages. Now that imports are +satisfied by export data, the optimization no longer seems necessary. + +Despite some early attempts, the old loader did not exploit export data, +instead always using the equivalent of WholeProgram mode. This was due +to the complexity of mixing source and export data packages (now +resolved by the upward traversal mentioned above), and because export data +files were nearly always missing or stale. Now that 'go build' supports +caching, all the underlying build systems can guarantee to produce +export data in a reasonable (amortized) time. + +Test "main" packages synthesized by the build system are now reported as +first-class packages, avoiding the need for clients (such as go/ssa) to +reinvent this generation logic. + +One way in which go/packages is simpler than the old loader is in its +treatment of in-package tests. In-package tests are packages that +consist of all the files of the library under test, plus the test files. +The old loader constructed in-package tests by a two-phase process of +mutation called "augmentation": first it would construct and type check +all the ordinary library packages and type-check the packages that +depend on them; then it would add more (test) files to the package and +type-check again. This two-phase approach had four major problems: +1) in processing the tests, the loader modified the library package, + leaving no way for a client application to see both the test + package and the library package; one would mutate into the other. +2) because test files can declare additional methods on types defined in + the library portion of the package, the dispatch of method calls in + the library portion was affected by the presence of the test files. + This should have been a clue that the packages were logically + different. +3) this model of "augmentation" assumed at most one in-package test + per library package, which is true of projects using 'go build', + but not other build systems. +4) because of the two-phase nature of test processing, all packages that + import the library package had to be processed before augmentation, + forcing a "one-shot" API and preventing the client from calling Load + in several times in sequence as is now possible in WholeProgram mode. + (TypeCheck mode has a similar one-shot restriction for a different reason.) + +Early drafts of this package supported "multi-shot" operation. +Although it allowed clients to make a sequence of calls (or concurrent +calls) to Load, building up the graph of Packages incrementally, +it was of marginal value: it complicated the API +(since it allowed some options to vary across calls but not others), +it complicated the implementation, +it cannot be made to work in Types mode, as explained above, +and it was less efficient than making one combined call (when this is possible). +Among the clients we have inspected, none made multiple calls to load +but could not be easily and satisfactorily modified to make only a single call. +However, applications changes may be required. +For example, the ssadump command loads the user-specified packages +and in addition the runtime package. It is tempting to simply append +"runtime" to the user-provided list, but that does not work if the user +specified an ad-hoc package such as [a.go b.go]. +Instead, ssadump no longer requests the runtime package, +but seeks it among the dependencies of the user-specified packages, +and emits an error if it is not found. + +Overlays: The Overlay field in the Config allows providing alternate contents +for Go source files, by providing a mapping from file path to contents. +go/packages will pull in new imports added in overlay files when go/packages +is run in LoadImports mode or greater. +Overlay support for the go list driver isn't complete yet: if the file doesn't +exist on disk, it will only be recognized in an overlay if it is a non-test file +and the package would be reported even without the overlay. + +Questions & Tasks + +- Add GOARCH/GOOS? + They are not portable concepts, but could be made portable. + Our goal has been to allow users to express themselves using the conventions + of the underlying build system: if the build system honors GOARCH + during a build and during a metadata query, then so should + applications built atop that query mechanism. + Conversely, if the target architecture of the build is determined by + command-line flags, the application can pass the relevant + flags through to the build system using a command such as: + myapp -query_flag="--cpu=amd64" -query_flag="--os=darwin" + However, this approach is low-level, unwieldy, and non-portable. + GOOS and GOARCH seem important enough to warrant a dedicated option. + +- How should we handle partial failures such as a mixture of good and + malformed patterns, existing and non-existent packages, successful and + failed builds, import failures, import cycles, and so on, in a call to + Load? + +- Support bazel, blaze, and go1.10 list, not just go1.11 list. + +- Handle (and test) various partial success cases, e.g. + a mixture of good packages and: + invalid patterns + nonexistent packages + empty packages + packages with malformed package or import declarations + unreadable files + import cycles + other parse errors + type errors + Make sure we record errors at the correct place in the graph. + +- Missing packages among initial arguments are not reported. + Return bogus packages for them, like golist does. + +- "undeclared name" errors (for example) are reported out of source file + order. I suspect this is due to the breadth-first resolution now used + by go/types. Is that a bug? Discuss with gri. + +*/ diff --git a/vendor/golang.org/x/tools/go/packages/external.go b/vendor/golang.org/x/tools/go/packages/external.go new file mode 100644 index 0000000000..7242a0a7d2 --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/external.go @@ -0,0 +1,101 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file enables an external tool to intercept package requests. +// If the tool is present then its results are used in preference to +// the go list command. + +package packages + +import ( + "bytes" + "encoding/json" + "fmt" + exec "golang.org/x/sys/execabs" + "os" + "strings" +) + +// The Driver Protocol +// +// The driver, given the inputs to a call to Load, returns metadata about the packages specified. +// This allows for different build systems to support go/packages by telling go/packages how the +// packages' source is organized. +// The driver is a binary, either specified by the GOPACKAGESDRIVER environment variable or in +// the path as gopackagesdriver. It's given the inputs to load in its argv. See the package +// documentation in doc.go for the full description of the patterns that need to be supported. +// A driver receives as a JSON-serialized driverRequest struct in standard input and will +// produce a JSON-serialized driverResponse (see definition in packages.go) in its standard output. + +// driverRequest is used to provide the portion of Load's Config that is needed by a driver. +type driverRequest struct { + Mode LoadMode `json:"mode"` + // Env specifies the environment the underlying build system should be run in. + Env []string `json:"env"` + // BuildFlags are flags that should be passed to the underlying build system. + BuildFlags []string `json:"build_flags"` + // Tests specifies whether the patterns should also return test packages. + Tests bool `json:"tests"` + // Overlay maps file paths (relative to the driver's working directory) to the byte contents + // of overlay files. + Overlay map[string][]byte `json:"overlay"` +} + +// findExternalDriver returns the file path of a tool that supplies +// the build system package structure, or "" if not found." +// If GOPACKAGESDRIVER is set in the environment findExternalTool returns its +// value, otherwise it searches for a binary named gopackagesdriver on the PATH. +func findExternalDriver(cfg *Config) driver { + const toolPrefix = "GOPACKAGESDRIVER=" + tool := "" + for _, env := range cfg.Env { + if val := strings.TrimPrefix(env, toolPrefix); val != env { + tool = val + } + } + if tool != "" && tool == "off" { + return nil + } + if tool == "" { + var err error + tool, err = exec.LookPath("gopackagesdriver") + if err != nil { + return nil + } + } + return func(cfg *Config, words ...string) (*driverResponse, error) { + req, err := json.Marshal(driverRequest{ + Mode: cfg.Mode, + Env: cfg.Env, + BuildFlags: cfg.BuildFlags, + Tests: cfg.Tests, + Overlay: cfg.Overlay, + }) + if err != nil { + return nil, fmt.Errorf("failed to encode message to driver tool: %v", err) + } + + buf := new(bytes.Buffer) + stderr := new(bytes.Buffer) + cmd := exec.CommandContext(cfg.Context, tool, words...) + cmd.Dir = cfg.Dir + cmd.Env = cfg.Env + cmd.Stdin = bytes.NewReader(req) + cmd.Stdout = buf + cmd.Stderr = stderr + + if err := cmd.Run(); err != nil { + return nil, fmt.Errorf("%v: %v: %s", tool, err, cmd.Stderr) + } + if len(stderr.Bytes()) != 0 && os.Getenv("GOPACKAGESPRINTDRIVERERRORS") != "" { + fmt.Fprintf(os.Stderr, "%s stderr: <<%s>>\n", cmdDebugStr(cmd), stderr) + } + + var response driverResponse + if err := json.Unmarshal(buf.Bytes(), &response); err != nil { + return nil, err + } + return &response, nil + } +} diff --git a/vendor/golang.org/x/tools/go/packages/golist.go b/vendor/golang.org/x/tools/go/packages/golist.go new file mode 100644 index 0000000000..ec417ba830 --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/golist.go @@ -0,0 +1,1096 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package packages + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "go/types" + exec "golang.org/x/sys/execabs" + "io/ioutil" + "log" + "os" + "path" + "path/filepath" + "reflect" + "sort" + "strconv" + "strings" + "sync" + "unicode" + + "golang.org/x/tools/go/internal/packagesdriver" + "golang.org/x/tools/internal/gocommand" + "golang.org/x/xerrors" +) + +// debug controls verbose logging. +var debug, _ = strconv.ParseBool(os.Getenv("GOPACKAGESDEBUG")) + +// A goTooOldError reports that the go command +// found by exec.LookPath is too old to use the new go list behavior. +type goTooOldError struct { + error +} + +// responseDeduper wraps a driverResponse, deduplicating its contents. +type responseDeduper struct { + seenRoots map[string]bool + seenPackages map[string]*Package + dr *driverResponse +} + +func newDeduper() *responseDeduper { + return &responseDeduper{ + dr: &driverResponse{}, + seenRoots: map[string]bool{}, + seenPackages: map[string]*Package{}, + } +} + +// addAll fills in r with a driverResponse. +func (r *responseDeduper) addAll(dr *driverResponse) { + for _, pkg := range dr.Packages { + r.addPackage(pkg) + } + for _, root := range dr.Roots { + r.addRoot(root) + } +} + +func (r *responseDeduper) addPackage(p *Package) { + if r.seenPackages[p.ID] != nil { + return + } + r.seenPackages[p.ID] = p + r.dr.Packages = append(r.dr.Packages, p) +} + +func (r *responseDeduper) addRoot(id string) { + if r.seenRoots[id] { + return + } + r.seenRoots[id] = true + r.dr.Roots = append(r.dr.Roots, id) +} + +type golistState struct { + cfg *Config + ctx context.Context + + envOnce sync.Once + goEnvError error + goEnv map[string]string + + rootsOnce sync.Once + rootDirsError error + rootDirs map[string]string + + goVersionOnce sync.Once + goVersionError error + goVersion int // The X in Go 1.X. + + // vendorDirs caches the (non)existence of vendor directories. + vendorDirs map[string]bool +} + +// getEnv returns Go environment variables. Only specific variables are +// populated -- computing all of them is slow. +func (state *golistState) getEnv() (map[string]string, error) { + state.envOnce.Do(func() { + var b *bytes.Buffer + b, state.goEnvError = state.invokeGo("env", "-json", "GOMOD", "GOPATH") + if state.goEnvError != nil { + return + } + + state.goEnv = make(map[string]string) + decoder := json.NewDecoder(b) + if state.goEnvError = decoder.Decode(&state.goEnv); state.goEnvError != nil { + return + } + }) + return state.goEnv, state.goEnvError +} + +// mustGetEnv is a convenience function that can be used if getEnv has already succeeded. +func (state *golistState) mustGetEnv() map[string]string { + env, err := state.getEnv() + if err != nil { + panic(fmt.Sprintf("mustGetEnv: %v", err)) + } + return env +} + +// goListDriver uses the go list command to interpret the patterns and produce +// the build system package structure. +// See driver for more details. +func goListDriver(cfg *Config, patterns ...string) (*driverResponse, error) { + // Make sure that any asynchronous go commands are killed when we return. + parentCtx := cfg.Context + if parentCtx == nil { + parentCtx = context.Background() + } + ctx, cancel := context.WithCancel(parentCtx) + defer cancel() + + response := newDeduper() + + state := &golistState{ + cfg: cfg, + ctx: ctx, + vendorDirs: map[string]bool{}, + } + + // Fill in response.Sizes asynchronously if necessary. + var sizeserr error + var sizeswg sync.WaitGroup + if cfg.Mode&NeedTypesSizes != 0 || cfg.Mode&NeedTypes != 0 { + sizeswg.Add(1) + go func() { + var sizes types.Sizes + sizes, sizeserr = packagesdriver.GetSizesGolist(ctx, state.cfgInvocation(), cfg.gocmdRunner) + // types.SizesFor always returns nil or a *types.StdSizes. + response.dr.Sizes, _ = sizes.(*types.StdSizes) + sizeswg.Done() + }() + } + + // Determine files requested in contains patterns + var containFiles []string + restPatterns := make([]string, 0, len(patterns)) + // Extract file= and other [querytype]= patterns. Report an error if querytype + // doesn't exist. +extractQueries: + for _, pattern := range patterns { + eqidx := strings.Index(pattern, "=") + if eqidx < 0 { + restPatterns = append(restPatterns, pattern) + } else { + query, value := pattern[:eqidx], pattern[eqidx+len("="):] + switch query { + case "file": + containFiles = append(containFiles, value) + case "pattern": + restPatterns = append(restPatterns, value) + case "": // not a reserved query + restPatterns = append(restPatterns, pattern) + default: + for _, rune := range query { + if rune < 'a' || rune > 'z' { // not a reserved query + restPatterns = append(restPatterns, pattern) + continue extractQueries + } + } + // Reject all other patterns containing "=" + return nil, fmt.Errorf("invalid query type %q in query pattern %q", query, pattern) + } + } + } + + // See if we have any patterns to pass through to go list. Zero initial + // patterns also requires a go list call, since it's the equivalent of + // ".". + if len(restPatterns) > 0 || len(patterns) == 0 { + dr, err := state.createDriverResponse(restPatterns...) + if err != nil { + return nil, err + } + response.addAll(dr) + } + + if len(containFiles) != 0 { + if err := state.runContainsQueries(response, containFiles); err != nil { + return nil, err + } + } + + // Only use go/packages' overlay processing if we're using a Go version + // below 1.16. Otherwise, go list handles it. + if goVersion, err := state.getGoVersion(); err == nil && goVersion < 16 { + modifiedPkgs, needPkgs, err := state.processGolistOverlay(response) + if err != nil { + return nil, err + } + + var containsCandidates []string + if len(containFiles) > 0 { + containsCandidates = append(containsCandidates, modifiedPkgs...) + containsCandidates = append(containsCandidates, needPkgs...) + } + if err := state.addNeededOverlayPackages(response, needPkgs); err != nil { + return nil, err + } + // Check candidate packages for containFiles. + if len(containFiles) > 0 { + for _, id := range containsCandidates { + pkg, ok := response.seenPackages[id] + if !ok { + response.addPackage(&Package{ + ID: id, + Errors: []Error{{ + Kind: ListError, + Msg: fmt.Sprintf("package %s expected but not seen", id), + }}, + }) + continue + } + for _, f := range containFiles { + for _, g := range pkg.GoFiles { + if sameFile(f, g) { + response.addRoot(id) + } + } + } + } + } + // Add root for any package that matches a pattern. This applies only to + // packages that are modified by overlays, since they are not added as + // roots automatically. + for _, pattern := range restPatterns { + match := matchPattern(pattern) + for _, pkgID := range modifiedPkgs { + pkg, ok := response.seenPackages[pkgID] + if !ok { + continue + } + if match(pkg.PkgPath) { + response.addRoot(pkg.ID) + } + } + } + } + + sizeswg.Wait() + if sizeserr != nil { + return nil, sizeserr + } + return response.dr, nil +} + +func (state *golistState) addNeededOverlayPackages(response *responseDeduper, pkgs []string) error { + if len(pkgs) == 0 { + return nil + } + dr, err := state.createDriverResponse(pkgs...) + if err != nil { + return err + } + for _, pkg := range dr.Packages { + response.addPackage(pkg) + } + _, needPkgs, err := state.processGolistOverlay(response) + if err != nil { + return err + } + return state.addNeededOverlayPackages(response, needPkgs) +} + +func (state *golistState) runContainsQueries(response *responseDeduper, queries []string) error { + for _, query := range queries { + // TODO(matloob): Do only one query per directory. + fdir := filepath.Dir(query) + // Pass absolute path of directory to go list so that it knows to treat it as a directory, + // not a package path. + pattern, err := filepath.Abs(fdir) + if err != nil { + return fmt.Errorf("could not determine absolute path of file= query path %q: %v", query, err) + } + dirResponse, err := state.createDriverResponse(pattern) + + // If there was an error loading the package, or the package is returned + // with errors, try to load the file as an ad-hoc package. + // Usually the error will appear in a returned package, but may not if we're + // in module mode and the ad-hoc is located outside a module. + if err != nil || len(dirResponse.Packages) == 1 && len(dirResponse.Packages[0].GoFiles) == 0 && + len(dirResponse.Packages[0].Errors) == 1 { + var queryErr error + if dirResponse, queryErr = state.adhocPackage(pattern, query); queryErr != nil { + return err // return the original error + } + } + isRoot := make(map[string]bool, len(dirResponse.Roots)) + for _, root := range dirResponse.Roots { + isRoot[root] = true + } + for _, pkg := range dirResponse.Packages { + // Add any new packages to the main set + // We don't bother to filter packages that will be dropped by the changes of roots, + // that will happen anyway during graph construction outside this function. + // Over-reporting packages is not a problem. + response.addPackage(pkg) + // if the package was not a root one, it cannot have the file + if !isRoot[pkg.ID] { + continue + } + for _, pkgFile := range pkg.GoFiles { + if filepath.Base(query) == filepath.Base(pkgFile) { + response.addRoot(pkg.ID) + break + } + } + } + } + return nil +} + +// adhocPackage attempts to load or construct an ad-hoc package for a given +// query, if the original call to the driver produced inadequate results. +func (state *golistState) adhocPackage(pattern, query string) (*driverResponse, error) { + response, err := state.createDriverResponse(query) + if err != nil { + return nil, err + } + // If we get nothing back from `go list`, + // try to make this file into its own ad-hoc package. + // TODO(rstambler): Should this check against the original response? + if len(response.Packages) == 0 { + response.Packages = append(response.Packages, &Package{ + ID: "command-line-arguments", + PkgPath: query, + GoFiles: []string{query}, + CompiledGoFiles: []string{query}, + Imports: make(map[string]*Package), + }) + response.Roots = append(response.Roots, "command-line-arguments") + } + // Handle special cases. + if len(response.Packages) == 1 { + // golang/go#33482: If this is a file= query for ad-hoc packages where + // the file only exists on an overlay, and exists outside of a module, + // add the file to the package and remove the errors. + if response.Packages[0].ID == "command-line-arguments" || + filepath.ToSlash(response.Packages[0].PkgPath) == filepath.ToSlash(query) { + if len(response.Packages[0].GoFiles) == 0 { + filename := filepath.Join(pattern, filepath.Base(query)) // avoid recomputing abspath + // TODO(matloob): check if the file is outside of a root dir? + for path := range state.cfg.Overlay { + if path == filename { + response.Packages[0].Errors = nil + response.Packages[0].GoFiles = []string{path} + response.Packages[0].CompiledGoFiles = []string{path} + } + } + } + } + } + return response, nil +} + +// Fields must match go list; +// see $GOROOT/src/cmd/go/internal/load/pkg.go. +type jsonPackage struct { + ImportPath string + Dir string + Name string + Export string + GoFiles []string + CompiledGoFiles []string + IgnoredGoFiles []string + IgnoredOtherFiles []string + CFiles []string + CgoFiles []string + CXXFiles []string + MFiles []string + HFiles []string + FFiles []string + SFiles []string + SwigFiles []string + SwigCXXFiles []string + SysoFiles []string + Imports []string + ImportMap map[string]string + Deps []string + Module *Module + TestGoFiles []string + TestImports []string + XTestGoFiles []string + XTestImports []string + ForTest string // q in a "p [q.test]" package, else "" + DepOnly bool + + Error *jsonPackageError +} + +type jsonPackageError struct { + ImportStack []string + Pos string + Err string +} + +func otherFiles(p *jsonPackage) [][]string { + return [][]string{p.CFiles, p.CXXFiles, p.MFiles, p.HFiles, p.FFiles, p.SFiles, p.SwigFiles, p.SwigCXXFiles, p.SysoFiles} +} + +// createDriverResponse uses the "go list" command to expand the pattern +// words and return a response for the specified packages. +func (state *golistState) createDriverResponse(words ...string) (*driverResponse, error) { + // go list uses the following identifiers in ImportPath and Imports: + // + // "p" -- importable package or main (command) + // "q.test" -- q's test executable + // "p [q.test]" -- variant of p as built for q's test executable + // "q_test [q.test]" -- q's external test package + // + // The packages p that are built differently for a test q.test + // are q itself, plus any helpers used by the external test q_test, + // typically including "testing" and all its dependencies. + + // Run "go list" for complete + // information on the specified packages. + buf, err := state.invokeGo("list", golistargs(state.cfg, words)...) + if err != nil { + return nil, err + } + seen := make(map[string]*jsonPackage) + pkgs := make(map[string]*Package) + additionalErrors := make(map[string][]Error) + // Decode the JSON and convert it to Package form. + var response driverResponse + for dec := json.NewDecoder(buf); dec.More(); { + p := new(jsonPackage) + if err := dec.Decode(p); err != nil { + return nil, fmt.Errorf("JSON decoding failed: %v", err) + } + + if p.ImportPath == "" { + // The documentation for go list says that “[e]rroneous packages will have + // a non-empty ImportPath”. If for some reason it comes back empty, we + // prefer to error out rather than silently discarding data or handing + // back a package without any way to refer to it. + if p.Error != nil { + return nil, Error{ + Pos: p.Error.Pos, + Msg: p.Error.Err, + } + } + return nil, fmt.Errorf("package missing import path: %+v", p) + } + + // Work around https://golang.org/issue/33157: + // go list -e, when given an absolute path, will find the package contained at + // that directory. But when no package exists there, it will return a fake package + // with an error and the ImportPath set to the absolute path provided to go list. + // Try to convert that absolute path to what its package path would be if it's + // contained in a known module or GOPATH entry. This will allow the package to be + // properly "reclaimed" when overlays are processed. + if filepath.IsAbs(p.ImportPath) && p.Error != nil { + pkgPath, ok, err := state.getPkgPath(p.ImportPath) + if err != nil { + return nil, err + } + if ok { + p.ImportPath = pkgPath + } + } + + if old, found := seen[p.ImportPath]; found { + // If one version of the package has an error, and the other doesn't, assume + // that this is a case where go list is reporting a fake dependency variant + // of the imported package: When a package tries to invalidly import another + // package, go list emits a variant of the imported package (with the same + // import path, but with an error on it, and the package will have a + // DepError set on it). An example of when this can happen is for imports of + // main packages: main packages can not be imported, but they may be + // separately matched and listed by another pattern. + // See golang.org/issue/36188 for more details. + + // The plan is that eventually, hopefully in Go 1.15, the error will be + // reported on the importing package rather than the duplicate "fake" + // version of the imported package. Once all supported versions of Go + // have the new behavior this logic can be deleted. + // TODO(matloob): delete the workaround logic once all supported versions of + // Go return the errors on the proper package. + + // There should be exactly one version of a package that doesn't have an + // error. + if old.Error == nil && p.Error == nil { + if !reflect.DeepEqual(p, old) { + return nil, fmt.Errorf("internal error: go list gives conflicting information for package %v", p.ImportPath) + } + continue + } + + // Determine if this package's error needs to be bubbled up. + // This is a hack, and we expect for go list to eventually set the error + // on the package. + if old.Error != nil { + var errkind string + if strings.Contains(old.Error.Err, "not an importable package") { + errkind = "not an importable package" + } else if strings.Contains(old.Error.Err, "use of internal package") && strings.Contains(old.Error.Err, "not allowed") { + errkind = "use of internal package not allowed" + } + if errkind != "" { + if len(old.Error.ImportStack) < 1 { + return nil, fmt.Errorf(`internal error: go list gave a %q error with empty import stack`, errkind) + } + importingPkg := old.Error.ImportStack[len(old.Error.ImportStack)-1] + if importingPkg == old.ImportPath { + // Using an older version of Go which put this package itself on top of import + // stack, instead of the importer. Look for importer in second from top + // position. + if len(old.Error.ImportStack) < 2 { + return nil, fmt.Errorf(`internal error: go list gave a %q error with an import stack without importing package`, errkind) + } + importingPkg = old.Error.ImportStack[len(old.Error.ImportStack)-2] + } + additionalErrors[importingPkg] = append(additionalErrors[importingPkg], Error{ + Pos: old.Error.Pos, + Msg: old.Error.Err, + Kind: ListError, + }) + } + } + + // Make sure that if there's a version of the package without an error, + // that's the one reported to the user. + if old.Error == nil { + continue + } + + // This package will replace the old one at the end of the loop. + } + seen[p.ImportPath] = p + + pkg := &Package{ + Name: p.Name, + ID: p.ImportPath, + GoFiles: absJoin(p.Dir, p.GoFiles, p.CgoFiles), + CompiledGoFiles: absJoin(p.Dir, p.CompiledGoFiles), + OtherFiles: absJoin(p.Dir, otherFiles(p)...), + IgnoredFiles: absJoin(p.Dir, p.IgnoredGoFiles, p.IgnoredOtherFiles), + forTest: p.ForTest, + Module: p.Module, + } + + if (state.cfg.Mode&typecheckCgo) != 0 && len(p.CgoFiles) != 0 { + if len(p.CompiledGoFiles) > len(p.GoFiles) { + // We need the cgo definitions, which are in the first + // CompiledGoFile after the non-cgo ones. This is a hack but there + // isn't currently a better way to find it. We also need the pure + // Go files and unprocessed cgo files, all of which are already + // in pkg.GoFiles. + cgoTypes := p.CompiledGoFiles[len(p.GoFiles)] + pkg.CompiledGoFiles = append([]string{cgoTypes}, pkg.GoFiles...) + } else { + // golang/go#38990: go list silently fails to do cgo processing + pkg.CompiledGoFiles = nil + pkg.Errors = append(pkg.Errors, Error{ + Msg: "go list failed to return CompiledGoFiles; https://golang.org/issue/38990?", + Kind: ListError, + }) + } + } + + // Work around https://golang.org/issue/28749: + // cmd/go puts assembly, C, and C++ files in CompiledGoFiles. + // Filter out any elements of CompiledGoFiles that are also in OtherFiles. + // We have to keep this workaround in place until go1.12 is a distant memory. + if len(pkg.OtherFiles) > 0 { + other := make(map[string]bool, len(pkg.OtherFiles)) + for _, f := range pkg.OtherFiles { + other[f] = true + } + + out := pkg.CompiledGoFiles[:0] + for _, f := range pkg.CompiledGoFiles { + if other[f] { + continue + } + out = append(out, f) + } + pkg.CompiledGoFiles = out + } + + // Extract the PkgPath from the package's ID. + if i := strings.IndexByte(pkg.ID, ' '); i >= 0 { + pkg.PkgPath = pkg.ID[:i] + } else { + pkg.PkgPath = pkg.ID + } + + if pkg.PkgPath == "unsafe" { + pkg.GoFiles = nil // ignore fake unsafe.go file + } + + // Assume go list emits only absolute paths for Dir. + if p.Dir != "" && !filepath.IsAbs(p.Dir) { + log.Fatalf("internal error: go list returned non-absolute Package.Dir: %s", p.Dir) + } + + if p.Export != "" && !filepath.IsAbs(p.Export) { + pkg.ExportFile = filepath.Join(p.Dir, p.Export) + } else { + pkg.ExportFile = p.Export + } + + // imports + // + // Imports contains the IDs of all imported packages. + // ImportsMap records (path, ID) only where they differ. + ids := make(map[string]bool) + for _, id := range p.Imports { + ids[id] = true + } + pkg.Imports = make(map[string]*Package) + for path, id := range p.ImportMap { + pkg.Imports[path] = &Package{ID: id} // non-identity import + delete(ids, id) + } + for id := range ids { + if id == "C" { + continue + } + + pkg.Imports[id] = &Package{ID: id} // identity import + } + if !p.DepOnly { + response.Roots = append(response.Roots, pkg.ID) + } + + // Work around for pre-go.1.11 versions of go list. + // TODO(matloob): they should be handled by the fallback. + // Can we delete this? + if len(pkg.CompiledGoFiles) == 0 { + pkg.CompiledGoFiles = pkg.GoFiles + } + + // Temporary work-around for golang/go#39986. Parse filenames out of + // error messages. This happens if there are unrecoverable syntax + // errors in the source, so we can't match on a specific error message. + if err := p.Error; err != nil && state.shouldAddFilenameFromError(p) { + addFilenameFromPos := func(pos string) bool { + split := strings.Split(pos, ":") + if len(split) < 1 { + return false + } + filename := strings.TrimSpace(split[0]) + if filename == "" { + return false + } + if !filepath.IsAbs(filename) { + filename = filepath.Join(state.cfg.Dir, filename) + } + info, _ := os.Stat(filename) + if info == nil { + return false + } + pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, filename) + pkg.GoFiles = append(pkg.GoFiles, filename) + return true + } + found := addFilenameFromPos(err.Pos) + // In some cases, go list only reports the error position in the + // error text, not the error position. One such case is when the + // file's package name is a keyword (see golang.org/issue/39763). + if !found { + addFilenameFromPos(err.Err) + } + } + + if p.Error != nil { + msg := strings.TrimSpace(p.Error.Err) // Trim to work around golang.org/issue/32363. + // Address golang.org/issue/35964 by appending import stack to error message. + if msg == "import cycle not allowed" && len(p.Error.ImportStack) != 0 { + msg += fmt.Sprintf(": import stack: %v", p.Error.ImportStack) + } + pkg.Errors = append(pkg.Errors, Error{ + Pos: p.Error.Pos, + Msg: msg, + Kind: ListError, + }) + } + + pkgs[pkg.ID] = pkg + } + + for id, errs := range additionalErrors { + if p, ok := pkgs[id]; ok { + p.Errors = append(p.Errors, errs...) + } + } + for _, pkg := range pkgs { + response.Packages = append(response.Packages, pkg) + } + sort.Slice(response.Packages, func(i, j int) bool { return response.Packages[i].ID < response.Packages[j].ID }) + + return &response, nil +} + +func (state *golistState) shouldAddFilenameFromError(p *jsonPackage) bool { + if len(p.GoFiles) > 0 || len(p.CompiledGoFiles) > 0 { + return false + } + + goV, err := state.getGoVersion() + if err != nil { + return false + } + + // On Go 1.14 and earlier, only add filenames from errors if the import stack is empty. + // The import stack behaves differently for these versions than newer Go versions. + if goV < 15 { + return len(p.Error.ImportStack) == 0 + } + + // On Go 1.15 and later, only parse filenames out of error if there's no import stack, + // or the current package is at the top of the import stack. This is not guaranteed + // to work perfectly, but should avoid some cases where files in errors don't belong to this + // package. + return len(p.Error.ImportStack) == 0 || p.Error.ImportStack[len(p.Error.ImportStack)-1] == p.ImportPath +} + +func (state *golistState) getGoVersion() (int, error) { + state.goVersionOnce.Do(func() { + state.goVersion, state.goVersionError = gocommand.GoVersion(state.ctx, state.cfgInvocation(), state.cfg.gocmdRunner) + }) + return state.goVersion, state.goVersionError +} + +// getPkgPath finds the package path of a directory if it's relative to a root +// directory. +func (state *golistState) getPkgPath(dir string) (string, bool, error) { + absDir, err := filepath.Abs(dir) + if err != nil { + return "", false, err + } + roots, err := state.determineRootDirs() + if err != nil { + return "", false, err + } + + for rdir, rpath := range roots { + // Make sure that the directory is in the module, + // to avoid creating a path relative to another module. + if !strings.HasPrefix(absDir, rdir) { + continue + } + // TODO(matloob): This doesn't properly handle symlinks. + r, err := filepath.Rel(rdir, dir) + if err != nil { + continue + } + if rpath != "" { + // We choose only one root even though the directory even it can belong in multiple modules + // or GOPATH entries. This is okay because we only need to work with absolute dirs when a + // file is missing from disk, for instance when gopls calls go/packages in an overlay. + // Once the file is saved, gopls, or the next invocation of the tool will get the correct + // result straight from golist. + // TODO(matloob): Implement module tiebreaking? + return path.Join(rpath, filepath.ToSlash(r)), true, nil + } + return filepath.ToSlash(r), true, nil + } + return "", false, nil +} + +// absJoin absolutizes and flattens the lists of files. +func absJoin(dir string, fileses ...[]string) (res []string) { + for _, files := range fileses { + for _, file := range files { + if !filepath.IsAbs(file) { + file = filepath.Join(dir, file) + } + res = append(res, file) + } + } + return res +} + +func golistargs(cfg *Config, words []string) []string { + const findFlags = NeedImports | NeedTypes | NeedSyntax | NeedTypesInfo + fullargs := []string{ + "-e", "-json", + fmt.Sprintf("-compiled=%t", cfg.Mode&(NeedCompiledGoFiles|NeedSyntax|NeedTypes|NeedTypesInfo|NeedTypesSizes) != 0), + fmt.Sprintf("-test=%t", cfg.Tests), + fmt.Sprintf("-export=%t", usesExportData(cfg)), + fmt.Sprintf("-deps=%t", cfg.Mode&NeedImports != 0), + // go list doesn't let you pass -test and -find together, + // probably because you'd just get the TestMain. + fmt.Sprintf("-find=%t", !cfg.Tests && cfg.Mode&findFlags == 0), + } + fullargs = append(fullargs, cfg.BuildFlags...) + fullargs = append(fullargs, "--") + fullargs = append(fullargs, words...) + return fullargs +} + +// cfgInvocation returns an Invocation that reflects cfg's settings. +func (state *golistState) cfgInvocation() gocommand.Invocation { + cfg := state.cfg + return gocommand.Invocation{ + BuildFlags: cfg.BuildFlags, + ModFile: cfg.modFile, + ModFlag: cfg.modFlag, + CleanEnv: cfg.Env != nil, + Env: cfg.Env, + Logf: cfg.Logf, + WorkingDir: cfg.Dir, + } +} + +// invokeGo returns the stdout of a go command invocation. +func (state *golistState) invokeGo(verb string, args ...string) (*bytes.Buffer, error) { + cfg := state.cfg + + inv := state.cfgInvocation() + + // For Go versions 1.16 and above, `go list` accepts overlays directly via + // the -overlay flag. Set it, if it's available. + // + // The check for "list" is not necessarily required, but we should avoid + // getting the go version if possible. + if verb == "list" { + goVersion, err := state.getGoVersion() + if err != nil { + return nil, err + } + if goVersion >= 16 { + filename, cleanup, err := state.writeOverlays() + if err != nil { + return nil, err + } + defer cleanup() + inv.Overlay = filename + } + } + inv.Verb = verb + inv.Args = args + gocmdRunner := cfg.gocmdRunner + if gocmdRunner == nil { + gocmdRunner = &gocommand.Runner{} + } + stdout, stderr, _, err := gocmdRunner.RunRaw(cfg.Context, inv) + if err != nil { + // Check for 'go' executable not being found. + if ee, ok := err.(*exec.Error); ok && ee.Err == exec.ErrNotFound { + return nil, fmt.Errorf("'go list' driver requires 'go', but %s", exec.ErrNotFound) + } + + exitErr, ok := err.(*exec.ExitError) + if !ok { + // Catastrophic error: + // - context cancellation + return nil, xerrors.Errorf("couldn't run 'go': %w", err) + } + + // Old go version? + if strings.Contains(stderr.String(), "flag provided but not defined") { + return nil, goTooOldError{fmt.Errorf("unsupported version of go: %s: %s", exitErr, stderr)} + } + + // Related to #24854 + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "unexpected directory layout") { + return nil, fmt.Errorf("%s", stderr.String()) + } + + // Is there an error running the C compiler in cgo? This will be reported in the "Error" field + // and should be suppressed by go list -e. + // + // This condition is not perfect yet because the error message can include other error messages than runtime/cgo. + isPkgPathRune := func(r rune) bool { + // From https://golang.org/ref/spec#Import_declarations: + // Implementation restriction: A compiler may restrict ImportPaths to non-empty strings + // using only characters belonging to Unicode's L, M, N, P, and S general categories + // (the Graphic characters without spaces) and may also exclude the + // characters !"#$%&'()*,:;<=>?[\]^`{|} and the Unicode replacement character U+FFFD. + return unicode.IsOneOf([]*unicode.RangeTable{unicode.L, unicode.M, unicode.N, unicode.P, unicode.S}, r) && + !strings.ContainsRune("!\"#$%&'()*,:;<=>?[\\]^`{|}\uFFFD", r) + } + // golang/go#36770: Handle case where cmd/go prints module download messages before the error. + msg := stderr.String() + for strings.HasPrefix(msg, "go: downloading") { + msg = msg[strings.IndexRune(msg, '\n')+1:] + } + if len(stderr.String()) > 0 && strings.HasPrefix(stderr.String(), "# ") { + msg := msg[len("# "):] + if strings.HasPrefix(strings.TrimLeftFunc(msg, isPkgPathRune), "\n") { + return stdout, nil + } + // Treat pkg-config errors as a special case (golang.org/issue/36770). + if strings.HasPrefix(msg, "pkg-config") { + return stdout, nil + } + } + + // This error only appears in stderr. See golang.org/cl/166398 for a fix in go list to show + // the error in the Err section of stdout in case -e option is provided. + // This fix is provided for backwards compatibility. + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "named files must be .go files") { + output := fmt.Sprintf(`{"ImportPath": "command-line-arguments","Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Similar to the previous error, but currently lacks a fix in Go. + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "named files must all be in one directory") { + output := fmt.Sprintf(`{"ImportPath": "command-line-arguments","Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Backwards compatibility for Go 1.11 because 1.12 and 1.13 put the directory in the ImportPath. + // If the package doesn't exist, put the absolute path of the directory into the error message, + // as Go 1.13 list does. + const noSuchDirectory = "no such directory" + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), noSuchDirectory) { + errstr := stderr.String() + abspath := strings.TrimSpace(errstr[strings.Index(errstr, noSuchDirectory)+len(noSuchDirectory):]) + output := fmt.Sprintf(`{"ImportPath": %q,"Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + abspath, strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Workaround for #29280: go list -e has incorrect behavior when an ad-hoc package doesn't exist. + // Note that the error message we look for in this case is different that the one looked for above. + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "no such file or directory") { + output := fmt.Sprintf(`{"ImportPath": "command-line-arguments","Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Workaround for #34273. go list -e with GO111MODULE=on has incorrect behavior when listing a + // directory outside any module. + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "outside available modules") { + output := fmt.Sprintf(`{"ImportPath": %q,"Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + // TODO(matloob): command-line-arguments isn't correct here. + "command-line-arguments", strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Another variation of the previous error + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "outside module root") { + output := fmt.Sprintf(`{"ImportPath": %q,"Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + // TODO(matloob): command-line-arguments isn't correct here. + "command-line-arguments", strings.Trim(stderr.String(), "\n")) + return bytes.NewBufferString(output), nil + } + + // Workaround for an instance of golang.org/issue/26755: go list -e will return a non-zero exit + // status if there's a dependency on a package that doesn't exist. But it should return + // a zero exit status and set an error on that package. + if len(stderr.String()) > 0 && strings.Contains(stderr.String(), "no Go files in") { + // Don't clobber stdout if `go list` actually returned something. + if len(stdout.String()) > 0 { + return stdout, nil + } + // try to extract package name from string + stderrStr := stderr.String() + var importPath string + colon := strings.Index(stderrStr, ":") + if colon > 0 && strings.HasPrefix(stderrStr, "go build ") { + importPath = stderrStr[len("go build "):colon] + } + output := fmt.Sprintf(`{"ImportPath": %q,"Incomplete": true,"Error": {"Pos": "","Err": %q}}`, + importPath, strings.Trim(stderrStr, "\n")) + return bytes.NewBufferString(output), nil + } + + // Export mode entails a build. + // If that build fails, errors appear on stderr + // (despite the -e flag) and the Export field is blank. + // Do not fail in that case. + // The same is true if an ad-hoc package given to go list doesn't exist. + // TODO(matloob): Remove these once we can depend on go list to exit with a zero status with -e even when + // packages don't exist or a build fails. + if !usesExportData(cfg) && !containsGoFile(args) { + return nil, fmt.Errorf("go %v: %s: %s", args, exitErr, stderr) + } + } + return stdout, nil +} + +// OverlayJSON is the format overlay files are expected to be in. +// The Replace map maps from overlaid paths to replacement paths: +// the Go command will forward all reads trying to open +// each overlaid path to its replacement path, or consider the overlaid +// path not to exist if the replacement path is empty. +// +// From golang/go#39958. +type OverlayJSON struct { + Replace map[string]string `json:"replace,omitempty"` +} + +// writeOverlays writes out files for go list's -overlay flag, as described +// above. +func (state *golistState) writeOverlays() (filename string, cleanup func(), err error) { + // Do nothing if there are no overlays in the config. + if len(state.cfg.Overlay) == 0 { + return "", func() {}, nil + } + dir, err := ioutil.TempDir("", "gopackages-*") + if err != nil { + return "", nil, err + } + // The caller must clean up this directory, unless this function returns an + // error. + cleanup = func() { + os.RemoveAll(dir) + } + defer func() { + if err != nil { + cleanup() + } + }() + overlays := map[string]string{} + for k, v := range state.cfg.Overlay { + // Create a unique filename for the overlaid files, to avoid + // creating nested directories. + noSeparator := strings.Join(strings.Split(filepath.ToSlash(k), "/"), "") + f, err := ioutil.TempFile(dir, fmt.Sprintf("*-%s", noSeparator)) + if err != nil { + return "", func() {}, err + } + if _, err := f.Write(v); err != nil { + return "", func() {}, err + } + if err := f.Close(); err != nil { + return "", func() {}, err + } + overlays[k] = f.Name() + } + b, err := json.Marshal(OverlayJSON{Replace: overlays}) + if err != nil { + return "", func() {}, err + } + // Write out the overlay file that contains the filepath mappings. + filename = filepath.Join(dir, "overlay.json") + if err := ioutil.WriteFile(filename, b, 0665); err != nil { + return "", func() {}, err + } + return filename, cleanup, nil +} + +func containsGoFile(s []string) bool { + for _, f := range s { + if strings.HasSuffix(f, ".go") { + return true + } + } + return false +} + +func cmdDebugStr(cmd *exec.Cmd) string { + env := make(map[string]string) + for _, kv := range cmd.Env { + split := strings.SplitN(kv, "=", 2) + k, v := split[0], split[1] + env[k] = v + } + + var args []string + for _, arg := range cmd.Args { + quoted := strconv.Quote(arg) + if quoted[1:len(quoted)-1] != arg || strings.Contains(arg, " ") { + args = append(args, quoted) + } else { + args = append(args, arg) + } + } + return fmt.Sprintf("GOROOT=%v GOPATH=%v GO111MODULE=%v GOPROXY=%v PWD=%v %v", env["GOROOT"], env["GOPATH"], env["GO111MODULE"], env["GOPROXY"], env["PWD"], strings.Join(args, " ")) +} diff --git a/vendor/golang.org/x/tools/go/packages/golist_overlay.go b/vendor/golang.org/x/tools/go/packages/golist_overlay.go new file mode 100644 index 0000000000..9576b472f9 --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/golist_overlay.go @@ -0,0 +1,575 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package packages + +import ( + "encoding/json" + "fmt" + "go/parser" + "go/token" + "os" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + + "golang.org/x/tools/internal/gocommand" +) + +// processGolistOverlay provides rudimentary support for adding +// files that don't exist on disk to an overlay. The results can be +// sometimes incorrect. +// TODO(matloob): Handle unsupported cases, including the following: +// - determining the correct package to add given a new import path +func (state *golistState) processGolistOverlay(response *responseDeduper) (modifiedPkgs, needPkgs []string, err error) { + havePkgs := make(map[string]string) // importPath -> non-test package ID + needPkgsSet := make(map[string]bool) + modifiedPkgsSet := make(map[string]bool) + + pkgOfDir := make(map[string][]*Package) + for _, pkg := range response.dr.Packages { + // This is an approximation of import path to id. This can be + // wrong for tests, vendored packages, and a number of other cases. + havePkgs[pkg.PkgPath] = pkg.ID + dir, err := commonDir(pkg.GoFiles) + if err != nil { + return nil, nil, err + } + if dir != "" { + pkgOfDir[dir] = append(pkgOfDir[dir], pkg) + } + } + + // If no new imports are added, it is safe to avoid loading any needPkgs. + // Otherwise, it's hard to tell which package is actually being loaded + // (due to vendoring) and whether any modified package will show up + // in the transitive set of dependencies (because new imports are added, + // potentially modifying the transitive set of dependencies). + var overlayAddsImports bool + + // If both a package and its test package are created by the overlay, we + // need the real package first. Process all non-test files before test + // files, and make the whole process deterministic while we're at it. + var overlayFiles []string + for opath := range state.cfg.Overlay { + overlayFiles = append(overlayFiles, opath) + } + sort.Slice(overlayFiles, func(i, j int) bool { + iTest := strings.HasSuffix(overlayFiles[i], "_test.go") + jTest := strings.HasSuffix(overlayFiles[j], "_test.go") + if iTest != jTest { + return !iTest // non-tests are before tests. + } + return overlayFiles[i] < overlayFiles[j] + }) + for _, opath := range overlayFiles { + contents := state.cfg.Overlay[opath] + base := filepath.Base(opath) + dir := filepath.Dir(opath) + var pkg *Package // if opath belongs to both a package and its test variant, this will be the test variant + var testVariantOf *Package // if opath is a test file, this is the package it is testing + var fileExists bool + isTestFile := strings.HasSuffix(opath, "_test.go") + pkgName, ok := extractPackageName(opath, contents) + if !ok { + // Don't bother adding a file that doesn't even have a parsable package statement + // to the overlay. + continue + } + // If all the overlay files belong to a different package, change the + // package name to that package. + maybeFixPackageName(pkgName, isTestFile, pkgOfDir[dir]) + nextPackage: + for _, p := range response.dr.Packages { + if pkgName != p.Name && p.ID != "command-line-arguments" { + continue + } + for _, f := range p.GoFiles { + if !sameFile(filepath.Dir(f), dir) { + continue + } + // Make sure to capture information on the package's test variant, if needed. + if isTestFile && !hasTestFiles(p) { + // TODO(matloob): Are there packages other than the 'production' variant + // of a package that this can match? This shouldn't match the test main package + // because the file is generated in another directory. + testVariantOf = p + continue nextPackage + } else if !isTestFile && hasTestFiles(p) { + // We're examining a test variant, but the overlaid file is + // a non-test file. Because the overlay implementation + // (currently) only adds a file to one package, skip this + // package, so that we can add the file to the production + // variant of the package. (https://golang.org/issue/36857 + // tracks handling overlays on both the production and test + // variant of a package). + continue nextPackage + } + if pkg != nil && p != pkg && pkg.PkgPath == p.PkgPath { + // We have already seen the production version of the + // for which p is a test variant. + if hasTestFiles(p) { + testVariantOf = pkg + } + } + pkg = p + if filepath.Base(f) == base { + fileExists = true + } + } + } + // The overlay could have included an entirely new package or an + // ad-hoc package. An ad-hoc package is one that we have manually + // constructed from inadequate `go list` results for a file= query. + // It will have the ID command-line-arguments. + if pkg == nil || pkg.ID == "command-line-arguments" { + // Try to find the module or gopath dir the file is contained in. + // Then for modules, add the module opath to the beginning. + pkgPath, ok, err := state.getPkgPath(dir) + if err != nil { + return nil, nil, err + } + if !ok { + break + } + var forTest string // only set for x tests + isXTest := strings.HasSuffix(pkgName, "_test") + if isXTest { + forTest = pkgPath + pkgPath += "_test" + } + id := pkgPath + if isTestFile { + if isXTest { + id = fmt.Sprintf("%s [%s.test]", pkgPath, forTest) + } else { + id = fmt.Sprintf("%s [%s.test]", pkgPath, pkgPath) + } + } + if pkg != nil { + // TODO(rstambler): We should change the package's path and ID + // here. The only issue is that this messes with the roots. + } else { + // Try to reclaim a package with the same ID, if it exists in the response. + for _, p := range response.dr.Packages { + if reclaimPackage(p, id, opath, contents) { + pkg = p + break + } + } + // Otherwise, create a new package. + if pkg == nil { + pkg = &Package{ + PkgPath: pkgPath, + ID: id, + Name: pkgName, + Imports: make(map[string]*Package), + } + response.addPackage(pkg) + havePkgs[pkg.PkgPath] = id + // Add the production package's sources for a test variant. + if isTestFile && !isXTest && testVariantOf != nil { + pkg.GoFiles = append(pkg.GoFiles, testVariantOf.GoFiles...) + pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, testVariantOf.CompiledGoFiles...) + // Add the package under test and its imports to the test variant. + pkg.forTest = testVariantOf.PkgPath + for k, v := range testVariantOf.Imports { + pkg.Imports[k] = &Package{ID: v.ID} + } + } + if isXTest { + pkg.forTest = forTest + } + } + } + } + if !fileExists { + pkg.GoFiles = append(pkg.GoFiles, opath) + // TODO(matloob): Adding the file to CompiledGoFiles can exhibit the wrong behavior + // if the file will be ignored due to its build tags. + pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, opath) + modifiedPkgsSet[pkg.ID] = true + } + imports, err := extractImports(opath, contents) + if err != nil { + // Let the parser or type checker report errors later. + continue + } + for _, imp := range imports { + // TODO(rstambler): If the package is an x test and the import has + // a test variant, make sure to replace it. + if _, found := pkg.Imports[imp]; found { + continue + } + overlayAddsImports = true + id, ok := havePkgs[imp] + if !ok { + var err error + id, err = state.resolveImport(dir, imp) + if err != nil { + return nil, nil, err + } + } + pkg.Imports[imp] = &Package{ID: id} + // Add dependencies to the non-test variant version of this package as well. + if testVariantOf != nil { + testVariantOf.Imports[imp] = &Package{ID: id} + } + } + } + + // toPkgPath guesses the package path given the id. + toPkgPath := func(sourceDir, id string) (string, error) { + if i := strings.IndexByte(id, ' '); i >= 0 { + return state.resolveImport(sourceDir, id[:i]) + } + return state.resolveImport(sourceDir, id) + } + + // Now that new packages have been created, do another pass to determine + // the new set of missing packages. + for _, pkg := range response.dr.Packages { + for _, imp := range pkg.Imports { + if len(pkg.GoFiles) == 0 { + return nil, nil, fmt.Errorf("cannot resolve imports for package %q with no Go files", pkg.PkgPath) + } + pkgPath, err := toPkgPath(filepath.Dir(pkg.GoFiles[0]), imp.ID) + if err != nil { + return nil, nil, err + } + if _, ok := havePkgs[pkgPath]; !ok { + needPkgsSet[pkgPath] = true + } + } + } + + if overlayAddsImports { + needPkgs = make([]string, 0, len(needPkgsSet)) + for pkg := range needPkgsSet { + needPkgs = append(needPkgs, pkg) + } + } + modifiedPkgs = make([]string, 0, len(modifiedPkgsSet)) + for pkg := range modifiedPkgsSet { + modifiedPkgs = append(modifiedPkgs, pkg) + } + return modifiedPkgs, needPkgs, err +} + +// resolveImport finds the ID of a package given its import path. +// In particular, it will find the right vendored copy when in GOPATH mode. +func (state *golistState) resolveImport(sourceDir, importPath string) (string, error) { + env, err := state.getEnv() + if err != nil { + return "", err + } + if env["GOMOD"] != "" { + return importPath, nil + } + + searchDir := sourceDir + for { + vendorDir := filepath.Join(searchDir, "vendor") + exists, ok := state.vendorDirs[vendorDir] + if !ok { + info, err := os.Stat(vendorDir) + exists = err == nil && info.IsDir() + state.vendorDirs[vendorDir] = exists + } + + if exists { + vendoredPath := filepath.Join(vendorDir, importPath) + if info, err := os.Stat(vendoredPath); err == nil && info.IsDir() { + // We should probably check for .go files here, but shame on anyone who fools us. + path, ok, err := state.getPkgPath(vendoredPath) + if err != nil { + return "", err + } + if ok { + return path, nil + } + } + } + + // We know we've hit the top of the filesystem when we Dir / and get /, + // or C:\ and get C:\, etc. + next := filepath.Dir(searchDir) + if next == searchDir { + break + } + searchDir = next + } + return importPath, nil +} + +func hasTestFiles(p *Package) bool { + for _, f := range p.GoFiles { + if strings.HasSuffix(f, "_test.go") { + return true + } + } + return false +} + +// determineRootDirs returns a mapping from absolute directories that could +// contain code to their corresponding import path prefixes. +func (state *golistState) determineRootDirs() (map[string]string, error) { + env, err := state.getEnv() + if err != nil { + return nil, err + } + if env["GOMOD"] != "" { + state.rootsOnce.Do(func() { + state.rootDirs, state.rootDirsError = state.determineRootDirsModules() + }) + } else { + state.rootsOnce.Do(func() { + state.rootDirs, state.rootDirsError = state.determineRootDirsGOPATH() + }) + } + return state.rootDirs, state.rootDirsError +} + +func (state *golistState) determineRootDirsModules() (map[string]string, error) { + // List all of the modules--the first will be the directory for the main + // module. Any replaced modules will also need to be treated as roots. + // Editing files in the module cache isn't a great idea, so we don't + // plan to ever support that. + out, err := state.invokeGo("list", "-m", "-json", "all") + if err != nil { + // 'go list all' will fail if we're outside of a module and + // GO111MODULE=on. Try falling back without 'all'. + var innerErr error + out, innerErr = state.invokeGo("list", "-m", "-json") + if innerErr != nil { + return nil, err + } + } + roots := map[string]string{} + modules := map[string]string{} + var i int + for dec := json.NewDecoder(out); dec.More(); { + mod := new(gocommand.ModuleJSON) + if err := dec.Decode(mod); err != nil { + return nil, err + } + if mod.Dir != "" && mod.Path != "" { + // This is a valid module; add it to the map. + absDir, err := filepath.Abs(mod.Dir) + if err != nil { + return nil, err + } + modules[absDir] = mod.Path + // The first result is the main module. + if i == 0 || mod.Replace != nil && mod.Replace.Path != "" { + roots[absDir] = mod.Path + } + } + i++ + } + return roots, nil +} + +func (state *golistState) determineRootDirsGOPATH() (map[string]string, error) { + m := map[string]string{} + for _, dir := range filepath.SplitList(state.mustGetEnv()["GOPATH"]) { + absDir, err := filepath.Abs(dir) + if err != nil { + return nil, err + } + m[filepath.Join(absDir, "src")] = "" + } + return m, nil +} + +func extractImports(filename string, contents []byte) ([]string, error) { + f, err := parser.ParseFile(token.NewFileSet(), filename, contents, parser.ImportsOnly) // TODO(matloob): reuse fileset? + if err != nil { + return nil, err + } + var res []string + for _, imp := range f.Imports { + quotedPath := imp.Path.Value + path, err := strconv.Unquote(quotedPath) + if err != nil { + return nil, err + } + res = append(res, path) + } + return res, nil +} + +// reclaimPackage attempts to reuse a package that failed to load in an overlay. +// +// If the package has errors and has no Name, GoFiles, or Imports, +// then it's possible that it doesn't yet exist on disk. +func reclaimPackage(pkg *Package, id string, filename string, contents []byte) bool { + // TODO(rstambler): Check the message of the actual error? + // It differs between $GOPATH and module mode. + if pkg.ID != id { + return false + } + if len(pkg.Errors) != 1 { + return false + } + if pkg.Name != "" || pkg.ExportFile != "" { + return false + } + if len(pkg.GoFiles) > 0 || len(pkg.CompiledGoFiles) > 0 || len(pkg.OtherFiles) > 0 { + return false + } + if len(pkg.Imports) > 0 { + return false + } + pkgName, ok := extractPackageName(filename, contents) + if !ok { + return false + } + pkg.Name = pkgName + pkg.Errors = nil + return true +} + +func extractPackageName(filename string, contents []byte) (string, bool) { + // TODO(rstambler): Check the message of the actual error? + // It differs between $GOPATH and module mode. + f, err := parser.ParseFile(token.NewFileSet(), filename, contents, parser.PackageClauseOnly) // TODO(matloob): reuse fileset? + if err != nil { + return "", false + } + return f.Name.Name, true +} + +// commonDir returns the directory that all files are in, "" if files is empty, +// or an error if they aren't in the same directory. +func commonDir(files []string) (string, error) { + seen := make(map[string]bool) + for _, f := range files { + seen[filepath.Dir(f)] = true + } + if len(seen) > 1 { + return "", fmt.Errorf("files (%v) are in more than one directory: %v", files, seen) + } + for k := range seen { + // seen has only one element; return it. + return k, nil + } + return "", nil // no files +} + +// It is possible that the files in the disk directory dir have a different package +// name from newName, which is deduced from the overlays. If they all have a different +// package name, and they all have the same package name, then that name becomes +// the package name. +// It returns true if it changes the package name, false otherwise. +func maybeFixPackageName(newName string, isTestFile bool, pkgsOfDir []*Package) { + names := make(map[string]int) + for _, p := range pkgsOfDir { + names[p.Name]++ + } + if len(names) != 1 { + // some files are in different packages + return + } + var oldName string + for k := range names { + oldName = k + } + if newName == oldName { + return + } + // We might have a case where all of the package names in the directory are + // the same, but the overlay file is for an x test, which belongs to its + // own package. If the x test does not yet exist on disk, we may not yet + // have its package name on disk, but we should not rename the packages. + // + // We use a heuristic to determine if this file belongs to an x test: + // The test file should have a package name whose package name has a _test + // suffix or looks like "newName_test". + maybeXTest := strings.HasPrefix(oldName+"_test", newName) || strings.HasSuffix(newName, "_test") + if isTestFile && maybeXTest { + return + } + for _, p := range pkgsOfDir { + p.Name = newName + } +} + +// This function is copy-pasted from +// https://github.com/golang/go/blob/9706f510a5e2754595d716bd64be8375997311fb/src/cmd/go/internal/search/search.go#L360. +// It should be deleted when we remove support for overlays from go/packages. +// +// NOTE: This does not handle any ./... or ./ style queries, as this function +// doesn't know the working directory. +// +// matchPattern(pattern)(name) reports whether +// name matches pattern. Pattern is a limited glob +// pattern in which '...' means 'any string' and there +// is no other special syntax. +// Unfortunately, there are two special cases. Quoting "go help packages": +// +// First, /... at the end of the pattern can match an empty string, +// so that net/... matches both net and packages in its subdirectories, like net/http. +// Second, any slash-separated pattern element containing a wildcard never +// participates in a match of the "vendor" element in the path of a vendored +// package, so that ./... does not match packages in subdirectories of +// ./vendor or ./mycode/vendor, but ./vendor/... and ./mycode/vendor/... do. +// Note, however, that a directory named vendor that itself contains code +// is not a vendored package: cmd/vendor would be a command named vendor, +// and the pattern cmd/... matches it. +func matchPattern(pattern string) func(name string) bool { + // Convert pattern to regular expression. + // The strategy for the trailing /... is to nest it in an explicit ? expression. + // The strategy for the vendor exclusion is to change the unmatchable + // vendor strings to a disallowed code point (vendorChar) and to use + // "(anything but that codepoint)*" as the implementation of the ... wildcard. + // This is a bit complicated but the obvious alternative, + // namely a hand-written search like in most shell glob matchers, + // is too easy to make accidentally exponential. + // Using package regexp guarantees linear-time matching. + + const vendorChar = "\x00" + + if strings.Contains(pattern, vendorChar) { + return func(name string) bool { return false } + } + + re := regexp.QuoteMeta(pattern) + re = replaceVendor(re, vendorChar) + switch { + case strings.HasSuffix(re, `/`+vendorChar+`/\.\.\.`): + re = strings.TrimSuffix(re, `/`+vendorChar+`/\.\.\.`) + `(/vendor|/` + vendorChar + `/\.\.\.)` + case re == vendorChar+`/\.\.\.`: + re = `(/vendor|/` + vendorChar + `/\.\.\.)` + case strings.HasSuffix(re, `/\.\.\.`): + re = strings.TrimSuffix(re, `/\.\.\.`) + `(/\.\.\.)?` + } + re = strings.ReplaceAll(re, `\.\.\.`, `[^`+vendorChar+`]*`) + + reg := regexp.MustCompile(`^` + re + `$`) + + return func(name string) bool { + if strings.Contains(name, vendorChar) { + return false + } + return reg.MatchString(replaceVendor(name, vendorChar)) + } +} + +// replaceVendor returns the result of replacing +// non-trailing vendor path elements in x with repl. +func replaceVendor(x, repl string) string { + if !strings.Contains(x, "vendor") { + return x + } + elem := strings.Split(x, "/") + for i := 0; i < len(elem)-1; i++ { + if elem[i] == "vendor" { + elem[i] = repl + } + } + return strings.Join(elem, "/") +} diff --git a/vendor/golang.org/x/tools/go/packages/loadmode_string.go b/vendor/golang.org/x/tools/go/packages/loadmode_string.go new file mode 100644 index 0000000000..7ea37e7eea --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/loadmode_string.go @@ -0,0 +1,57 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package packages + +import ( + "fmt" + "strings" +) + +var allModes = []LoadMode{ + NeedName, + NeedFiles, + NeedCompiledGoFiles, + NeedImports, + NeedDeps, + NeedExportsFile, + NeedTypes, + NeedSyntax, + NeedTypesInfo, + NeedTypesSizes, +} + +var modeStrings = []string{ + "NeedName", + "NeedFiles", + "NeedCompiledGoFiles", + "NeedImports", + "NeedDeps", + "NeedExportsFile", + "NeedTypes", + "NeedSyntax", + "NeedTypesInfo", + "NeedTypesSizes", +} + +func (mod LoadMode) String() string { + m := mod + if m == 0 { + return "LoadMode(0)" + } + var out []string + for i, x := range allModes { + if x > m { + break + } + if (m & x) != 0 { + out = append(out, modeStrings[i]) + m = m ^ x + } + } + if m != 0 { + out = append(out, "Unknown") + } + return fmt.Sprintf("LoadMode(%s)", strings.Join(out, "|")) +} diff --git a/vendor/golang.org/x/tools/go/packages/packages.go b/vendor/golang.org/x/tools/go/packages/packages.go new file mode 100644 index 0000000000..38475e8712 --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/packages.go @@ -0,0 +1,1233 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package packages + +// See doc.go for package documentation and implementation notes. + +import ( + "context" + "encoding/json" + "fmt" + "go/ast" + "go/parser" + "go/scanner" + "go/token" + "go/types" + "io/ioutil" + "log" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "golang.org/x/tools/go/gcexportdata" + "golang.org/x/tools/internal/gocommand" + "golang.org/x/tools/internal/packagesinternal" + "golang.org/x/tools/internal/typesinternal" +) + +// A LoadMode controls the amount of detail to return when loading. +// The bits below can be combined to specify which fields should be +// filled in the result packages. +// The zero value is a special case, equivalent to combining +// the NeedName, NeedFiles, and NeedCompiledGoFiles bits. +// ID and Errors (if present) will always be filled. +// Load may return more information than requested. +type LoadMode int + +// TODO(matloob): When a V2 of go/packages is released, rename NeedExportsFile to +// NeedExportFile to make it consistent with the Package field it's adding. + +const ( + // NeedName adds Name and PkgPath. + NeedName LoadMode = 1 << iota + + // NeedFiles adds GoFiles and OtherFiles. + NeedFiles + + // NeedCompiledGoFiles adds CompiledGoFiles. + NeedCompiledGoFiles + + // NeedImports adds Imports. If NeedDeps is not set, the Imports field will contain + // "placeholder" Packages with only the ID set. + NeedImports + + // NeedDeps adds the fields requested by the LoadMode in the packages in Imports. + NeedDeps + + // NeedExportsFile adds ExportFile. + NeedExportsFile + + // NeedTypes adds Types, Fset, and IllTyped. + NeedTypes + + // NeedSyntax adds Syntax. + NeedSyntax + + // NeedTypesInfo adds TypesInfo. + NeedTypesInfo + + // NeedTypesSizes adds TypesSizes. + NeedTypesSizes + + // typecheckCgo enables full support for type checking cgo. Requires Go 1.15+. + // Modifies CompiledGoFiles and Types, and has no effect on its own. + typecheckCgo + + // NeedModule adds Module. + NeedModule +) + +const ( + // Deprecated: LoadFiles exists for historical compatibility + // and should not be used. Please directly specify the needed fields using the Need values. + LoadFiles = NeedName | NeedFiles | NeedCompiledGoFiles + + // Deprecated: LoadImports exists for historical compatibility + // and should not be used. Please directly specify the needed fields using the Need values. + LoadImports = LoadFiles | NeedImports + + // Deprecated: LoadTypes exists for historical compatibility + // and should not be used. Please directly specify the needed fields using the Need values. + LoadTypes = LoadImports | NeedTypes | NeedTypesSizes + + // Deprecated: LoadSyntax exists for historical compatibility + // and should not be used. Please directly specify the needed fields using the Need values. + LoadSyntax = LoadTypes | NeedSyntax | NeedTypesInfo + + // Deprecated: LoadAllSyntax exists for historical compatibility + // and should not be used. Please directly specify the needed fields using the Need values. + LoadAllSyntax = LoadSyntax | NeedDeps +) + +// A Config specifies details about how packages should be loaded. +// The zero value is a valid configuration. +// Calls to Load do not modify this struct. +type Config struct { + // Mode controls the level of information returned for each package. + Mode LoadMode + + // Context specifies the context for the load operation. + // If the context is cancelled, the loader may stop early + // and return an ErrCancelled error. + // If Context is nil, the load cannot be cancelled. + Context context.Context + + // Logf is the logger for the config. + // If the user provides a logger, debug logging is enabled. + // If the GOPACKAGESDEBUG environment variable is set to true, + // but the logger is nil, default to log.Printf. + Logf func(format string, args ...interface{}) + + // Dir is the directory in which to run the build system's query tool + // that provides information about the packages. + // If Dir is empty, the tool is run in the current directory. + Dir string + + // Env is the environment to use when invoking the build system's query tool. + // If Env is nil, the current environment is used. + // As in os/exec's Cmd, only the last value in the slice for + // each environment key is used. To specify the setting of only + // a few variables, append to the current environment, as in: + // + // opt.Env = append(os.Environ(), "GOOS=plan9", "GOARCH=386") + // + Env []string + + // gocmdRunner guards go command calls from concurrency errors. + gocmdRunner *gocommand.Runner + + // BuildFlags is a list of command-line flags to be passed through to + // the build system's query tool. + BuildFlags []string + + // modFile will be used for -modfile in go command invocations. + modFile string + + // modFlag will be used for -modfile in go command invocations. + modFlag string + + // Fset provides source position information for syntax trees and types. + // If Fset is nil, Load will use a new fileset, but preserve Fset's value. + Fset *token.FileSet + + // ParseFile is called to read and parse each file + // when preparing a package's type-checked syntax tree. + // It must be safe to call ParseFile simultaneously from multiple goroutines. + // If ParseFile is nil, the loader will uses parser.ParseFile. + // + // ParseFile should parse the source from src and use filename only for + // recording position information. + // + // An application may supply a custom implementation of ParseFile + // to change the effective file contents or the behavior of the parser, + // or to modify the syntax tree. For example, selectively eliminating + // unwanted function bodies can significantly accelerate type checking. + ParseFile func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) + + // If Tests is set, the loader includes not just the packages + // matching a particular pattern but also any related test packages, + // including test-only variants of the package and the test executable. + // + // For example, when using the go command, loading "fmt" with Tests=true + // returns four packages, with IDs "fmt" (the standard package), + // "fmt [fmt.test]" (the package as compiled for the test), + // "fmt_test" (the test functions from source files in package fmt_test), + // and "fmt.test" (the test binary). + // + // In build systems with explicit names for tests, + // setting Tests may have no effect. + Tests bool + + // Overlay provides a mapping of absolute file paths to file contents. + // If the file with the given path already exists, the parser will use the + // alternative file contents provided by the map. + // + // Overlays provide incomplete support for when a given file doesn't + // already exist on disk. See the package doc above for more details. + Overlay map[string][]byte +} + +// driver is the type for functions that query the build system for the +// packages named by the patterns. +type driver func(cfg *Config, patterns ...string) (*driverResponse, error) + +// driverResponse contains the results for a driver query. +type driverResponse struct { + // NotHandled is returned if the request can't be handled by the current + // driver. If an external driver returns a response with NotHandled, the + // rest of the driverResponse is ignored, and go/packages will fallback + // to the next driver. If go/packages is extended in the future to support + // lists of multiple drivers, go/packages will fall back to the next driver. + NotHandled bool + + // Sizes, if not nil, is the types.Sizes to use when type checking. + Sizes *types.StdSizes + + // Roots is the set of package IDs that make up the root packages. + // We have to encode this separately because when we encode a single package + // we cannot know if it is one of the roots as that requires knowledge of the + // graph it is part of. + Roots []string `json:",omitempty"` + + // Packages is the full set of packages in the graph. + // The packages are not connected into a graph. + // The Imports if populated will be stubs that only have their ID set. + // Imports will be connected and then type and syntax information added in a + // later pass (see refine). + Packages []*Package +} + +// Load loads and returns the Go packages named by the given patterns. +// +// Config specifies loading options; +// nil behaves the same as an empty Config. +// +// Load returns an error if any of the patterns was invalid +// as defined by the underlying build system. +// It may return an empty list of packages without an error, +// for instance for an empty expansion of a valid wildcard. +// Errors associated with a particular package are recorded in the +// corresponding Package's Errors list, and do not cause Load to +// return an error. Clients may need to handle such errors before +// proceeding with further analysis. The PrintErrors function is +// provided for convenient display of all errors. +func Load(cfg *Config, patterns ...string) ([]*Package, error) { + l := newLoader(cfg) + response, err := defaultDriver(&l.Config, patterns...) + if err != nil { + return nil, err + } + l.sizes = response.Sizes + return l.refine(response.Roots, response.Packages...) +} + +// defaultDriver is a driver that implements go/packages' fallback behavior. +// It will try to request to an external driver, if one exists. If there's +// no external driver, or the driver returns a response with NotHandled set, +// defaultDriver will fall back to the go list driver. +func defaultDriver(cfg *Config, patterns ...string) (*driverResponse, error) { + driver := findExternalDriver(cfg) + if driver == nil { + driver = goListDriver + } + response, err := driver(cfg, patterns...) + if err != nil { + return response, err + } else if response.NotHandled { + return goListDriver(cfg, patterns...) + } + return response, nil +} + +// A Package describes a loaded Go package. +type Package struct { + // ID is a unique identifier for a package, + // in a syntax provided by the underlying build system. + // + // Because the syntax varies based on the build system, + // clients should treat IDs as opaque and not attempt to + // interpret them. + ID string + + // Name is the package name as it appears in the package source code. + Name string + + // PkgPath is the package path as used by the go/types package. + PkgPath string + + // Errors contains any errors encountered querying the metadata + // of the package, or while parsing or type-checking its files. + Errors []Error + + // GoFiles lists the absolute file paths of the package's Go source files. + GoFiles []string + + // CompiledGoFiles lists the absolute file paths of the package's source + // files that are suitable for type checking. + // This may differ from GoFiles if files are processed before compilation. + CompiledGoFiles []string + + // OtherFiles lists the absolute file paths of the package's non-Go source files, + // including assembly, C, C++, Fortran, Objective-C, SWIG, and so on. + OtherFiles []string + + // IgnoredFiles lists source files that are not part of the package + // using the current build configuration but that might be part of + // the package using other build configurations. + IgnoredFiles []string + + // ExportFile is the absolute path to a file containing type + // information for the package as provided by the build system. + ExportFile string + + // Imports maps import paths appearing in the package's Go source files + // to corresponding loaded Packages. + Imports map[string]*Package + + // Types provides type information for the package. + // The NeedTypes LoadMode bit sets this field for packages matching the + // patterns; type information for dependencies may be missing or incomplete, + // unless NeedDeps and NeedImports are also set. + Types *types.Package + + // Fset provides position information for Types, TypesInfo, and Syntax. + // It is set only when Types is set. + Fset *token.FileSet + + // IllTyped indicates whether the package or any dependency contains errors. + // It is set only when Types is set. + IllTyped bool + + // Syntax is the package's syntax trees, for the files listed in CompiledGoFiles. + // + // The NeedSyntax LoadMode bit populates this field for packages matching the patterns. + // If NeedDeps and NeedImports are also set, this field will also be populated + // for dependencies. + Syntax []*ast.File + + // TypesInfo provides type information about the package's syntax trees. + // It is set only when Syntax is set. + TypesInfo *types.Info + + // TypesSizes provides the effective size function for types in TypesInfo. + TypesSizes types.Sizes + + // forTest is the package under test, if any. + forTest string + + // module is the module information for the package if it exists. + Module *Module +} + +// Module provides module information for a package. +type Module struct { + Path string // module path + Version string // module version + Replace *Module // replaced by this module + Time *time.Time // time version was created + Main bool // is this the main module? + Indirect bool // is this module only an indirect dependency of main module? + Dir string // directory holding files for this module, if any + GoMod string // path to go.mod file used when loading this module, if any + GoVersion string // go version used in module + Error *ModuleError // error loading module +} + +// ModuleError holds errors loading a module. +type ModuleError struct { + Err string // the error itself +} + +func init() { + packagesinternal.GetForTest = func(p interface{}) string { + return p.(*Package).forTest + } + packagesinternal.GetGoCmdRunner = func(config interface{}) *gocommand.Runner { + return config.(*Config).gocmdRunner + } + packagesinternal.SetGoCmdRunner = func(config interface{}, runner *gocommand.Runner) { + config.(*Config).gocmdRunner = runner + } + packagesinternal.SetModFile = func(config interface{}, value string) { + config.(*Config).modFile = value + } + packagesinternal.SetModFlag = func(config interface{}, value string) { + config.(*Config).modFlag = value + } + packagesinternal.TypecheckCgo = int(typecheckCgo) +} + +// An Error describes a problem with a package's metadata, syntax, or types. +type Error struct { + Pos string // "file:line:col" or "file:line" or "" or "-" + Msg string + Kind ErrorKind +} + +// ErrorKind describes the source of the error, allowing the user to +// differentiate between errors generated by the driver, the parser, or the +// type-checker. +type ErrorKind int + +const ( + UnknownError ErrorKind = iota + ListError + ParseError + TypeError +) + +func (err Error) Error() string { + pos := err.Pos + if pos == "" { + pos = "-" // like token.Position{}.String() + } + return pos + ": " + err.Msg +} + +// flatPackage is the JSON form of Package +// It drops all the type and syntax fields, and transforms the Imports +// +// TODO(adonovan): identify this struct with Package, effectively +// publishing the JSON protocol. +type flatPackage struct { + ID string + Name string `json:",omitempty"` + PkgPath string `json:",omitempty"` + Errors []Error `json:",omitempty"` + GoFiles []string `json:",omitempty"` + CompiledGoFiles []string `json:",omitempty"` + OtherFiles []string `json:",omitempty"` + IgnoredFiles []string `json:",omitempty"` + ExportFile string `json:",omitempty"` + Imports map[string]string `json:",omitempty"` +} + +// MarshalJSON returns the Package in its JSON form. +// For the most part, the structure fields are written out unmodified, and +// the type and syntax fields are skipped. +// The imports are written out as just a map of path to package id. +// The errors are written using a custom type that tries to preserve the +// structure of error types we know about. +// +// This method exists to enable support for additional build systems. It is +// not intended for use by clients of the API and we may change the format. +func (p *Package) MarshalJSON() ([]byte, error) { + flat := &flatPackage{ + ID: p.ID, + Name: p.Name, + PkgPath: p.PkgPath, + Errors: p.Errors, + GoFiles: p.GoFiles, + CompiledGoFiles: p.CompiledGoFiles, + OtherFiles: p.OtherFiles, + IgnoredFiles: p.IgnoredFiles, + ExportFile: p.ExportFile, + } + if len(p.Imports) > 0 { + flat.Imports = make(map[string]string, len(p.Imports)) + for path, ipkg := range p.Imports { + flat.Imports[path] = ipkg.ID + } + } + return json.Marshal(flat) +} + +// UnmarshalJSON reads in a Package from its JSON format. +// See MarshalJSON for details about the format accepted. +func (p *Package) UnmarshalJSON(b []byte) error { + flat := &flatPackage{} + if err := json.Unmarshal(b, &flat); err != nil { + return err + } + *p = Package{ + ID: flat.ID, + Name: flat.Name, + PkgPath: flat.PkgPath, + Errors: flat.Errors, + GoFiles: flat.GoFiles, + CompiledGoFiles: flat.CompiledGoFiles, + OtherFiles: flat.OtherFiles, + ExportFile: flat.ExportFile, + } + if len(flat.Imports) > 0 { + p.Imports = make(map[string]*Package, len(flat.Imports)) + for path, id := range flat.Imports { + p.Imports[path] = &Package{ID: id} + } + } + return nil +} + +func (p *Package) String() string { return p.ID } + +// loaderPackage augments Package with state used during the loading phase +type loaderPackage struct { + *Package + importErrors map[string]error // maps each bad import to its error + loadOnce sync.Once + color uint8 // for cycle detection + needsrc bool // load from source (Mode >= LoadTypes) + needtypes bool // type information is either requested or depended on + initial bool // package was matched by a pattern +} + +// loader holds the working state of a single call to load. +type loader struct { + pkgs map[string]*loaderPackage + Config + sizes types.Sizes + parseCache map[string]*parseValue + parseCacheMu sync.Mutex + exportMu sync.Mutex // enforces mutual exclusion of exportdata operations + + // Config.Mode contains the implied mode (see impliedLoadMode). + // Implied mode contains all the fields we need the data for. + // In requestedMode there are the actually requested fields. + // We'll zero them out before returning packages to the user. + // This makes it easier for us to get the conditions where + // we need certain modes right. + requestedMode LoadMode +} + +type parseValue struct { + f *ast.File + err error + ready chan struct{} +} + +func newLoader(cfg *Config) *loader { + ld := &loader{ + parseCache: map[string]*parseValue{}, + } + if cfg != nil { + ld.Config = *cfg + // If the user has provided a logger, use it. + ld.Config.Logf = cfg.Logf + } + if ld.Config.Logf == nil { + // If the GOPACKAGESDEBUG environment variable is set to true, + // but the user has not provided a logger, default to log.Printf. + if debug { + ld.Config.Logf = log.Printf + } else { + ld.Config.Logf = func(format string, args ...interface{}) {} + } + } + if ld.Config.Mode == 0 { + ld.Config.Mode = NeedName | NeedFiles | NeedCompiledGoFiles // Preserve zero behavior of Mode for backwards compatibility. + } + if ld.Config.Env == nil { + ld.Config.Env = os.Environ() + } + if ld.Config.gocmdRunner == nil { + ld.Config.gocmdRunner = &gocommand.Runner{} + } + if ld.Context == nil { + ld.Context = context.Background() + } + if ld.Dir == "" { + if dir, err := os.Getwd(); err == nil { + ld.Dir = dir + } + } + + // Save the actually requested fields. We'll zero them out before returning packages to the user. + ld.requestedMode = ld.Mode + ld.Mode = impliedLoadMode(ld.Mode) + + if ld.Mode&NeedTypes != 0 || ld.Mode&NeedSyntax != 0 { + if ld.Fset == nil { + ld.Fset = token.NewFileSet() + } + + // ParseFile is required even in LoadTypes mode + // because we load source if export data is missing. + if ld.ParseFile == nil { + ld.ParseFile = func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) { + const mode = parser.AllErrors | parser.ParseComments + return parser.ParseFile(fset, filename, src, mode) + } + } + } + + return ld +} + +// refine connects the supplied packages into a graph and then adds type and +// and syntax information as requested by the LoadMode. +func (ld *loader) refine(roots []string, list ...*Package) ([]*Package, error) { + rootMap := make(map[string]int, len(roots)) + for i, root := range roots { + rootMap[root] = i + } + ld.pkgs = make(map[string]*loaderPackage) + // first pass, fixup and build the map and roots + var initial = make([]*loaderPackage, len(roots)) + for _, pkg := range list { + rootIndex := -1 + if i, found := rootMap[pkg.ID]; found { + rootIndex = i + } + + // Overlays can invalidate export data. + // TODO(matloob): make this check fine-grained based on dependencies on overlaid files + exportDataInvalid := len(ld.Overlay) > 0 || pkg.ExportFile == "" && pkg.PkgPath != "unsafe" + // This package needs type information if the caller requested types and the package is + // either a root, or it's a non-root and the user requested dependencies ... + needtypes := (ld.Mode&NeedTypes|NeedTypesInfo != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0)) + // This package needs source if the call requested source (or types info, which implies source) + // and the package is either a root, or itas a non- root and the user requested dependencies... + needsrc := ((ld.Mode&(NeedSyntax|NeedTypesInfo) != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0)) || + // ... or if we need types and the exportData is invalid. We fall back to (incompletely) + // typechecking packages from source if they fail to compile. + (ld.Mode&NeedTypes|NeedTypesInfo != 0 && exportDataInvalid)) && pkg.PkgPath != "unsafe" + lpkg := &loaderPackage{ + Package: pkg, + needtypes: needtypes, + needsrc: needsrc, + } + ld.pkgs[lpkg.ID] = lpkg + if rootIndex >= 0 { + initial[rootIndex] = lpkg + lpkg.initial = true + } + } + for i, root := range roots { + if initial[i] == nil { + return nil, fmt.Errorf("root package %v is missing", root) + } + } + + // Materialize the import graph. + + const ( + white = 0 // new + grey = 1 // in progress + black = 2 // complete + ) + + // visit traverses the import graph, depth-first, + // and materializes the graph as Packages.Imports. + // + // Valid imports are saved in the Packages.Import map. + // Invalid imports (cycles and missing nodes) are saved in the importErrors map. + // Thus, even in the presence of both kinds of errors, the Import graph remains a DAG. + // + // visit returns whether the package needs src or has a transitive + // dependency on a package that does. These are the only packages + // for which we load source code. + var stack []*loaderPackage + var visit func(lpkg *loaderPackage) bool + var srcPkgs []*loaderPackage + visit = func(lpkg *loaderPackage) bool { + switch lpkg.color { + case black: + return lpkg.needsrc + case grey: + panic("internal error: grey node") + } + lpkg.color = grey + stack = append(stack, lpkg) // push + stubs := lpkg.Imports // the structure form has only stubs with the ID in the Imports + // If NeedImports isn't set, the imports fields will all be zeroed out. + if ld.Mode&NeedImports != 0 { + lpkg.Imports = make(map[string]*Package, len(stubs)) + for importPath, ipkg := range stubs { + var importErr error + imp := ld.pkgs[ipkg.ID] + if imp == nil { + // (includes package "C" when DisableCgo) + importErr = fmt.Errorf("missing package: %q", ipkg.ID) + } else if imp.color == grey { + importErr = fmt.Errorf("import cycle: %s", stack) + } + if importErr != nil { + if lpkg.importErrors == nil { + lpkg.importErrors = make(map[string]error) + } + lpkg.importErrors[importPath] = importErr + continue + } + + if visit(imp) { + lpkg.needsrc = true + } + lpkg.Imports[importPath] = imp.Package + } + } + if lpkg.needsrc { + srcPkgs = append(srcPkgs, lpkg) + } + if ld.Mode&NeedTypesSizes != 0 { + lpkg.TypesSizes = ld.sizes + } + stack = stack[:len(stack)-1] // pop + lpkg.color = black + + return lpkg.needsrc + } + + if ld.Mode&NeedImports == 0 { + // We do this to drop the stub import packages that we are not even going to try to resolve. + for _, lpkg := range initial { + lpkg.Imports = nil + } + } else { + // For each initial package, create its import DAG. + for _, lpkg := range initial { + visit(lpkg) + } + } + if ld.Mode&NeedImports != 0 && ld.Mode&NeedTypes != 0 { + for _, lpkg := range srcPkgs { + // Complete type information is required for the + // immediate dependencies of each source package. + for _, ipkg := range lpkg.Imports { + imp := ld.pkgs[ipkg.ID] + imp.needtypes = true + } + } + } + // Load type data and syntax if needed, starting at + // the initial packages (roots of the import DAG). + if ld.Mode&NeedTypes != 0 || ld.Mode&NeedSyntax != 0 { + var wg sync.WaitGroup + for _, lpkg := range initial { + wg.Add(1) + go func(lpkg *loaderPackage) { + ld.loadRecursive(lpkg) + wg.Done() + }(lpkg) + } + wg.Wait() + } + + result := make([]*Package, len(initial)) + for i, lpkg := range initial { + result[i] = lpkg.Package + } + for i := range ld.pkgs { + // Clear all unrequested fields, + // to catch programs that use more than they request. + if ld.requestedMode&NeedName == 0 { + ld.pkgs[i].Name = "" + ld.pkgs[i].PkgPath = "" + } + if ld.requestedMode&NeedFiles == 0 { + ld.pkgs[i].GoFiles = nil + ld.pkgs[i].OtherFiles = nil + ld.pkgs[i].IgnoredFiles = nil + } + if ld.requestedMode&NeedCompiledGoFiles == 0 { + ld.pkgs[i].CompiledGoFiles = nil + } + if ld.requestedMode&NeedImports == 0 { + ld.pkgs[i].Imports = nil + } + if ld.requestedMode&NeedExportsFile == 0 { + ld.pkgs[i].ExportFile = "" + } + if ld.requestedMode&NeedTypes == 0 { + ld.pkgs[i].Types = nil + ld.pkgs[i].Fset = nil + ld.pkgs[i].IllTyped = false + } + if ld.requestedMode&NeedSyntax == 0 { + ld.pkgs[i].Syntax = nil + } + if ld.requestedMode&NeedTypesInfo == 0 { + ld.pkgs[i].TypesInfo = nil + } + if ld.requestedMode&NeedTypesSizes == 0 { + ld.pkgs[i].TypesSizes = nil + } + if ld.requestedMode&NeedModule == 0 { + ld.pkgs[i].Module = nil + } + } + + return result, nil +} + +// loadRecursive loads the specified package and its dependencies, +// recursively, in parallel, in topological order. +// It is atomic and idempotent. +// Precondition: ld.Mode&NeedTypes. +func (ld *loader) loadRecursive(lpkg *loaderPackage) { + lpkg.loadOnce.Do(func() { + // Load the direct dependencies, in parallel. + var wg sync.WaitGroup + for _, ipkg := range lpkg.Imports { + imp := ld.pkgs[ipkg.ID] + wg.Add(1) + go func(imp *loaderPackage) { + ld.loadRecursive(imp) + wg.Done() + }(imp) + } + wg.Wait() + ld.loadPackage(lpkg) + }) +} + +// loadPackage loads the specified package. +// It must be called only once per Package, +// after immediate dependencies are loaded. +// Precondition: ld.Mode & NeedTypes. +func (ld *loader) loadPackage(lpkg *loaderPackage) { + if lpkg.PkgPath == "unsafe" { + // Fill in the blanks to avoid surprises. + lpkg.Types = types.Unsafe + lpkg.Fset = ld.Fset + lpkg.Syntax = []*ast.File{} + lpkg.TypesInfo = new(types.Info) + lpkg.TypesSizes = ld.sizes + return + } + + // Call NewPackage directly with explicit name. + // This avoids skew between golist and go/types when the files' + // package declarations are inconsistent. + lpkg.Types = types.NewPackage(lpkg.PkgPath, lpkg.Name) + lpkg.Fset = ld.Fset + + // Subtle: we populate all Types fields with an empty Package + // before loading export data so that export data processing + // never has to create a types.Package for an indirect dependency, + // which would then require that such created packages be explicitly + // inserted back into the Import graph as a final step after export data loading. + // The Diamond test exercises this case. + if !lpkg.needtypes && !lpkg.needsrc { + return + } + if !lpkg.needsrc { + ld.loadFromExportData(lpkg) + return // not a source package, don't get syntax trees + } + + appendError := func(err error) { + // Convert various error types into the one true Error. + var errs []Error + switch err := err.(type) { + case Error: + // from driver + errs = append(errs, err) + + case *os.PathError: + // from parser + errs = append(errs, Error{ + Pos: err.Path + ":1", + Msg: err.Err.Error(), + Kind: ParseError, + }) + + case scanner.ErrorList: + // from parser + for _, err := range err { + errs = append(errs, Error{ + Pos: err.Pos.String(), + Msg: err.Msg, + Kind: ParseError, + }) + } + + case types.Error: + // from type checker + errs = append(errs, Error{ + Pos: err.Fset.Position(err.Pos).String(), + Msg: err.Msg, + Kind: TypeError, + }) + + default: + // unexpected impoverished error from parser? + errs = append(errs, Error{ + Pos: "-", + Msg: err.Error(), + Kind: UnknownError, + }) + + // If you see this error message, please file a bug. + log.Printf("internal error: error %q (%T) without position", err, err) + } + + lpkg.Errors = append(lpkg.Errors, errs...) + } + + if ld.Config.Mode&NeedTypes != 0 && len(lpkg.CompiledGoFiles) == 0 && lpkg.ExportFile != "" { + // The config requested loading sources and types, but sources are missing. + // Add an error to the package and fall back to loading from export data. + appendError(Error{"-", fmt.Sprintf("sources missing for package %s", lpkg.ID), ParseError}) + ld.loadFromExportData(lpkg) + return // can't get syntax trees for this package + } + + files, errs := ld.parseFiles(lpkg.CompiledGoFiles) + for _, err := range errs { + appendError(err) + } + + lpkg.Syntax = files + if ld.Config.Mode&NeedTypes == 0 { + return + } + + lpkg.TypesInfo = &types.Info{ + Types: make(map[ast.Expr]types.TypeAndValue), + Defs: make(map[*ast.Ident]types.Object), + Uses: make(map[*ast.Ident]types.Object), + Implicits: make(map[ast.Node]types.Object), + Scopes: make(map[ast.Node]*types.Scope), + Selections: make(map[*ast.SelectorExpr]*types.Selection), + } + lpkg.TypesSizes = ld.sizes + + importer := importerFunc(func(path string) (*types.Package, error) { + if path == "unsafe" { + return types.Unsafe, nil + } + + // The imports map is keyed by import path. + ipkg := lpkg.Imports[path] + if ipkg == nil { + if err := lpkg.importErrors[path]; err != nil { + return nil, err + } + // There was skew between the metadata and the + // import declarations, likely due to an edit + // race, or because the ParseFile feature was + // used to supply alternative file contents. + return nil, fmt.Errorf("no metadata for %s", path) + } + + if ipkg.Types != nil && ipkg.Types.Complete() { + return ipkg.Types, nil + } + log.Fatalf("internal error: package %q without types was imported from %q", path, lpkg) + panic("unreachable") + }) + + // type-check + tc := &types.Config{ + Importer: importer, + + // Type-check bodies of functions only in non-initial packages. + // Example: for import graph A->B->C and initial packages {A,C}, + // we can ignore function bodies in B. + IgnoreFuncBodies: ld.Mode&NeedDeps == 0 && !lpkg.initial, + + Error: appendError, + Sizes: ld.sizes, + } + if (ld.Mode & typecheckCgo) != 0 { + if !typesinternal.SetUsesCgo(tc) { + appendError(Error{ + Msg: "typecheckCgo requires Go 1.15+", + Kind: ListError, + }) + return + } + } + types.NewChecker(tc, ld.Fset, lpkg.Types, lpkg.TypesInfo).Files(lpkg.Syntax) + + lpkg.importErrors = nil // no longer needed + + // If !Cgo, the type-checker uses FakeImportC mode, so + // it doesn't invoke the importer for import "C", + // nor report an error for the import, + // or for any undefined C.f reference. + // We must detect this explicitly and correctly + // mark the package as IllTyped (by reporting an error). + // TODO(adonovan): if these errors are annoying, + // we could just set IllTyped quietly. + if tc.FakeImportC { + outer: + for _, f := range lpkg.Syntax { + for _, imp := range f.Imports { + if imp.Path.Value == `"C"` { + err := types.Error{Fset: ld.Fset, Pos: imp.Pos(), Msg: `import "C" ignored`} + appendError(err) + break outer + } + } + } + } + + // Record accumulated errors. + illTyped := len(lpkg.Errors) > 0 + if !illTyped { + for _, imp := range lpkg.Imports { + if imp.IllTyped { + illTyped = true + break + } + } + } + lpkg.IllTyped = illTyped +} + +// An importFunc is an implementation of the single-method +// types.Importer interface based on a function value. +type importerFunc func(path string) (*types.Package, error) + +func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) } + +// We use a counting semaphore to limit +// the number of parallel I/O calls per process. +var ioLimit = make(chan bool, 20) + +func (ld *loader) parseFile(filename string) (*ast.File, error) { + ld.parseCacheMu.Lock() + v, ok := ld.parseCache[filename] + if ok { + // cache hit + ld.parseCacheMu.Unlock() + <-v.ready + } else { + // cache miss + v = &parseValue{ready: make(chan struct{})} + ld.parseCache[filename] = v + ld.parseCacheMu.Unlock() + + var src []byte + for f, contents := range ld.Config.Overlay { + if sameFile(f, filename) { + src = contents + } + } + var err error + if src == nil { + ioLimit <- true // wait + src, err = ioutil.ReadFile(filename) + <-ioLimit // signal + } + if err != nil { + v.err = err + } else { + v.f, v.err = ld.ParseFile(ld.Fset, filename, src) + } + + close(v.ready) + } + return v.f, v.err +} + +// parseFiles reads and parses the Go source files and returns the ASTs +// of the ones that could be at least partially parsed, along with a +// list of I/O and parse errors encountered. +// +// Because files are scanned in parallel, the token.Pos +// positions of the resulting ast.Files are not ordered. +// +func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) { + var wg sync.WaitGroup + n := len(filenames) + parsed := make([]*ast.File, n) + errors := make([]error, n) + for i, file := range filenames { + if ld.Config.Context.Err() != nil { + parsed[i] = nil + errors[i] = ld.Config.Context.Err() + continue + } + wg.Add(1) + go func(i int, filename string) { + parsed[i], errors[i] = ld.parseFile(filename) + wg.Done() + }(i, file) + } + wg.Wait() + + // Eliminate nils, preserving order. + var o int + for _, f := range parsed { + if f != nil { + parsed[o] = f + o++ + } + } + parsed = parsed[:o] + + o = 0 + for _, err := range errors { + if err != nil { + errors[o] = err + o++ + } + } + errors = errors[:o] + + return parsed, errors +} + +// sameFile returns true if x and y have the same basename and denote +// the same file. +// +func sameFile(x, y string) bool { + if x == y { + // It could be the case that y doesn't exist. + // For instance, it may be an overlay file that + // hasn't been written to disk. To handle that case + // let x == y through. (We added the exact absolute path + // string to the CompiledGoFiles list, so the unwritten + // overlay case implies x==y.) + return true + } + if strings.EqualFold(filepath.Base(x), filepath.Base(y)) { // (optimisation) + if xi, err := os.Stat(x); err == nil { + if yi, err := os.Stat(y); err == nil { + return os.SameFile(xi, yi) + } + } + } + return false +} + +// loadFromExportData returns type information for the specified +// package, loading it from an export data file on the first request. +func (ld *loader) loadFromExportData(lpkg *loaderPackage) (*types.Package, error) { + if lpkg.PkgPath == "" { + log.Fatalf("internal error: Package %s has no PkgPath", lpkg) + } + + // Because gcexportdata.Read has the potential to create or + // modify the types.Package for each node in the transitive + // closure of dependencies of lpkg, all exportdata operations + // must be sequential. (Finer-grained locking would require + // changes to the gcexportdata API.) + // + // The exportMu lock guards the Package.Pkg field and the + // types.Package it points to, for each Package in the graph. + // + // Not all accesses to Package.Pkg need to be protected by exportMu: + // graph ordering ensures that direct dependencies of source + // packages are fully loaded before the importer reads their Pkg field. + ld.exportMu.Lock() + defer ld.exportMu.Unlock() + + if tpkg := lpkg.Types; tpkg != nil && tpkg.Complete() { + return tpkg, nil // cache hit + } + + lpkg.IllTyped = true // fail safe + + if lpkg.ExportFile == "" { + // Errors while building export data will have been printed to stderr. + return nil, fmt.Errorf("no export data file") + } + f, err := os.Open(lpkg.ExportFile) + if err != nil { + return nil, err + } + defer f.Close() + + // Read gc export data. + // + // We don't currently support gccgo export data because all + // underlying workspaces use the gc toolchain. (Even build + // systems that support gccgo don't use it for workspace + // queries.) + r, err := gcexportdata.NewReader(f) + if err != nil { + return nil, fmt.Errorf("reading %s: %v", lpkg.ExportFile, err) + } + + // Build the view. + // + // The gcexportdata machinery has no concept of package ID. + // It identifies packages by their PkgPath, which although not + // globally unique is unique within the scope of one invocation + // of the linker, type-checker, or gcexportdata. + // + // So, we must build a PkgPath-keyed view of the global + // (conceptually ID-keyed) cache of packages and pass it to + // gcexportdata. The view must contain every existing + // package that might possibly be mentioned by the + // current package---its transitive closure. + // + // In loadPackage, we unconditionally create a types.Package for + // each dependency so that export data loading does not + // create new ones. + // + // TODO(adonovan): it would be simpler and more efficient + // if the export data machinery invoked a callback to + // get-or-create a package instead of a map. + // + view := make(map[string]*types.Package) // view seen by gcexportdata + seen := make(map[*loaderPackage]bool) // all visited packages + var visit func(pkgs map[string]*Package) + visit = func(pkgs map[string]*Package) { + for _, p := range pkgs { + lpkg := ld.pkgs[p.ID] + if !seen[lpkg] { + seen[lpkg] = true + view[lpkg.PkgPath] = lpkg.Types + visit(lpkg.Imports) + } + } + } + visit(lpkg.Imports) + + viewLen := len(view) + 1 // adding the self package + // Parse the export data. + // (May modify incomplete packages in view but not create new ones.) + tpkg, err := gcexportdata.Read(r, ld.Fset, view, lpkg.PkgPath) + if err != nil { + return nil, fmt.Errorf("reading %s: %v", lpkg.ExportFile, err) + } + if viewLen != len(view) { + log.Fatalf("Unexpected package creation during export data loading") + } + + lpkg.Types = tpkg + lpkg.IllTyped = false + + return tpkg, nil +} + +// impliedLoadMode returns loadMode with its dependencies. +func impliedLoadMode(loadMode LoadMode) LoadMode { + if loadMode&NeedTypesInfo != 0 && loadMode&NeedImports == 0 { + // If NeedTypesInfo, go/packages needs to do typechecking itself so it can + // associate type info with the AST. To do so, we need the export data + // for dependencies, which means we need to ask for the direct dependencies. + // NeedImports is used to ask for the direct dependencies. + loadMode |= NeedImports + } + + if loadMode&NeedDeps != 0 && loadMode&NeedImports == 0 { + // With NeedDeps we need to load at least direct dependencies. + // NeedImports is used to ask for the direct dependencies. + loadMode |= NeedImports + } + + return loadMode +} + +func usesExportData(cfg *Config) bool { + return cfg.Mode&NeedExportsFile != 0 || cfg.Mode&NeedTypes != 0 && cfg.Mode&NeedDeps == 0 +} diff --git a/vendor/golang.org/x/tools/go/packages/visit.go b/vendor/golang.org/x/tools/go/packages/visit.go new file mode 100644 index 0000000000..a1dcc40b72 --- /dev/null +++ b/vendor/golang.org/x/tools/go/packages/visit.go @@ -0,0 +1,59 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package packages + +import ( + "fmt" + "os" + "sort" +) + +// Visit visits all the packages in the import graph whose roots are +// pkgs, calling the optional pre function the first time each package +// is encountered (preorder), and the optional post function after a +// package's dependencies have been visited (postorder). +// The boolean result of pre(pkg) determines whether +// the imports of package pkg are visited. +func Visit(pkgs []*Package, pre func(*Package) bool, post func(*Package)) { + seen := make(map[*Package]bool) + var visit func(*Package) + visit = func(pkg *Package) { + if !seen[pkg] { + seen[pkg] = true + + if pre == nil || pre(pkg) { + paths := make([]string, 0, len(pkg.Imports)) + for path := range pkg.Imports { + paths = append(paths, path) + } + sort.Strings(paths) // Imports is a map, this makes visit stable + for _, path := range paths { + visit(pkg.Imports[path]) + } + } + + if post != nil { + post(pkg) + } + } + } + for _, pkg := range pkgs { + visit(pkg) + } +} + +// PrintErrors prints to os.Stderr the accumulated errors of all +// packages in the import graph rooted at pkgs, dependencies first. +// PrintErrors returns the number of errors printed. +func PrintErrors(pkgs []*Package) int { + var n int + Visit(pkgs, nil, func(pkg *Package) { + for _, err := range pkg.Errors { + fmt.Fprintln(os.Stderr, err) + n++ + } + }) + return n +} diff --git a/vendor/golang.org/x/tools/internal/packagesinternal/packages.go b/vendor/golang.org/x/tools/internal/packagesinternal/packages.go new file mode 100644 index 0000000000..d4ec6f9715 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/packagesinternal/packages.go @@ -0,0 +1,21 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package packagesinternal exposes internal-only fields from go/packages. +package packagesinternal + +import ( + "golang.org/x/tools/internal/gocommand" +) + +var GetForTest = func(p interface{}) string { return "" } + +var GetGoCmdRunner = func(config interface{}) *gocommand.Runner { return nil } + +var SetGoCmdRunner = func(config interface{}, runner *gocommand.Runner) {} + +var TypecheckCgo int + +var SetModFlag = func(config interface{}, value string) {} +var SetModFile = func(config interface{}, value string) {} diff --git a/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go b/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go new file mode 100644 index 0000000000..65473eb226 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typesinternal/errorcode.go @@ -0,0 +1,1358 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package typesinternal + +//go:generate stringer -type=ErrorCode + +type ErrorCode int + +// This file defines the error codes that can be produced during type-checking. +// Collectively, these codes provide an identifier that may be used to +// implement special handling for certain types of errors. +// +// Error codes should be fine-grained enough that the exact nature of the error +// can be easily determined, but coarse enough that they are not an +// implementation detail of the type checking algorithm. As a rule-of-thumb, +// errors should be considered equivalent if there is a theoretical refactoring +// of the type checker in which they are emitted in exactly one place. For +// example, the type checker emits different error messages for "too many +// arguments" and "too few arguments", but one can imagine an alternative type +// checker where this check instead just emits a single "wrong number of +// arguments", so these errors should have the same code. +// +// Error code names should be as brief as possible while retaining accuracy and +// distinctiveness. In most cases names should start with an adjective +// describing the nature of the error (e.g. "invalid", "unused", "misplaced"), +// and end with a noun identifying the relevant language object. For example, +// "DuplicateDecl" or "InvalidSliceExpr". For brevity, naming follows the +// convention that "bad" implies a problem with syntax, and "invalid" implies a +// problem with types. + +const ( + _ ErrorCode = iota + + // Test is reserved for errors that only apply while in self-test mode. + Test + + /* package names */ + + // BlankPkgName occurs when a package name is the blank identifier "_". + // + // Per the spec: + // "The PackageName must not be the blank identifier." + BlankPkgName + + // MismatchedPkgName occurs when a file's package name doesn't match the + // package name already established by other files. + MismatchedPkgName + + // InvalidPkgUse occurs when a package identifier is used outside of a + // selector expression. + // + // Example: + // import "fmt" + // + // var _ = fmt + InvalidPkgUse + + /* imports */ + + // BadImportPath occurs when an import path is not valid. + BadImportPath + + // BrokenImport occurs when importing a package fails. + // + // Example: + // import "amissingpackage" + BrokenImport + + // ImportCRenamed occurs when the special import "C" is renamed. "C" is a + // pseudo-package, and must not be renamed. + // + // Example: + // import _ "C" + ImportCRenamed + + // UnusedImport occurs when an import is unused. + // + // Example: + // import "fmt" + // + // func main() {} + UnusedImport + + /* initialization */ + + // InvalidInitCycle occurs when an invalid cycle is detected within the + // initialization graph. + // + // Example: + // var x int = f() + // + // func f() int { return x } + InvalidInitCycle + + /* decls */ + + // DuplicateDecl occurs when an identifier is declared multiple times. + // + // Example: + // var x = 1 + // var x = 2 + DuplicateDecl + + // InvalidDeclCycle occurs when a declaration cycle is not valid. + // + // Example: + // import "unsafe" + // + // type T struct { + // a [n]int + // } + // + // var n = unsafe.Sizeof(T{}) + InvalidDeclCycle + + // InvalidTypeCycle occurs when a cycle in type definitions results in a + // type that is not well-defined. + // + // Example: + // import "unsafe" + // + // type T [unsafe.Sizeof(T{})]int + InvalidTypeCycle + + /* decls > const */ + + // InvalidConstInit occurs when a const declaration has a non-constant + // initializer. + // + // Example: + // var x int + // const _ = x + InvalidConstInit + + // InvalidConstVal occurs when a const value cannot be converted to its + // target type. + // + // TODO(findleyr): this error code and example are not very clear. Consider + // removing it. + // + // Example: + // const _ = 1 << "hello" + InvalidConstVal + + // InvalidConstType occurs when the underlying type in a const declaration + // is not a valid constant type. + // + // Example: + // const c *int = 4 + InvalidConstType + + /* decls > var (+ other variable assignment codes) */ + + // UntypedNil occurs when the predeclared (untyped) value nil is used to + // initialize a variable declared without an explicit type. + // + // Example: + // var x = nil + UntypedNil + + // WrongAssignCount occurs when the number of values on the right-hand side + // of an assignment or or initialization expression does not match the number + // of variables on the left-hand side. + // + // Example: + // var x = 1, 2 + WrongAssignCount + + // UnassignableOperand occurs when the left-hand side of an assignment is + // not assignable. + // + // Example: + // func f() { + // const c = 1 + // c = 2 + // } + UnassignableOperand + + // NoNewVar occurs when a short variable declaration (':=') does not declare + // new variables. + // + // Example: + // func f() { + // x := 1 + // x := 2 + // } + NoNewVar + + // MultiValAssignOp occurs when an assignment operation (+=, *=, etc) does + // not have single-valued left-hand or right-hand side. + // + // Per the spec: + // "In assignment operations, both the left- and right-hand expression lists + // must contain exactly one single-valued expression" + // + // Example: + // func f() int { + // x, y := 1, 2 + // x, y += 1 + // return x + y + // } + MultiValAssignOp + + // InvalidIfaceAssign occurs when a value of type T is used as an + // interface, but T does not implement a method of the expected interface. + // + // Example: + // type I interface { + // f() + // } + // + // type T int + // + // var x I = T(1) + InvalidIfaceAssign + + // InvalidChanAssign occurs when a chan assignment is invalid. + // + // Per the spec, a value x is assignable to a channel type T if: + // "x is a bidirectional channel value, T is a channel type, x's type V and + // T have identical element types, and at least one of V or T is not a + // defined type." + // + // Example: + // type T1 chan int + // type T2 chan int + // + // var x T1 + // // Invalid assignment because both types are named + // var _ T2 = x + InvalidChanAssign + + // IncompatibleAssign occurs when the type of the right-hand side expression + // in an assignment cannot be assigned to the type of the variable being + // assigned. + // + // Example: + // var x []int + // var _ int = x + IncompatibleAssign + + // UnaddressableFieldAssign occurs when trying to assign to a struct field + // in a map value. + // + // Example: + // func f() { + // m := make(map[string]struct{i int}) + // m["foo"].i = 42 + // } + UnaddressableFieldAssign + + /* decls > type (+ other type expression codes) */ + + // NotAType occurs when the identifier used as the underlying type in a type + // declaration or the right-hand side of a type alias does not denote a type. + // + // Example: + // var S = 2 + // + // type T S + NotAType + + // InvalidArrayLen occurs when an array length is not a constant value. + // + // Example: + // var n = 3 + // var _ = [n]int{} + InvalidArrayLen + + // BlankIfaceMethod occurs when a method name is '_'. + // + // Per the spec: + // "The name of each explicitly specified method must be unique and not + // blank." + // + // Example: + // type T interface { + // _(int) + // } + BlankIfaceMethod + + // IncomparableMapKey occurs when a map key type does not support the == and + // != operators. + // + // Per the spec: + // "The comparison operators == and != must be fully defined for operands of + // the key type; thus the key type must not be a function, map, or slice." + // + // Example: + // var x map[T]int + // + // type T []int + IncomparableMapKey + + // InvalidIfaceEmbed occurs when a non-interface type is embedded in an + // interface. + // + // Example: + // type T struct {} + // + // func (T) m() + // + // type I interface { + // T + // } + InvalidIfaceEmbed + + // InvalidPtrEmbed occurs when an embedded field is of the pointer form *T, + // and T itself is itself a pointer, an unsafe.Pointer, or an interface. + // + // Per the spec: + // "An embedded field must be specified as a type name T or as a pointer to + // a non-interface type name *T, and T itself may not be a pointer type." + // + // Example: + // type T *int + // + // type S struct { + // *T + // } + InvalidPtrEmbed + + /* decls > func and method */ + + // BadRecv occurs when a method declaration does not have exactly one + // receiver parameter. + // + // Example: + // func () _() {} + BadRecv + + // InvalidRecv occurs when a receiver type expression is not of the form T + // or *T, or T is a pointer type. + // + // Example: + // type T struct {} + // + // func (**T) m() {} + InvalidRecv + + // DuplicateFieldAndMethod occurs when an identifier appears as both a field + // and method name. + // + // Example: + // type T struct { + // m int + // } + // + // func (T) m() {} + DuplicateFieldAndMethod + + // DuplicateMethod occurs when two methods on the same receiver type have + // the same name. + // + // Example: + // type T struct {} + // func (T) m() {} + // func (T) m(i int) int { return i } + DuplicateMethod + + /* decls > special */ + + // InvalidBlank occurs when a blank identifier is used as a value or type. + // + // Per the spec: + // "The blank identifier may appear as an operand only on the left-hand side + // of an assignment." + // + // Example: + // var x = _ + InvalidBlank + + // InvalidIota occurs when the predeclared identifier iota is used outside + // of a constant declaration. + // + // Example: + // var x = iota + InvalidIota + + // MissingInitBody occurs when an init function is missing its body. + // + // Example: + // func init() + MissingInitBody + + // InvalidInitSig occurs when an init function declares parameters or + // results. + // + // Example: + // func init() int { return 1 } + InvalidInitSig + + // InvalidInitDecl occurs when init is declared as anything other than a + // function. + // + // Example: + // var init = 1 + InvalidInitDecl + + // InvalidMainDecl occurs when main is declared as anything other than a + // function, in a main package. + InvalidMainDecl + + /* exprs */ + + // TooManyValues occurs when a function returns too many values for the + // expression context in which it is used. + // + // Example: + // func ReturnTwo() (int, int) { + // return 1, 2 + // } + // + // var x = ReturnTwo() + TooManyValues + + // NotAnExpr occurs when a type expression is used where a value expression + // is expected. + // + // Example: + // type T struct {} + // + // func f() { + // T + // } + NotAnExpr + + /* exprs > const */ + + // TruncatedFloat occurs when a float constant is truncated to an integer + // value. + // + // Example: + // var _ int = 98.6 + TruncatedFloat + + // NumericOverflow occurs when a numeric constant overflows its target type. + // + // Example: + // var x int8 = 1000 + NumericOverflow + + /* exprs > operation */ + + // UndefinedOp occurs when an operator is not defined for the type(s) used + // in an operation. + // + // Example: + // var c = "a" - "b" + UndefinedOp + + // MismatchedTypes occurs when operand types are incompatible in a binary + // operation. + // + // Example: + // var a = "hello" + // var b = 1 + // var c = a - b + MismatchedTypes + + // DivByZero occurs when a division operation is provable at compile + // time to be a division by zero. + // + // Example: + // const divisor = 0 + // var x int = 1/divisor + DivByZero + + // NonNumericIncDec occurs when an increment or decrement operator is + // applied to a non-numeric value. + // + // Example: + // func f() { + // var c = "c" + // c++ + // } + NonNumericIncDec + + /* exprs > ptr */ + + // UnaddressableOperand occurs when the & operator is applied to an + // unaddressable expression. + // + // Example: + // var x = &1 + UnaddressableOperand + + // InvalidIndirection occurs when a non-pointer value is indirected via the + // '*' operator. + // + // Example: + // var x int + // var y = *x + InvalidIndirection + + /* exprs > [] */ + + // NonIndexableOperand occurs when an index operation is applied to a value + // that cannot be indexed. + // + // Example: + // var x = 1 + // var y = x[1] + NonIndexableOperand + + // InvalidIndex occurs when an index argument is not of integer type, + // negative, or out-of-bounds. + // + // Example: + // var s = [...]int{1,2,3} + // var x = s[5] + // + // Example: + // var s = []int{1,2,3} + // var _ = s[-1] + // + // Example: + // var s = []int{1,2,3} + // var i string + // var _ = s[i] + InvalidIndex + + // SwappedSliceIndices occurs when constant indices in a slice expression + // are decreasing in value. + // + // Example: + // var _ = []int{1,2,3}[2:1] + SwappedSliceIndices + + /* operators > slice */ + + // NonSliceableOperand occurs when a slice operation is applied to a value + // whose type is not sliceable, or is unaddressable. + // + // Example: + // var x = [...]int{1, 2, 3}[:1] + // + // Example: + // var x = 1 + // var y = 1[:1] + NonSliceableOperand + + // InvalidSliceExpr occurs when a three-index slice expression (a[x:y:z]) is + // applied to a string. + // + // Example: + // var s = "hello" + // var x = s[1:2:3] + InvalidSliceExpr + + /* exprs > shift */ + + // InvalidShiftCount occurs when the right-hand side of a shift operation is + // either non-integer, negative, or too large. + // + // Example: + // var ( + // x string + // y int = 1 << x + // ) + InvalidShiftCount + + // InvalidShiftOperand occurs when the shifted operand is not an integer. + // + // Example: + // var s = "hello" + // var x = s << 2 + InvalidShiftOperand + + /* exprs > chan */ + + // InvalidReceive occurs when there is a channel receive from a value that + // is either not a channel, or is a send-only channel. + // + // Example: + // func f() { + // var x = 1 + // <-x + // } + InvalidReceive + + // InvalidSend occurs when there is a channel send to a value that is not a + // channel, or is a receive-only channel. + // + // Example: + // func f() { + // var x = 1 + // x <- "hello!" + // } + InvalidSend + + /* exprs > literal */ + + // DuplicateLitKey occurs when an index is duplicated in a slice, array, or + // map literal. + // + // Example: + // var _ = []int{0:1, 0:2} + // + // Example: + // var _ = map[string]int{"a": 1, "a": 2} + DuplicateLitKey + + // MissingLitKey occurs when a map literal is missing a key expression. + // + // Example: + // var _ = map[string]int{1} + MissingLitKey + + // InvalidLitIndex occurs when the key in a key-value element of a slice or + // array literal is not an integer constant. + // + // Example: + // var i = 0 + // var x = []string{i: "world"} + InvalidLitIndex + + // OversizeArrayLit occurs when an array literal exceeds its length. + // + // Example: + // var _ = [2]int{1,2,3} + OversizeArrayLit + + // MixedStructLit occurs when a struct literal contains a mix of positional + // and named elements. + // + // Example: + // var _ = struct{i, j int}{i: 1, 2} + MixedStructLit + + // InvalidStructLit occurs when a positional struct literal has an incorrect + // number of values. + // + // Example: + // var _ = struct{i, j int}{1,2,3} + InvalidStructLit + + // MissingLitField occurs when a struct literal refers to a field that does + // not exist on the struct type. + // + // Example: + // var _ = struct{i int}{j: 2} + MissingLitField + + // DuplicateLitField occurs when a struct literal contains duplicated + // fields. + // + // Example: + // var _ = struct{i int}{i: 1, i: 2} + DuplicateLitField + + // UnexportedLitField occurs when a positional struct literal implicitly + // assigns an unexported field of an imported type. + UnexportedLitField + + // InvalidLitField occurs when a field name is not a valid identifier. + // + // Example: + // var _ = struct{i int}{1: 1} + InvalidLitField + + // UntypedLit occurs when a composite literal omits a required type + // identifier. + // + // Example: + // type outer struct{ + // inner struct { i int } + // } + // + // var _ = outer{inner: {1}} + UntypedLit + + // InvalidLit occurs when a composite literal expression does not match its + // type. + // + // Example: + // type P *struct{ + // x int + // } + // var _ = P {} + InvalidLit + + /* exprs > selector */ + + // AmbiguousSelector occurs when a selector is ambiguous. + // + // Example: + // type E1 struct { i int } + // type E2 struct { i int } + // type T struct { E1; E2 } + // + // var x T + // var _ = x.i + AmbiguousSelector + + // UndeclaredImportedName occurs when a package-qualified identifier is + // undeclared by the imported package. + // + // Example: + // import "go/types" + // + // var _ = types.NotAnActualIdentifier + UndeclaredImportedName + + // UnexportedName occurs when a selector refers to an unexported identifier + // of an imported package. + // + // Example: + // import "reflect" + // + // type _ reflect.flag + UnexportedName + + // UndeclaredName occurs when an identifier is not declared in the current + // scope. + // + // Example: + // var x T + UndeclaredName + + // MissingFieldOrMethod occurs when a selector references a field or method + // that does not exist. + // + // Example: + // type T struct {} + // + // var x = T{}.f + MissingFieldOrMethod + + /* exprs > ... */ + + // BadDotDotDotSyntax occurs when a "..." occurs in a context where it is + // not valid. + // + // Example: + // var _ = map[int][...]int{0: {}} + BadDotDotDotSyntax + + // NonVariadicDotDotDot occurs when a "..." is used on the final argument to + // a non-variadic function. + // + // Example: + // func printArgs(s []string) { + // for _, a := range s { + // println(a) + // } + // } + // + // func f() { + // s := []string{"a", "b", "c"} + // printArgs(s...) + // } + NonVariadicDotDotDot + + // MisplacedDotDotDot occurs when a "..." is used somewhere other than the + // final argument to a function call. + // + // Example: + // func printArgs(args ...int) { + // for _, a := range args { + // println(a) + // } + // } + // + // func f() { + // a := []int{1,2,3} + // printArgs(0, a...) + // } + MisplacedDotDotDot + + // InvalidDotDotDotOperand occurs when a "..." operator is applied to a + // single-valued operand. + // + // Example: + // func printArgs(args ...int) { + // for _, a := range args { + // println(a) + // } + // } + // + // func f() { + // a := 1 + // printArgs(a...) + // } + // + // Example: + // func args() (int, int) { + // return 1, 2 + // } + // + // func printArgs(args ...int) { + // for _, a := range args { + // println(a) + // } + // } + // + // func g() { + // printArgs(args()...) + // } + InvalidDotDotDotOperand + + // InvalidDotDotDot occurs when a "..." is used in a non-variadic built-in + // function. + // + // Example: + // var s = []int{1, 2, 3} + // var l = len(s...) + InvalidDotDotDot + + /* exprs > built-in */ + + // UncalledBuiltin occurs when a built-in function is used as a + // function-valued expression, instead of being called. + // + // Per the spec: + // "The built-in functions do not have standard Go types, so they can only + // appear in call expressions; they cannot be used as function values." + // + // Example: + // var _ = copy + UncalledBuiltin + + // InvalidAppend occurs when append is called with a first argument that is + // not a slice. + // + // Example: + // var _ = append(1, 2) + InvalidAppend + + // InvalidCap occurs when an argument to the cap built-in function is not of + // supported type. + // + // See https://golang.org/ref/spec#Lengthand_capacity for information on + // which underlying types are supported as arguments to cap and len. + // + // Example: + // var s = 2 + // var x = cap(s) + InvalidCap + + // InvalidClose occurs when close(...) is called with an argument that is + // not of channel type, or that is a receive-only channel. + // + // Example: + // func f() { + // var x int + // close(x) + // } + InvalidClose + + // InvalidCopy occurs when the arguments are not of slice type or do not + // have compatible type. + // + // See https://golang.org/ref/spec#Appendingand_copying_slices for more + // information on the type requirements for the copy built-in. + // + // Example: + // func f() { + // var x []int + // y := []int64{1,2,3} + // copy(x, y) + // } + InvalidCopy + + // InvalidComplex occurs when the complex built-in function is called with + // arguments with incompatible types. + // + // Example: + // var _ = complex(float32(1), float64(2)) + InvalidComplex + + // InvalidDelete occurs when the delete built-in function is called with a + // first argument that is not a map. + // + // Example: + // func f() { + // m := "hello" + // delete(m, "e") + // } + InvalidDelete + + // InvalidImag occurs when the imag built-in function is called with an + // argument that does not have complex type. + // + // Example: + // var _ = imag(int(1)) + InvalidImag + + // InvalidLen occurs when an argument to the len built-in function is not of + // supported type. + // + // See https://golang.org/ref/spec#Lengthand_capacity for information on + // which underlying types are supported as arguments to cap and len. + // + // Example: + // var s = 2 + // var x = len(s) + InvalidLen + + // SwappedMakeArgs occurs when make is called with three arguments, and its + // length argument is larger than its capacity argument. + // + // Example: + // var x = make([]int, 3, 2) + SwappedMakeArgs + + // InvalidMake occurs when make is called with an unsupported type argument. + // + // See https://golang.org/ref/spec#Makingslices_maps_and_channels for + // information on the types that may be created using make. + // + // Example: + // var x = make(int) + InvalidMake + + // InvalidReal occurs when the real built-in function is called with an + // argument that does not have complex type. + // + // Example: + // var _ = real(int(1)) + InvalidReal + + /* exprs > assertion */ + + // InvalidAssert occurs when a type assertion is applied to a + // value that is not of interface type. + // + // Example: + // var x = 1 + // var _ = x.(float64) + InvalidAssert + + // ImpossibleAssert occurs for a type assertion x.(T) when the value x of + // interface cannot have dynamic type T, due to a missing or mismatching + // method on T. + // + // Example: + // type T int + // + // func (t *T) m() int { return int(*t) } + // + // type I interface { m() int } + // + // var x I + // var _ = x.(T) + ImpossibleAssert + + /* exprs > conversion */ + + // InvalidConversion occurs when the argument type cannot be converted to the + // target. + // + // See https://golang.org/ref/spec#Conversions for the rules of + // convertibility. + // + // Example: + // var x float64 + // var _ = string(x) + InvalidConversion + + // InvalidUntypedConversion occurs when an there is no valid implicit + // conversion from an untyped value satisfying the type constraints of the + // context in which it is used. + // + // Example: + // var _ = 1 + "" + InvalidUntypedConversion + + /* offsetof */ + + // BadOffsetofSyntax occurs when unsafe.Offsetof is called with an argument + // that is not a selector expression. + // + // Example: + // import "unsafe" + // + // var x int + // var _ = unsafe.Offsetof(x) + BadOffsetofSyntax + + // InvalidOffsetof occurs when unsafe.Offsetof is called with a method + // selector, rather than a field selector, or when the field is embedded via + // a pointer. + // + // Per the spec: + // + // "If f is an embedded field, it must be reachable without pointer + // indirections through fields of the struct. " + // + // Example: + // import "unsafe" + // + // type T struct { f int } + // type S struct { *T } + // var s S + // var _ = unsafe.Offsetof(s.f) + // + // Example: + // import "unsafe" + // + // type S struct{} + // + // func (S) m() {} + // + // var s S + // var _ = unsafe.Offsetof(s.m) + InvalidOffsetof + + /* control flow > scope */ + + // UnusedExpr occurs when a side-effect free expression is used as a + // statement. Such a statement has no effect. + // + // Example: + // func f(i int) { + // i*i + // } + UnusedExpr + + // UnusedVar occurs when a variable is declared but unused. + // + // Example: + // func f() { + // x := 1 + // } + UnusedVar + + // MissingReturn occurs when a function with results is missing a return + // statement. + // + // Example: + // func f() int {} + MissingReturn + + // WrongResultCount occurs when a return statement returns an incorrect + // number of values. + // + // Example: + // func ReturnOne() int { + // return 1, 2 + // } + WrongResultCount + + // OutOfScopeResult occurs when the name of a value implicitly returned by + // an empty return statement is shadowed in a nested scope. + // + // Example: + // func factor(n int) (i int) { + // for i := 2; i < n; i++ { + // if n%i == 0 { + // return + // } + // } + // return 0 + // } + OutOfScopeResult + + /* control flow > if */ + + // InvalidCond occurs when an if condition is not a boolean expression. + // + // Example: + // func checkReturn(i int) { + // if i { + // panic("non-zero return") + // } + // } + InvalidCond + + /* control flow > for */ + + // InvalidPostDecl occurs when there is a declaration in a for-loop post + // statement. + // + // Example: + // func f() { + // for i := 0; i < 10; j := 0 {} + // } + InvalidPostDecl + + // InvalidChanRange occurs when a send-only channel used in a range + // expression. + // + // Example: + // func sum(c chan<- int) { + // s := 0 + // for i := range c { + // s += i + // } + // } + InvalidChanRange + + // InvalidIterVar occurs when two iteration variables are used while ranging + // over a channel. + // + // Example: + // func f(c chan int) { + // for k, v := range c { + // println(k, v) + // } + // } + InvalidIterVar + + // InvalidRangeExpr occurs when the type of a range expression is not array, + // slice, string, map, or channel. + // + // Example: + // func f(i int) { + // for j := range i { + // println(j) + // } + // } + InvalidRangeExpr + + /* control flow > switch */ + + // MisplacedBreak occurs when a break statement is not within a for, switch, + // or select statement of the innermost function definition. + // + // Example: + // func f() { + // break + // } + MisplacedBreak + + // MisplacedContinue occurs when a continue statement is not within a for + // loop of the innermost function definition. + // + // Example: + // func sumeven(n int) int { + // proceed := func() { + // continue + // } + // sum := 0 + // for i := 1; i <= n; i++ { + // if i % 2 != 0 { + // proceed() + // } + // sum += i + // } + // return sum + // } + MisplacedContinue + + // MisplacedFallthrough occurs when a fallthrough statement is not within an + // expression switch. + // + // Example: + // func typename(i interface{}) string { + // switch i.(type) { + // case int64: + // fallthrough + // case int: + // return "int" + // } + // return "unsupported" + // } + MisplacedFallthrough + + // DuplicateCase occurs when a type or expression switch has duplicate + // cases. + // + // Example: + // func printInt(i int) { + // switch i { + // case 1: + // println("one") + // case 1: + // println("One") + // } + // } + DuplicateCase + + // DuplicateDefault occurs when a type or expression switch has multiple + // default clauses. + // + // Example: + // func printInt(i int) { + // switch i { + // case 1: + // println("one") + // default: + // println("One") + // default: + // println("1") + // } + // } + DuplicateDefault + + // BadTypeKeyword occurs when a .(type) expression is used anywhere other + // than a type switch. + // + // Example: + // type I interface { + // m() + // } + // var t I + // var _ = t.(type) + BadTypeKeyword + + // InvalidTypeSwitch occurs when .(type) is used on an expression that is + // not of interface type. + // + // Example: + // func f(i int) { + // switch x := i.(type) {} + // } + InvalidTypeSwitch + + /* control flow > select */ + + // InvalidSelectCase occurs when a select case is not a channel send or + // receive. + // + // Example: + // func checkChan(c <-chan int) bool { + // select { + // case c: + // return true + // default: + // return false + // } + // } + InvalidSelectCase + + /* control flow > labels and jumps */ + + // UndeclaredLabel occurs when an undeclared label is jumped to. + // + // Example: + // func f() { + // goto L + // } + UndeclaredLabel + + // DuplicateLabel occurs when a label is declared more than once. + // + // Example: + // func f() int { + // L: + // L: + // return 1 + // } + DuplicateLabel + + // MisplacedLabel occurs when a break or continue label is not on a for, + // switch, or select statement. + // + // Example: + // func f() { + // L: + // a := []int{1,2,3} + // for _, e := range a { + // if e > 10 { + // break L + // } + // println(a) + // } + // } + MisplacedLabel + + // UnusedLabel occurs when a label is declared but not used. + // + // Example: + // func f() { + // L: + // } + UnusedLabel + + // JumpOverDecl occurs when a label jumps over a variable declaration. + // + // Example: + // func f() int { + // goto L + // x := 2 + // L: + // x++ + // return x + // } + JumpOverDecl + + // JumpIntoBlock occurs when a forward jump goes to a label inside a nested + // block. + // + // Example: + // func f(x int) { + // goto L + // if x > 0 { + // L: + // print("inside block") + // } + // } + JumpIntoBlock + + /* control flow > calls */ + + // InvalidMethodExpr occurs when a pointer method is called but the argument + // is not addressable. + // + // Example: + // type T struct {} + // + // func (*T) m() int { return 1 } + // + // var _ = T.m(T{}) + InvalidMethodExpr + + // WrongArgCount occurs when too few or too many arguments are passed by a + // function call. + // + // Example: + // func f(i int) {} + // var x = f() + WrongArgCount + + // InvalidCall occurs when an expression is called that is not of function + // type. + // + // Example: + // var x = "x" + // var y = x() + InvalidCall + + /* control flow > suspended */ + + // UnusedResults occurs when a restricted expression-only built-in function + // is suspended via go or defer. Such a suspension discards the results of + // these side-effect free built-in functions, and therefore is ineffectual. + // + // Example: + // func f(a []int) int { + // defer len(a) + // return i + // } + UnusedResults + + // InvalidDefer occurs when a deferred expression is not a function call, + // for example if the expression is a type conversion. + // + // Example: + // func f(i int) int { + // defer int32(i) + // return i + // } + InvalidDefer + + // InvalidGo occurs when a go expression is not a function call, for example + // if the expression is a type conversion. + // + // Example: + // func f(i int) int { + // go int32(i) + // return i + // } + InvalidGo +) diff --git a/vendor/golang.org/x/tools/internal/typesinternal/errorcode_string.go b/vendor/golang.org/x/tools/internal/typesinternal/errorcode_string.go new file mode 100644 index 0000000000..97f3ec891f --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typesinternal/errorcode_string.go @@ -0,0 +1,152 @@ +// Code generated by "stringer -type=ErrorCode"; DO NOT EDIT. + +package typesinternal + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[Test-1] + _ = x[BlankPkgName-2] + _ = x[MismatchedPkgName-3] + _ = x[InvalidPkgUse-4] + _ = x[BadImportPath-5] + _ = x[BrokenImport-6] + _ = x[ImportCRenamed-7] + _ = x[UnusedImport-8] + _ = x[InvalidInitCycle-9] + _ = x[DuplicateDecl-10] + _ = x[InvalidDeclCycle-11] + _ = x[InvalidTypeCycle-12] + _ = x[InvalidConstInit-13] + _ = x[InvalidConstVal-14] + _ = x[InvalidConstType-15] + _ = x[UntypedNil-16] + _ = x[WrongAssignCount-17] + _ = x[UnassignableOperand-18] + _ = x[NoNewVar-19] + _ = x[MultiValAssignOp-20] + _ = x[InvalidIfaceAssign-21] + _ = x[InvalidChanAssign-22] + _ = x[IncompatibleAssign-23] + _ = x[UnaddressableFieldAssign-24] + _ = x[NotAType-25] + _ = x[InvalidArrayLen-26] + _ = x[BlankIfaceMethod-27] + _ = x[IncomparableMapKey-28] + _ = x[InvalidIfaceEmbed-29] + _ = x[InvalidPtrEmbed-30] + _ = x[BadRecv-31] + _ = x[InvalidRecv-32] + _ = x[DuplicateFieldAndMethod-33] + _ = x[DuplicateMethod-34] + _ = x[InvalidBlank-35] + _ = x[InvalidIota-36] + _ = x[MissingInitBody-37] + _ = x[InvalidInitSig-38] + _ = x[InvalidInitDecl-39] + _ = x[InvalidMainDecl-40] + _ = x[TooManyValues-41] + _ = x[NotAnExpr-42] + _ = x[TruncatedFloat-43] + _ = x[NumericOverflow-44] + _ = x[UndefinedOp-45] + _ = x[MismatchedTypes-46] + _ = x[DivByZero-47] + _ = x[NonNumericIncDec-48] + _ = x[UnaddressableOperand-49] + _ = x[InvalidIndirection-50] + _ = x[NonIndexableOperand-51] + _ = x[InvalidIndex-52] + _ = x[SwappedSliceIndices-53] + _ = x[NonSliceableOperand-54] + _ = x[InvalidSliceExpr-55] + _ = x[InvalidShiftCount-56] + _ = x[InvalidShiftOperand-57] + _ = x[InvalidReceive-58] + _ = x[InvalidSend-59] + _ = x[DuplicateLitKey-60] + _ = x[MissingLitKey-61] + _ = x[InvalidLitIndex-62] + _ = x[OversizeArrayLit-63] + _ = x[MixedStructLit-64] + _ = x[InvalidStructLit-65] + _ = x[MissingLitField-66] + _ = x[DuplicateLitField-67] + _ = x[UnexportedLitField-68] + _ = x[InvalidLitField-69] + _ = x[UntypedLit-70] + _ = x[InvalidLit-71] + _ = x[AmbiguousSelector-72] + _ = x[UndeclaredImportedName-73] + _ = x[UnexportedName-74] + _ = x[UndeclaredName-75] + _ = x[MissingFieldOrMethod-76] + _ = x[BadDotDotDotSyntax-77] + _ = x[NonVariadicDotDotDot-78] + _ = x[MisplacedDotDotDot-79] + _ = x[InvalidDotDotDotOperand-80] + _ = x[InvalidDotDotDot-81] + _ = x[UncalledBuiltin-82] + _ = x[InvalidAppend-83] + _ = x[InvalidCap-84] + _ = x[InvalidClose-85] + _ = x[InvalidCopy-86] + _ = x[InvalidComplex-87] + _ = x[InvalidDelete-88] + _ = x[InvalidImag-89] + _ = x[InvalidLen-90] + _ = x[SwappedMakeArgs-91] + _ = x[InvalidMake-92] + _ = x[InvalidReal-93] + _ = x[InvalidAssert-94] + _ = x[ImpossibleAssert-95] + _ = x[InvalidConversion-96] + _ = x[InvalidUntypedConversion-97] + _ = x[BadOffsetofSyntax-98] + _ = x[InvalidOffsetof-99] + _ = x[UnusedExpr-100] + _ = x[UnusedVar-101] + _ = x[MissingReturn-102] + _ = x[WrongResultCount-103] + _ = x[OutOfScopeResult-104] + _ = x[InvalidCond-105] + _ = x[InvalidPostDecl-106] + _ = x[InvalidChanRange-107] + _ = x[InvalidIterVar-108] + _ = x[InvalidRangeExpr-109] + _ = x[MisplacedBreak-110] + _ = x[MisplacedContinue-111] + _ = x[MisplacedFallthrough-112] + _ = x[DuplicateCase-113] + _ = x[DuplicateDefault-114] + _ = x[BadTypeKeyword-115] + _ = x[InvalidTypeSwitch-116] + _ = x[InvalidSelectCase-117] + _ = x[UndeclaredLabel-118] + _ = x[DuplicateLabel-119] + _ = x[MisplacedLabel-120] + _ = x[UnusedLabel-121] + _ = x[JumpOverDecl-122] + _ = x[JumpIntoBlock-123] + _ = x[InvalidMethodExpr-124] + _ = x[WrongArgCount-125] + _ = x[InvalidCall-126] + _ = x[UnusedResults-127] + _ = x[InvalidDefer-128] + _ = x[InvalidGo-129] +} + +const _ErrorCode_name = "TestBlankPkgNameMismatchedPkgNameInvalidPkgUseBadImportPathBrokenImportImportCRenamedUnusedImportInvalidInitCycleDuplicateDeclInvalidDeclCycleInvalidTypeCycleInvalidConstInitInvalidConstValInvalidConstTypeUntypedNilWrongAssignCountUnassignableOperandNoNewVarMultiValAssignOpInvalidIfaceAssignInvalidChanAssignIncompatibleAssignUnaddressableFieldAssignNotATypeInvalidArrayLenBlankIfaceMethodIncomparableMapKeyInvalidIfaceEmbedInvalidPtrEmbedBadRecvInvalidRecvDuplicateFieldAndMethodDuplicateMethodInvalidBlankInvalidIotaMissingInitBodyInvalidInitSigInvalidInitDeclInvalidMainDeclTooManyValuesNotAnExprTruncatedFloatNumericOverflowUndefinedOpMismatchedTypesDivByZeroNonNumericIncDecUnaddressableOperandInvalidIndirectionNonIndexableOperandInvalidIndexSwappedSliceIndicesNonSliceableOperandInvalidSliceExprInvalidShiftCountInvalidShiftOperandInvalidReceiveInvalidSendDuplicateLitKeyMissingLitKeyInvalidLitIndexOversizeArrayLitMixedStructLitInvalidStructLitMissingLitFieldDuplicateLitFieldUnexportedLitFieldInvalidLitFieldUntypedLitInvalidLitAmbiguousSelectorUndeclaredImportedNameUnexportedNameUndeclaredNameMissingFieldOrMethodBadDotDotDotSyntaxNonVariadicDotDotDotMisplacedDotDotDotInvalidDotDotDotOperandInvalidDotDotDotUncalledBuiltinInvalidAppendInvalidCapInvalidCloseInvalidCopyInvalidComplexInvalidDeleteInvalidImagInvalidLenSwappedMakeArgsInvalidMakeInvalidRealInvalidAssertImpossibleAssertInvalidConversionInvalidUntypedConversionBadOffsetofSyntaxInvalidOffsetofUnusedExprUnusedVarMissingReturnWrongResultCountOutOfScopeResultInvalidCondInvalidPostDeclInvalidChanRangeInvalidIterVarInvalidRangeExprMisplacedBreakMisplacedContinueMisplacedFallthroughDuplicateCaseDuplicateDefaultBadTypeKeywordInvalidTypeSwitchInvalidSelectCaseUndeclaredLabelDuplicateLabelMisplacedLabelUnusedLabelJumpOverDeclJumpIntoBlockInvalidMethodExprWrongArgCountInvalidCallUnusedResultsInvalidDeferInvalidGo" + +var _ErrorCode_index = [...]uint16{0, 4, 16, 33, 46, 59, 71, 85, 97, 113, 126, 142, 158, 174, 189, 205, 215, 231, 250, 258, 274, 292, 309, 327, 351, 359, 374, 390, 408, 425, 440, 447, 458, 481, 496, 508, 519, 534, 548, 563, 578, 591, 600, 614, 629, 640, 655, 664, 680, 700, 718, 737, 749, 768, 787, 803, 820, 839, 853, 864, 879, 892, 907, 923, 937, 953, 968, 985, 1003, 1018, 1028, 1038, 1055, 1077, 1091, 1105, 1125, 1143, 1163, 1181, 1204, 1220, 1235, 1248, 1258, 1270, 1281, 1295, 1308, 1319, 1329, 1344, 1355, 1366, 1379, 1395, 1412, 1436, 1453, 1468, 1478, 1487, 1500, 1516, 1532, 1543, 1558, 1574, 1588, 1604, 1618, 1635, 1655, 1668, 1684, 1698, 1715, 1732, 1747, 1761, 1775, 1786, 1798, 1811, 1828, 1841, 1852, 1865, 1877, 1886} + +func (i ErrorCode) String() string { + i -= 1 + if i < 0 || i >= ErrorCode(len(_ErrorCode_index)-1) { + return "ErrorCode(" + strconv.FormatInt(int64(i+1), 10) + ")" + } + return _ErrorCode_name[_ErrorCode_index[i]:_ErrorCode_index[i+1]] +} diff --git a/vendor/golang.org/x/tools/internal/typesinternal/types.go b/vendor/golang.org/x/tools/internal/typesinternal/types.go new file mode 100644 index 0000000000..c3e1a397db --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typesinternal/types.go @@ -0,0 +1,45 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package typesinternal provides access to internal go/types APIs that are not +// yet exported. +package typesinternal + +import ( + "go/token" + "go/types" + "reflect" + "unsafe" +) + +func SetUsesCgo(conf *types.Config) bool { + v := reflect.ValueOf(conf).Elem() + + f := v.FieldByName("go115UsesCgo") + if !f.IsValid() { + f = v.FieldByName("UsesCgo") + if !f.IsValid() { + return false + } + } + + addr := unsafe.Pointer(f.UnsafeAddr()) + *(*bool)(addr) = true + + return true +} + +func ReadGo116ErrorData(terr types.Error) (ErrorCode, token.Pos, token.Pos, bool) { + var data [3]int + // By coincidence all of these fields are ints, which simplifies things. + v := reflect.ValueOf(terr) + for i, name := range []string{"go116code", "go116start", "go116end"} { + f := v.FieldByName(name) + if !f.IsValid() { + return 0, 0, 0, false + } + data[i] = int(f.Int()) + } + return ErrorCode(data[0]), token.Pos(data[1]), token.Pos(data[2]), true +} diff --git a/vendor/modules.txt b/vendor/modules.txt index a0c120a3ea..b3ba5192f7 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -700,20 +700,12 @@ github.com/jmespath/go-jmespath github.com/jonboulle/clockwork # github.com/json-iterator/go v1.1.10 github.com/json-iterator/go -# github.com/k3s-io/helm-controller v0.10.8 +# github.com/k3s-io/helm-controller v0.11.7 ## explicit github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1 -github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned -github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/scheme -github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1 github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io/v1 -github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions -github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io -github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/helm.cattle.io/v1 -github.com/k3s-io/helm-controller/pkg/generated/informers/externalversions/internalinterfaces -github.com/k3s-io/helm-controller/pkg/generated/listers/helm.cattle.io/v1 github.com/k3s-io/helm-controller/pkg/helm # github.com/k3s-io/kine v0.6.2 ## explicit @@ -940,7 +932,7 @@ github.com/prometheus/common/model github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/rancher/dynamiclistener v0.2.3 +# github.com/rancher/dynamiclistener v0.2.6 ## explicit github.com/rancher/dynamiclistener github.com/rancher/dynamiclistener/cert @@ -948,13 +940,21 @@ github.com/rancher/dynamiclistener/factory github.com/rancher/dynamiclistener/storage/file github.com/rancher/dynamiclistener/storage/kubernetes github.com/rancher/dynamiclistener/storage/memory +# github.com/rancher/lasso v0.0.0-20210616224652-fc3ebd901c08 +## explicit +github.com/rancher/lasso/pkg/cache +github.com/rancher/lasso/pkg/client +github.com/rancher/lasso/pkg/controller +github.com/rancher/lasso/pkg/log +github.com/rancher/lasso/pkg/mapper +github.com/rancher/lasso/pkg/scheme # github.com/rancher/remotedialer v0.2.0 ## explicit github.com/rancher/remotedialer # github.com/rancher/wharfie v0.3.4 ## explicit github.com/rancher/wharfie/pkg/registries -# github.com/rancher/wrangler v0.6.2 +# github.com/rancher/wrangler v0.8.5 ## explicit github.com/rancher/wrangler/pkg/apply github.com/rancher/wrangler/pkg/apply/injectors @@ -966,6 +966,15 @@ github.com/rancher/wrangler/pkg/controller-gen/generators github.com/rancher/wrangler/pkg/crd github.com/rancher/wrangler/pkg/data github.com/rancher/wrangler/pkg/data/convert +github.com/rancher/wrangler/pkg/generated/controllers/apiextensions.k8s.io/v1 +github.com/rancher/wrangler/pkg/generated/controllers/apps +github.com/rancher/wrangler/pkg/generated/controllers/apps/v1 +github.com/rancher/wrangler/pkg/generated/controllers/batch +github.com/rancher/wrangler/pkg/generated/controllers/batch/v1 +github.com/rancher/wrangler/pkg/generated/controllers/core +github.com/rancher/wrangler/pkg/generated/controllers/core/v1 +github.com/rancher/wrangler/pkg/generated/controllers/rbac +github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1 github.com/rancher/wrangler/pkg/generic github.com/rancher/wrangler/pkg/gvk github.com/rancher/wrangler/pkg/kv @@ -983,16 +992,7 @@ github.com/rancher/wrangler/pkg/schemes github.com/rancher/wrangler/pkg/signals github.com/rancher/wrangler/pkg/slice github.com/rancher/wrangler/pkg/start -# github.com/rancher/wrangler-api v0.6.0 -## explicit -github.com/rancher/wrangler-api/pkg/generated/controllers/apps -github.com/rancher/wrangler-api/pkg/generated/controllers/apps/v1 -github.com/rancher/wrangler-api/pkg/generated/controllers/batch -github.com/rancher/wrangler-api/pkg/generated/controllers/batch/v1 -github.com/rancher/wrangler-api/pkg/generated/controllers/core -github.com/rancher/wrangler-api/pkg/generated/controllers/core/v1 -github.com/rancher/wrangler-api/pkg/generated/controllers/rbac -github.com/rancher/wrangler-api/pkg/generated/controllers/rbac/v1 +github.com/rancher/wrangler/pkg/yaml # github.com/robfig/cron v1.1.0 github.com/robfig/cron # github.com/robfig/cron/v3 v3.0.1 @@ -1333,6 +1333,10 @@ golang.org/x/time/rate # golang.org/x/tools v0.1.0 golang.org/x/tools/container/intsets golang.org/x/tools/go/ast/astutil +golang.org/x/tools/go/gcexportdata +golang.org/x/tools/go/internal/gcimporter +golang.org/x/tools/go/internal/packagesdriver +golang.org/x/tools/go/packages golang.org/x/tools/imports golang.org/x/tools/internal/event golang.org/x/tools/internal/event/core @@ -1342,6 +1346,8 @@ golang.org/x/tools/internal/fastwalk golang.org/x/tools/internal/gocommand golang.org/x/tools/internal/gopathwalk golang.org/x/tools/internal/imports +golang.org/x/tools/internal/packagesinternal +golang.org/x/tools/internal/typesinternal # golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 golang.org/x/xerrors golang.org/x/xerrors/internal @@ -1804,7 +1810,7 @@ k8s.io/apiserver/plugin/pkg/audit/webhook k8s.io/apiserver/plugin/pkg/authenticator/token/oidc k8s.io/apiserver/plugin/pkg/authenticator/token/webhook k8s.io/apiserver/plugin/pkg/authorizer/webhook -# k8s.io/cli-runtime v0.0.0 => github.com/k3s-io/kubernetes/staging/src/k8s.io/cli-runtime v1.21.6-k3s1 +# k8s.io/cli-runtime v0.17.2 => github.com/k3s-io/kubernetes/staging/src/k8s.io/cli-runtime v1.21.6-k3s1 k8s.io/cli-runtime/pkg/genericclioptions k8s.io/cli-runtime/pkg/printers k8s.io/cli-runtime/pkg/resource