github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/state/errors/model.go (about)

     1  // Copyright 2020 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package errors
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  
    10  	"github.com/juju/errors"
    11  )
    12  
    13  const (
    14  	// HasHostedModelsError defines if an attempt was made to destroy the
    15  	// controller model while it contained non-empty hosted models, without
    16  	// specifying that they should also be destroyed.
    17  	HasHostedModelsError = errors.ConstError("has hosted models")
    18  
    19  	// ModelNotEmptyError reports whether or not the given error was caused
    20  	// due to an operation requiring a model to be empty, where the model is
    21  	// non-empty.
    22  	ModelNotEmptyError = errors.ConstError("model not empty")
    23  
    24  	// PersistentStorageError indicates  whether or not the given error was
    25  	// caused by an attempt to destroy a model while it contained persistent
    26  	// storage, without specifying how the storage should be removed
    27  	// (destroyed or released).
    28  	PersistentStorageError = errors.ConstError("model contains persistent storage")
    29  )
    30  
    31  func NewHasHostedModelsError(i int) error {
    32  	sep := ""
    33  	if i != 1 {
    34  		sep = "s"
    35  	}
    36  	return errors.WithType(
    37  		fmt.Errorf("hosting %d other model%s", i, sep),
    38  		HasHostedModelsError)
    39  }
    40  
    41  // NewModelNotEmptyError constructs a ModelNotEmpty with the error message
    42  // tailored to match the number of machines, applications, volumes and
    43  // filesystem's left. The returned error satisfies ModelNotEmptyError.
    44  func NewModelNotEmptyError(machines, applications, volumes, filesystems int) error {
    45  	if machines+applications+volumes+filesystems == 0 {
    46  		return nil
    47  	}
    48  	plural := func(n int, thing string) string {
    49  		s := fmt.Sprintf("%d %s", n, thing)
    50  		if n != 1 {
    51  			s += "s"
    52  		}
    53  		return s
    54  	}
    55  	var contains []string
    56  	if n := machines; n > 0 {
    57  		contains = append(contains, plural(n, "machine"))
    58  	}
    59  	if n := applications; n > 0 {
    60  		contains = append(contains, plural(n, "application"))
    61  	}
    62  	if n := volumes; n > 0 {
    63  		contains = append(contains, plural(n, "volume"))
    64  	}
    65  	if n := filesystems; n > 0 {
    66  		contains = append(contains, plural(n, "filesystem"))
    67  	}
    68  	return fmt.Errorf("%w, found %s", ModelNotEmptyError, strings.Join(contains, ", "))
    69  }