diff --git a/go.mod b/go.mod index db77e63d..44f1c385 100644 --- a/go.mod +++ b/go.mod @@ -8,8 +8,6 @@ require ( github.com/google/cel-go v0.17.7 github.com/google/go-cmp v0.6.0 github.com/google/gofuzz v1.2.0 - github.com/json-iterator/go v1.1.12 - github.com/pkg/errors v0.9.1 github.com/spf13/cobra v1.8.0 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.9.0 @@ -28,7 +26,7 @@ require ( k8s.io/utils v0.0.0-20240102154912-e7106e64919e kmodules.xyz/client-go v0.29.13 kmodules.xyz/go-containerregistry v0.0.12 - sigs.k8s.io/controller-runtime v0.17.2 + sigs.k8s.io/controller-runtime v0.17.4 sigs.k8s.io/yaml v1.4.0 ) @@ -110,6 +108,7 @@ require ( github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jonboulle/clockwork v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.17.2 // indirect github.com/klauspost/cpuid/v2 v2.0.9 // indirect github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect @@ -126,6 +125,7 @@ require ( github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.0-rc3 // indirect github.com/peterbourgon/diskv v2.0.1+incompatible // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/prometheus/client_golang v1.18.0 // indirect github.com/prometheus/client_model v0.5.0 // indirect @@ -167,7 +167,6 @@ require ( gomodules.xyz/clock v0.0.0-20200817085942-06523dba733f // indirect gomodules.xyz/flags v0.1.3 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect - gomodules.xyz/mergo v0.3.13 // indirect gomodules.xyz/sets v0.2.1 // indirect gomodules.xyz/wait v0.2.0 // indirect google.golang.org/appengine v1.6.8 // indirect @@ -194,7 +193,7 @@ require ( replace github.com/Masterminds/sprig/v3 => github.com/gomodules/sprig/v3 v3.2.3-0.20220405051441-0a8a99bac1b8 -replace sigs.k8s.io/controller-runtime => github.com/kmodules/controller-runtime v0.17.2-0.20240213085617-b6aac9684c00 +replace sigs.k8s.io/controller-runtime => github.com/kmodules/controller-runtime v0.17.5-0.20240506165850-9bc6cbeccc8a replace github.com/imdario/mergo => github.com/imdario/mergo v0.3.6 diff --git a/go.sum b/go.sum index 40ec536a..cab02dc3 100644 --- a/go.sum +++ b/go.sum @@ -328,8 +328,8 @@ github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBF github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/kmodules/apiserver v0.29.1-0.20240104121741-1fb217d4a573 h1:6v7bTFGH/Ha1idq1sLX9px2KJhcx6cpuMowuYRyCht4= github.com/kmodules/apiserver v0.29.1-0.20240104121741-1fb217d4a573/go.mod h1:31n78PsRKPmfpee7/l9NYEv67u6hOL6AfcE761HapDM= -github.com/kmodules/controller-runtime v0.17.2-0.20240213085617-b6aac9684c00 h1:+2add9izgyGZb+ZOkMwPH/fswvgfIxWilUatbp2nPo8= -github.com/kmodules/controller-runtime v0.17.2-0.20240213085617-b6aac9684c00/go.mod h1:+MngTvIQQQhfXtwfdGw/UOQ/aIaqsYywfCINOtwMO/s= +github.com/kmodules/controller-runtime v0.17.5-0.20240506165850-9bc6cbeccc8a h1:u8HKIdgkhL3sN8Xie0+/JyoLbPCLkG8SHxtEpU1Meo0= +github.com/kmodules/controller-runtime v0.17.5-0.20240506165850-9bc6cbeccc8a/go.mod h1:N0jpP5Lo7lMTF9aL56Z/B2oWBJjey6StQM0jRbKQXtY= github.com/kmodules/kubernetes v1.30.0-alpha.0.0.20231224075822-3bd9a13c86db h1:mxGSSonND38OzJ8W6zfKEUY5JMe04OcgjRLEgCXbjLM= github.com/kmodules/kubernetes v1.30.0-alpha.0.0.20231224075822-3bd9a13c86db/go.mod h1:V78f/rAOcRUt4c3Dd4NbjY7u4VG9ApaovqIgNacJqBc= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -703,8 +703,6 @@ gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY= gomodules.xyz/logs v0.0.7 h1:dkhpdQuzj+pOS3S7VaOq+JV7BVU7f68/k3uDYufhPow= gomodules.xyz/logs v0.0.7/go.mod h1:IEIZbRl9zua2jb35NU4KoqxUEDPmKvem3PhfRHqQI54= -gomodules.xyz/mergo v0.3.13 h1:q6cL/MMXZH/MrR2+yjSihFFq6UifXqjwaqI48B6cMEM= -gomodules.xyz/mergo v0.3.13/go.mod h1:F/2rKC7j0URTnHUKDiTiLcGdLMhdv8jK2Za3cRTUVmc= gomodules.xyz/pointer v0.1.0 h1:sG2UKrYVSo6E3r4itAjXfPfe4fuXMi0KdyTHpR3vGCg= gomodules.xyz/pointer v0.1.0/go.mod h1:sPLsC0+yLTRecUiC5yVlyvXhZ6LAGojNCRWNNqoplvo= gomodules.xyz/sets v0.2.0/go.mod h1:jKgNp01/iDs+svOWXaPk5cKP3VXy0mWUoTF/ore+aMc= @@ -783,7 +781,6 @@ gopkg.in/yaml.v2 v2.2.8/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-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.1.0 h1:rVV8Tcg/8jHUkPUorwjaMTtemIMVXfIPKiOqnhEhakk= diff --git a/vendor/gomodules.xyz/mergo/.deepsource.toml b/vendor/gomodules.xyz/mergo/.deepsource.toml deleted file mode 100644 index 92e07ffd..00000000 --- a/vendor/gomodules.xyz/mergo/.deepsource.toml +++ /dev/null @@ -1,12 +0,0 @@ -version = 1 - -test_patterns = [ - "*_test.go" -] - -[[analyzers]] -name = "go" -enabled = true - - [analyzers.meta] - import_path = "gomodules.xyz/mergo" \ No newline at end of file diff --git a/vendor/gomodules.xyz/mergo/.gitignore b/vendor/gomodules.xyz/mergo/.gitignore deleted file mode 100644 index 529c3412..00000000 --- a/vendor/gomodules.xyz/mergo/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -#### joe made this: http://goel.io/joe - -#### go #### -# Binaries for programs and plugins -*.exe -*.dll -*.so -*.dylib - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 -.glide/ - -#### vim #### -# Swap -[._]*.s[a-v][a-z] -[._]*.sw[a-p] -[._]s[a-v][a-z] -[._]sw[a-p] - -# Session -Session.vim - -# Temporary -.netrwhist -*~ -# Auto-generated tag files -tags diff --git a/vendor/gomodules.xyz/mergo/CODE_OF_CONDUCT.md b/vendor/gomodules.xyz/mergo/CODE_OF_CONDUCT.md deleted file mode 100644 index 469b4490..00000000 --- a/vendor/gomodules.xyz/mergo/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at i@dario.im. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/gomodules.xyz/mergo/LICENSE b/vendor/gomodules.xyz/mergo/LICENSE deleted file mode 100644 index 68668029..00000000 --- a/vendor/gomodules.xyz/mergo/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2013 Dario Castañé. All rights reserved. -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/gomodules.xyz/mergo/README.md b/vendor/gomodules.xyz/mergo/README.md deleted file mode 100644 index e469c322..00000000 --- a/vendor/gomodules.xyz/mergo/README.md +++ /dev/null @@ -1,233 +0,0 @@ -# Mergo - - -[![GoDoc][3]][4] -[![GitHub release][5]][6] -[![GoCard][7]][8] -[![Build Status][1]][2] -[![Coverage Status][9]][10] -[![Sourcegraph][11]][12] -[![FOSSA Status][13]][14] -[![Become my sponsor][15]][16] - -[1]: https://travis-ci.org/imdario/mergo.png -[2]: https://travis-ci.org/imdario/mergo -[3]: https://godoc.org/gomodules.xyz/mergo?status.svg -[4]: https://godoc.org/gomodules.xyz/mergo -[5]: https://img.shields.io/github/release/imdario/mergo.svg -[6]: https://gomodules.xyz/mergo/releases -[7]: https://goreportcard.com/badge/imdario/mergo -[8]: https://goreportcard.com/report/gomodules.xyz/mergo -[9]: https://coveralls.io/repos/github/imdario/mergo/badge.svg?branch=master -[10]: https://coveralls.io/github/imdario/mergo?branch=master -[11]: https://sourcegraph.com/gomodules.xyz/mergo/-/badge.svg -[12]: https://sourcegraph.com/gomodules.xyz/mergo?badge -[13]: https://app.fossa.io/api/projects/git%2Bgitpro.ttaallkk.top%2Fimdario%2Fmergo.svg?type=shield -[14]: https://app.fossa.io/projects/git%2Bgitpro.ttaallkk.top%2Fimdario%2Fmergo?ref=badge_shield - -A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. - -Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). - -Also a lovely [comune](http://en.wikipedia.org/wiki/Mergo) (municipality) in the Province of Ancona in the Italian region of Marche. - -## Status - -It is ready for production use. [It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, Microsoft, etc](https://github.com/gomodules/mergo#mergo-in-the-wild). - -### Important note - -Please keep in mind that a problematic PR broke [0.3.9](//gomodules.xyz/mergo/releases/tag/0.3.9). I reverted it in [0.3.10](//gomodules.xyz/mergo/releases/tag/0.3.10), and I consider it stable but not bug-free. Also, this version adds support for go modules. - -Keep in mind that in [0.3.2](//gomodules.xyz/mergo/releases/tag/0.3.2), Mergo changed `Merge()`and `Map()` signatures to support [transformers](#transformers). I added an optional/variadic argument so that it won't break the existing code. - -If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with ```go get -u gomodules.xyz/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0). - -### Donations - -If Mergo is useful to you, consider buying me a coffee, a beer, or making a monthly donation to allow me to keep building great free software. :heart_eyes: - -Buy Me a Coffee at ko-fi.com -Donate using Liberapay -Become my sponsor - -### Mergo in the wild - -- [cli/cli](https://github.com/cli/cli) -- [moby/moby](https://github.com/moby/moby) -- [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes) -- [vmware/dispatch](https://github.com/vmware/dispatch) -- [Shopify/themekit](https://github.com/Shopify/themekit) -- [imdario/zas](https://github.com/imdario/zas) -- [matcornic/hermes](https://github.com/matcornic/hermes) -- [OpenBazaar/openbazaar-go](https://github.com/OpenBazaar/openbazaar-go) -- [kataras/iris](https://github.com/kataras/iris) -- [michaelsauter/crane](https://github.com/michaelsauter/crane) -- [go-task/task](https://github.com/go-task/task) -- [sensu/uchiwa](https://github.com/sensu/uchiwa) -- [ory/hydra](https://github.com/ory/hydra) -- [sisatech/vcli](https://github.com/sisatech/vcli) -- [dairycart/dairycart](https://github.com/dairycart/dairycart) -- [projectcalico/felix](https://github.com/projectcalico/felix) -- [resin-os/balena](https://github.com/resin-os/balena) -- [go-kivik/kivik](https://github.com/go-kivik/kivik) -- [Telefonica/govice](https://github.com/Telefonica/govice) -- [supergiant/supergiant](supergiant/supergiant) -- [SergeyTsalkov/brooce](https://github.com/SergeyTsalkov/brooce) -- [soniah/dnsmadeeasy](https://github.com/soniah/dnsmadeeasy) -- [ohsu-comp-bio/funnel](https://github.com/ohsu-comp-bio/funnel) -- [EagerIO/Stout](https://github.com/EagerIO/Stout) -- [lynndylanhurley/defsynth-api](https://github.com/lynndylanhurley/defsynth-api) -- [russross/canvasassignments](https://github.com/russross/canvasassignments) -- [rdegges/cryptly-api](https://github.com/rdegges/cryptly-api) -- [casualjim/exeggutor](https://github.com/casualjim/exeggutor) -- [divshot/gitling](https://github.com/divshot/gitling) -- [RWJMurphy/gorl](https://github.com/RWJMurphy/gorl) -- [andrerocker/deploy42](https://github.com/andrerocker/deploy42) -- [elwinar/rambler](https://github.com/elwinar/rambler) -- [tmaiaroto/gopartman](https://github.com/tmaiaroto/gopartman) -- [jfbus/impressionist](https://github.com/jfbus/impressionist) -- [Jmeyering/zealot](https://github.com/Jmeyering/zealot) -- [godep-migrator/rigger-host](https://github.com/godep-migrator/rigger-host) -- [Dronevery/MultiwaySwitch-Go](https://github.com/Dronevery/MultiwaySwitch-Go) -- [thoas/picfit](https://github.com/thoas/picfit) -- [mantasmatelis/whooplist-server](https://github.com/mantasmatelis/whooplist-server) -- [jnuthong/item_search](https://github.com/jnuthong/item_search) -- [bukalapak/snowboard](https://github.com/bukalapak/snowboard) -- [containerssh/containerssh](https://github.com/containerssh/containerssh) -- [goreleaser/goreleaser](https://github.com/goreleaser/goreleaser) -- [tjpnz/structbot](https://github.com/tjpnz/structbot) - -## Install - - go get gomodules.xyz/mergo - - // use in your .go code - import ( - "gomodules.xyz/mergo" - ) - -## Usage - -You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as [they are zero values](https://golang.org/ref/spec#The_zero_value) too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). - -```go -if err := mergo.Merge(&dst, src); err != nil { - // ... -} -``` - -Also, you can merge overwriting values using the transformer `WithOverride`. - -```go -if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil { - // ... -} -``` - -Additionally, you can map a `map[string]interface{}` to a struct (and otherwise, from struct to map), following the same restrictions as in `Merge()`. Keys are capitalized to find each corresponding exported field. - -```go -if err := mergo.Map(&dst, srcMap); err != nil { - // ... -} -``` - -Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as `map[string]interface{}`. They will be just assigned as values. - -Here is a nice example: - -```go -package main - -import ( - "fmt" - "gomodules.xyz/mergo" -) - -type Foo struct { - A string - B int64 -} - -func main() { - src := Foo{ - A: "one", - B: 2, - } - dest := Foo{ - A: "two", - } - mergo.Merge(&dest, src) - fmt.Println(dest) - // Will print - // {two 2} -} -``` - -Note: if test are failing due missing package, please execute: - - go get gopkg.in/yaml.v3 - -### Transformers - -Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, `time.Time` is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero `time.Time`? - -```go -package main - -import ( - "fmt" - "gomodules.xyz/mergo" - "reflect" - "time" -) - -type timeTransformer struct { -} - -func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { - if typ == reflect.TypeOf(time.Time{}) { - return func(dst, src reflect.Value) error { - if dst.CanSet() { - isZero := dst.MethodByName("IsZero") - result := isZero.Call([]reflect.Value{}) - if result[0].Bool() { - dst.Set(src) - } - } - return nil - } - } - return nil -} - -type Snapshot struct { - Time time.Time - // ... -} - -func main() { - src := Snapshot{time.Now()} - dest := Snapshot{} - mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) - fmt.Println(dest) - // Will print - // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } -} -``` - -## Contact me - -If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): [@im_dario](https://twitter.com/im_dario) - -## About - -Written by [Dario Castañé](http://dario.im). - -## License - -[BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE). - - -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgitpro.ttaallkk.top%2Fimdario%2Fmergo.svg?type=large)](https://app.fossa.io/projects/git%2Bgitpro.ttaallkk.top%2Fimdario%2Fmergo?ref=badge_large) diff --git a/vendor/gomodules.xyz/mergo/doc.go b/vendor/gomodules.xyz/mergo/doc.go deleted file mode 100644 index ee0e2b99..00000000 --- a/vendor/gomodules.xyz/mergo/doc.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. - -Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). - -Status - -It is ready for production use. It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc. - -Important note - -Please keep in mind that a problematic PR broke 0.3.9. We reverted it in 0.3.10. We consider 0.3.10 as stable but not bug-free. . Also, this version adds suppot for go modules. - -Keep in mind that in 0.3.2, Mergo changed Merge() and Map() signatures to support transformers. We added an optional/variadic argument so that it won't break the existing code. - -If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with go get -u gomodules.xyz/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0). - -Install - -Do your usual installation procedure: - - go get gomodules.xyz/mergo - - // use in your .go code - import ( - "gomodules.xyz/mergo" - ) - -Usage - -You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as they are zero values too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). - - if err := mergo.Merge(&dst, src); err != nil { - // ... - } - -Also, you can merge overwriting values using the transformer WithOverride. - - if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil { - // ... - } - -Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field. - - if err := mergo.Map(&dst, srcMap); err != nil { - // ... - } - -Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values. - -Here is a nice example: - - package main - - import ( - "fmt" - "gomodules.xyz/mergo" - ) - - type Foo struct { - A string - B int64 - } - - func main() { - src := Foo{ - A: "one", - B: 2, - } - dest := Foo{ - A: "two", - } - mergo.Merge(&dest, src) - fmt.Println(dest) - // Will print - // {two 2} - } - -Transformers - -Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, time.Time is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero time.Time? - - package main - - import ( - "fmt" - "gomodules.xyz/mergo" - "reflect" - "time" - ) - - type timeTransformer struct { - } - - func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { - if typ == reflect.TypeOf(time.Time{}) { - return func(dst, src reflect.Value) error { - if dst.CanSet() { - isZero := dst.MethodByName("IsZero") - result := isZero.Call([]reflect.Value{}) - if result[0].Bool() { - dst.Set(src) - } - } - return nil - } - } - return nil - } - - type Snapshot struct { - Time time.Time - // ... - } - - func main() { - src := Snapshot{time.Now()} - dest := Snapshot{} - mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) - fmt.Println(dest) - // Will print - // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } - } - -Contact me - -If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): https://twitter.com/im_dario - -About - -Written by Dario Castañé: https://da.rio.hn - -License - -BSD 3-Clause license, as Go language. - -*/ -package mergo diff --git a/vendor/gomodules.xyz/mergo/map.go b/vendor/gomodules.xyz/mergo/map.go deleted file mode 100644 index a13a7ee4..00000000 --- a/vendor/gomodules.xyz/mergo/map.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2014 Dario Castañé. All rights reserved. -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Based on src/pkg/reflect/deepequal.go from official -// golang's stdlib. - -package mergo - -import ( - "fmt" - "reflect" - "unicode" - "unicode/utf8" -) - -func changeInitialCase(s string, mapper func(rune) rune) string { - if s == "" { - return s - } - r, n := utf8.DecodeRuneInString(s) - return string(mapper(r)) + s[n:] -} - -func isExported(field reflect.StructField) bool { - r, _ := utf8.DecodeRuneInString(field.Name) - return r >= 'A' && r <= 'Z' -} - -// Traverses recursively both values, assigning src's fields values to dst. -// The map argument tracks comparisons that have already been seen, which allows -// short circuiting on recursive types. -func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { - overwrite := config.Overwrite - if dst.CanAddr() { - addr := dst.UnsafeAddr() - h := 17 * addr - seen := visited[h] - typ := dst.Type() - for p := seen; p != nil; p = p.next { - if p.ptr == addr && p.typ == typ { - return nil - } - } - // Remember, remember... - visited[h] = &visit{addr, typ, seen} - } - zeroValue := reflect.Value{} - switch dst.Kind() { - case reflect.Map: - dstMap := dst.Interface().(map[string]interface{}) - for i, n := 0, src.NumField(); i < n; i++ { - srcType := src.Type() - field := srcType.Field(i) - if !isExported(field) { - continue - } - fieldName := field.Name - fieldName = changeInitialCase(fieldName, unicode.ToLower) - if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v)) || overwrite) { - dstMap[fieldName] = src.Field(i).Interface() - } - } - case reflect.Ptr: - if dst.IsNil() { - v := reflect.New(dst.Type().Elem()) - dst.Set(v) - } - dst = dst.Elem() - fallthrough - case reflect.Struct: - srcMap := src.Interface().(map[string]interface{}) - for key := range srcMap { - config.overwriteWithEmptyValue = true - srcValue := srcMap[key] - fieldName := changeInitialCase(key, unicode.ToUpper) - dstElement := dst.FieldByName(fieldName) - if dstElement == zeroValue { - // We discard it because the field doesn't exist. - continue - } - srcElement := reflect.ValueOf(srcValue) - dstKind := dstElement.Kind() - srcKind := srcElement.Kind() - if srcKind == reflect.Ptr && dstKind != reflect.Ptr { - srcElement = srcElement.Elem() - srcKind = reflect.TypeOf(srcElement.Interface()).Kind() - } else if dstKind == reflect.Ptr { - // Can this work? I guess it can't. - if srcKind != reflect.Ptr && srcElement.CanAddr() { - srcPtr := srcElement.Addr() - srcElement = reflect.ValueOf(srcPtr) - srcKind = reflect.Ptr - } - } - - if !srcElement.IsValid() { - continue - } - if srcKind == dstKind { - if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { - return - } - } else if dstKind == reflect.Interface && dstElement.Kind() == reflect.Interface { - if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { - return - } - } else if srcKind == reflect.Map { - if err = deepMap(dstElement, srcElement, visited, depth+1, config); err != nil { - return - } - } else { - return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind) - } - } - } - return -} - -// Map sets fields' values in dst from src. -// src can be a map with string keys or a struct. dst must be the opposite: -// if src is a map, dst must be a valid pointer to struct. If src is a struct, -// dst must be map[string]interface{}. -// It won't merge unexported (private) fields and will do recursively -// any exported field. -// If dst is a map, keys will be src fields' names in lower camel case. -// Missing key in src that doesn't match a field in dst will be skipped. This -// doesn't apply if dst is a map. -// This is separated method from Merge because it is cleaner and it keeps sane -// semantics: merging equal types, mapping different (restricted) types. -func Map(dst, src interface{}, opts ...func(*Config)) error { - return _map(dst, src, opts...) -} - -// MapWithOverwrite will do the same as Map except that non-empty dst attributes will be overridden by -// non-empty src attribute values. -// Deprecated: Use Map(…) with WithOverride -func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { - return _map(dst, src, append(opts, WithOverride)...) -} - -func _map(dst, src interface{}, opts ...func(*Config)) error { - if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { - return ErrNonPointerAgument - } - var ( - vDst, vSrc reflect.Value - err error - ) - config := &Config{} - - for _, opt := range opts { - opt(config) - } - - if vDst, vSrc, err = resolveValues(dst, src); err != nil { - return err - } - // To be friction-less, we redirect equal-type arguments - // to deepMerge. Only because arguments can be anything. - if vSrc.Kind() == vDst.Kind() { - return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) - } - switch vSrc.Kind() { - case reflect.Struct: - if vDst.Kind() != reflect.Map { - return ErrExpectedMapAsDestination - } - case reflect.Map: - if vDst.Kind() != reflect.Struct { - return ErrExpectedStructAsDestination - } - default: - return ErrNotSupported - } - return deepMap(vDst, vSrc, make(map[uintptr]*visit), 0, config) -} diff --git a/vendor/gomodules.xyz/mergo/merge.go b/vendor/gomodules.xyz/mergo/merge.go deleted file mode 100644 index 8b4e2f47..00000000 --- a/vendor/gomodules.xyz/mergo/merge.go +++ /dev/null @@ -1,380 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Based on src/pkg/reflect/deepequal.go from official -// golang's stdlib. - -package mergo - -import ( - "fmt" - "reflect" -) - -func hasMergeableFields(dst reflect.Value) (exported bool) { - for i, n := 0, dst.NumField(); i < n; i++ { - field := dst.Type().Field(i) - if field.Anonymous && dst.Field(i).Kind() == reflect.Struct { - exported = exported || hasMergeableFields(dst.Field(i)) - } else if isExportedComponent(&field) { - exported = exported || len(field.PkgPath) == 0 - } - } - return -} - -func isExportedComponent(field *reflect.StructField) bool { - pkgPath := field.PkgPath - if len(pkgPath) > 0 { - return false - } - c := field.Name[0] - if 'a' <= c && c <= 'z' || c == '_' { - return false - } - return true -} - -type Config struct { - Overwrite bool - AppendSlice bool - TypeCheck bool - Transformers Transformers - overwriteWithEmptyValue bool - overwriteSliceWithEmptyValue bool - sliceDeepCopy bool - debug bool -} - -type Transformers interface { - Transformer(reflect.Type) func(dst, src reflect.Value) error -} - -// Traverses recursively both values, assigning src's fields values to dst. -// The map argument tracks comparisons that have already been seen, which allows -// short circuiting on recursive types. -func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { - overwrite := config.Overwrite - typeCheck := config.TypeCheck - overwriteWithEmptySrc := config.overwriteWithEmptyValue - overwriteSliceWithEmptySrc := config.overwriteSliceWithEmptyValue - sliceDeepCopy := config.sliceDeepCopy - - if !src.IsValid() { - return - } - if dst.CanAddr() { - addr := dst.UnsafeAddr() - h := 17 * addr - seen := visited[h] - typ := dst.Type() - for p := seen; p != nil; p = p.next { - if p.ptr == addr && p.typ == typ { - return nil - } - } - // Remember, remember... - visited[h] = &visit{addr, typ, seen} - } - - if config.Transformers != nil && !isReflectNil(dst) && dst.IsValid() { - if fn := config.Transformers.Transformer(dst.Type()); fn != nil { - err = fn(dst, src) - return - } - } - - switch dst.Kind() { - case reflect.Struct: - if hasMergeableFields(dst) { - for i, n := 0, dst.NumField(); i < n; i++ { - if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, config); err != nil { - return - } - } - } else { - if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) { - dst.Set(src) - } - } - case reflect.Map: - if dst.IsNil() && !src.IsNil() { - if dst.CanSet() { - dst.Set(reflect.MakeMap(dst.Type())) - } else { - dst = src - return - } - } - - if src.Kind() != reflect.Map { - if overwrite { - dst.Set(src) - } - return - } - - for _, key := range src.MapKeys() { - srcElement := src.MapIndex(key) - if !srcElement.IsValid() { - continue - } - dstElement := dst.MapIndex(key) - switch srcElement.Kind() { - case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice: - if srcElement.IsNil() { - if overwrite { - dst.SetMapIndex(key, srcElement) - } - continue - } - fallthrough - default: - if !srcElement.CanInterface() { - continue - } - switch reflect.TypeOf(srcElement.Interface()).Kind() { - case reflect.Struct: - fallthrough - case reflect.Ptr: - fallthrough - case reflect.Map: - srcMapElm := srcElement - dstMapElm := dstElement - if srcMapElm.CanInterface() { - srcMapElm = reflect.ValueOf(srcMapElm.Interface()) - if dstMapElm.IsValid() { - dstMapElm = reflect.ValueOf(dstMapElm.Interface()) - } - } - if err = deepMerge(dstMapElm, srcMapElm, visited, depth+1, config); err != nil { - return - } - case reflect.Slice: - srcSlice := reflect.ValueOf(srcElement.Interface()) - - var dstSlice reflect.Value - if !dstElement.IsValid() || dstElement.IsNil() { - dstSlice = reflect.MakeSlice(srcSlice.Type(), 0, srcSlice.Len()) - } else { - dstSlice = reflect.ValueOf(dstElement.Interface()) - } - - if (!isEmptyValue(src) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice && !sliceDeepCopy { - if typeCheck && srcSlice.Type() != dstSlice.Type() { - return fmt.Errorf("cannot override two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) - } - dstSlice = srcSlice - } else if config.AppendSlice { - if srcSlice.Type() != dstSlice.Type() { - return fmt.Errorf("cannot append two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) - } - dstSlice = reflect.AppendSlice(dstSlice, srcSlice) - } else if sliceDeepCopy { - i := 0 - for ; i < srcSlice.Len() && i < dstSlice.Len(); i++ { - srcElement := srcSlice.Index(i) - dstElement := dstSlice.Index(i) - - if srcElement.CanInterface() { - srcElement = reflect.ValueOf(srcElement.Interface()) - } - if dstElement.CanInterface() { - dstElement = reflect.ValueOf(dstElement.Interface()) - } - - if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { - return - } - } - - } - dst.SetMapIndex(key, dstSlice) - } - } - if dstElement.IsValid() && !isEmptyValue(dstElement) && (reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map || reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice) { - continue - } - - if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement)) { - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - dst.SetMapIndex(key, srcElement) - } - } - case reflect.Slice: - if !dst.CanSet() { - break - } - if (!isEmptyValue(src) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice && !sliceDeepCopy { - dst.Set(src) - } else if config.AppendSlice { - if src.Type() != dst.Type() { - return fmt.Errorf("cannot append two slice with different type (%s, %s)", src.Type(), dst.Type()) - } - dst.Set(reflect.AppendSlice(dst, src)) - } else if sliceDeepCopy { - for i := 0; i < src.Len() && i < dst.Len(); i++ { - srcElement := src.Index(i) - dstElement := dst.Index(i) - if srcElement.CanInterface() { - srcElement = reflect.ValueOf(srcElement.Interface()) - } - if dstElement.CanInterface() { - dstElement = reflect.ValueOf(dstElement.Interface()) - } - - if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { - return - } - } - } - case reflect.Ptr: - fallthrough - case reflect.Interface: - if isReflectNil(src) { - if overwriteWithEmptySrc && dst.CanSet() && src.Type().AssignableTo(dst.Type()) { - dst.Set(src) - } - break - } - - if src.Kind() != reflect.Interface { - if dst.IsNil() || (src.Kind() != reflect.Ptr && overwrite) { - if dst.CanSet() && (overwrite || isEmptyValue(dst)) { - dst.Set(src) - } - } else if src.Kind() == reflect.Ptr { - if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { - return - } - } else if dst.Elem().Type() == src.Type() { - if err = deepMerge(dst.Elem(), src, visited, depth+1, config); err != nil { - return - } - } else { - return ErrDifferentArgumentsTypes - } - break - } - - if dst.IsNil() || overwrite { - if dst.CanSet() && (overwrite || isEmptyValue(dst)) { - dst.Set(src) - } - break - } - - if dst.Elem().Kind() == src.Elem().Kind() { - if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { - return - } - break - } - default: - mustSet := (isEmptyValue(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) - if mustSet { - if dst.CanSet() { - dst.Set(src) - } else { - dst = src - } - } - } - - return -} - -// Merge will fill any empty for value type attributes on the dst struct using corresponding -// src attributes if they themselves are not empty. dst and src must be valid same-type structs -// and dst must be a pointer to struct. -// It won't merge unexported (private) fields and will do recursively any exported field. -func Merge(dst, src interface{}, opts ...func(*Config)) error { - return merge(dst, src, opts...) -} - -// MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overridden by -// non-empty src attribute values. -// Deprecated: use Merge(…) with WithOverride -func MergeWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { - return merge(dst, src, append(opts, WithOverride)...) -} - -// WithTransformers adds transformers to merge, allowing to customize the merging of some types. -func WithTransformers(transformers Transformers) func(*Config) { - return func(config *Config) { - config.Transformers = transformers - } -} - -// WithOverride will make merge override non-empty dst attributes with non-empty src attributes values. -func WithOverride(config *Config) { - config.Overwrite = true -} - -// WithOverwriteWithEmptyValue will make merge override non empty dst attributes with empty src attributes values. -func WithOverwriteWithEmptyValue(config *Config) { - config.Overwrite = true - config.overwriteWithEmptyValue = true -} - -// WithOverrideEmptySlice will make merge override empty dst slice with empty src slice. -func WithOverrideEmptySlice(config *Config) { - config.overwriteSliceWithEmptyValue = true -} - -// WithAppendSlice will make merge append slices instead of overwriting it. -func WithAppendSlice(config *Config) { - config.AppendSlice = true -} - -// WithTypeCheck will make merge check types while overwriting it (must be used with WithOverride). -func WithTypeCheck(config *Config) { - config.TypeCheck = true -} - -// WithSliceDeepCopy will merge slice element one by one with Overwrite flag. -func WithSliceDeepCopy(config *Config) { - config.sliceDeepCopy = true - config.Overwrite = true -} - -func merge(dst, src interface{}, opts ...func(*Config)) error { - if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { - return ErrNonPointerAgument - } - var ( - vDst, vSrc reflect.Value - err error - ) - - config := &Config{} - - for _, opt := range opts { - opt(config) - } - - if vDst, vSrc, err = resolveValues(dst, src); err != nil { - return err - } - if vDst.Type() != vSrc.Type() { - return ErrDifferentArgumentsTypes - } - return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) -} - -// IsReflectNil is the reflect value provided nil -func isReflectNil(v reflect.Value) bool { - k := v.Kind() - switch k { - case reflect.Interface, reflect.Slice, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr: - // Both interface and slice are nil if first word is 0. - // Both are always bigger than a word; assume flagIndir. - return v.IsNil() - default: - return false - } -} diff --git a/vendor/gomodules.xyz/mergo/mergo.go b/vendor/gomodules.xyz/mergo/mergo.go deleted file mode 100644 index 9fe362d4..00000000 --- a/vendor/gomodules.xyz/mergo/mergo.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Based on src/pkg/reflect/deepequal.go from official -// golang's stdlib. - -package mergo - -import ( - "errors" - "reflect" -) - -// Errors reported by Mergo when it finds invalid arguments. -var ( - ErrNilArguments = errors.New("src and dst must not be nil") - ErrDifferentArgumentsTypes = errors.New("src and dst must be of same type") - ErrNotSupported = errors.New("only structs, maps, and slices are supported") - ErrExpectedMapAsDestination = errors.New("dst was expected to be a map") - ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct") - ErrNonPointerAgument = errors.New("dst must be a pointer") -) - -// During deepMerge, must keep track of checks that are -// in progress. The comparison algorithm assumes that all -// checks in progress are true when it reencounters them. -// Visited are stored in a map indexed by 17 * a1 + a2; -type visit struct { - ptr uintptr - typ reflect.Type - next *visit -} - -// From src/pkg/encoding/json/encode.go. -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - if v.IsNil() { - return true - } - return isEmptyValue(v.Elem()) - case reflect.Func: - return v.IsNil() - case reflect.Invalid: - return true - } - return false -} - -func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) { - if dst == nil || src == nil { - err = ErrNilArguments - return - } - vDst = reflect.ValueOf(dst).Elem() - if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map && vDst.Kind() != reflect.Slice { - err = ErrNotSupported - return - } - vSrc = reflect.ValueOf(src) - // We check if vSrc is a pointer to dereference it. - if vSrc.Kind() == reflect.Ptr { - vSrc = vSrc.Elem() - } - return -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/configmap.go b/vendor/kmodules.xyz/client-go/core/v1/configmap.go deleted file mode 100644 index a354b82a..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/configmap.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - "github.com/pkg/errors" - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchConfigMap(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.ConfigMap) *core.ConfigMap, opts metav1.PatchOptions) (*core.ConfigMap, kutil.VerbType, error) { - cur, err := c.CoreV1().ConfigMaps(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating ConfigMap %s/%s.", meta.Namespace, meta.Name) - out, err := c.CoreV1().ConfigMaps(meta.Namespace).Create(ctx, transform(&core.ConfigMap{ - TypeMeta: metav1.TypeMeta{ - Kind: "ConfigMap", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - return PatchConfigMap(ctx, c, cur, transform, opts) -} - -func PatchConfigMap(ctx context.Context, c kubernetes.Interface, cur *core.ConfigMap, transform func(*core.ConfigMap) *core.ConfigMap, opts metav1.PatchOptions) (*core.ConfigMap, kutil.VerbType, error) { - return PatchConfigMapObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchConfigMapObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.ConfigMap, opts metav1.PatchOptions) (*core.ConfigMap, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.ConfigMap{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching ConfigMap %s/%s with %s", cur.Namespace, cur.Name, string(patch)) - out, err := c.CoreV1().ConfigMaps(cur.Namespace).Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} - -func TryUpdateConfigMap(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.ConfigMap) *core.ConfigMap, opts metav1.UpdateOptions) (result *core.ConfigMap, err error) { - attempt := 0 - err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) { - attempt++ - cur, e2 := c.CoreV1().ConfigMaps(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(e2) { - return false, e2 - } else if e2 == nil { - result, e2 = c.CoreV1().ConfigMaps(cur.Namespace).Update(ctx, transform(cur.DeepCopy()), opts) - return e2 == nil, nil - } - klog.Errorf("Attempt %d failed to update ConfigMap %s/%s due to %v.", attempt, cur.Namespace, cur.Name, e2) - return false, nil - }) - - if err != nil { - err = errors.Errorf("failed to update ConfigMap %s/%s after %d attempts due to %v", meta.Namespace, meta.Name, attempt, err) - } - return -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/endpoints.go b/vendor/kmodules.xyz/client-go/core/v1/endpoints.go deleted file mode 100644 index 32ef8832..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/endpoints.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchEndpoints(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Endpoints) *core.Endpoints, opts metav1.PatchOptions) (*core.Endpoints, kutil.VerbType, error) { - cur, err := c.CoreV1().Endpoints(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating Endpoints %s/%s.", meta.Namespace, meta.Name) - out, err := c.CoreV1().Endpoints(meta.Namespace).Create(ctx, transform(&core.Endpoints{ - TypeMeta: metav1.TypeMeta{ - Kind: "Endpoints", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - return PatchEndpoints(ctx, c, cur, transform, opts) -} - -func PatchEndpoints(ctx context.Context, c kubernetes.Interface, cur *core.Endpoints, transform func(*core.Endpoints) *core.Endpoints, opts metav1.PatchOptions) (*core.Endpoints, kutil.VerbType, error) { - return PatchEndpointsObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchEndpointsObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.Endpoints, opts metav1.PatchOptions) (*core.Endpoints, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.Endpoints{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching Endpoints %s/%s with %s.", cur.Namespace, cur.Name, string(patch)) - out, err := c.CoreV1().Endpoints(cur.Namespace).Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/events.go b/vendor/kmodules.xyz/client-go/core/v1/events.go deleted file mode 100644 index 31e3ea40..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/events.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - "github.com/pkg/errors" - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchEvent(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Event) *core.Event, opts metav1.PatchOptions) (*core.Event, kutil.VerbType, error) { - cur, err := c.CoreV1().Events(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating Event %s/%s.", meta.Namespace, meta.Name) - out, err := c.CoreV1().Events(meta.Namespace).Create(ctx, transform(&core.Event{ - TypeMeta: metav1.TypeMeta{ - Kind: "Event", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - return PatchEvent(ctx, c, cur, transform, opts) -} - -func PatchEvent(ctx context.Context, c kubernetes.Interface, cur *core.Event, transform func(*core.Event) *core.Event, opts metav1.PatchOptions) (*core.Event, kutil.VerbType, error) { - return PatchEventObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchEventObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.Event, opts metav1.PatchOptions) (*core.Event, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.Event{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching Event %s/%s with %s", cur.Namespace, cur.Name, string(patch)) - out, err := c.CoreV1().Events(cur.Namespace).Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} - -func TryUpdateEvent(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Event) *core.Event, opts metav1.UpdateOptions) (result *core.Event, err error) { - attempt := 0 - err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) { - attempt++ - cur, e2 := c.CoreV1().Events(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(e2) { - return false, e2 - } else if e2 == nil { - result, e2 = c.CoreV1().Events(cur.Namespace).Update(ctx, transform(cur.DeepCopy()), opts) - return e2 == nil, nil - } - klog.Errorf("Attempt %d failed to update Event %s/%s due to %v.", attempt, cur.Namespace, cur.Name, e2) - return false, nil - }) - - if err != nil { - err = errors.Errorf("failed to update Event %s/%s after %d attempts due to %v", meta.Namespace, meta.Name, attempt, err) - } - return -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/kubernetes.go b/vendor/kmodules.xyz/client-go/core/v1/kubernetes.go deleted file mode 100644 index d53222dd..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/kubernetes.go +++ /dev/null @@ -1,513 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "sort" - - "kmodules.xyz/client-go/meta" - - jsoniter "github.com/json-iterator/go" - "gomodules.xyz/mergo" - core "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -var json = jsoniter.ConfigFastest - -func AddFinalizer(m metav1.ObjectMeta, finalizer string) metav1.ObjectMeta { - for _, name := range m.Finalizers { - if name == finalizer { - return m - } - } - m.Finalizers = append(m.Finalizers, finalizer) - return m -} - -func HasFinalizer(m metav1.ObjectMeta, finalizer string) bool { - for _, name := range m.Finalizers { - if name == finalizer { - return true - } - } - return false -} - -func RemoveFinalizer(m metav1.ObjectMeta, finalizer string) metav1.ObjectMeta { - // https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating - r := m.Finalizers[:0] - for _, name := range m.Finalizers { - if name != finalizer { - r = append(r, name) - } - } - m.Finalizers = r - return m -} - -func EnsureContainerDeleted(containers []core.Container, name string) []core.Container { - for i, c := range containers { - if c.Name == name { - return append(containers[:i], containers[i+1:]...) - } - } - return containers -} - -func GetContainerByName(containers []core.Container, name string) *core.Container { - for i := range containers { - if containers[i].Name == name { - return &containers[i] - } - } - return nil -} - -func UpsertContainer(containers []core.Container, upsert core.Container) []core.Container { - for i, container := range containers { - if container.Name == upsert.Name { - err := mergo.Merge(&container, upsert, mergo.WithOverride) - if err != nil { - panic(err) - } - // mergo does not overwrite "dst (container)" using empty "src (upsert)" values. - // This causes problem we want to remove args or commands (eg, disable TLS). - // TODO: should this be done for all the []string type fields (eg, EnvFrom etc.)? - container.Command = upsert.Command - container.Args = upsert.Args - for i, env := range upsert.Env { - if env.ValueFrom != nil && - env.ValueFrom.FieldRef != nil && - env.ValueFrom.FieldRef.APIVersion == "" { - env.ValueFrom.FieldRef.APIVersion = "v1" - } - upsert.Env[i] = env - } - container.Env = upsert.Env - container.VolumeMounts = upsert.VolumeMounts - container.VolumeDevices = upsert.VolumeDevices - container.Resources = upsert.Resources - containers[i] = container - return containers - } - } - return append(containers, upsert) -} - -func MergeContainer(container core.Container, containerTemplate core.Container) core.Container { - if len(containerTemplate.Command) > 0 { - container.Command = containerTemplate.Command - } - container.Args = meta.UpsertArgumentList(container.Args, containerTemplate.Args) - container.WorkingDir = containerTemplate.WorkingDir - container.EnvFrom = containerTemplate.EnvFrom - container.Env = UpsertEnvVars(container.Env, containerTemplate.Env...) - container.Ports = UpsertContainerPorts(container.Ports, containerTemplate.Ports...) - container.Resources = containerTemplate.Resources - container.ResizePolicy = containerTemplate.ResizePolicy - container.RestartPolicy = containerTemplate.RestartPolicy - container.VolumeMounts = UpsertVolumeMount(container.VolumeMounts, containerTemplate.VolumeMounts...) - container.VolumeDevices = containerTemplate.VolumeDevices - container.LivenessProbe = containerTemplate.LivenessProbe - container.ReadinessProbe = containerTemplate.ReadinessProbe - container.StartupProbe = containerTemplate.StartupProbe - container.Lifecycle = containerTemplate.Lifecycle - container.TerminationMessagePath = containerTemplate.TerminationMessagePath - container.TerminationMessagePolicy = containerTemplate.TerminationMessagePolicy - container.ImagePullPolicy = containerTemplate.ImagePullPolicy - container.SecurityContext = containerTemplate.SecurityContext - container.StdinOnce = containerTemplate.StdinOnce - container.TTY = containerTemplate.TTY - return container -} - -func UpsertContainers(containers []core.Container, addons []core.Container) []core.Container { - out := containers - for _, c := range addons { - out = UpsertContainer(out, c) - } - return out -} - -func DeleteContainer(containers []core.Container, name string) []core.Container { - for i, v := range containers { - if v.Name == name { - return append(containers[:i], containers[i+1:]...) - } - } - return containers -} - -func GetVolumeByName(volumes []core.Volume, name string) *core.Volume { - for i := range volumes { - if volumes[i].Name == name { - return &volumes[i] - } - } - return nil -} - -func UpsertVolume(volumes []core.Volume, nv ...core.Volume) []core.Volume { - upsert := func(v core.Volume) { - for i, vol := range volumes { - if vol.Name == v.Name { - err := mergo.Merge(&volumes[i], v, mergo.WithOverride) - if err != nil { - panic(err) - } - return - } - } - volumes = append(volumes, v) - } - - for _, volume := range nv { - upsert(volume) - } - return volumes -} - -func ReplaceVolumes(existing []core.Volume, desired ...core.Volume) ([]core.Volume, error) { - merge := func(cur core.Volume) error { - for i, v := range desired { - if v.Name == cur.Name { - if err := mergo.Merge(&cur, v, mergo.WithOverride); err != nil { - return err - } - desired[i] = cur - break - } - } - return nil - } - - for _, cur := range existing { - if err := merge(cur); err != nil { - return nil, err - } - } - sort.Slice(desired, func(i, j int) bool { - return desired[i].Name < desired[j].Name - }) - return desired, nil -} - -func MustReplaceVolumes(existing []core.Volume, desired ...core.Volume) []core.Volume { - result, err := ReplaceVolumes(existing, desired...) - if err != nil { - panic(err) - } - return result -} - -func UpsertVolumeClaim(volumeClaims []core.PersistentVolumeClaim, upsert core.PersistentVolumeClaim) []core.PersistentVolumeClaim { - for i, vc := range volumeClaims { - if vc.Name == upsert.Name { - volumeClaims[i].Labels = upsert.Labels - volumeClaims[i].Annotations = upsert.Annotations - if err := mergo.Merge(&volumeClaims[i].Spec, upsert.Spec, mergo.WithOverride); err != nil { - panic(err) - } - return volumeClaims - } - } - return append(volumeClaims, upsert) -} - -func EnsureVolumeDeleted(volumes []core.Volume, name string) []core.Volume { - for i, v := range volumes { - if v.Name == name { - return append(volumes[:i], volumes[i+1:]...) - } - } - return volumes -} - -func GetVolumeMountByName(volumeMounts []core.VolumeMount, name string) *core.VolumeMount { - for i := range volumeMounts { - if volumeMounts[i].Name == name { - return &volumeMounts[i] - } - } - return nil -} - -func UpsertVolumeMount(mounts []core.VolumeMount, nv ...core.VolumeMount) []core.VolumeMount { - upsert := func(m core.VolumeMount) { - for i, vol := range mounts { - if vol.Name == m.Name { - mounts[i] = m - return - } - } - mounts = append(mounts, m) - } - - for _, mount := range nv { - upsert(mount) - } - return mounts -} - -func EnsureVolumeMountDeleted(mounts []core.VolumeMount, name string) []core.VolumeMount { - for i, v := range mounts { - if v.Name == name { - return append(mounts[:i], mounts[i+1:]...) - } - } - return mounts -} - -func UpsertVolumeMountByPath(mounts []core.VolumeMount, nv core.VolumeMount) []core.VolumeMount { - for i, vol := range mounts { - if vol.MountPath == nv.MountPath { - mounts[i] = nv - return mounts - } - } - return append(mounts, nv) -} - -func EnsureVolumeMountDeletedByPath(mounts []core.VolumeMount, mountPath string) []core.VolumeMount { - for i, v := range mounts { - if v.MountPath == mountPath { - return append(mounts[:i], mounts[i+1:]...) - } - } - return mounts -} - -func UpsertContainerPorts(ports []core.ContainerPort, np ...core.ContainerPort) []core.ContainerPort { - upsert := func(p core.ContainerPort) { - for i, port := range ports { - if port.Name == p.Name { - err := mergo.Merge(&ports[i], p, mergo.WithOverride) - if err != nil { - panic(err) - } - return - } - } - ports = append(ports, p) - } - - for _, port := range np { - upsert(port) - } - return ports -} - -func GetEnvByName(envs []core.EnvVar, name string) *core.EnvVar { - for i := range envs { - if envs[i].Name == name { - return &envs[i] - } - } - return nil -} - -func UpsertEnvVars(vars []core.EnvVar, nv ...core.EnvVar) []core.EnvVar { - upsert := func(env core.EnvVar) { - if env.ValueFrom != nil && - env.ValueFrom.FieldRef != nil && - env.ValueFrom.FieldRef.APIVersion == "" { - env.ValueFrom.FieldRef.APIVersion = "v1" - } - - for i, v := range vars { - if v.Name == env.Name { - vars[i] = env - return - } - } - vars = append(vars, env) - } - - for _, env := range nv { - upsert(env) - } - return vars -} - -func EnsureEnvVarDeleted(vars []core.EnvVar, name string) []core.EnvVar { - for i, v := range vars { - if v.Name == name { - return append(vars[:i], vars[i+1:]...) - } - } - return vars -} - -func MergeLocalObjectReferences(l1, l2 []core.LocalObjectReference) []core.LocalObjectReference { - result := make([]core.LocalObjectReference, 0, len(l1)+len(l2)) - m := make(map[string]core.LocalObjectReference) - for _, ref := range l1 { - m[ref.Name] = ref - result = append(result, ref) - } - for _, ref := range l2 { - if _, found := m[ref.Name]; !found { - result = append(result, ref) - } - } - sort.Slice(result, func(i, j int) bool { return result[i].Name < result[j].Name }) - return result -} - -// NewOwnerRef creates an OwnerReference pointing to the given owner. -func NewOwnerRef(owner metav1.Object, gvk schema.GroupVersionKind) *metav1.OwnerReference { - blockOwnerDeletion := false - isController := false - return &metav1.OwnerReference{ - APIVersion: gvk.GroupVersion().String(), - Kind: gvk.Kind, - Name: owner.GetName(), - UID: owner.GetUID(), - BlockOwnerDeletion: &blockOwnerDeletion, - Controller: &isController, - } -} - -// EnsureOwnerReference adds owner if absent or syncs owner if already present. -// -// If you are writing a controller or an operator, use the following code snippet for dependent objects. -// Here, `controller = true` and `blockOwnerDeletion = true` -// -// owner := metav1.NewControllerRef(foo, samplev1alpha1.SchemeGroupVersion.WithKind("Foo")) -// EnsureOwnerReference(dependent, owner) -// -// If our CRD is not a controller but just want to be a owner, use the following code snippet. -// Here, `controller = false` and `blockOwnerDeletion = false` -// -// owner := NewOwnerRef(foo, samplev1alpha1.SchemeGroupVersion.WithKind("Foo")) -// EnsureOwnerReference(dependent, owner) -// -// To understand the impact of `blockOwnerDeletion`, read: -// - https://kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/#foreground-cascading-deletion -// - https://github.com/kubernetes/apimachinery/blob/v0.17.0/pkg/apis/meta/v1/types.go#L297-L323 -func EnsureOwnerReference(dependent metav1.Object, owner *metav1.OwnerReference) { - if owner == nil { - return - } - - refs := dependent.GetOwnerReferences() - - fi := -1 - for i := range refs { - if refs[i].UID == owner.UID { - fi = i - break - } - } - if fi == -1 { - refs = append(refs, *owner) - } else { - refs[fi] = *owner - } - - dependent.SetOwnerReferences(refs) -} - -func RemoveOwnerReference(dependent metav1.Object, owner metav1.Object) { - refs := dependent.GetOwnerReferences() - for i := range refs { - if refs[i].UID == owner.GetUID() { - refs = append(refs[:i], refs[i+1:]...) - break - } - } - dependent.SetOwnerReferences(refs) -} - -// IsOwnedBy checks if the dependent has a owner reference to the given owner -func IsOwnedBy(dependent metav1.Object, owner metav1.Object) (owned bool, controller bool) { - refs := dependent.GetOwnerReferences() - for i := range refs { - if refs[i].UID == owner.GetUID() { - return true, refs[i].Controller != nil && *refs[i].Controller - } - } - return false, false -} - -func IsOwnerOfGroup(ctrl *metav1.OwnerReference, group string) (bool, string, error) { - if ctrl == nil { - return false, "", nil - } - gv, err := schema.ParseGroupVersion(ctrl.APIVersion) - if err != nil { - return false, "", err - } - if gv.Group != group { - return false, "", nil - } - return true, ctrl.Kind, nil -} - -func IsOwnerOfGroupKind(ctrl *metav1.OwnerReference, group, kind string) (bool, error) { - if ctrl == nil { - return false, nil - } - gv, err := schema.ParseGroupVersion(ctrl.APIVersion) - if err != nil { - return false, err - } - if gv.Group != group { - return false, nil - } - if ctrl.Kind != kind { - return false, nil - } - return true, nil -} - -func UpsertToleration(tolerations []core.Toleration, upsert core.Toleration) []core.Toleration { - for i, toleration := range tolerations { - if toleration.Key == upsert.Key { - tolerations[i] = upsert - return tolerations - } - } - return append(tolerations, upsert) -} - -func RemoveToleration(tolerations []core.Toleration, key string) []core.Toleration { - for i, toleration := range tolerations { - if toleration.Key == key { - return append(tolerations[:i], tolerations[i+1:]...) - } - } - return tolerations -} - -func UpsertImagePullSecrets(refs []core.LocalObjectReference, upsert ...core.LocalObjectReference) []core.LocalObjectReference { - for i := range upsert { - var found bool - for j := range refs { - if refs[j].Name == upsert[i].Name { - found = true - break - } - } - if !found { - refs = append(refs, upsert[i]) - } - } - return refs -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/node.go b/vendor/kmodules.xyz/client-go/core/v1/node.go deleted file mode 100644 index 7282a20d..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/node.go +++ /dev/null @@ -1,287 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - meta_util "kmodules.xyz/client-go/meta" - - "github.com/pkg/errors" - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - "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/util/sets" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/metadata" - "k8s.io/client-go/tools/pager" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchNode(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Node) *core.Node, opts metav1.PatchOptions) (*core.Node, kutil.VerbType, error) { - cur, err := c.CoreV1().Nodes().Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating Node %s", meta.Name) - out, err := c.CoreV1().Nodes().Create(ctx, transform(&core.Node{ - TypeMeta: metav1.TypeMeta{ - Kind: "Node", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - return PatchNode(ctx, c, cur, transform, opts) -} - -func PatchNode(ctx context.Context, c kubernetes.Interface, cur *core.Node, transform func(*core.Node) *core.Node, opts metav1.PatchOptions) (*core.Node, kutil.VerbType, error) { - return PatchNodeObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchNodeObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.Node, opts metav1.PatchOptions) (*core.Node, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.Node{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching Node %s with %s", cur.Name, string(patch)) - out, err := c.CoreV1().Nodes().Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} - -func TryUpdateNode(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Node) *core.Node, opts metav1.UpdateOptions) (result *core.Node, err error) { - attempt := 0 - err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) { - attempt++ - cur, e2 := c.CoreV1().Nodes().Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(e2) { - return false, e2 - } else if e2 == nil { - result, e2 = c.CoreV1().Nodes().Update(ctx, transform(cur.DeepCopy()), opts) - return e2 == nil, nil - } - klog.Errorf("Attempt %d failed to update Node %s due to %v.", attempt, cur.Name, e2) - return false, nil - }) - - if err != nil { - err = errors.Errorf("failed to update Node %s after %d attempts due to %v", meta.Name, attempt, err) - } - return -} - -// NodeReady returns whether a node is ready. -func NodeReady(node core.Node) bool { - for _, cond := range node.Status.Conditions { - if cond.Type != core.NodeReady { - continue - } - return cond.Status == core.ConditionTrue - } - return false -} - -// IsMaster returns whether a node is a master. -func IsMaster(node core.Node) bool { - _, ok17 := node.Labels["node-role.kubernetes.io/master"] - role16, ok16 := node.Labels["kubernetes.io/role"] - return ok17 || (ok16 && role16 == "master") -} - -type Topology struct { - Regions map[string][]string - TotalNodes int - InstanceTypes map[string]int - - LabelZone string - LabelRegion string - LabelInstanceType string - - // https://github.com/kubernetes/kubernetes/blob/v1.17.2/staging/src/k8s.io/api/core/v1/well_known_labels.go - - //LabelHostname = "kubernetes.io/hostname" - // - //LabelZoneFailureDomain = "failure-domain.beta.kubernetes.io/zone" - //LabelZoneRegion = "failure-domain.beta.kubernetes.io/region" - //LabelZoneFailureDomainStable = "topology.kubernetes.io/zone" - //LabelZoneRegionStable = "topology.kubernetes.io/region" - // - //LabelInstanceType = "beta.kubernetes.io/instance-type" - //LabelInstanceTypeStable = "node.kubernetes.io/instance-type" -} - -func (t Topology) ConvertAffinity(affinity *core.Affinity) { - if affinity == nil { - return - } - - if affinity.PodAffinity != nil { - t.convertPodAffinityTerm(affinity.PodAffinity.RequiredDuringSchedulingIgnoredDuringExecution) - t.convertWeightedPodAffinityTerm(affinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution) - } - - if affinity.PodAntiAffinity != nil { - t.convertPodAffinityTerm(affinity.PodAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution) - t.convertWeightedPodAffinityTerm(affinity.PodAntiAffinity.PreferredDuringSchedulingIgnoredDuringExecution) - } -} - -func isZoneKey(key string) bool { - return key == core.LabelZoneFailureDomain || key == "topology.kubernetes.io/zone" -} - -func isRegionKey(key string) bool { - return key == core.LabelZoneRegion || key == "topology.kubernetes.io/region" -} - -func isInstanceTypeKey(key string) bool { - return key == core.LabelInstanceType || key == "node.kubernetes.io/instance-type" -} - -func (t Topology) convertPodAffinityTerm(terms []core.PodAffinityTerm) { - for i := range terms { - if isZoneKey(terms[i].TopologyKey) { - terms[i].TopologyKey = t.LabelZone - } else if isRegionKey(terms[i].TopologyKey) { - terms[i].TopologyKey = t.LabelRegion - } else if isInstanceTypeKey(terms[i].TopologyKey) { - terms[i].TopologyKey = t.LabelInstanceType - } - } -} - -func (t Topology) convertWeightedPodAffinityTerm(terms []core.WeightedPodAffinityTerm) { - for i := range terms { - if isZoneKey(terms[i].PodAffinityTerm.TopologyKey) { - terms[i].PodAffinityTerm.TopologyKey = t.LabelZone - } else if isRegionKey(terms[i].PodAffinityTerm.TopologyKey) { - terms[i].PodAffinityTerm.TopologyKey = t.LabelRegion - } else if isInstanceTypeKey(terms[i].PodAffinityTerm.TopologyKey) { - terms[i].PodAffinityTerm.TopologyKey = t.LabelInstanceType - } - } -} - -func DetectTopology(ctx context.Context, mc metadata.Interface) (*Topology, error) { - var topology Topology - topology.TotalNodes = 0 - - mapRegion := make(map[string]sets.Set[string]) - instances := make(map[string]int) - first := true - - nc := mc.Resource(schema.GroupVersionResource{ - Version: "v1", - Resource: "nodes", - }) - lister := pager.New(pager.SimplePageFunc(func(opts metav1.ListOptions) (runtime.Object, error) { - return nc.List(ctx, opts) - })) - err := lister.EachListItem(context.Background(), metav1.ListOptions{}, func(obj runtime.Object) error { - topology.TotalNodes++ - - m, err := meta.Accessor(obj) - if err != nil { - return err - } - - labels := m.GetLabels() - - if first { - if _, ok := labels[core.LabelZoneRegionStable]; ok { - topology.LabelRegion = core.LabelZoneRegionStable - } else { - topology.LabelRegion = core.LabelZoneRegion - } - - if _, ok := labels[core.LabelZoneFailureDomainStable]; ok { - topology.LabelZone = core.LabelZoneFailureDomainStable - } else { - topology.LabelZone = core.LabelZoneFailureDomain - } - - if _, ok := labels[core.LabelInstanceTypeStable]; ok { - topology.LabelInstanceType = core.LabelInstanceTypeStable - } else { - topology.LabelInstanceType = core.LabelInstanceType - } - - first = false - } - - os, _ := meta_util.GetStringValueForKeys(labels, core.LabelOSStable, "beta.kubernetes.io/os") - if os != "linux" { - return nil - } - arch, _ := meta_util.GetStringValueForKeys(labels, core.LabelArchStable, "beta.kubernetes.io/arch") - if arch != "amd64" { - return nil - } - - region, _ := meta_util.GetStringValueForKeys(labels, topology.LabelRegion) - zone, _ := meta_util.GetStringValueForKeys(labels, topology.LabelZone) - if _, ok := mapRegion[region]; !ok { - mapRegion[region] = sets.Set[string]{} - } - mapRegion[region].Insert(zone) - - instance, _ := meta_util.GetStringValueForKeys(labels, topology.LabelInstanceType) - if n, ok := instances[instance]; ok { - instances[instance] = n + 1 - } else { - instances[instance] = 1 - } - - return nil - }) - if err != nil { - return nil, err - } - - regions := make(map[string][]string) - for k, v := range mapRegion { - regions[k] = sets.List(v) - } - topology.Regions = regions - topology.InstanceTypes = instances - - return &topology, nil -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/pod.go b/vendor/kmodules.xyz/client-go/core/v1/pod.go deleted file mode 100644 index df808928..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/pod.go +++ /dev/null @@ -1,210 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - "github.com/pkg/errors" - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchPod(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Pod) *core.Pod, opts metav1.PatchOptions) (*core.Pod, kutil.VerbType, error) { - cur, err := c.CoreV1().Pods(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating Pod %s/%s.", meta.Namespace, meta.Name) - out, err := c.CoreV1().Pods(meta.Namespace).Create(ctx, transform(&core.Pod{ - TypeMeta: metav1.TypeMeta{ - Kind: "Pod", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - return PatchPod(ctx, c, cur, transform, opts) -} - -func PatchPod(ctx context.Context, c kubernetes.Interface, cur *core.Pod, transform func(*core.Pod) *core.Pod, opts metav1.PatchOptions) (*core.Pod, kutil.VerbType, error) { - return PatchPodObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchPodObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.Pod, opts metav1.PatchOptions) (*core.Pod, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.Pod{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching Pod %s/%s with %s", cur.Namespace, cur.Name, string(patch)) - out, err := c.CoreV1().Pods(cur.Namespace).Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} - -func TryUpdatePod(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Pod) *core.Pod, opts metav1.UpdateOptions) (result *core.Pod, err error) { - attempt := 0 - err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) { - attempt++ - cur, e2 := c.CoreV1().Pods(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(e2) { - return false, e2 - } else if e2 == nil { - result, e2 = c.CoreV1().Pods(cur.Namespace).Update(ctx, transform(cur.DeepCopy()), opts) - return e2 == nil, nil - } - klog.Errorf("Attempt %d failed to update Pod %s/%s due to %v.", attempt, cur.Namespace, cur.Name, e2) - return false, nil - }) - - if err != nil { - err = errors.Errorf("failed to update Pod %s/%s after %d attempts due to %v", meta.Namespace, meta.Name, attempt, err) - } - return -} - -// IsPodReady returns true if a pod is ready considering readiness gates; false otherwise. -func IsPodReady(pod *core.Pod) bool { - conditions := []core.PodConditionType{ - core.PodReady, - } - for _, gate := range pod.Spec.ReadinessGates { - conditions = append(conditions, gate.ConditionType) - } - - for _, condition := range conditions { - if !IsPodConditionTrue(pod.Status.Conditions, condition) { - return false - } - } - return true -} - -// ref: https://github.com/coreos/prometheus-operator/blob/c79166fcff3dae7bb8bc1e6bddc81837c2d97c04/pkg/k8sutil/k8sutil.go#L64 -// PodRunningAndReady returns whether a pod is running and each container has -// passed it's ready state. -func PodRunningAndReady(pod core.Pod) (bool, error) { - switch pod.Status.Phase { - case core.PodFailed, core.PodSucceeded: - return false, errors.New("pod completed") - case core.PodRunning: - if IsPodReady(&pod) { - return true, nil - } - return false, errors.New("pod ready condition not found") - } - return false, nil -} - -func RestartPods(ctx context.Context, c kubernetes.Interface, namespace string, selector *metav1.LabelSelector) error { - r, err := metav1.LabelSelectorAsSelector(selector) - if err != nil { - return err - } - return c.CoreV1().Pods(namespace).DeleteCollection(ctx, metav1.DeleteOptions{}, metav1.ListOptions{ - LabelSelector: r.String(), - }) -} - -func WaitUntilPodRunning(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta) error { - return wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.ReadinessTimeout, true, func(ctx context.Context) (bool, error) { - if pod, err := c.CoreV1().Pods(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}); err == nil { - runningAndReady, _ := PodRunningAndReady(*pod) - return runningAndReady, nil - } - return false, nil - }) -} - -func WaitUntilPodRunningBySelector(ctx context.Context, c kubernetes.Interface, namespace string, selector *metav1.LabelSelector, count int) error { - r, err := metav1.LabelSelectorAsSelector(selector) - if err != nil { - return err - } - - return wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.ReadinessTimeout, true, func(ctx context.Context) (bool, error) { - podList, err := c.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{ - LabelSelector: r.String(), - }) - if err != nil { - return false, nil - } - - if len(podList.Items) != count { - return false, nil - } - - for _, pod := range podList.Items { - runningAndReady, _ := PodRunningAndReady(pod) - if !runningAndReady { - return false, nil - } - } - return true, nil - }) -} - -func WaitUntilPodDeletedBySelector(ctx context.Context, c kubernetes.Interface, namespace string, selector *metav1.LabelSelector) error { - sel, err := metav1.LabelSelectorAsSelector(selector) - if err != nil { - return err - } - - return wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.ReadinessTimeout, true, func(ctx context.Context) (bool, error) { - podList, err := c.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{ - LabelSelector: sel.String(), - }) - if err != nil { - return false, nil - } - return len(podList.Items) == 0, nil - }) -} - -// WaitUntillPodTerminatedByLabel waits until all pods with the label are terminated. Timeout is 5 minutes. -func WaitUntillPodTerminatedByLabel(ctx context.Context, c kubernetes.Interface, namespace string, label string) error { - return wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.GCTimeout, true, func(ctx context.Context) (bool, error) { - podList, err := c.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{LabelSelector: label}) - if err != nil { - return false, nil - } - return len(podList.Items) == 0, nil - }) -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/pod_status.go b/vendor/kmodules.xyz/client-go/core/v1/pod_status.go deleted file mode 100644 index cf87120a..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/pod_status.go +++ /dev/null @@ -1,236 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "fmt" - - core "k8s.io/api/core/v1" -) - -const ( - PodConditionTypeReady = core.PodConditionType("kubedb.com/Ready") -) - -// HasCondition returns "true" if the desired condition provided in "condType" is present in the condition list. -// Otherwise, it returns "false". -func HasPodCondition(conditions []core.PodCondition, condType core.PodConditionType) bool { - for i := range conditions { - if conditions[i].Type == condType { - return true - } - } - return false -} - -// GetPodCondition returns a pointer to the desired condition referred by "condType". Otherwise, it returns nil. -func GetPodCondition(conditions []core.PodCondition, condType core.PodConditionType) (int, *core.PodCondition) { - for i := range conditions { - c := conditions[i] - if c.Type == condType { - return i, &c - } - } - return -1, nil -} - -// SetPodCondition add/update the desired condition to the condition list. It does nothing if the condition is already in -// its desired state. -func SetPodCondition(conditions []core.PodCondition, newCondition core.PodCondition) []core.PodCondition { - idx, curCond := GetPodCondition(conditions, newCondition.Type) - // The desired conditions is not in the condition list or is not in its desired state. - // If the current condition status is in its desired state, we have nothing to do. Just return the original condition list. - // Update it if present in the condition list, or append the new condition if it does not present. - if curCond == nil || idx == -1 { - return append(conditions, newCondition) - } else if curCond.Status == newCondition.Status { - return conditions - } else if curCond.Status != newCondition.Status { - conditions[idx].Status = newCondition.Status - conditions[idx].LastTransitionTime = newCondition.LastTransitionTime - conditions[idx].Reason = newCondition.Reason - conditions[idx].Message = newCondition.Message - } - return conditions -} - -// RemovePodCondition remove a condition from the condition list referred by "condType" parameter. -func RemovePodCondition(conditions []core.PodCondition, condType core.PodConditionType) []core.PodCondition { - idx, _ := GetPodCondition(conditions, condType) - if idx == -1 { - // The desired condition is not present in the condition list. So, nothing to do. - return conditions - } - return append(conditions[:idx], conditions[idx+1:]...) -} - -// IsPodConditionTrue returns "true" if the desired condition is in true state. -// It returns "false" if the desired condition is not in "true" state or is not in the condition list. -func IsPodConditionTrue(conditions []core.PodCondition, condType core.PodConditionType) bool { - for i := range conditions { - if conditions[i].Type == condType && conditions[i].Status == core.ConditionTrue { - return true - } - } - return false -} - -// IsPodConditionFalse returns "true" if the desired condition is in false state. -// It returns "false" if the desired condition is not in "false" state or is not in the condition list. -func IsPodConditionFalse(conditions []core.PodCondition, condType core.PodConditionType) bool { - for i := range conditions { - if conditions[i].Type == condType && conditions[i].Status == core.ConditionFalse { - return true - } - } - return false -} - -func UpsertPodReadinessGateConditionType(readinessGates []core.PodReadinessGate, conditionType core.PodConditionType) []core.PodReadinessGate { - for i := range readinessGates { - if readinessGates[i].ConditionType == conditionType { - return readinessGates - } - } - return append(readinessGates, core.PodReadinessGate{ - ConditionType: conditionType, - }) -} - -const ( - // NodeUnreachablePodReason is the reason on a pod when its state cannot be confirmed as kubelet is unresponsive - // on the node it is (was) running. - NodeUnreachablePodReason = "NodeLost" -) - -// GetPodStatus returns pod status like kubectl -// Adapted from: https://github.com/kubernetes/kubernetes/blob/735804dc812ce647f8c130dced45b5ba4079b76e/pkg/printers/internalversion/printers.go#L825 -func GetPodStatus(pod *core.Pod) string { - reason := string(pod.Status.Phase) - if pod.Status.Reason != "" { - reason = pod.Status.Reason - } - - // If the Pod carries {type:PodScheduled, reason:WaitingForGates}, set reason to 'SchedulingGated'. - for _, condition := range pod.Status.Conditions { - if condition.Type == core.PodScheduled && condition.Reason == core.PodReasonSchedulingGated { - reason = core.PodReasonSchedulingGated - } - } - - initContainers := make(map[string]*core.Container) - for i := range pod.Spec.InitContainers { - initContainers[pod.Spec.InitContainers[i].Name] = &pod.Spec.InitContainers[i] - } - - initializing := false - for i := range pod.Status.InitContainerStatuses { - container := pod.Status.InitContainerStatuses[i] - switch { - case container.State.Terminated != nil && container.State.Terminated.ExitCode == 0: - continue - case isRestartableInitContainer(initContainers[container.Name]) && - container.Started != nil && *container.Started: - continue - case container.State.Terminated != nil: - // initialization is failed - if len(container.State.Terminated.Reason) == 0 { - if container.State.Terminated.Signal != 0 { - reason = fmt.Sprintf("Init:Signal:%d", container.State.Terminated.Signal) - } else { - reason = fmt.Sprintf("Init:ExitCode:%d", container.State.Terminated.ExitCode) - } - } else { - reason = "Init:" + container.State.Terminated.Reason - } - initializing = true - case container.State.Waiting != nil && len(container.State.Waiting.Reason) > 0 && container.State.Waiting.Reason != "PodInitializing": - reason = "Init:" + container.State.Waiting.Reason - initializing = true - default: - reason = fmt.Sprintf("Init:%d/%d", i, len(pod.Spec.InitContainers)) - initializing = true - } - break - } - - if !initializing || isPodInitializedConditionTrue(&pod.Status) { - hasRunning := false - for i := len(pod.Status.ContainerStatuses) - 1; i >= 0; i-- { - container := pod.Status.ContainerStatuses[i] - - if container.State.Waiting != nil && container.State.Waiting.Reason != "" { - reason = container.State.Waiting.Reason - } else if container.State.Terminated != nil && container.State.Terminated.Reason != "" { - reason = container.State.Terminated.Reason - } else if container.State.Terminated != nil && container.State.Terminated.Reason == "" { - if container.State.Terminated.Signal != 0 { - reason = fmt.Sprintf("Signal:%d", container.State.Terminated.Signal) - } else { - reason = fmt.Sprintf("ExitCode:%d", container.State.Terminated.ExitCode) - } - } else if container.Ready && container.State.Running != nil { - hasRunning = true - } - } - - // change pod status back to "Running" if there is at least one container still reporting as "Running" status - if reason == "Completed" && hasRunning { - if hasPodReadyCondition(pod.Status.Conditions) { - reason = "Running" - } else { - reason = "NotReady" - } - } - } - - if pod.DeletionTimestamp != nil && pod.Status.Reason == NodeUnreachablePodReason { - reason = "Unknown" - } else if pod.DeletionTimestamp != nil { - reason = "Terminating" - } - - return reason -} - -func hasPodReadyCondition(conditions []core.PodCondition) bool { - for _, condition := range conditions { - if condition.Type == core.PodReady && condition.Status == core.ConditionTrue { - return true - } - } - return false -} - -func isRestartableInitContainer(initContainer *core.Container) bool { - if initContainer.RestartPolicy == nil { - return false - } - - return *initContainer.RestartPolicy == core.ContainerRestartPolicyAlways -} - -func isPodInitializedConditionTrue(status *core.PodStatus) bool { - for _, condition := range status.Conditions { - if condition.Type != core.PodInitialized { - continue - } - - return condition.Status == core.ConditionTrue - } - return false -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/pv.go b/vendor/kmodules.xyz/client-go/core/v1/pv.go deleted file mode 100644 index 102e9684..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/pv.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - "github.com/pkg/errors" - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchPV(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.PersistentVolume) *core.PersistentVolume, opts metav1.PatchOptions) (*core.PersistentVolume, kutil.VerbType, error) { - cur, err := c.CoreV1().PersistentVolumes().Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating PersistentVolume %s.", meta.Name) - out, err := c.CoreV1().PersistentVolumes().Create(ctx, transform(&core.PersistentVolume{ - TypeMeta: metav1.TypeMeta{ - Kind: "PersistentVolume", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - return PatchPV(ctx, c, cur, transform, opts) -} - -func PatchPV(ctx context.Context, c kubernetes.Interface, cur *core.PersistentVolume, transform func(*core.PersistentVolume) *core.PersistentVolume, opts metav1.PatchOptions) (*core.PersistentVolume, kutil.VerbType, error) { - return PatchPVObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchPVObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.PersistentVolume, opts metav1.PatchOptions) (*core.PersistentVolume, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.PersistentVolume{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching PersistentVolume %s with %s.", cur.Name, string(patch)) - out, err := c.CoreV1().PersistentVolumes().Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} - -func TryUpdatePV(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.PersistentVolume) *core.PersistentVolume, opts metav1.UpdateOptions) (result *core.PersistentVolume, err error) { - attempt := 0 - err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) { - attempt++ - cur, e2 := c.CoreV1().PersistentVolumes().Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(e2) { - return false, e2 - } else if e2 == nil { - result, e2 = c.CoreV1().PersistentVolumes().Update(ctx, transform(cur.DeepCopy()), opts) - return e2 == nil, nil - } - klog.Errorf("Attempt %d failed to update PersistentVolume %s due to %v.", attempt, cur.Name, e2) - return false, nil - }) - - if err != nil { - err = errors.Errorf("failed to update PersistentVolume %s after %d attempts due to %v", meta.Name, attempt, err) - } - return -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/pvc.go b/vendor/kmodules.xyz/client-go/core/v1/pvc.go deleted file mode 100644 index 1bd228d8..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/pvc.go +++ /dev/null @@ -1,101 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - "github.com/pkg/errors" - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchPVC(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.PersistentVolumeClaim) *core.PersistentVolumeClaim, opts metav1.PatchOptions) (*core.PersistentVolumeClaim, kutil.VerbType, error) { - cur, err := c.CoreV1().PersistentVolumeClaims(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating PersistentVolumeClaim %s/%s.", meta.Namespace, meta.Name) - out, err := c.CoreV1().PersistentVolumeClaims(meta.Namespace).Create(ctx, transform(&core.PersistentVolumeClaim{ - TypeMeta: metav1.TypeMeta{ - Kind: "PersistentVolumeClaim", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - return PatchPVC(ctx, c, cur, transform, opts) -} - -func PatchPVC(ctx context.Context, c kubernetes.Interface, cur *core.PersistentVolumeClaim, transform func(*core.PersistentVolumeClaim) *core.PersistentVolumeClaim, opts metav1.PatchOptions) (*core.PersistentVolumeClaim, kutil.VerbType, error) { - return PatchPVCObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchPVCObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.PersistentVolumeClaim, opts metav1.PatchOptions) (*core.PersistentVolumeClaim, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.PersistentVolumeClaim{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching PersistentVolumeClaim %s/%s with %s.", cur.Namespace, cur.Name, string(patch)) - out, err := c.CoreV1().PersistentVolumeClaims(cur.Namespace).Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} - -func TryUpdatePVC(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.PersistentVolumeClaim) *core.PersistentVolumeClaim, opts metav1.UpdateOptions) (result *core.PersistentVolumeClaim, err error) { - attempt := 0 - err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) { - attempt++ - cur, e2 := c.CoreV1().PersistentVolumeClaims(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(e2) { - return false, e2 - } else if e2 == nil { - result, e2 = c.CoreV1().PersistentVolumeClaims(cur.Namespace).Update(ctx, transform(cur.DeepCopy()), opts) - return e2 == nil, nil - } - klog.Errorf("Attempt %d failed to update PersistentVolumeClaim %s/%s due to %v.", attempt, cur.Namespace, cur.Name, e2) - return false, nil - }) - - if err != nil { - err = errors.Errorf("failed to update PersistentVolumeClaim %s/%s after %d attempts due to %v", meta.Namespace, meta.Name, attempt, err) - } - return -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/rc.go b/vendor/kmodules.xyz/client-go/core/v1/rc.go deleted file mode 100644 index 6f7fa20b..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/rc.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - "github.com/pkg/errors" - "gomodules.xyz/pointer" - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchRC(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.ReplicationController) *core.ReplicationController, opts metav1.PatchOptions) (*core.ReplicationController, kutil.VerbType, error) { - cur, err := c.CoreV1().ReplicationControllers(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating ReplicationController %s/%s.", meta.Namespace, meta.Name) - out, err := c.CoreV1().ReplicationControllers(meta.Namespace).Create(ctx, transform(&core.ReplicationController{ - TypeMeta: metav1.TypeMeta{ - Kind: "ReplicationController", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - return PatchRC(ctx, c, cur, transform, opts) -} - -func PatchRC(ctx context.Context, c kubernetes.Interface, cur *core.ReplicationController, transform func(*core.ReplicationController) *core.ReplicationController, opts metav1.PatchOptions) (*core.ReplicationController, kutil.VerbType, error) { - return PatchRCObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchRCObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.ReplicationController, opts metav1.PatchOptions) (*core.ReplicationController, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.ReplicationController{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching ReplicationController %s/%s with %s.", cur.Namespace, cur.Name, string(patch)) - out, err := c.CoreV1().ReplicationControllers(cur.Namespace).Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} - -func TryUpdateRC(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.ReplicationController) *core.ReplicationController, opts metav1.UpdateOptions) (result *core.ReplicationController, err error) { - attempt := 0 - err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) { - attempt++ - cur, e2 := c.CoreV1().ReplicationControllers(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(e2) { - return false, e2 - } else if e2 == nil { - result, e2 = c.CoreV1().ReplicationControllers(cur.Namespace).Update(ctx, transform(cur.DeepCopy()), opts) - return e2 == nil, nil - } - klog.Errorf("Attempt %d failed to update ReplicationController %s/%s due to %v.", attempt, cur.Namespace, cur.Name, e2) - return false, nil - }) - - if err != nil { - err = errors.Errorf("failed to update ReplicationController %s/%s after %d attempts due to %v", meta.Namespace, meta.Name, attempt, err) - } - return -} - -func WaitUntilRCReady(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta) error { - return wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.ReadinessTimeout, true, func(ctx context.Context) (bool, error) { - if obj, err := c.CoreV1().ReplicationControllers(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}); err == nil { - return pointer.Int32(obj.Spec.Replicas) == obj.Status.ReadyReplicas, nil - } - - return false, nil - }) -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/sa-token.go b/vendor/kmodules.xyz/client-go/core/v1/sa-token.go deleted file mode 100644 index 034c365c..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/sa-token.go +++ /dev/null @@ -1,111 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - "time" - - meta_util "kmodules.xyz/client-go/meta" - - "github.com/pkg/errors" - core "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - utilrand "k8s.io/apimachinery/pkg/util/rand" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -// https://kubernetes.io/docs/reference/access-authn-authz/service-accounts-admin/#token-controller -func getServiceAccountTokenSecret(kc kubernetes.Interface, sa types.NamespacedName) (*core.Secret, error) { - list, err := kc.CoreV1().Secrets(sa.Namespace).List(context.TODO(), metav1.ListOptions{}) - if err != nil { - return nil, err - } - if len(list.Items) == 0 { - return nil, errors.New("token secret still haven't created yet") - } - for _, s := range list.Items { - if s.Type == core.SecretTypeServiceAccountToken && - s.Annotations[core.ServiceAccountNameKey] == sa.Name { - - _, caFound := s.Data["ca.crt"] - _, tokenFound := s.Data["token"] - if caFound && tokenFound { - return &s, nil - } - } - } - return nil, errors.New("token secret is not ready yet") -} - -const ( - retryTimeout = 10 * time.Second -) - -func tryGetServiceAccountTokenSecret(kc kubernetes.Interface, sa types.NamespacedName) (secret *core.Secret, err error) { - err = wait.PollUntilContextTimeout(context.Background(), kutil.RetryInterval, retryTimeout, true, func(ctx context.Context) (bool, error) { - var e2 error - secret, e2 = getServiceAccountTokenSecret(kc, sa) - if e2 == nil { - return true, nil - } - klog.V(5).Infof("trying to get token secret for service account %s", sa) - return false, nil - }) - return -} - -func GetServiceAccountTokenSecret(kc kubernetes.Interface, sa types.NamespacedName) (*core.Secret, error) { - secret, err := tryGetServiceAccountTokenSecret(kc, sa) - if err == nil { - klog.V(5).Infof("secret found for ServiceAccount %s", sa) - return secret, nil - } - - saObj, err := kc.CoreV1().ServiceAccounts(sa.Namespace).Get(context.TODO(), sa.Name, metav1.GetOptions{}) - if err != nil { - return nil, errors.Wrapf(err, "failed to get ServiceAccount %s", sa) - } - - secretName := sa.Name + "-token-" + utilrand.String(6) - secret = &core.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: secretName, - Namespace: sa.Namespace, - }, - } - secret, vt, err := CreateOrPatchSecret(context.TODO(), kc, secret.ObjectMeta, func(in *core.Secret) *core.Secret { - in.Type = core.SecretTypeServiceAccountToken - ref := metav1.NewControllerRef(saObj, core.SchemeGroupVersion.WithKind("ServiceAccount")) - EnsureOwnerReference(in, ref) - in.Annotations = meta_util.OverwriteKeys(in.Annotations, map[string]string{ - core.ServiceAccountNameKey: sa.Name, - }) - - return in - }, metav1.PatchOptions{}) - if err != nil { - return nil, err - } - klog.Infof("%s Secret %s/%s", vt, secret.Namespace, secret.Name) - - return tryGetServiceAccountTokenSecret(kc, sa) -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/secret.go b/vendor/kmodules.xyz/client-go/core/v1/secret.go deleted file mode 100644 index 058a5c36..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/secret.go +++ /dev/null @@ -1,134 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - "github.com/pkg/errors" - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchSecret(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Secret) *core.Secret, opts metav1.PatchOptions, forceSyncType ...bool) (*core.Secret, kutil.VerbType, error) { - syncType := len(forceSyncType) == 1 && forceSyncType[0] - - cur, err := c.CoreV1().Secrets(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating Secret %s/%s.", meta.Namespace, meta.Name) - out, err := c.CoreV1().Secrets(meta.Namespace).Create(ctx, transform(&core.Secret{ - TypeMeta: metav1.TypeMeta{ - Kind: "Secret", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - - mod := transform(cur.DeepCopy()) - if mod.Type != cur.Type && syncType && len(opts.DryRun) == 0 { - // secret type can't be modified once created, so we have to delete first, then recreate with correct type - klog.Warningf("Secret %s/%s type is modified, deleting first.", meta.Namespace, meta.Name) - foregroundDeletion := metav1.DeletePropagationForeground - err = c.CoreV1().Secrets(meta.Namespace).Delete(ctx, meta.Name, metav1.DeleteOptions{ - TypeMeta: metav1.TypeMeta{}, - PropagationPolicy: &foregroundDeletion, - DryRun: opts.DryRun, - }) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - klog.V(3).Infof("Creating Secret %s/%s.", meta.Namespace, meta.Name) - out, err := c.CoreV1().Secrets(meta.Namespace).Create(ctx, mod, metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } - return PatchSecretObject(ctx, c, cur, mod, opts) -} - -func PatchSecret(ctx context.Context, c kubernetes.Interface, cur *core.Secret, transform func(*core.Secret) *core.Secret, opts metav1.PatchOptions) (*core.Secret, kutil.VerbType, error) { - return PatchSecretObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchSecretObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.Secret, opts metav1.PatchOptions) (*core.Secret, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.Secret{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching Secret %s/%s", cur.Namespace, cur.Name) - out, err := c.CoreV1().Secrets(cur.Namespace).Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} - -func TryUpdateSecret(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Secret) *core.Secret, opts metav1.UpdateOptions) (result *core.Secret, err error) { - attempt := 0 - err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) { - attempt++ - cur, e2 := c.CoreV1().Secrets(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(e2) { - return false, e2 - } else if e2 == nil { - result, e2 = c.CoreV1().Secrets(cur.Namespace).Update(ctx, transform(cur.DeepCopy()), opts) - return e2 == nil, nil - } - klog.Errorf("Attempt %d failed to update Secret %s/%s due to %v.", attempt, cur.Namespace, cur.Name, e2) - return false, nil - }) - - if err != nil { - err = errors.Errorf("failed to update Secret %s/%s after %d attempts due to %v", meta.Namespace, meta.Name, attempt, err) - } - return -} - -func ObfuscateSecret(in core.Secret) *core.Secret { - data := make(map[string][]byte) - for k := range in.Data { - data[k] = []byte("-") - } - in.Data = data - return &in -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/service.go b/vendor/kmodules.xyz/client-go/core/v1/service.go deleted file mode 100644 index 88e63996..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/service.go +++ /dev/null @@ -1,153 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - "github.com/pkg/errors" - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchService(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Service) *core.Service, opts metav1.PatchOptions) (*core.Service, kutil.VerbType, error) { - cur, err := c.CoreV1().Services(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating Service %s/%s.", meta.Namespace, meta.Name) - out, err := c.CoreV1().Services(meta.Namespace).Create(ctx, transform(&core.Service{ - TypeMeta: metav1.TypeMeta{ - Kind: "Service", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - return PatchService(ctx, c, cur, transform, opts) -} - -func PatchService(ctx context.Context, c kubernetes.Interface, cur *core.Service, transform func(*core.Service) *core.Service, opts metav1.PatchOptions) (*core.Service, kutil.VerbType, error) { - return PatchServiceObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchServiceObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.Service, opts metav1.PatchOptions) (*core.Service, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.Service{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching Service %s/%s with %s.", cur.Namespace, cur.Name, string(patch)) - out, err := c.CoreV1().Services(cur.Namespace).Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} - -func TryUpdateService(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.Service) *core.Service, opts metav1.UpdateOptions) (result *core.Service, err error) { - attempt := 0 - err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) { - attempt++ - cur, e2 := c.CoreV1().Services(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(e2) { - return false, e2 - } else if e2 == nil { - result, e2 = c.CoreV1().Services(cur.Namespace).Update(ctx, transform(cur.DeepCopy()), opts) - return e2 == nil, nil - } - klog.Errorf("Attempt %d failed to update Service %s/%s due to %v.", attempt, cur.Namespace, cur.Name, e2) - return false, nil - }) - - if err != nil { - err = errors.Errorf("failed to update Service %s/%s after %d attempts due to %v", meta.Namespace, meta.Name, attempt, err) - } - return -} - -func MergeServicePorts(cur, desired []core.ServicePort) []core.ServicePort { - if len(cur) == 0 { - return desired - } - - // ports - curPorts := make(map[string]core.ServicePort) - for _, p := range cur { - curPorts[p.Name] = p - } - for i, dp := range desired { - cp, ok := curPorts[dp.Name] - - // svc port not found - if !ok { - continue - } - - if dp.Port == 0 { - dp.Port = cp.Port - } - if dp.NodePort == 0 { - dp.NodePort = cp.NodePort // avoid reassigning port - } - if dp.Protocol == "" { - dp.Protocol = cp.Protocol - } - if dp.AppProtocol == nil { - dp.AppProtocol = cp.AppProtocol - } - desired[i] = dp - } - return desired -} - -func WaitUntilServiceDeletedBySelector(ctx context.Context, c kubernetes.Interface, namespace string, selector *metav1.LabelSelector) error { - sel, err := metav1.LabelSelectorAsSelector(selector) - if err != nil { - return err - } - - return wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.ReadinessTimeout, true, func(ctx context.Context) (bool, error) { - svcList, err := c.CoreV1().Services(namespace).List(ctx, metav1.ListOptions{ - LabelSelector: sel.String(), - }) - if err != nil { - return false, nil - } - return len(svcList.Items) == 0, nil - }) -} diff --git a/vendor/kmodules.xyz/client-go/core/v1/serviceaccount.go b/vendor/kmodules.xyz/client-go/core/v1/serviceaccount.go deleted file mode 100644 index 3d08a625..00000000 --- a/vendor/kmodules.xyz/client-go/core/v1/serviceaccount.go +++ /dev/null @@ -1,131 +0,0 @@ -/* -Copyright AppsCode Inc. and Contributors - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "context" - - "github.com/pkg/errors" - core "k8s.io/api/core/v1" - kerr "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - kutil "kmodules.xyz/client-go" -) - -func CreateOrPatchServiceAccount(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.ServiceAccount) *core.ServiceAccount, opts metav1.PatchOptions) (*core.ServiceAccount, kutil.VerbType, error) { - cur, err := c.CoreV1().ServiceAccounts(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(err) { - klog.V(3).Infof("Creating ServiceAccount %s/%s.", meta.Namespace, meta.Name) - out, err := c.CoreV1().ServiceAccounts(meta.Namespace).Create(ctx, transform(&core.ServiceAccount{ - TypeMeta: metav1.TypeMeta{ - Kind: "ServiceAccount", - APIVersion: core.SchemeGroupVersion.String(), - }, - ObjectMeta: meta, - }), metav1.CreateOptions{ - DryRun: opts.DryRun, - FieldManager: opts.FieldManager, - }) - return out, kutil.VerbCreated, err - } else if err != nil { - return nil, kutil.VerbUnchanged, err - } - return PatchServiceAccount(ctx, c, cur, transform, opts) -} - -func PatchServiceAccount(ctx context.Context, c kubernetes.Interface, cur *core.ServiceAccount, transform func(*core.ServiceAccount) *core.ServiceAccount, opts metav1.PatchOptions) (*core.ServiceAccount, kutil.VerbType, error) { - return PatchServiceAccountObject(ctx, c, cur, transform(cur.DeepCopy()), opts) -} - -func PatchServiceAccountObject(ctx context.Context, c kubernetes.Interface, cur, mod *core.ServiceAccount, opts metav1.PatchOptions) (*core.ServiceAccount, kutil.VerbType, error) { - curJson, err := json.Marshal(cur) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - modJson, err := json.Marshal(mod) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - - patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, core.ServiceAccount{}) - if err != nil { - return nil, kutil.VerbUnchanged, err - } - if len(patch) == 0 || string(patch) == "{}" { - return cur, kutil.VerbUnchanged, nil - } - klog.V(3).Infof("Patching ServiceAccount %s/%s with %s", cur.Namespace, cur.Name, string(patch)) - out, err := c.CoreV1().ServiceAccounts(cur.Namespace).Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts) - return out, kutil.VerbPatched, err -} - -func TryUpdateServiceAccount(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta, transform func(*core.ServiceAccount) *core.ServiceAccount, opts metav1.UpdateOptions) (result *core.ServiceAccount, err error) { - attempt := 0 - err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) { - attempt++ - cur, e2 := c.CoreV1().ServiceAccounts(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if kerr.IsNotFound(e2) { - return false, e2 - } else if e2 == nil { - result, e2 = c.CoreV1().ServiceAccounts(cur.Namespace).Update(ctx, transform(cur.DeepCopy()), opts) - return e2 == nil, nil - } - klog.Errorf("Attempt %d failed to update ServiceAccount %s/%s due to %v.", attempt, cur.Namespace, cur.Name, e2) - return false, nil - }) - - if err != nil { - err = errors.Errorf("failed to update ServiceAccount %s/%s after %d attempts due to %v", meta.Namespace, meta.Name, attempt, err) - } - return -} - -func WaitUntillServiceAccountDeleted(ctx context.Context, c kubernetes.Interface, meta metav1.ObjectMeta) error { - return wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.GCTimeout, true, func(ctx context.Context) (bool, error) { - _, err := c.CoreV1().ServiceAccounts(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}) - if err != nil && kerr.IsNotFound(err) { - return true, nil - } - return false, nil - }) -} - -// IsServiceAccountToken returns true if the secret is a valid api token for the service account -func IsServiceAccountToken(secret *core.Secret, sa *core.ServiceAccount) bool { - if secret.Type != core.SecretTypeServiceAccountToken { - return false - } - - name := secret.Annotations[core.ServiceAccountNameKey] - uid := secret.Annotations[core.ServiceAccountUIDKey] - if name != sa.Name { - // Name must match - return false - } - if len(uid) > 0 && uid != string(sa.UID) { - // If UID is specified, it must match - return false - } - - return true -} diff --git a/vendor/modules.txt b/vendor/modules.txt index c9b19b0e..18c8381c 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -687,9 +687,6 @@ gomodules.xyz/jsonpatch/v2 # gomodules.xyz/logs v0.0.7 ## explicit; go 1.16 gomodules.xyz/logs -# gomodules.xyz/mergo v0.3.13 -## explicit; go 1.13 -gomodules.xyz/mergo # gomodules.xyz/pointer v0.1.0 ## explicit; go 1.15 gomodules.xyz/pointer @@ -1511,7 +1508,6 @@ k8s.io/utils/trace kmodules.xyz/client-go kmodules.xyz/client-go/apiextensions kmodules.xyz/client-go/apiextensions/v1 -kmodules.xyz/client-go/core/v1 kmodules.xyz/client-go/meta kmodules.xyz/client-go/tools/clientcmd # kmodules.xyz/go-containerregistry v0.0.12 @@ -1523,7 +1519,7 @@ sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client/metrics sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client -# sigs.k8s.io/controller-runtime v0.17.2 => github.com/kmodules/controller-runtime v0.17.2-0.20240213085617-b6aac9684c00 +# sigs.k8s.io/controller-runtime v0.17.4 => github.com/kmodules/controller-runtime v0.17.5-0.20240506165850-9bc6cbeccc8a ## explicit; go 1.21 sigs.k8s.io/controller-runtime sigs.k8s.io/controller-runtime/pkg/builder @@ -1666,7 +1662,7 @@ sigs.k8s.io/structured-merge-diff/v4/value sigs.k8s.io/yaml sigs.k8s.io/yaml/goyaml.v2 # github.com/Masterminds/sprig/v3 => github.com/gomodules/sprig/v3 v3.2.3-0.20220405051441-0a8a99bac1b8 -# sigs.k8s.io/controller-runtime => github.com/kmodules/controller-runtime v0.17.2-0.20240213085617-b6aac9684c00 +# sigs.k8s.io/controller-runtime => github.com/kmodules/controller-runtime v0.17.5-0.20240506165850-9bc6cbeccc8a # github.com/imdario/mergo => github.com/imdario/mergo v0.3.6 # k8s.io/apiserver => github.com/kmodules/apiserver v0.29.1-0.20240104121741-1fb217d4a573 # k8s.io/kubernetes => github.com/kmodules/kubernetes v1.30.0-alpha.0.0.20231224075822-3bd9a13c86db diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go index 1cecf88e..73ad68fe 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/cache/cache.go @@ -20,6 +20,7 @@ import ( "context" "fmt" "net/http" + "sort" "time" "golang.org/x/exp/maps" @@ -418,14 +419,6 @@ func defaultOpts(config *rest.Config, opts Options) (Options, error) { } } - for namespace, cfg := range opts.DefaultNamespaces { - cfg = defaultConfig(cfg, optionDefaultsToConfig(&opts)) - if namespace == metav1.NamespaceAll { - cfg.FieldSelector = fields.AndSelectors(appendIfNotNil(namespaceAllSelector(maps.Keys(opts.DefaultNamespaces)), cfg.FieldSelector)...) - } - opts.DefaultNamespaces[namespace] = cfg - } - for obj, byObject := range opts.ByObject { isNamespaced, err := apiutil.IsObjectNamespaced(obj, opts.Scheme, opts.Mapper) if err != nil { @@ -435,7 +428,12 @@ func defaultOpts(config *rest.Config, opts Options) (Options, error) { return opts, fmt.Errorf("type %T is not namespaced, but its ByObject.Namespaces setting is not nil", obj) } - // Default the namespace-level configs first, because they need to use the undefaulted type-level config. + if isNamespaced && byObject.Namespaces == nil { + byObject.Namespaces = maps.Clone(opts.DefaultNamespaces) + } + + // Default the namespace-level configs first, because they need to use the undefaulted type-level config + // to be able to potentially fall through to settings from DefaultNamespaces. for namespace, config := range byObject.Namespaces { // 1. Default from the undefaulted type-level config config = defaultConfig(config, byObjectToConfig(byObject)) @@ -461,19 +459,35 @@ func defaultOpts(config *rest.Config, opts Options) (Options, error) { byObject.Namespaces[namespace] = config } - defaultedConfig := defaultConfig(byObjectToConfig(byObject), optionDefaultsToConfig(&opts)) - byObject.Label = defaultedConfig.LabelSelector - byObject.Field = defaultedConfig.FieldSelector - byObject.Transform = defaultedConfig.Transform - byObject.UnsafeDisableDeepCopy = defaultedConfig.UnsafeDisableDeepCopy - - if isNamespaced && byObject.Namespaces == nil { - byObject.Namespaces = opts.DefaultNamespaces + // Only default ByObject iself if it isn't namespaced or has no namespaces configured, as only + // then any of this will be honored. + if !isNamespaced || len(byObject.Namespaces) == 0 { + defaultedConfig := defaultConfig(byObjectToConfig(byObject), optionDefaultsToConfig(&opts)) + byObject.Label = defaultedConfig.LabelSelector + byObject.Field = defaultedConfig.FieldSelector + byObject.Transform = defaultedConfig.Transform + byObject.UnsafeDisableDeepCopy = defaultedConfig.UnsafeDisableDeepCopy } opts.ByObject[obj] = byObject } + // Default namespaces after byObject has been defaulted, otherwise a namespace without selectors + // will get the `Default` selectors, then get copied to byObject and then not get defaulted from + // byObject, as it already has selectors. + for namespace, cfg := range opts.DefaultNamespaces { + cfg = defaultConfig(cfg, optionDefaultsToConfig(&opts)) + if namespace == metav1.NamespaceAll { + cfg.FieldSelector = fields.AndSelectors( + appendIfNotNil( + namespaceAllSelector(maps.Keys(opts.DefaultNamespaces)), + cfg.FieldSelector, + )..., + ) + } + opts.DefaultNamespaces[namespace] = cfg + } + // Default the resync period to 10 hours if unset if opts.SyncPeriod == nil { opts.SyncPeriod = &defaultSyncPeriod @@ -498,20 +512,21 @@ func defaultConfig(toDefault, defaultFrom Config) Config { return toDefault } -func namespaceAllSelector(namespaces []string) fields.Selector { +func namespaceAllSelector(namespaces []string) []fields.Selector { selectors := make([]fields.Selector, 0, len(namespaces)-1) + sort.Strings(namespaces) for _, namespace := range namespaces { if namespace != metav1.NamespaceAll { selectors = append(selectors, fields.OneTermNotEqualSelector("metadata.namespace", namespace)) } } - return fields.AndSelectors(selectors...) + return selectors } -func appendIfNotNil[T comparable](a, b T) []T { +func appendIfNotNil[T comparable](a []T, b T) []T { if b != *new(T) { - return []T{a, b} + return append(a, b) } - return []T{a} + return a } diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/apiutil/restmapper.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/apiutil/restmapper.go index 24af330c..927be22b 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/client/apiutil/restmapper.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/apiutil/restmapper.go @@ -53,7 +53,7 @@ func NewDynamicRESTMapper(cfg *rest.Config, httpClient *http.Client) (meta.RESTM // client for discovery information to do REST mappings. type mapper struct { mapper meta.RESTMapper - client *discovery.DiscoveryClient + client discovery.DiscoveryInterface knownGroups map[string]*restmapper.APIGroupResources apiGroups map[string]*metav1.APIGroup @@ -280,11 +280,15 @@ func (m *mapper) fetchGroupVersionResourcesLocked(groupName string, versions ... groupVersion := schema.GroupVersion{Group: groupName, Version: version} apiResourceList, err := m.client.ServerResourcesForGroupVersion(groupVersion.String()) - if apierrors.IsNotFound(err) && m.isGroupVersionCached(groupVersion) { + if apierrors.IsNotFound(err) { // If the version is not found, we remove the group from the cache // so it gets refreshed on the next call. - delete(m.apiGroups, groupName) - delete(m.knownGroups, groupName) + if m.isAPIGroupCached(groupVersion) { + delete(m.apiGroups, groupName) + } + if m.isGroupVersionCached(groupVersion) { + delete(m.knownGroups, groupName) + } continue } else if err != nil { failedGroups[groupVersion] = err @@ -313,3 +317,19 @@ func (m *mapper) isGroupVersionCached(gv schema.GroupVersion) bool { return false } + +// isAPIGroupCached checks if a version for a group is cached in the api groups cache. +func (m *mapper) isAPIGroupCached(gv schema.GroupVersion) bool { + cachedGroup, ok := m.apiGroups[gv.Group] + if !ok { + return false + } + + for _, version := range cachedGroup.Versions { + if version.Version == gv.Version { + return true + } + } + + return false +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldowner.go b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldowner.go new file mode 100644 index 00000000..2f2f892e --- /dev/null +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/client/fieldowner.go @@ -0,0 +1,106 @@ +/* +Copyright 2024 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package client + +import ( + "context" + + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// WithFieldOwner wraps a Client and adds the fieldOwner as the field +// manager to all write requests from this client. If additional [FieldOwner] +// options are specified on methods of this client, the value specified here +// will be overridden. +func WithFieldOwner(c Client, fieldOwner string) Client { + return &clientWithFieldManager{ + manager: fieldOwner, + c: c, + Reader: c, + } +} + +type clientWithFieldManager struct { + manager string + c Client + Reader +} + +func (f *clientWithFieldManager) Create(ctx context.Context, obj Object, opts ...CreateOption) error { + return f.c.Create(ctx, obj, append([]CreateOption{FieldOwner(f.manager)}, opts...)...) +} + +func (f *clientWithFieldManager) Update(ctx context.Context, obj Object, opts ...UpdateOption) error { + return f.c.Update(ctx, obj, append([]UpdateOption{FieldOwner(f.manager)}, opts...)...) +} + +func (f *clientWithFieldManager) Patch(ctx context.Context, obj Object, patch Patch, opts ...PatchOption) error { + return f.c.Patch(ctx, obj, patch, append([]PatchOption{FieldOwner(f.manager)}, opts...)...) +} + +func (f *clientWithFieldManager) Delete(ctx context.Context, obj Object, opts ...DeleteOption) error { + return f.c.Delete(ctx, obj, opts...) +} + +func (f *clientWithFieldManager) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { + return f.c.DeleteAllOf(ctx, obj, opts...) +} + +func (f *clientWithFieldManager) Scheme() *runtime.Scheme { return f.c.Scheme() } +func (f *clientWithFieldManager) RESTMapper() meta.RESTMapper { return f.c.RESTMapper() } +func (f *clientWithFieldManager) GroupVersionKindFor(obj runtime.Object) (schema.GroupVersionKind, error) { + return f.c.GroupVersionKindFor(obj) +} +func (f *clientWithFieldManager) IsObjectNamespaced(obj runtime.Object) (bool, error) { + return f.c.IsObjectNamespaced(obj) +} + +func (f *clientWithFieldManager) Status() StatusWriter { + return &subresourceClientWithFieldOwner{ + owner: f.manager, + subresourceWriter: f.c.Status(), + } +} + +func (f *clientWithFieldManager) SubResource(subresource string) SubResourceClient { + c := f.c.SubResource(subresource) + return &subresourceClientWithFieldOwner{ + owner: f.manager, + subresourceWriter: c, + SubResourceReader: c, + } +} + +type subresourceClientWithFieldOwner struct { + owner string + subresourceWriter SubResourceWriter + SubResourceReader +} + +func (f *subresourceClientWithFieldOwner) Create(ctx context.Context, obj Object, subresource Object, opts ...SubResourceCreateOption) error { + return f.subresourceWriter.Create(ctx, obj, subresource, append([]SubResourceCreateOption{FieldOwner(f.owner)}, opts...)...) +} + +func (f *subresourceClientWithFieldOwner) Update(ctx context.Context, obj Object, opts ...SubResourceUpdateOption) error { + return f.subresourceWriter.Update(ctx, obj, append([]SubResourceUpdateOption{FieldOwner(f.owner)}, opts...)...) +} + +func (f *subresourceClientWithFieldOwner) Patch(ctx context.Context, obj Object, patch Patch, opts ...SubResourcePatchOption) error { + return f.subresourceWriter.Patch(ctx, obj, patch, append([]SubResourcePatchOption{FieldOwner(f.owner)}, opts...)...) +} diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go index a16f354a..fdb9d982 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/internal.go @@ -518,6 +518,8 @@ func (cm *controllerManager) engageStopProcedure(stopComplete <-chan struct{}) e // Stop all the leader election runnables, which includes reconcilers. cm.logger.Info("Stopping and waiting for leader election runnables") + // Prevent leader election when shutting down a non-elected manager + cm.runnables.LeaderElection.startOnce.Do(func() {}) cm.runnables.LeaderElection.StopAndWait(cm.shutdownCtx) // Stop the caches before the leader election runnables, this is an important diff --git a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go index 96566f5d..60609104 100644 --- a/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go +++ b/vendor/sigs.k8s.io/controller-runtime/pkg/manager/runnable_group.go @@ -263,6 +263,15 @@ func (r *runnableGroup) Add(rn Runnable, ready runnableCheck) error { r.start.Unlock() } + // Recheck if we're stopped and hold the readlock, given that the stop and start can be called + // at the same time, we can end up in a situation where the runnable is added + // after the group is stopped and the channel is closed. + r.stop.RLock() + defer r.stop.RUnlock() + if r.stopped { + return errRunnableGroupStopped + } + // Enqueue the runnable. r.ch <- readyRunnable return nil @@ -272,7 +281,11 @@ func (r *runnableGroup) Add(rn Runnable, ready runnableCheck) error { func (r *runnableGroup) StopAndWait(ctx context.Context) { r.stopOnce.Do(func() { // Close the reconciler channel once we're done. - defer close(r.ch) + defer func() { + r.stop.Lock() + close(r.ch) + r.stop.Unlock() + }() _ = r.Start(ctx) r.stop.Lock()