@@ -267,6 +267,8 @@ func (c *Service) CreateHPA(ctx context.Context, tortoise *autoscalingv1beta3.To
267267 },
268268 }
269269
270+ c .copyLabelsFromTortoiseToHPA (tortoise , hpa )
271+
270272 hpa , tortoise , _ = c .syncHPAMetricsWithTortoiseAutoscalingPolicy (ctx , tortoise , hpa , now )
271273
272274 tortoise .Status .Targets .HorizontalPodAutoscaler = hpa .Name
@@ -275,6 +277,62 @@ func (c *Service) CreateHPA(ctx context.Context, tortoise *autoscalingv1beta3.To
275277 return hpa .DeepCopy (), tortoise , err
276278}
277279
280+ func (c * Service ) copyLabelsFromTortoiseToHPA (tortoise * autoscalingv1beta3.Tortoise , hpa * v2.HorizontalPodAutoscaler ) {
281+ if len (tortoise .ObjectMeta .Labels ) == 0 {
282+ return
283+ }
284+
285+ hpa .ObjectMeta .Labels = make (map [string ]string , len (tortoise .ObjectMeta .Labels ))
286+ for k , v := range tortoise .ObjectMeta .Labels {
287+ hpa .ObjectMeta .Labels [k ] = v
288+ }
289+ }
290+
291+ // UpdateHPA updates HPA labels from Tortoise.
292+ // Note that it will not perform any update if the UpdateMode is Off, user specified the existing HPA, or there is no horizontal policy.
293+ func (c * Service ) UpdateHPALabelsFromTortoise (ctx context.Context , tortoise * autoscalingv1beta3.Tortoise ) error {
294+ if tortoise .Spec .UpdateMode == autoscalingv1beta3 .UpdateModeOff {
295+ // When UpdateMode is Off, we don't update HPA.
296+ return nil
297+ }
298+ if ! HasHorizontal (tortoise ) {
299+ // no need to handle when there is no horizontal policy.
300+ return nil
301+ }
302+ if tortoise .Spec .TargetRefs .HorizontalPodAutoscalerName != nil {
303+ // no need to handle when the user specified existing HPA.
304+ return nil
305+ }
306+
307+ retryNumber := - 1
308+ updateFn := func () error {
309+ retryNumber ++
310+ hpa := & v2.HorizontalPodAutoscaler {}
311+ if err := c .c .Get (ctx , types.NamespacedName {Namespace : tortoise .Namespace , Name : tortoise .Status .Targets .HorizontalPodAutoscaler }, hpa ); err != nil {
312+ return fmt .Errorf ("failed to get hpa on tortoise: %w" , err )
313+ }
314+ hpa = hpa .DeepCopy ()
315+
316+ if reflect .DeepEqual (hpa .ObjectMeta .Labels , tortoise .ObjectMeta .Labels ) {
317+ // Labels are already in sync, no need to update.
318+ return nil
319+ }
320+ c .copyLabelsFromTortoiseToHPA (tortoise , hpa )
321+
322+ if err := c .c .Update (ctx , hpa ); err != nil {
323+ return fmt .Errorf ("failed to update hpa: %w" , err )
324+ }
325+
326+ return nil
327+ }
328+
329+ if err := retry .RetryOnConflict (retry .DefaultRetry , updateFn ); err != nil {
330+ return fmt .Errorf ("update hpa labels: %w (%v times retried)" , err , retryNumber )
331+ }
332+
333+ return nil
334+ }
335+
278336func (c * Service ) GetHPAOnTortoiseSpec (ctx context.Context , tortoise * autoscalingv1beta3.Tortoise ) (* v2.HorizontalPodAutoscaler , error ) {
279337 if tortoise .Spec .TargetRefs .HorizontalPodAutoscalerName == nil {
280338 return nil , nil
0 commit comments