replicas.go 15.9 KB
Newer Older
L
leonwanghui 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// Copyright 2018 The Kubeflow Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package trainer

import (
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"strings"

	log "github.com/golang/glog"
	"k8s.io/api/core/v1"
	k8s_errors "k8s.io/apimachinery/pkg/api/errors"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	k8sErrors "k8s.io/apimachinery/pkg/util/errors"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/record"

32
	msv1 "gitee.com/mindspore/ms-operator/pkg/apis/mindspore/v1"
L
leonwanghui 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
	"gitee.com/mindspore/ms-operator/pkg/util/k8sutil"
	"gitee.com/mindspore/ms-operator/pkg/apis/mindspore/helper"
	"gitee.com/mindspore/ms-operator/pkg/util"
)

const (
	SuccessfulCreateReason = "SuccessfulCreate"
	FailedCreateReason     = "FailedCreate"
)

// MSReplicaSet is a set of MS processes all acting as the same role (e.g. worker
type MSReplicaSet struct {
	ClientSet kubernetes.Interface
	recorder  record.EventRecorder
	// Job is a pointer to the TrainingJob to which this replica belongs.
	Job  *TrainingJob
49
	Spec msv1.MSReplicaSpec
L
leonwanghui 已提交
50 51 52 53 54 55
}

// MSReplicas is an interface for managing a set of replicas.
type MSReplicaSetInterface interface {
	Create() error
	Delete() error
56
	GetStatus() (msv1.MSReplicaStatus, error)
L
leonwanghui 已提交
57 58
}

59 60
// MSConfig is a struct representing the MindSpore config. This struct is turned into an environment
// which is used by MindSpore processes to configure themselves.
L
leonwanghui 已提交
61 62 63 64 65 66
type MSConfig struct {
	Cluster     ClusterSpec `json:"cluster"`
	Task        TaskSpec    `json:"task"`
	Environment string      `json:"environment"`
}

67 68
func NewMSReplicaSet(clientSet kubernetes.Interface, recorder record.EventRecorder, msReplicaSpec msv1.MSReplicaSpec, job *TrainingJob) (*MSReplicaSet, error) {
	if msReplicaSpec.MSReplicaType == msv1.MASTER && *msReplicaSpec.Replicas != 1 {
L
leonwanghui 已提交
69 70 71
		return nil, errors.New("The MASTER must have Replicas = 1")
	}

72 73
	if msReplicaSpec.MasterPort == nil {
		return nil, errors.New("msReplicaSpec.MasterPort can't be nil.")
L
leonwanghui 已提交
74 75 76
	}

	// Make sure the replica type is valid.
77
	validReplicaTypes := []msv1.MSReplicaType{msv1.MASTER, msv1.WORKER}
L
leonwanghui 已提交
78 79 80

	isValidReplicaType := false
	for _, t := range validReplicaTypes {
81
		if t == msReplicaSpec.MSReplicaType {
L
leonwanghui 已提交
82 83 84 85 86 87
			isValidReplicaType = true
			break
		}
	}

	if !isValidReplicaType {
88
		return nil, fmt.Errorf("msReplicaSpec.MSReplicaType is %v but must be one of %v", msReplicaSpec.MSReplicaType, validReplicaTypes)
L
leonwanghui 已提交
89 90 91 92 93 94
	}

	return &MSReplicaSet{
		ClientSet: clientSet,
		recorder:  recorder,
		Job:       job,
95
		Spec:      msReplicaSpec,
L
leonwanghui 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109
	}, nil
}

// Labels returns the labels for this replica set.
func (s *MSReplicaSet) Labels() KubernetesLabels {
	return KubernetesLabels(map[string]string{
		"kubeflow.org": "",
		"job_type":     string(s.Spec.MSReplicaType),
		// runtime_id is set by Job.setup, which is called after the MSReplicaSet is created.
		// this is why labels aren't a member variable.
		"runtime_id":       s.Job.job.Spec.RuntimeId,
		"ms_job_name": s.Job.job.ObjectMeta.Name})
}

110
func (s *MSReplicaSet) Create(config *msv1.ControllerConfig, worldSize int32) error {
L
leonwanghui 已提交
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
	// Create services
	err := s.SyncServices()
	if err != nil {
		return err
	}

	// Create pods
	return s.SyncPods(worldSize)
}

