dijob_controller_test.go 11.8 KB
Newer Older
L
liqingping 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package controllers

import (
	"context"
	"fmt"
	"strings"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"sigs.k8s.io/controller-runtime/pkg/client"

	div1alpha1 "opendilab.org/di-orchestrator/api/v1alpha1"
L
liqingping 已提交
16
	dicommon "opendilab.org/di-orchestrator/common"
L
liqingping 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
	diutil "opendilab.org/di-orchestrator/utils"
	testutil "opendilab.org/di-orchestrator/utils/testutils"
)

var _ = Describe("DIJob Controller", func() {

	Context("When creating a DIJob", func() {
		It("Should be succeeded", func() {
			By("Create a DIJob")
			var err error
			ctx := context.Background()
			jobTmpl := testutil.NewDIJob()
			dijob, jobKey := createDIJob(ctx, k8sClient, jobTmpl)

			By("Update coordinator to Running")
			for _, replicaName := range []string{
				diutil.ReplicaPodName(dijob.Name, "coordinator"),
			} {
				podKey := types.NamespacedName{Namespace: dijob.Namespace, Name: replicaName}
				err = testutil.UpdatePodPhase(ctx, k8sClient, podKey, corev1.PodRunning)
				Expect(err).NotTo(HaveOccurred())
			}

L
liqingping 已提交
40
			var createdDIjob div1alpha1.DIJob
L
liqingping 已提交
41 42 43
			By("Checking the created DIJob has enough coordinator")
			for _, rtype := range []div1alpha1.ReplicaType{div1alpha1.ReplicaTypeCoordinator} {
				Eventually(func() int {
L
liqingping 已提交
44
					err := k8sClient.Get(ctx, jobKey, &createdDIjob)
L
liqingping 已提交
45 46 47
					if err != nil {
						return -1
					}
L
liqingping 已提交
48
					if createdDIjob.Status.ReplicaStatus == nil {
L
liqingping 已提交
49 50
						return -1
					}
L
liqingping 已提交
51
					return int(createdDIjob.Status.ReplicaStatus[rtype].Active)
L
liqingping 已提交
52 53 54 55 56
				}, timeout, interval).Should(Equal(1))
			}

			By("Checking the created DIJob is in Running state")
			Eventually(func() bool {
L
liqingping 已提交
57
				err := k8sClient.Get(ctx, jobKey, &createdDIjob)
L
liqingping 已提交
58 59 60
				if err != nil {
					return false
				}
L
liqingping 已提交
61
				return createdDIjob.Status.Phase == div1alpha1.JobRunning
L
liqingping 已提交
62 63 64 65
			}, duration, interval).Should(BeTrue())

			By("Update coordinator to Succeeded")
			for _, replicaName := range []string{
L
liqingping 已提交
66
				diutil.ReplicaPodName(createdDIjob.Name, "coordinator"),
L
liqingping 已提交
67
			} {
L
liqingping 已提交
68
				podKey := types.NamespacedName{Namespace: createdDIjob.Namespace, Name: replicaName}
L
liqingping 已提交
69 70 71 72 73 74
				err = testutil.UpdatePodPhase(ctx, k8sClient, podKey, corev1.PodSucceeded)
				Expect(err).NotTo(HaveOccurred())
			}

			By("Checking the job is succeeded")
			Eventually(func() div1alpha1.Phase {
L
liqingping 已提交
75
				err := k8sClient.Get(ctx, jobKey, &createdDIjob)
L
liqingping 已提交
76 77 78
				if err != nil {
					return div1alpha1.JobUnknown
				}
L
liqingping 已提交
79
				return createdDIjob.Status.Phase
L
liqingping 已提交
80 81 82 83
			}, timeout, interval).Should(Equal(div1alpha1.JobSucceeded))

			By("Checking the coordinator is succeeded")
			Eventually(func() int {
L
liqingping 已提交
84
				err := k8sClient.Get(ctx, jobKey, &createdDIjob)
L
liqingping 已提交
85 86 87
				if err != nil {
					return -1
				}
L
liqingping 已提交
88
				return int(createdDIjob.Status.ReplicaStatus[div1alpha1.ReplicaTypeCoordinator].Succeeded)
L
liqingping 已提交
89 90 91
			}, timeout, interval).Should(Equal(1))

			By("Cleaning up")
L
liqingping 已提交
92
			err = testutil.CleanUpJob(ctx, k8sClient, createdDIjob.DeepCopy())
L
liqingping 已提交
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
			Expect(err).NotTo(HaveOccurred())
		})

		It("DIJob status changed with components status", func() {
			type testCase struct {
				coorStatus   corev1.PodPhase
				expectStatus div1alpha1.Phase
			}
			testCases := []testCase{
				{coorStatus: corev1.PodRunning, expectStatus: div1alpha1.JobRunning},
				{coorStatus: corev1.PodFailed, expectStatus: div1alpha1.JobFailed},
				{coorStatus: corev1.PodSucceeded, expectStatus: div1alpha1.JobSucceeded},
			}
			for i := range testCases {
				c := testCases[i]

				By(fmt.Sprintf("Create the %dth DIJob", i+1))
				var err error
				ctx := context.Background()
				jobTmpl := testutil.NewDIJob()
				dijob, jobKey := createDIJob(ctx, k8sClient, jobTmpl)

				By("Update coordinator status")
				for _, replicaName := range []string{
					diutil.ReplicaPodName(dijob.Name, "coordinator"),
				} {
					podKey := types.NamespacedName{Namespace: dijob.Namespace, Name: replicaName}
					if strings.HasSuffix(replicaName, "coordinator") {
						err = testutil.UpdatePodPhase(ctx, k8sClient, podKey, c.coorStatus)
					}
					Expect(err).NotTo(HaveOccurred())
				}

				By("Checking the created DIJob has enough coordinator")
				Eventually(func() int {
					err := k8sClient.Get(ctx, jobKey, &dijob)
					if err != nil {
						return -1
					}
					if dijob.Status.ReplicaStatus == nil {
						return -1
					}

					// get phase
					var phase corev1.PodPhase = c.coorStatus
					count := 0
					switch phase {
					case corev1.PodRunning:
						count = int(dijob.Status.ReplicaStatus[div1alpha1.ReplicaTypeCoordinator].Active)
					case corev1.PodFailed:
						count = int(dijob.Status.ReplicaStatus[div1alpha1.ReplicaTypeCoordinator].Failed)
					case corev1.PodSucceeded:
						count = int(dijob.Status.ReplicaStatus[div1alpha1.ReplicaTypeCoordinator].Succeeded)
					}
					return count
				}, timeout, interval).Should(Equal(1))

				By("Checking the created DIJob's state")
				Eventually(func() div1alpha1.Phase {
					err := k8sClient.Get(ctx, jobKey, &dijob)
					if err != nil {
						return div1alpha1.JobUnknown
					}
					return dijob.Status.Phase
				}, timeout, interval).Should(Equal(c.expectStatus))

				By("Cleaning up")
L
liqingping 已提交
160
				err = testutil.CleanUpJob(ctx, k8sClient, dijob.DeepCopy())
L
liqingping 已提交
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
				Expect(err).NotTo(HaveOccurred())
			}
		})
	})
	Context("When creating a DIJob with collectors and learners", func() {
		It("Should record collector and learner status to job status", func() {
			type replica struct {
				name   string
				status corev1.PodPhase
			}
			type testCase struct {
				collectors []replica
				learners   []replica
			}
			testCases := []testCase{
				{
					collectors: []replica{
						{name: "job-collector-sdf", status: corev1.PodRunning},
					},
					learners: []replica{
						{name: "job-learner-sdf", status: corev1.PodRunning},
					},
				},
				{
					collectors: []replica{
						{name: "job-collector-sdf", status: corev1.PodRunning},
						{name: "job-collector-4tf", status: corev1.PodFailed},
					},
					learners: []replica{
						{name: "job-learner-sdf", status: corev1.PodRunning},
					},
				},
				{
					collectors: []replica{
						{name: "job-collector-sdf", status: corev1.PodRunning},
						{name: "job-collector-4tf", status: corev1.PodFailed},
					},
					learners: []replica{
						{name: "job-learner-sdf", status: corev1.PodSucceeded},
						{name: "job-learner-s4t", status: corev1.PodRunning},
					},
				},
			}
			for i := range testCases {
				c := testCases[i]
				By(fmt.Sprintf("Create %dth DIJob", i+1))
				var err error
				ctx := context.Background()
				jobTmpl := testutil.NewDIJob()
				dijob, jobKey := createDIJob(ctx, k8sClient, jobTmpl)

				// build owner reference
				ownRefer := metav1.OwnerReference{
					APIVersion: div1alpha1.GroupVersion.String(),
					Kind:       div1alpha1.KindDIJob,
					Name:       dijob.Name,
					UID:        dijob.GetUID(),
					Controller: func(c bool) *bool { return &c }(true),
				}

				By(fmt.Sprintf("Create replicas for DIJob %s", dijob.Name))
				colStatus := make([]int, 3)
				for _, col := range c.collectors {
L
liqingping 已提交
224
					createAndUpdatePodPhase(ctx, k8sClient, col.name, dijob.Name, col.status, dicommon.CollectorName, ownRefer, colStatus)
L
liqingping 已提交
225 226 227 228
				}

				lrStatus := make([]int, 3)
				for _, lr := range c.learners {
L
liqingping 已提交
229
					createAndUpdatePodPhase(ctx, k8sClient, lr.name, dijob.Name, lr.status, dicommon.LearnerName, ownRefer, lrStatus)
L
liqingping 已提交
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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
				}

				By("Checking the ReplicaStatus is as expected")
				for _, rtype := range []div1alpha1.ReplicaType{
					div1alpha1.ReplicaTypeCollector,
					div1alpha1.ReplicaTypeLearner,
				} {
					var status []int
					switch rtype {
					case div1alpha1.ReplicaTypeCollector:
						status = colStatus
					case div1alpha1.ReplicaTypeLearner:
						status = lrStatus
					}
					Eventually(func() []int {
						err = k8sClient.Get(ctx, jobKey, &dijob)
						if err != nil {
							return nil
						}
						result := make([]int, 3)
						result[0] = int(dijob.Status.ReplicaStatus[rtype].Active)
						result[1] = int(dijob.Status.ReplicaStatus[rtype].Failed)
						result[2] = int(dijob.Status.ReplicaStatus[rtype].Succeeded)
						return result
					}, timeout, interval).Should(Equal(status))
				}

				By("Update coordinator to Succeeded")
				for _, replicaName := range []string{
					diutil.ReplicaPodName(dijob.Name, "coordinator"),
				} {
					podKey := types.NamespacedName{Namespace: dijob.Namespace, Name: replicaName}
					err = testutil.UpdatePodPhase(ctx, k8sClient, podKey, corev1.PodSucceeded)
					Expect(err).NotTo(HaveOccurred())
				}

				By("Checking the job is successfully succeeded")
				Eventually(func() div1alpha1.Phase {
					err := k8sClient.Get(ctx, jobKey, &dijob)
					if err != nil {
						return div1alpha1.JobUnknown
					}
					return dijob.Status.Phase
				}, timeout, interval).Should(Equal(div1alpha1.JobSucceeded))

				By("Checking the coordinator is succeeded")
				Eventually(func() int {
					err := k8sClient.Get(ctx, jobKey, &dijob)
					if err != nil {
						return -1
					}
					return int(dijob.Status.ReplicaStatus[div1alpha1.ReplicaTypeCoordinator].Succeeded)
				}, timeout, interval).Should(Equal(1))

				colStatus1 := make([]int, 3)
				lrStatus1 := make([]int, 3)
				colStatus1[0] = 0
				colStatus1[1] = colStatus[1]
				colStatus1[2] = colStatus[0] + colStatus[2]
				lrStatus1[0] = 0
				lrStatus1[1] = lrStatus[1]
				lrStatus1[2] = lrStatus[0] + lrStatus[2]

				By("Checking the ReplicaStatus is as expected")
				for _, rtype := range []div1alpha1.ReplicaType{
					div1alpha1.ReplicaTypeCollector,
					div1alpha1.ReplicaTypeLearner,
				} {
					var status []int
					switch rtype {
					case div1alpha1.ReplicaTypeCollector:
						status = colStatus1
					case div1alpha1.ReplicaTypeLearner:
						status = lrStatus1
					}
					Eventually(func() []int {
						err = k8sClient.Get(ctx, jobKey, &dijob)
						if err != nil {
							return nil
						}
						result := make([]int, 3)
						result[0] = int(dijob.Status.ReplicaStatus[rtype].Active)
						result[1] = int(dijob.Status.ReplicaStatus[rtype].Failed)
						result[2] = int(dijob.Status.ReplicaStatus[rtype].Succeeded)
						return result
					}, timeout, interval).Should(Equal(status))
				}

L
liqingping 已提交
318
				err = testutil.CleanUpJob(ctx, k8sClient, dijob.DeepCopy())
L
liqingping 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
				Expect(err).NotTo(HaveOccurred())
			}
		})
	})
})

