func NewScale()

in tools/mig-scaler/scale.go [48:119]


func NewScale(cfg *Config) (*Scale, error) {
	var err error

	// expecting 2 arguments: scale <name> <target>
	if len(cfg.Args) != 2 {
		return nil, fmt.Errorf("scale expects 2 arguments but %d were provided", len(cfg.Args))
	}

	name := cfg.Arg(0)
	target, err := parseUint32(cfg.Arg(1))
	if err != nil {
		return nil, fmt.Errorf("target: %w", err)
	}

	cmd := &Scale{
		Workflow:   cfg.Workflow,
		MIG:        cfg.MIG.Ref(name),
		TargetSize: target,
		Increment:  cfg.MIG.Increment,
		Wait:       cfg.MIG.Wait,
		Duration:   cfg.MIG.Duration,
	}

	err = multierr.Append(err, cmd.Workflow.Validate())
	err = multierr.Append(err, cmd.MIG.Validate())

	if cmd.TargetSize > cfg.Workflow.MaxSize {
		err = multierr.Append(err, fmt.Errorf(
			"target cannot be greater than workflow-max-target (%d)",
			cfg.Workflow.MaxSize,
		))
	}

	if cmd.Duration <= 0 {
		err = multierr.Append(err, errors.New("duration must be greater than 0"))
	} else if cmd.Duration > cmd.Workflow.MaxDuration {
		err = multierr.Append(err, fmt.Errorf(
			"duration cannot be greater than workflow-max-duration (%s)",
			cmd.Workflow.MaxDuration,
		))
	}

	if cmd.Wait <= 0 {
		err = multierr.Append(err, errors.New("wait must be greater than 0"))
	}

	if cmd.Increment == 0 {
		// apply a default increment of 5%
		err = multierr.Append(err, errors.New("increment must by greater than 0"))
	}

	if err == nil {
		// Only try to check if the increment/wait is valid for the duration
		// if there's no error so far. If there is an error then the config
		// values are not trustworthy so this calculation could be nonsense.
		minIncrement := cmd.EstimateMinIncrement()
		maxWait := cmd.EstimateMaxWait()

		if cmd.Increment < minIncrement {
			err = multierr.Append(err, fmt.Errorf("increment is too small, based on wait and duration the minimum increment is %d", minIncrement))
		}
		if maxWait > 0 && cmd.Wait > maxWait {
			err = multierr.Append(err, fmt.Errorf("wait is too long, based on the increment and duration the maximum wait is %s", maxWait))
		}
	}

	if err != nil {
		return nil, err
	} else {
		return cmd, nil
	}
}