1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| package builders
import ( "bytes" "context" dbconfigv1 "github.com/haojianxun/dbcore/pkg/apis/dbconfig/v1" appv1 "k8s.io/api/apps/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/yaml" "sigs.k8s.io/controller-runtime/pkg/client" "text/template" )
type DeployBuilder struct { client.Client config *dbconfigv1.DbConfig deploy *appv1.Deployment }
func deployName(name string ) string { return "dbcore-"+name }
func NewDeployBuilder(config *dbconfigv1.DbConfig,c client.Client) (*DeployBuilder,error) { deploy:=&appv1.Deployment{} err:= c.Get(context.Background(),types.NamespacedName{ Name: deployName(config.Name), Namespace: config.Namespace, },deploy) if err != nil { deploy.Name,deploy.Namespace=config.Name,config.Namespace tmp,err:= template.New("deploy").Parse(deptpl) if err !=nil{return nil, err} var doc bytes.Buffer err=tmp.Execute(&doc,deploy) if err!=nil{return nil, err} err=yaml.Unmarshal(doc.Bytes(),deploy) if err!=nil{return nil, err} } return &DeployBuilder{deploy: deploy,Client:c},nil }
func (this *DeployBuilder)Apply() *DeployBuilder{ *this.deploy.Spec.Replicas=int32(this.config.Spec.Replicas) return this } func (this *DeployBuilder)setOwner() *DeployBuilder{ this.deploy.OwnerReferences=append(this.deploy.OwnerReferences,v1.OwnerReference{ Name: this.config.Name, Kind: this.config.Kind, APIVersion: this.config.APIVersion, UID: this.config.UID, }) return this }
func(this *DeployBuilder) Build(ctx context.Context) error { if this.deploy.CreationTimestamp.IsZero(){ this.Apply().setOwner() err:= this.Client.Create(ctx,this.deploy) if err != nil { return err } }else{ patch:=client.MergeFrom(this.deploy.DeepCopy()) this.Apply() err:=this.Patch(ctx,this.deploy,patch) if err != nil { return err }
} return nil }
|