// CreateServiceWithIndex will create a new service with specify index
func (s *MSReplicaSet) CreateServiceWithIndex(index int32) (*v1.Service, error) {
	taskLabels := s.Labels()
	taskLabels["task_index"] = fmt.Sprintf("%v", index)

	// Create the service.
	service := &v1.Service{
		ObjectMeta: meta_v1.ObjectMeta{
			Name:   s.genName(index),
			Labels: taskLabels,
			OwnerReferences: []meta_v1.OwnerReference{
				helper.AsOwner(s.Job.job),
			},
		},
		Spec: v1.ServiceSpec{
			Selector: taskLabels,
			Ports: []v1.ServicePort{
				{
139
					Name: "ms-port",
L
leonwanghui 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
					Port: *s.Spec.MasterPort,
				},
			},
		},
	}

	log.Infof("Creating service: %v", service.ObjectMeta.Name)
	return s.ClientSet.CoreV1().Services(s.Job.job.ObjectMeta.Namespace).Create(service)
}

// CreatePodWithIndex will create a new pod with specify index
func (s *MSReplicaSet) CreatePodWithIndex(index int32, worldSize int32) (*v1.Pod, error) {
	taskLabels := s.Labels()
	taskLabels["task_index"] = fmt.Sprintf("%v", index)

	pod := &v1.Pod{
		ObjectMeta: meta_v1.ObjectMeta{
			Name:   s.genPodName(index),
			Labels: taskLabels,
			OwnerReferences: []meta_v1.OwnerReference{
				helper.AsOwner(s.Job.job),
			},
		},
		Spec: *s.Spec.Template.Spec.DeepCopy(),
	}

	pod.Spec.SchedulerName = s.Job.SchedulerName()

	// Configure the MS distributed environment variables
	masterPort := strconv.Itoa(int(*s.Spec.MasterPort))
	masterAddr := fmt.Sprintf("%v-%v-%v-%v", fmt.Sprintf("%.40s", s.Job.job.ObjectMeta.Name), "master", s.Job.job.Spec.RuntimeId, 0)
	if index == 0 {
		masterAddr = "localhost"
	}
	rank := strconv.Itoa(int(index))
175
	msConfig := MSConfig{
L
leonwanghui 已提交
176 177 178 179 180 181 182 183 184
		Cluster: s.Job.ClusterSpec(),
		Task: TaskSpec{
			Type:  strings.ToLower(string(s.Spec.MSReplicaType)),
			Index: int(index),
		},
		// We need to set environment to cloud  otherwise it will default to local which isn't what we want.
		Environment: "cloud",
	}

185
	msConfigJson, err := json.Marshal(msConfig)
L
leonwanghui 已提交
186
	if err != nil {
187
		log.Errorf("Job: %v serializing msConfig: %v return error; %v", s.Job.job.ObjectMeta.Name, util.Pformat(msConfig), err)
L
leonwanghui 已提交
188 189 190
		return nil, err
	}

191
	// Add MS_CONFIG environment variable.
L
leonwanghui 已提交
192 193 194 195
	for i, _ := range pod.Spec.Containers {
		// We can't get c in the loop variable because that would be by value so our modifications
		// wouldn't have any effect.
		c := &pod.Spec.Containers[i]
196
		if c.Name != msv1.DefaultMSContainer {
L
leonwanghui 已提交
197 198 199 200 201 202
			continue
		}
		if len(c.Env) == 0 {
			c.Env = make([]v1.EnvVar, 0)
		}
		c.Env = append(c.Env, v1.EnvVar{
203 204
			Name:  "MS_CONFIG",
			Value: string(msConfigJson),
L
leonwanghui 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 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
		})
		c.Env = append(c.Env, v1.EnvVar{
			Name:  "MASTER_PORT",
			Value: masterPort,
		})
		c.Env = append(c.Env, v1.EnvVar{
			Name:  "MASTER_ADDR",
			Value: masterAddr,
		})
		c.Env = append(c.Env, v1.EnvVar{
			Name:  "WORLD_SIZE",
			Value: strconv.Itoa(int(worldSize)),
		})
		c.Env = append(c.Env, v1.EnvVar{
			Name:  "RANK",
			Value: rank,
		})
	}

	log.Infof("Creating pod: %v", pod.ObjectMeta.Name)
	return s.ClientSet.CoreV1().Pods(s.Job.job.ObjectMeta.Namespace).Create(pod)
}

