/
reconcile_deployment.go
81 lines (68 loc) · 2.71 KB
/
reconcile_deployment.go
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
78
79
80
81
/*
Copyright 2020,2021 Avi Zimmerman
This file is part of kvdi.
kvdi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
kvdi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with kvdi. If not, see <https://www.gnu.org/licenses/>.
*/
package reconcile
import (
"context"
"fmt"
"github.com/kvdi/kvdi/pkg/util/errors"
"github.com/kvdi/kvdi/pkg/util/k8sutil"
"github.com/go-logr/logr"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// Deployment reconciles a deployment with the cluster and opionally
// returns a requeue error if it isn't fully running yet.
func Deployment(ctx context.Context, reqLogger logr.Logger, c client.Client, deployment *appsv1.Deployment, wait bool) error {
if err := k8sutil.SetCreationSpecAnnotation(&deployment.ObjectMeta, deployment); err != nil {
return err
}
foundDeployment := &appsv1.Deployment{}
if err := c.Get(ctx, types.NamespacedName{Name: deployment.Name, Namespace: deployment.Namespace}, foundDeployment); err != nil {
// Return API error
if client.IgnoreNotFound(err) != nil {
return err
}
// Create the deployment
reqLogger.Info("Creating new deployment", "Deployment.Name", deployment.Name, "Deployment.Namespace", deployment.Namespace)
if err := c.Create(ctx, deployment); err != nil {
return err
}
if wait {
return errors.NewRequeueError("Created new deployment with wait, requeing for status check", 3)
}
return nil
}
// Check the found deployment spec
if !k8sutil.CreationSpecsEqual(deployment.ObjectMeta, foundDeployment.ObjectMeta) {
// We need to update the deployment
reqLogger.Info("Deployment annotation spec has changed, updating", "Deployment.Name", deployment.Name, "Deployment.Namespace", deployment.Namespace)
foundDeployment.Spec = deployment.Spec
foundDeployment.SetAnnotations(deployment.GetAnnotations())
if err := c.Update(ctx, foundDeployment); err != nil {
return err
}
}
if wait {
runningDeploy := &appsv1.Deployment{}
if err := c.Get(ctx, types.NamespacedName{Name: deployment.Name, Namespace: deployment.Namespace}, runningDeploy); err != nil {
return err
}
if runningDeploy.Status.ReadyReplicas != *deployment.Spec.Replicas {
return errors.NewRequeueError(fmt.Sprintf("Waiting for %s to be ready", deployment.Name), 3)
}
}
return nil
}