-
Notifications
You must be signed in to change notification settings - Fork 877
/
autoscaler_controller.go
163 lines (141 loc) · 5.87 KB
/
autoscaler_controller.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/*
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 autoscaler
import (
"context"
"fmt"
"time"
cpv1alpha1 "github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
"github.com/crossplane/crossplane-runtime/pkg/event"
"github.com/go-logr/logr"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/oam-dev/kubevela/apis/standard.oam.dev/v1alpha1"
"github.com/oam-dev/kubevela/pkg/controller/common"
"github.com/oam-dev/kubevela/pkg/oam/discoverymapper"
"github.com/oam-dev/kubevela/pkg/oam/util"
)
// nolint:golint
const (
SpecWarningTargetWorkloadNotSet = "Spec.targetWorkload is not set"
SpecWarningStartAtTimeFormat = "startAt is not in the right format, which should be like `12:01`"
SpecWarningStartAtTimeRequired = "spec.triggers.condition.startAt: Required value"
SpecWarningDurationTimeRequired = "spec.triggers.condition.duration: Required value"
SpecWarningReplicasRequired = "spec.triggers.condition.replicas: Required value"
SpecWarningDurationTimeNotInRightFormat = "spec.triggers.condition.duration: not in the right format"
)
// ReconcileWaitResult is the time to wait between reconciliation.
var ReconcileWaitResult = reconcile.Result{RequeueAfter: 30 * time.Second}
// Reconciler reconciles a Autoscaler object
type Reconciler struct {
client.Client
dm discoverymapper.DiscoveryMapper
Log logr.Logger
Scheme *runtime.Scheme
record event.Recorder
}
// Reconcile is the main logic for autoscaler controller
// +kubebuilder:rbac:groups=standard.oam.dev,resources=autoscalers,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=standard.oam.dev,resources=autoscalers/status,verbs=get;update;patch
func (r *Reconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
log := r.Log.WithValues("autoscaler", req.NamespacedName)
log.Info("Reconciling Autoscaler...")
ctx := context.Background()
var scaler v1alpha1.Autoscaler
if err := r.Get(ctx, req.NamespacedName, &scaler); err != nil {
log.Error(err, "Failed to get trait", "traitName", scaler.Name)
return ReconcileWaitResult, client.IgnoreNotFound(err)
}
log.Info("Retrieved trait Autoscaler", "APIVersion", scaler.APIVersion, "Kind", scaler.Kind)
// find the resource object to record the event to, default is the parent appConfig.
eventObj, err := util.LocateParentAppConfig(ctx, r.Client, &scaler)
if err != nil {
log.Error(err, "Failed to find the parent resource", "Autoscaler", scaler.Name)
return util.ReconcileWaitResult, util.PatchCondition(ctx, r, &scaler,
cpv1alpha1.ReconcileError(fmt.Errorf(util.ErrLocateAppConfig)))
}
if eventObj == nil {
// fallback to workload itself
log.Info("There is no parent resource", "Autoscaler", scaler.Name)
eventObj = &scaler
}
// Fetch the instance to which the trait refers to
workload, err := util.FetchWorkload(ctx, r, log, &scaler)
if err != nil {
log.Error(err, "Error while fetching the workload", "workload reference",
scaler.GetWorkloadReference())
r.record.Event(&scaler, event.Warning(common.ErrLocatingWorkload, err))
return util.ReconcileWaitResult,
util.PatchCondition(ctx, r, &scaler,
cpv1alpha1.ReconcileError(errors.Wrap(err, common.ErrLocatingWorkload)))
}
// Fetch the child resources list from the corresponding workload
resources, err := util.FetchWorkloadChildResources(ctx, log, r, r.dm, workload)
if err != nil {
log.Error(err, "Error while fetching the workload child resources", "workload", workload.UnstructuredContent())
r.record.Event(eventObj, event.Warning(util.ErrFetchChildResources, err))
return util.ReconcileWaitResult, util.PatchCondition(ctx, r, &scaler,
cpv1alpha1.ReconcileError(fmt.Errorf(util.ErrFetchChildResources)))
}
resources = append(resources, workload)
targetWorkloadSetFlag := false
for _, res := range resources {
// Keda only support these four built-in workload now.
if res.GetKind() == "Deployment" || res.GetKind() == "StatefulSet" || res.GetKind() == "DaemonSet" || res.GetKind() == "ReplicaSet" {
scaler.Spec.TargetWorkload = v1alpha1.TargetWorkload{
APIVersion: res.GetAPIVersion(),
Kind: res.GetKind(),
Name: res.GetName(),
}
targetWorkloadSetFlag = true
break
}
}
// if no child resource found, set the workload as target workload
if !targetWorkloadSetFlag {
scaler.Spec.TargetWorkload = v1alpha1.TargetWorkload{
APIVersion: workload.GetAPIVersion(),
Kind: workload.GetKind(),
Name: workload.GetName(),
}
}
namespace := req.NamespacedName.Namespace
if err := r.scaleByKEDA(scaler, namespace, log); err != nil {
return ReconcileWaitResult, err
}
return ctrl.Result{}, nil
}
// SetupWithManager will setup with event recorder
func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error {
r.record = event.NewAPIRecorder(mgr.GetEventRecorderFor("Autoscaler")).
WithAnnotations("controller", "Autoscaler")
return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.Autoscaler{}).
Complete(r)
}
// Setup adds a controller that reconciles MetricsTrait.
func Setup(mgr ctrl.Manager) error {
dm, err := discoverymapper.New(mgr.GetConfig())
if err != nil {
return err
}
r := Reconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("Autoscaler"),
Scheme: mgr.GetScheme(),
dm: dm,
}
return r.SetupWithManager(mgr)
}