/
sriovfecclusterconfig_controller.go
286 lines (241 loc) · 10.7 KB
/
sriovfecclusterconfig_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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2020-2021 Intel Corporation
/*
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 controllers
import (
"context"
"fmt"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/util/retry"
"os"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"time"
sriovfecv2 "github.com/smart-edge-open/sriov-fec-operator/sriov-fec/api/v2"
)
var NAMESPACE = os.Getenv("SRIOV_FEC_NAMESPACE")
// SriovFecClusterConfigReconciler reconciles a SriovFecClusterConfig object
type SriovFecClusterConfigReconciler struct {
client.Client
Log *logrus.Logger
Scheme *runtime.Scheme
}
// +kubebuilder:rbac:groups=sriovfec.intel.com,resources=sriovfecclusterconfigs,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=sriovfec.intel.com,resources=sriovfecclusterconfigs/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=sriovfec.intel.com,resources=sriovfecnodeconfigs,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=sriovfec.intel.com,resources=sriovfecnodeconfigs/status,verbs=get;update;patch
// +kubebuilder:rbac:groups="",resources=nodes,verbs=list;watch
// +kubebuilder:rbac:groups="",resources=namespaces;serviceaccounts;configmaps,verbs=*
// +kubebuilder:rbac:groups=apps,resources=daemonsets;deployments;deployments/finalizers,verbs=*
// +kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=roles;rolebindings;clusterroles;clusterrolebindings,verbs=*
// +kubebuilder:rbac:groups=security.openshift.io,resources=securitycontextconstraints,verbs=*
func (r *SriovFecClusterConfigReconciler) Reconcile(_ context.Context, req ctrl.Request) (ctrl.Result, error) {
r.Log.Infof("Reconcile(...) triggered by %s", req.NamespacedName.String())
clusterConfigList := new(sriovfecv2.SriovFecClusterConfigList)
if err := r.List(context.TODO(), clusterConfigList, client.InNamespace(NAMESPACE)); err != nil {
r.Log.WithError(err).Error("cannot obtain list of SriovFecClusterConfig, rescheduling rescheduling reconcile call")
return ctrl.Result{}, err
}
nodes, err := r.getAcceleratedNodes()
if err != nil {
r.Log.WithError(err).Info("cannot obtain list of accelerated nodes, rescheduling rescheduling reconcile call")
return reconcile.Result{}, err
}
clusterConfigurationMatcher := createClusterConfigMatcher(r.getOrInitializeSriovFecNodeConfig, r.Log)
for _, node := range nodes {
configurationContextProvider, err := clusterConfigurationMatcher.match(node, clusterConfigList.Items)
if err != nil {
r.Log.WithField("node", node.Name).WithField("error", err).Info("Error when matching SriovFecClusterConfigs")
continue
}
if err := r.synchronizeNodeConfigSpec(*configurationContextProvider); err != nil {
r.Log.WithField("name", node.Name).WithField("error", err).Info("failed to propagate configuration into SriovFecNodeConfig")
err := retry.RetryOnConflict(retry.DefaultBackoff, func() error {
snc := new(sriovfecv2.SriovFecNodeConfig)
if err := r.Get(context.TODO(), types.NamespacedName{Namespace: NAMESPACE, Name: node.Name}, snc); err != nil {
return err
}
setConfigurationPropagationConditionFailed(&snc.Status.Conditions, snc.GetGeneration(), err.Error())
r.Log.
WithField("sfnc", snc).
Info("updating svnc status")
return r.Status().Update(context.TODO(), snc)
})
if err != nil {
r.Log.WithError(err).WithField("name", node.Name).Error("failed to set ConfigurationPropagationCondition for SriovFecNodeConfig")
}
continue
}
}
return r.requeueIfClusterConfigExists(req.NamespacedName)
}
func (r *SriovFecClusterConfigReconciler) requeueIfClusterConfigExists(cc types.NamespacedName) (ctrl.Result, error) {
sfcc := &sriovfecv2.SriovFecClusterConfig{}
err := r.Get(context.TODO(), cc, sfcc)
if err != nil {
if errors.IsNotFound(err) {
return ctrl.Result{}, nil
}
return ctrl.Result{}, fmt.Errorf("failed to get ClusterConfig to determine whenever reconcile is needed - %v", err)
}
return ctrl.Result{RequeueAfter: time.Minute}, nil
}
func (r *SriovFecClusterConfigReconciler) synchronizeNodeConfigSpec(ncc NodeConfigurationCtx) error {
copyWithEmptySpec := func(nc sriovfecv2.SriovFecNodeConfig) *sriovfecv2.SriovFecNodeConfig {
newNC := nc.DeepCopy()
newNC.Spec = sriovfecv2.SriovFecNodeConfigSpec{
PhysicalFunctions: []sriovfecv2.PhysicalFunctionConfigExt{},
}
return newNC
}
currentNodeConfig := ncc.SriovFecNodeConfig
acceleratorConfigContext := ncc.AcceleratorConfigContext
newNodeConfig := copyWithEmptySpec(ncc.SriovFecNodeConfig)
for pciAddress, cc := range acceleratorConfigContext {
pf := sriovfecv2.PhysicalFunctionConfigExt{
PCIAddress: pciAddress,
PFDriver: cc.Spec.PhysicalFunction.PFDriver,
VFDriver: cc.Spec.PhysicalFunction.VFDriver,
VFAmount: cc.Spec.PhysicalFunction.VFAmount,
BBDevConfig: cc.Spec.PhysicalFunction.BBDevConfig,
}
newNodeConfig.Spec.DrainSkip = newNodeConfig.Spec.DrainSkip || cc.Spec.DrainSkip
newNodeConfig.Spec.PhysicalFunctions = append(newNodeConfig.Spec.PhysicalFunctions, pf)
}
// copy latest known drainSkip from NodeConfig for cleanup
if len(acceleratorConfigContext) == 0 {
newNodeConfig.Spec.DrainSkip = ncc.Spec.DrainSkip
}
if !equality.Semantic.DeepEqual(newNodeConfig.Spec, currentNodeConfig.Spec) {
return r.Update(context.TODO(), newNodeConfig)
}
return nil
}
func (r *SriovFecClusterConfigReconciler) getAcceleratedNodes() ([]corev1.Node, error) {
nl := new(corev1.NodeList)
labelsToMatch := &client.MatchingLabels{
"fpga.intel.com/intel-accelerator-present": "",
}
if err := r.List(context.TODO(), nl, labelsToMatch); err != nil {
return nil, err
}
return nl.Items, nil
}
func (r *SriovFecClusterConfigReconciler) getOrInitializeSriovFecNodeConfig(name string) (*sriovfecv2.SriovFecNodeConfig, error) {
nc := new(sriovfecv2.SriovFecNodeConfig)
if err := r.Get(context.TODO(), client.ObjectKey{Name: name, Namespace: NAMESPACE}, nc); err != nil {
if !errors.IsNotFound(err) {
return nil, err
}
nc.Name = name
nc.Namespace = NAMESPACE
nc.Spec.PhysicalFunctions = []sriovfecv2.PhysicalFunctionConfigExt{}
}
return nc, nil
}
func (r *SriovFecClusterConfigReconciler) SetupWithManager(mgr ctrl.Manager) error {
// Add NodeConfigs & DaemonSet
return ctrl.NewControllerManagedBy(mgr).
For(&sriovfecv2.SriovFecClusterConfig{}).
Complete(r)
}
// key: accelerator pciAddress
type AcceleratorConfigContext map[string]sriovfecv2.SriovFecClusterConfig
type NodeConfigurationCtx struct {
sriovfecv2.SriovFecNodeConfig
AcceleratorConfigContext
}
func createClusterConfigMatcher(ncp nodeConfigProvider, l *logrus.Logger) *clusterConfigMatcher {
return &clusterConfigMatcher{
getNodeConfig: ncp,
log: l,
}
}
type nodeConfigProvider func(nodeName string) (*sriovfecv2.SriovFecNodeConfig, error)
type clusterConfigMatcher struct {
getNodeConfig nodeConfigProvider
log *logrus.Logger
}
func (pm *clusterConfigMatcher) match(node corev1.Node, allConfigs []sriovfecv2.SriovFecClusterConfig) (*NodeConfigurationCtx, error) {
matchingClusterConfigs := matchConfigsForNode(&node, allConfigs)
nodeConfig, err := pm.getNodeConfig(node.Name)
if err != nil {
return nil, fmt.Errorf("error occurred when reading SriovFecNodeConfig: %s", err.Error())
}
acceleratorConfigContext := pm.prepareAcceleratorConfigContext(nodeConfig, matchingClusterConfigs)
return &NodeConfigurationCtx{*nodeConfig, acceleratorConfigContext}, nil
}
func (pm *clusterConfigMatcher) prepareAcceleratorConfigContext(nodeConfig *sriovfecv2.SriovFecNodeConfig, configs []sriovfecv2.SriovFecClusterConfig) AcceleratorConfigContext {
acceleratorConfigContext := make(AcceleratorConfigContext)
for _, current := range configs {
for _, accelerator := range nodeConfig.Status.Inventory.SriovAccelerators {
if current.Spec.AcceleratorSelector.Matches(accelerator) {
if _, ok := acceleratorConfigContext[accelerator.PCIAddress]; !ok {
acceleratorConfigContext[accelerator.PCIAddress] = current
continue
}
previous := acceleratorConfigContext[accelerator.PCIAddress]
switch {
case current.Spec.Priority > previous.Spec.Priority: //override with higher prioritized config
acceleratorConfigContext[accelerator.PCIAddress] = current
case current.Spec.Priority == previous.Spec.Priority: //multiple configs with same priority; drop older one
//TODO: Update Timestamp would be better than CreationTime
if current.CreationTimestamp.After(previous.CreationTimestamp.Time) {
pm.log.WithFields(logrus.Fields{
"Node": nodeConfig.Name,
"SriovFecClusterConfig": previous.Name,
"Priority": previous.Spec.Priority,
"CreationTimestamp": previous.CreationTimestamp.String(),
}).Info("Dropping older ClusterConfig")
acceleratorConfigContext[accelerator.PCIAddress] = current
}
case current.Spec.Priority < previous.Spec.Priority: //drop current with lower priority
pm.log.WithFields(logrus.Fields{
"node": nodeConfig.Name,
"SriovFecClusterConfig": current.Name,
"priority": current.Spec.Priority,
}).Info("Dropping low prioritized ClusterConfig")
}
}
}
}
return acceleratorConfigContext
}
func matchConfigsForNode(node *corev1.Node, allConfigs []sriovfecv2.SriovFecClusterConfig) (nodeConfigs []sriovfecv2.SriovFecClusterConfig) {
nodeLabels := labels.Set(node.Labels)
for _, config := range allConfigs {
nodeSelector := labels.Set(config.Spec.NodeSelector)
if nodeSelector.AsSelector().Matches(nodeLabels) {
nodeConfigs = append(nodeConfigs, config)
}
}
return
}
func setConfigurationPropagationConditionFailed(conditions *[]metav1.Condition, generation int64, msg string) {
meta.SetStatusCondition(conditions, metav1.Condition{
Type: "ConfigurationPropagationCondition",
Status: metav1.ConditionFalse,
ObservedGeneration: generation,
Reason: "Failed",
Message: msg,
})
}