// Delete deletes the replicas
func (s *MSReplicaSet) Delete() error {
	selector, err := s.Labels().ToSelector()
	if err != nil {
		return err
	}

	failures := false

	options := meta_v1.ListOptions{
		LabelSelector: selector,
	}

	log.V(1).Infof("Deleting Jobs namespace=%v selector=%v", s.Job.job.ObjectMeta.Namespace, selector)
	err = s.ClientSet.CoreV1().Pods(s.Job.job.ObjectMeta.Namespace).DeleteCollection(&meta_v1.DeleteOptions{}, options)

	if err != nil {
		log.Errorf("There was a problem deleting the jobs; %v", err)
		failures = true
	}

	// We need to delete the completed pods.
	log.Infof("Deleting Pods namespace=%v selector=%v", s.Job.job.ObjectMeta.Namespace, selector)
	err = s.ClientSet.CoreV1().Pods(s.Job.job.ObjectMeta.Namespace).DeleteCollection(&meta_v1.DeleteOptions{}, options)

	if err != nil {
		log.Errorf("There was a problem deleting the pods; %v", err)
		failures = true
	}

	// Services doesn't support DeleteCollection so we delete them individually.
	for index := int32(0); index < *s.Spec.Replicas; index++ {
		log.V(1).Infof("Deleting Service %v:%v", s.Job.job.ObjectMeta.Namespace, s.genName((index)))
		err = s.ClientSet.CoreV1().Services(s.Job.job.ObjectMeta.Namespace).Delete(s.genName(index), &meta_v1.DeleteOptions{})

		if err != nil {
			log.Errorf("Error deleting service %v; %v", s.genName(index), err)
			failures = true
		}
	}

269 270 271
	// If the ConfigMap for the default master exists, we delete it
	log.Infof("Get ConfigMaps %v:%v", s.Job.job.ObjectMeta.Namespace, s.defaultMasterConfigMapName())
	_, err = s.ClientSet.CoreV1().ConfigMaps(s.Job.job.ObjectMeta.Namespace).Get(s.defaultMasterConfigMapName(), meta_v1.GetOptions{})
L
leonwanghui 已提交
272 273
	if err != nil {
		if !k8sutil.IsKubernetesResourceNotFoundError(err) {
274
			log.Errorf("Error deleting ConfigMap %v; %v", s.defaultMasterConfigMapName(), err)
L
leonwanghui 已提交
275 276 277
			failures = true
		}
	} else {
278 279
		log.Infof("Delete ConfigMaps %v:%v", s.Job.job.ObjectMeta.Namespace, s.defaultMasterConfigMapName())
		err = s.ClientSet.CoreV1().ConfigMaps(s.Job.job.ObjectMeta.Namespace).Delete(s.defaultMasterConfigMapName(), &meta_v1.DeleteOptions{})
L
leonwanghui 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292
		if err != nil {
			log.Errorf("There was a problem deleting the ConfigMaps; %v", err)
			failures = true
		}
	}

	if failures {
		return errors.New("Some of the replicas resources could not be deleted")
	}
	return nil
}

// replicaStatusFromPodList returns a status from a list of pods for a job.
293
func replicaStatusFromPodList(l v1.PodList, name string) msv1.ReplicaState {
L
leonwanghui 已提交
294 295 296 297 298 299 300 301 302 303 304 305
	var latest *v1.Pod
	for _, i := range l.Items {
		if latest == nil {
			latest = &i
			continue
		}
		if latest.Status.StartTime.Before(i.Status.StartTime) {
			latest = &i
		}
	}

	if latest == nil {
306
		return msv1.ReplicaStateRunning
L
leonwanghui 已提交
307 308
	}

309
	var msState v1.ContainerState
L
leonwanghui 已提交
310 311 312 313 314 315 316

	for _, i := range latest.Status.ContainerStatuses {
		if i.Name != name {
			continue
		}

		// We need to decide whether to use the current state or the previous termination state.
317
		msState = i.State
L
leonwanghui 已提交
318 319 320 321

		// If the container previously terminated we will look at the termination to decide whether it is a retryable
		// or permanenent error.
		if i.LastTerminationState.Terminated != nil {
322
			msState = i.LastTerminationState
L
leonwanghui 已提交
323 324 325
		}
	}

326 327
	if msState.Running != nil || msState.Waiting != nil {
		return msv1.ReplicaStateRunning
L
leonwanghui 已提交
328 329
	}

330 331 332
	if msState.Terminated != nil {
		if msState.Terminated.ExitCode == 0 {
			return msv1.ReplicaStateSucceeded
L
leonwanghui 已提交
333 334
		}

335
		if isRetryableTerminationState(msState.Terminated) {
L
leonwanghui 已提交
336 337
			// Since its a retryable error just return RUNNING.
			// We can just let Kubernetes restart the container to retry.
338
			return msv1.ReplicaStateRunning
L
leonwanghui 已提交
339 340
		}

341
		return msv1.ReplicaStateFailed
L
leonwanghui 已提交
342 343
	}

344
	return msv1.ReplicaStateUnknown
L
leonwanghui 已提交
345 346
}

