Skip to content

Commit

Permalink
Add petset helper functions
Browse files Browse the repository at this point in the history
Signed-off-by: souravbiswassanto <saurov@appscode.com>
  • Loading branch information
souravbiswassanto committed Feb 26, 2024
1 parent 33623cc commit a1794c1
Show file tree
Hide file tree
Showing 30 changed files with 4,767 additions and 2 deletions.
161 changes: 161 additions & 0 deletions apis/apps/v1/petset_helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
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"
"fmt"

petsetcs "kubeops.dev/petset/client/clientset/versioned"

jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"gomodules.xyz/pointer"
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"
core_util "kmodules.xyz/client-go/core/v1"
)

var json = jsoniter.ConfigFastest

func CreateOrPatchPetSet(ctx context.Context, psc petsetcs.Interface, meta metav1.ObjectMeta, transform func(*PetSet) *PetSet, opts metav1.PatchOptions) (*PetSet, kutil.VerbType, error) {
cur, err := psc.AppsV1().PetSets(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{})
if kerr.IsNotFound(err) {
klog.V(3).Infof("Creating PetSet %s/%s.", meta.Namespace, meta.Name)
out, err := psc.AppsV1().PetSets(meta.Namespace).Create(ctx, transform(&PetSet{
TypeMeta: metav1.TypeMeta{
Kind: "PetSet",
APIVersion: 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 PatchPetSet(ctx, psc, cur, transform, opts)
}

func PatchPetSet(ctx context.Context, psc petsetcs.Interface, cur *PetSet, transform func(*PetSet) *PetSet, opts metav1.PatchOptions) (*PetSet, kutil.VerbType, error) {
return PatchPetSetObject(ctx, psc, cur, transform(cur.DeepCopy()), opts)
}

func PatchPetSetObject(ctx context.Context, psc petsetcs.Interface, cur, mod *PetSet, opts metav1.PatchOptions) (*PetSet, 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, PetSet{})
if err != nil {
return nil, kutil.VerbUnchanged, err
}
if len(patch) == 0 || string(patch) == "{}" {
return cur, kutil.VerbUnchanged, nil
}
klog.V(3).Infof("Patching PetSet %s/%s with %s.", cur.Namespace, cur.Name, string(patch))
out, err := psc.AppsV1().PetSets(cur.Namespace).Patch(ctx, cur.Name, types.StrategicMergePatchType, patch, opts)
return out, kutil.VerbPatched, err
}

func TryUpdatePetSet(ctx context.Context, psc petsetcs.Interface, meta metav1.ObjectMeta, transform func(*PetSet) *PetSet, opts metav1.UpdateOptions) (result *PetSet, err error) {
attempt := 0
err = wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.RetryTimeout, true, func(ctx context.Context) (bool, error) {
attempt++
cur, e2 := psc.AppsV1().PetSets(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{})
if kerr.IsNotFound(e2) {
return false, e2
} else if e2 == nil {
result, e2 = psc.AppsV1().PetSets(cur.Namespace).Update(ctx, transform(cur.DeepCopy()), opts)
return e2 == nil, nil
}
klog.Errorf("Attempt %d failed to update PetSet %s/%s due to %v.", attempt, cur.Namespace, cur.Name, e2)
return false, nil
})

if err != nil {
err = errors.Errorf("failed to update PetSet %s/%s after %d attempts due to %v", meta.Namespace, meta.Name, attempt, err)
}
return
}

func IsPetSetReady(obj *PetSet) bool {
replicas := int32(1)
if obj.Spec.Replicas != nil {
replicas = *obj.Spec.Replicas
}
return replicas == obj.Status.ReadyReplicas
}

func PetSetsAreReady(items []*PetSet) (bool, string) {
for _, ps := range items {
if !IsPetSetReady(ps) {
return false, fmt.Sprintf("All desired replicas are not ready. For PetSet: %s/%s desired replicas: %d, ready replicas: %d.", ps.Namespace, ps.Name, pointer.Int32(ps.Spec.Replicas), ps.Status.ReadyReplicas)
}
}
return true, "All desired replicas are ready."
}

func WaitUntilPetSetReady(ctx context.Context, psc petsetcs.Interface, meta metav1.ObjectMeta) error {
return wait.PollUntilContextTimeout(ctx, kutil.RetryInterval, kutil.ReadinessTimeout, true, func(ctx context.Context) (bool, error) {
if obj, err := psc.AppsV1().PetSets(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{}); err == nil {
return IsPetSetReady(obj), nil
}
return false, nil
})
}

func DeletePetSet(ctx context.Context, c kubernetes.Interface, psc petsetcs.Interface, meta metav1.ObjectMeta) error {
petSet, err := psc.AppsV1().PetSets(meta.Namespace).Get(ctx, meta.Name, metav1.GetOptions{})
if err != nil {
if kerr.IsNotFound(err) {
return nil
} else {
return err
}
}

// Update PetSet
_, _, err = PatchPetSet(ctx, psc, petSet, func(in *PetSet) *PetSet {
in.Spec.Replicas = pointer.Int32P(0)
return in
}, metav1.PatchOptions{})
if err != nil {
return err
}

err = core_util.WaitUntilPodDeletedBySelector(ctx, c, petSet.Namespace, petSet.Spec.Selector)
if err != nil {
return err
}

return psc.AppsV1().PetSets(petSet.Namespace).Delete(ctx, petSet.Name, metav1.DeleteOptions{})
}
6 changes: 4 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ 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.7.0
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.8.4
gomodules.xyz/logs v0.0.7
gomodules.xyz/pointer v0.1.0
gomodules.xyz/x v0.0.15
k8s.io/api v0.29.0
k8s.io/apiextensions-apiserver v0.29.0
Expand Down Expand Up @@ -103,7 +106,6 @@ require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jmespath/go-jmespath 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.16.5 // indirect
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect
Expand All @@ -121,7 +123,6 @@ 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.0 // indirect
github.com/prometheus/client_golang v1.18.0 // indirect
github.com/prometheus/client_model v0.5.0 // indirect
Expand Down Expand Up @@ -162,6 +163,7 @@ 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.7 // indirect
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,8 @@ 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=
Expand Down Expand Up @@ -774,6 +776,7 @@ 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=
Expand Down
12 changes: 12 additions & 0 deletions vendor/gomodules.xyz/mergo/.deepsource.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version = 1

test_patterns = [
"*_test.go"
]

[[analyzers]]
name = "go"
enabled = true

[analyzers.meta]
import_path = "gomodules.xyz/mergo"
33 changes: 33 additions & 0 deletions vendor/gomodules.xyz/mergo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#### 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
46 changes: 46 additions & 0 deletions vendor/gomodules.xyz/mergo/CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at 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/
28 changes: 28 additions & 0 deletions vendor/gomodules.xyz/mergo/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
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.
Loading

0 comments on commit a1794c1

Please sign in to comment.