Skip to content

Commit

Permalink
F - oldest first sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
brianberzins committed Apr 27, 2022
1 parent 7d65c75 commit e50d832
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
13 changes: 13 additions & 0 deletions reaper/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
v1 "k8s.io/api/core/v1"
"math/rand"
"os"
"sort"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -178,6 +179,18 @@ func podSortingStrategy() (func([]v1.Pod), error) {
return func(pods []v1.Pod) {
rand.Shuffle(len(pods), func(i, j int) { pods[i], pods[j] = pods[j], pods[i] })
}, nil
case "oldest-first":
return func(pods []v1.Pod) {
sort.Slice(pods, func(i, j int) bool {
if pods[i].Status.StartTime == nil {
return false
}
if pods[j].Status.StartTime == nil {
return true
}
return pods[i].Status.StartTime.Unix() < pods[j].Status.StartTime.Unix()
})
}, nil
default:
return nil, errors.New("unknown pod sorting strategy")
}
Expand Down
29 changes: 29 additions & 0 deletions reaper/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,32 @@ func init() {
logrus.SetOutput(ioutil.Discard)
}

func epocPlus(duration time.Duration) *metav1.Time {
t := metav1.NewTime(time.Unix(0, 0).Add(duration))
return &t
}
func testPodList() []v1.Pod {
return []v1.Pod{
{
Status: v1.PodStatus{
StartTime: epocPlus(2 * time.Minute),
},
ObjectMeta: metav1.ObjectMeta{
Name: "bearded-dragon",
Annotations: map[string]string{"example/key": "lizard"},
},
},
{
Status: v1.PodStatus{},
ObjectMeta: metav1.ObjectMeta{
Name: "nil-start-time",
Annotations: map[string]string{"example/key": "lizard"},
},
},
{
Status: v1.PodStatus{
StartTime: epocPlus(1 * time.Minute),
},
ObjectMeta: metav1.ObjectMeta{
Name: "corgi",
Annotations: map[string]string{"example/key": "not-lizard"},
Expand Down Expand Up @@ -297,6 +314,18 @@ func TestOptions(t *testing.T) {
sorter(subject)
assert.NotEqual(t, testPodList(), subject)
})
t.Run("oldest-first", func(t *testing.T) {
os.Clearenv()
os.Setenv(envPodSortingStrategy, "oldest-first")
sorter, err := podSortingStrategy()
assert.NotNil(t, sorter)
assert.NoError(t, err)
subject := testPodList()
sorter(subject)
assert.Equal(t, "corgi", subject[0].ObjectMeta.Name)
assert.Equal(t, "bearded-dragon", subject[1].ObjectMeta.Name)
assert.Equal(t, "nil-start-time", subject[2].ObjectMeta.Name)
})
})
}

Expand Down

0 comments on commit e50d832

Please sign in to comment.