func createDIJob(ctx context.Context, k8sClient client.Client, dijob *div1alpha1.DIJob) (
	div1alpha1.DIJob, types.NamespacedName) {
	name := diutil.GenerateName(dijob.Name)
	dijob.SetName(name)

	err := k8sClient.Create(ctx, dijob, &client.CreateOptions{})
	Expect(err).ShouldNot(HaveOccurred())

	By(fmt.Sprintf("Checking the DIJob %s is successfully created", name))
	key := types.NamespacedName{Namespace: dijob.Namespace, Name: dijob.Name}
L
liqingping 已提交
335
	createdDIjob := div1alpha1.DIJob{}
L
liqingping 已提交
336
	Eventually(func() bool {
L
liqingping 已提交
337
		err := k8sClient.Get(ctx, key, &createdDIjob)
L
liqingping 已提交
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
		if err != nil {
			return false
		}
		return true
	}, timeout, interval).Should(BeTrue())

	By("Checking coordinator are created")
	replicaName := diutil.ReplicaPodName(dijob.Name, "coordinator")
	var pod corev1.Pod
	podKey := types.NamespacedName{Namespace: dijob.Namespace, Name: replicaName}
	Eventually(func() bool {
		err = k8sClient.Get(ctx, podKey, &pod)
		if err != nil {
			return false
		}
		return true
	}, timeout, interval).Should(BeTrue())

L
liqingping 已提交
356
	return createdDIjob, key
L
liqingping 已提交
357 358 359 360 361 362 363 364 365
}

func createAndUpdatePodPhase(
	ctx context.Context, k8sClient client.Client,
	name, jobName string, status corev1.PodPhase, replicaType string,
	ownRefer metav1.OwnerReference, statuses []int) {

	pod := testutil.NewPod(name, jobName, ownRefer)
	labs := diutil.GenLabels(jobName)
L
liqingping 已提交
366 367
	labs[dicommon.ReplicaTypeLabel] = replicaType
	labs[dicommon.PodNameLabel] = pod.Name
L
liqingping 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
	pod.SetLabels(labs)

	err := k8sClient.Create(ctx, pod, &client.CreateOptions{})
	Expect(err).NotTo(HaveOccurred())

	podKey := types.NamespacedName{Namespace: pod.Namespace, Name: pod.Name}
	testutil.UpdatePodPhase(ctx, k8sClient, podKey, status)

	switch status {
	case corev1.PodRunning:
		statuses[0]++
	case corev1.PodFailed:
		statuses[1]++
	case corev1.PodSucceeded:
		statuses[2]++
	}
}