github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+incompatible/cf/commands/spacequota/create_space_quota.go (about)

     1  package spacequota
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strconv"
     7  
     8  	"code.cloudfoundry.org/cli/cf/api/resources"
     9  	"code.cloudfoundry.org/cli/cf/api/spacequotas"
    10  	"code.cloudfoundry.org/cli/cf/commandregistry"
    11  	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
    12  	"code.cloudfoundry.org/cli/cf/errors"
    13  	"code.cloudfoundry.org/cli/cf/flags"
    14  	"code.cloudfoundry.org/cli/cf/formatters"
    15  	. "code.cloudfoundry.org/cli/cf/i18n"
    16  	"code.cloudfoundry.org/cli/cf/models"
    17  	"code.cloudfoundry.org/cli/cf/requirements"
    18  	"code.cloudfoundry.org/cli/cf/terminal"
    19  )
    20  
    21  type CreateSpaceQuota struct {
    22  	ui        terminal.UI
    23  	config    coreconfig.Reader
    24  	quotaRepo spacequotas.SpaceQuotaRepository
    25  }
    26  
    27  func init() {
    28  	commandregistry.Register(&CreateSpaceQuota{})
    29  }
    30  
    31  func (cmd *CreateSpaceQuota) MetaData() commandregistry.CommandMetadata {
    32  	fs := make(map[string]flags.FlagSet)
    33  	fs["allow-paid-service-plans"] = &flags.BoolFlag{Name: "allow-paid-service-plans", Usage: T("Can provision instances of paid service plans (Default: disallowed)")}
    34  	fs["i"] = &flags.StringFlag{ShortName: "i", Usage: T("Maximum amount of memory an application instance can have (e.g. 1024M, 1G, 10G). -1 represents an unlimited amount. (Default: unlimited)")}
    35  	fs["m"] = &flags.StringFlag{ShortName: "m", Usage: T("Total amount of memory a space can have (e.g. 1024M, 1G, 10G)")}
    36  	fs["r"] = &flags.IntFlag{ShortName: "r", Usage: T("Total number of routes")}
    37  	fs["s"] = &flags.IntFlag{ShortName: "s", Usage: T("Total number of service instances")}
    38  	fs["a"] = &flags.IntFlag{ShortName: "a", Usage: T("Total number of application instances. -1 represents an unlimited amount. (Default: unlimited)")}
    39  	fs["reserved-route-ports"] = &flags.IntFlag{Name: "reserved-route-ports", Usage: T("Maximum number of routes that may be created with reserved ports (Default: 0)")}
    40  
    41  	return commandregistry.CommandMetadata{
    42  		Name:        "create-space-quota",
    43  		Description: T("Define a new space resource quota"),
    44  		Usage: []string{
    45  			"CF_NAME create-space-quota ",
    46  			T("QUOTA"),
    47  			" ",
    48  			fmt.Sprintf("[-i %s] ", T("INSTANCE_MEMORY")),
    49  			fmt.Sprintf("[-m %s] ", T("MEMORY")),
    50  			fmt.Sprintf("[-r %s] ", T("ROUTES")),
    51  			fmt.Sprintf("[-s %s] ", T("SERVICE_INSTANCES")),
    52  			fmt.Sprintf("[-a %s] ", T("APP_INSTANCES")),
    53  			"[--allow-paid-service-plans] ",
    54  			fmt.Sprintf("[--reserved-route-ports %s]", T("RESERVED_ROUTE_PORTS")),
    55  		},
    56  		Flags: fs,
    57  	}
    58  }
    59  
    60  func (cmd *CreateSpaceQuota) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
    61  	if len(fc.Args()) != 1 {
    62  		cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("create-space-quota"))
    63  		return nil, fmt.Errorf("Incorrect usage: %d arguments of %d required", len(fc.Args()), 1)
    64  	}
    65  
    66  	reqs := []requirements.Requirement{
    67  		requirementsFactory.NewLoginRequirement(),
    68  		requirementsFactory.NewTargetedOrgRequirement(),
    69  	}
    70  
    71  	return reqs, nil
    72  }
    73  
    74  func (cmd *CreateSpaceQuota) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command {
    75  	cmd.ui = deps.UI
    76  	cmd.config = deps.Config
    77  	cmd.quotaRepo = deps.RepoLocator.GetSpaceQuotaRepository()
    78  	return cmd
    79  }
    80  
    81  func (cmd *CreateSpaceQuota) Execute(context flags.FlagContext) error {
    82  	name := context.Args()[0]
    83  	org := cmd.config.OrganizationFields()
    84  
    85  	cmd.ui.Say(T("Creating space quota {{.QuotaName}} for org {{.OrgName}} as {{.Username}}...", map[string]interface{}{
    86  		"QuotaName": terminal.EntityNameColor(name),
    87  		"OrgName":   terminal.EntityNameColor(org.Name),
    88  		"Username":  terminal.EntityNameColor(cmd.config.Username()),
    89  	}))
    90  
    91  	quota := models.SpaceQuota{
    92  		Name:    name,
    93  		OrgGUID: org.GUID,
    94  	}
    95  
    96  	memoryLimit := context.String("m")
    97  	if memoryLimit != "" {
    98  		parsedMemory, errr := formatters.ToMegabytes(memoryLimit)
    99  		if errr != nil {
   100  			return errors.New(T("Invalid memory limit: {{.MemoryLimit}}\n{{.Err}}", map[string]interface{}{"MemoryLimit": memoryLimit, "Err": errr}))
   101  		}
   102  
   103  		quota.MemoryLimit = parsedMemory
   104  	}
   105  
   106  	instanceMemoryLimit := context.String("i")
   107  	var parsedMemory int64
   108  	var err error
   109  	if instanceMemoryLimit == "-1" || instanceMemoryLimit == "" {
   110  		parsedMemory = -1
   111  	} else {
   112  		parsedMemory, err = formatters.ToMegabytes(instanceMemoryLimit)
   113  		if err != nil {
   114  			return errors.New(T("Invalid instance memory limit: {{.MemoryLimit}}\n{{.Err}}", map[string]interface{}{"MemoryLimit": instanceMemoryLimit, "Err": err}))
   115  		}
   116  	}
   117  
   118  	quota.InstanceMemoryLimit = parsedMemory
   119  
   120  	if context.IsSet("r") {
   121  		quota.RoutesLimit = context.Int("r")
   122  	}
   123  
   124  	if context.IsSet("s") {
   125  		quota.ServicesLimit = context.Int("s")
   126  	}
   127  
   128  	if context.IsSet("allow-paid-service-plans") {
   129  		quota.NonBasicServicesAllowed = true
   130  	}
   131  
   132  	if context.IsSet("a") {
   133  		quota.AppInstanceLimit = context.Int("a")
   134  	} else {
   135  		quota.AppInstanceLimit = resources.UnlimitedAppInstances
   136  	}
   137  
   138  	if context.IsSet("reserved-route-ports") {
   139  		quota.ReservedRoutePortsLimit = json.Number(strconv.Itoa(context.Int("reserved-route-ports")))
   140  	}
   141  
   142  	err = cmd.quotaRepo.Create(quota)
   143  
   144  	httpErr, ok := err.(errors.HTTPError)
   145  	if ok && httpErr.ErrorCode() == errors.QuotaDefinitionNameTaken {
   146  		cmd.ui.Ok()
   147  		cmd.ui.Warn(T("Space Quota Definition {{.QuotaName}} already exists", map[string]interface{}{"QuotaName": quota.Name}))
   148  		return nil
   149  	}
   150  
   151  	if err != nil {
   152  		return err
   153  	}
   154  
   155  	cmd.ui.Ok()
   156  	return nil
   157  }