347
func (s *MSReplicaSet) GetSingleReplicaStatus(index int32) msv1.ReplicaState {
L
leonwanghui 已提交
348 349 350
	p, err := s.ClientSet.CoreV1().Pods(s.Job.job.ObjectMeta.Namespace).Get(s.genName(index), meta_v1.GetOptions{})

	if err != nil {
351
		return msv1.ReplicaStateUnknown
L
leonwanghui 已提交
352 353 354
	}

	if v1.PodSucceeded == p.Status.Phase {
355
		return msv1.ReplicaStateSucceeded
L
leonwanghui 已提交
356 357 358 359 360 361 362
	}

	labels := s.Labels()
	labels["task_index"] = fmt.Sprintf("%v", index)
	selector, err := labels.ToSelector()
	if err != nil {
		log.Errorf("labels.ToSelector() error; %v", err)
363
		return msv1.ReplicaStateFailed
L
leonwanghui 已提交
364 365 366 367 368 369 370
	}

	l, err := s.ClientSet.CoreV1().Pods(s.Job.job.ObjectMeta.Namespace).List(meta_v1.ListOptions{
		LabelSelector: selector,
	})

	if err != nil {
371
		return msv1.ReplicaStateFailed
L
leonwanghui 已提交
372 373
	}

374
	status := replicaStatusFromPodList(*l, msv1.DefaultMSContainer)
L
leonwanghui 已提交
375 376 377 378
	return status
}

// Status returns the status of the replica set.
379 380
func (s *MSReplicaSet) GetStatus() (msv1.MSReplicaStatus, error) {
	status := msv1.MSReplicaStatus{
L
leonwanghui 已提交
381
		MSReplicaType: s.Spec.MSReplicaType,
382 383
		State:              msv1.ReplicaStateUnknown,
		ReplicasStates:     make(map[msv1.ReplicaState]int),
L
leonwanghui 已提交
384 385
	}

386
	increment := func(state msv1.ReplicaState) {
L
leonwanghui 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
		v, ok := status.ReplicasStates[state]
		if ok {
			status.ReplicasStates[state] = v + 1
		} else {
			status.ReplicasStates[state] = 1
		}
	}

	for index := int32(0); index < *s.Spec.Replicas; index++ {
		increment(s.GetSingleReplicaStatus(index))
	}

	// Determine the overall status for the replica set based on the status of the individual
	// replicas.
	// If any of the replicas failed mark the set as failed.
402 403
	if _, ok := status.ReplicasStates[msv1.ReplicaStateFailed]; ok {
		status.State = msv1.ReplicaStateFailed
L
leonwanghui 已提交
404 405 406 407
		return status, nil
	}

	// If any replicas are RUNNING mark it as RUNNING.
408 409
	if _, ok := status.ReplicasStates[msv1.ReplicaStateRunning]; ok {
		status.State = msv1.ReplicaStateRunning
L
leonwanghui 已提交
410 411 412 413
		return status, nil
	}

	// If all of the replicas succeeded consider it success.
414 415
	if v, ok := status.ReplicasStates[msv1.ReplicaStateSucceeded]; ok && int32(v) == *s.Spec.Replicas {
		status.State = msv1.ReplicaStateSucceeded
L
leonwanghui 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
		return status, nil
	}

	return status, nil
}

