|
| 1 | +/* |
| 2 | +Copyright 2024 The CloudPilot AI Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package status |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "sort" |
| 22 | + "time" |
| 23 | + |
| 24 | + "github.com/samber/lo" |
| 25 | + corev1 "k8s.io/api/core/v1" |
| 26 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 27 | + "sigs.k8s.io/controller-runtime/pkg/reconcile" |
| 28 | + karpv1 "sigs.k8s.io/karpenter/pkg/apis/v1" |
| 29 | + |
| 30 | + "github.com/cloudpilot-ai/karpenter-provider-alicloud/pkg/apis/v1alpha1" |
| 31 | + "github.com/cloudpilot-ai/karpenter-provider-alicloud/pkg/providers/imagefamily" |
| 32 | +) |
| 33 | + |
| 34 | +type Image struct { |
| 35 | + imageProvider imagefamily.Provider |
| 36 | +} |
| 37 | + |
| 38 | +func (i *Image) Reconcile(ctx context.Context, nodeClass *v1alpha1.ECSNodeClass) (reconcile.Result, error) { |
| 39 | + images, err := i.imageProvider.List(ctx, nodeClass) |
| 40 | + if err != nil { |
| 41 | + log.FromContext(ctx).Error(err, "failed to list images") |
| 42 | + return reconcile.Result{}, err |
| 43 | + } |
| 44 | + |
| 45 | + if len(images) == 0 { |
| 46 | + nodeClass.Status.Images = nil |
| 47 | + nodeClass.StatusConditions().SetFalse(v1alpha1.ConditionTypeImagesReady, "ImagesNotFound", "ImageSelector did not match any Images") |
| 48 | + return reconcile.Result{}, nil |
| 49 | + } |
| 50 | + |
| 51 | + nodeClass.Status.Images = lo.Map(images, func(image imagefamily.Image, _ int) v1alpha1.Image { |
| 52 | + reqs := lo.Map(image.Requirements.NodeSelectorRequirements(), func(item karpv1.NodeSelectorRequirementWithMinValues, _ int) corev1.NodeSelectorRequirement { |
| 53 | + return item.NodeSelectorRequirement |
| 54 | + }) |
| 55 | + |
| 56 | + sort.Slice(reqs, func(i, j int) bool { |
| 57 | + if len(reqs[i].Key) != len(reqs[j].Key) { |
| 58 | + return len(reqs[i].Key) < len(reqs[j].Key) |
| 59 | + } |
| 60 | + return reqs[i].Key < reqs[j].Key |
| 61 | + }) |
| 62 | + return v1alpha1.Image{ |
| 63 | + Name: image.Name, |
| 64 | + ID: image.ImageID, |
| 65 | + Requirements: reqs, |
| 66 | + } |
| 67 | + }) |
| 68 | + nodeClass.StatusConditions().SetTrue(v1alpha1.ConditionTypeImagesReady) |
| 69 | + return reconcile.Result{RequeueAfter: 5 * time.Minute}, nil |
| 70 | +} |
0 commit comments