...

Source file src/github.com/chaos-mesh/chaos-mesh/controllers/schedule/cron/utils.go

Documentation: github.com/chaos-mesh/chaos-mesh/controllers/schedule/cron

     1  // Copyright 2021 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package cron
    15  
    16  import (
    17  	"fmt"
    18  	"time"
    19  
    20  	"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
    21  )
    22  
    23  // Get this function from Kubernetes
    24  
    25  // getRecentUnmetScheduleTime gets the most recent time that have passed when a Job should have started but did not.
    26  //
    27  // If there are too many (>100) unstarted times, just give up and return a nil.
    28  func getRecentUnmetScheduleTime(schedule *v1alpha1.Schedule, now time.Time) (*time.Time, *time.Time, error) {
    29  	sched, err := v1alpha1.StandardCronParser.Parse(schedule.Spec.Schedule)
    30  	if err != nil {
    31  		return nil, nil, fmt.Errorf("unparseable schedule: %s : %s", schedule.Spec.Schedule, err)
    32  	}
    33  
    34  	var earliestTime time.Time
    35  	if !schedule.Status.LastScheduleTime.UTC().IsZero() {
    36  		earliestTime = schedule.Status.LastScheduleTime.Time
    37  	} else {
    38  		earliestTime = schedule.ObjectMeta.CreationTimestamp.Time
    39  	}
    40  	if schedule.Spec.StartingDeadlineSeconds != nil {
    41  		schedulingDeadline := now.Add(-time.Second * time.Duration(*schedule.Spec.StartingDeadlineSeconds))
    42  
    43  		if schedulingDeadline.After(earliestTime) {
    44  			earliestTime = schedulingDeadline
    45  		}
    46  	}
    47  	if earliestTime.After(now) {
    48  		return nil, nil, fmt.Errorf("earliestTime is later than now: earliestTime: %v, now: %v", earliestTime, now)
    49  	}
    50  
    51  	iterateTime := 0
    52  	var missedRun *time.Time
    53  	nextRun := sched.Next(earliestTime)
    54  	for t := sched.Next(earliestTime); !t.After(now); t = sched.Next(t) {
    55  		t := t
    56  
    57  		missedRun = &t
    58  		nextRun = sched.Next(*missedRun)
    59  
    60  		iterateTime++
    61  		if iterateTime > 100 {
    62  			// We can't get the most recent times so just return an empty slice
    63  			return nil, nil, fmt.Errorf("too many missed start time (> 100). Set or decrease .spec.startingDeadlineSeconds or check clock skew")
    64  		}
    65  	}
    66  
    67  	return missedRun, &nextRun, nil
    68  }
    69