// SyncPods will try to check current pods for this MSReplicaSet and try to make it as desired.
func (s *MSReplicaSet) SyncPods(worldSize int32) error {
	for index := int32(0); index < *s.Spec.Replicas; index++ {

		// Label to get all pods of this MSReplicaType + index
		labels := s.Labels()
		labels["task_index"] = fmt.Sprintf("%v", index)
		rank := index
		if labels["job_type"] == "WORKER" {
			rank = index + 1
		}
		labels["task_index"] = fmt.Sprintf("%v", rank)

		labelSelector, err := labels.ToSelector()
		if err != nil {
			return err
		}

		// Filter the unactive pods
		fieldSelector := "status.phase!=" + string(v1.PodFailed)
		//",deletionTimestamp!=nil"

		options := meta_v1.ListOptions{
			LabelSelector: labelSelector,
			FieldSelector: fieldSelector,
		}
		// List to get pods
		pl, err := s.ClientSet.CoreV1().Pods(s.Job.job.ObjectMeta.Namespace).List(options)

		if len(pl.Items) == 0 {
			log.Infof("Pod  not found, create new one.")
			// Create the pod
			createdPod, err := s.CreatePodWithIndex(rank, worldSize)

			// If the pod already exists do nothing.
			if err != nil {
				if k8s_errors.IsAlreadyExists(err) {
					log.Infof("Pod: %v already exists.", createdPod.ObjectMeta.Name)
					continue
				}
				s.recorder.Eventf(s.Job.job, v1.EventTypeWarning, FailedCreateReason, "Error creating: %v", err)
				return k8sErrors.NewAggregate([]error{fmt.Errorf("Creating pod %v returned error.", createdPod.ObjectMeta.Name), err})
			}

			s.recorder.Eventf(s.Job.job, v1.EventTypeNormal, SuccessfulCreateReason, "Created pod: %v", createdPod.Name)
			continue
		}

		if err != nil {
			// TODO: handing this error
			continue
		}
	}

	return nil
}

// SyncServices will try to check current services for this MSReplicaSet and try to make it as desired.
func (s *MSReplicaSet) SyncServices() error {
	for index := int32(0); index < *s.Spec.Replicas; index++ {
		_, err := s.ClientSet.CoreV1().Services(s.Job.job.ObjectMeta.Namespace).Get(s.genName(index), meta_v1.GetOptions{})
		if err != nil && k8s_errors.IsNotFound(err) {
			log.Infof("Service: %v not found, create new one.", s.genName(index))
			// Create the service
			createdService, err := s.CreateServiceWithIndex(index)

			// If the service already exists do nothing.
			if err != nil {
				if k8s_errors.IsAlreadyExists(err) {
					log.Infof("Service: %v already exists.", s.genName(index))
					continue
				}
				s.recorder.Eventf(s.Job.job, v1.EventTypeWarning, FailedCreateReason, "Error creating: %v", err)
				return k8sErrors.NewAggregate([]error{fmt.Errorf("Creating Service %v returned error.", createdService.ObjectMeta.Name), err})
			}

			s.recorder.Eventf(s.Job.job, v1.EventTypeNormal, SuccessfulCreateReason, "Created Service: %v", createdService.Name)
			continue
		}

		if err != nil {
			// TODO: handing this error
			continue
		}
	}

	return nil
}

func (s *MSReplicaSet) genName(index int32) string {
512
	// Truncate msjob name to 40 characters
L
leonwanghui 已提交
513 514 515 516 517 518 519 520 521 522 523
	// The whole job name should be compliant with the DNS_LABEL spec, up to a max length of 63 characters
	// Thus genName(40 chars)-replicaType(6 chars)-runtimeId(4 chars)-index(4 chars), also leaving some spaces
	// See https://github.com/kubernetes/community/blob/master/contributors/design-proposals/architecture/identifiers.md
	return fmt.Sprintf("%v-%v-%v-%v", fmt.Sprintf("%.40s", s.Job.job.ObjectMeta.Name), strings.ToLower(string(s.Spec.MSReplicaType)), s.Job.job.Spec.RuntimeId, index)
}

func (s *MSReplicaSet) genPodName(index int32) string {
	// Generate a new pod name with random string
	return s.genName(index) + "-" + util.RandString(5)
}

524
func (s *MSReplicaSet) defaultMasterConfigMapName() string {
L
leonwanghui 已提交
525 526 527
	return fmt.Sprintf("cm-ps-%v", s.Job.job.Spec.RuntimeId)
}