github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/command/scaling_policy_list.go (about)

     1  package command
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  	"strings"
     7  
     8  	"github.com/hashicorp/nomad/api"
     9  	"github.com/mitchellh/cli"
    10  	"github.com/posener/complete"
    11  )
    12  
    13  // Ensure ScalingPolicyListCommand satisfies the cli.Command interface.
    14  var _ cli.Command = &ScalingPolicyListCommand{}
    15  
    16  // ScalingPolicyListCommand implements cli.Command.
    17  type ScalingPolicyListCommand struct {
    18  	Meta
    19  }
    20  
    21  // Help satisfies the cli.Command Help function.
    22  func (s *ScalingPolicyListCommand) Help() string {
    23  	helpText := `
    24  Usage: nomad scaling policy list [options]
    25  
    26    List is used to list the currently configured scaling policies.
    27  
    28    If ACLs are enabled, this command requires a token with the 'read-job' and
    29    'list-jobs' capabilities for the namespace of all policies. Any namespaces
    30    that the token does not have access to will have its policies filtered from
    31    the results.
    32  
    33  General Options:
    34  
    35    ` + generalOptionsUsage(usageOptsDefault) + `
    36  
    37  Policy Info Options:
    38  
    39    -job
    40      Specifies the job ID to filter the scaling policies list by.
    41  
    42    -type
    43      Filter scaling policies by type.
    44  
    45    -verbose
    46      Display full information.
    47  
    48    -json
    49      Output the scaling policy in its JSON format.
    50  
    51    -t
    52      Format and display the scaling policy using a Go template.
    53  `
    54  	return strings.TrimSpace(helpText)
    55  }
    56  
    57  // Synopsis satisfies the cli.Command Synopsis function.
    58  func (s *ScalingPolicyListCommand) Synopsis() string {
    59  	return "Display all Nomad scaling policies"
    60  }
    61  
    62  func (s *ScalingPolicyListCommand) AutocompleteFlags() complete.Flags {
    63  	return mergeAutocompleteFlags(s.Meta.AutocompleteFlags(FlagSetClient),
    64  		complete.Flags{
    65  			"-verbose": complete.PredictNothing,
    66  			"-job":     complete.PredictNothing,
    67  			"-type":    complete.PredictNothing,
    68  			"-json":    complete.PredictNothing,
    69  			"-t":       complete.PredictAnything,
    70  		})
    71  }
    72  
    73  // Name returns the name of this command.
    74  func (s *ScalingPolicyListCommand) Name() string { return "scaling policy list" }
    75  
    76  // Run satisfies the cli.Command Run function.
    77  func (s *ScalingPolicyListCommand) Run(args []string) int {
    78  	var json, verbose bool
    79  	var tmpl, policyType, job string
    80  
    81  	flags := s.Meta.FlagSet(s.Name(), FlagSetClient)
    82  	flags.Usage = func() { s.Ui.Output(s.Help()) }
    83  	flags.BoolVar(&verbose, "verbose", false, "")
    84  	flags.BoolVar(&json, "json", false, "")
    85  	flags.StringVar(&tmpl, "t", "", "")
    86  	flags.StringVar(&policyType, "type", "", "")
    87  	flags.StringVar(&job, "job", "", "")
    88  	if err := flags.Parse(args); err != nil {
    89  		return 1
    90  	}
    91  
    92  	if args = flags.Args(); len(args) > 0 {
    93  		s.Ui.Error("This command takes no arguments")
    94  		s.Ui.Error(commandErrorText(s))
    95  		return 1
    96  	}
    97  
    98  	// Truncate the id unless full length is requested
    99  	length := shortId
   100  	if verbose {
   101  		length = fullId
   102  	}
   103  
   104  	// Get the HTTP client.
   105  	client, err := s.Meta.Client()
   106  	if err != nil {
   107  		s.Ui.Error(fmt.Sprintf("Error initializing client: %s", err))
   108  		return 1
   109  	}
   110  
   111  	q := &api.QueryOptions{
   112  		Params: map[string]string{},
   113  	}
   114  	if policyType != "" {
   115  		q.Params["type"] = policyType
   116  	}
   117  	if job != "" {
   118  		q.Params["job"] = job
   119  	}
   120  	policies, _, err := client.Scaling().ListPolicies(q)
   121  	if err != nil {
   122  		s.Ui.Error(fmt.Sprintf("Error listing scaling policies: %s", err))
   123  		return 1
   124  	}
   125  
   126  	if json || len(tmpl) > 0 {
   127  		out, err := Format(json, tmpl, policies)
   128  		if err != nil {
   129  			s.Ui.Error(err.Error())
   130  			return 1
   131  		}
   132  		s.Ui.Output(out)
   133  		return 0
   134  	}
   135  
   136  	output := formatScalingPolicies(policies, length)
   137  	s.Ui.Output(output)
   138  	return 0
   139  }
   140  
   141  func formatScalingPolicies(stubs []*api.ScalingPolicyListStub, uuidLength int) string {
   142  	if len(stubs) == 0 {
   143  		return "No policies found"
   144  	}
   145  
   146  	// Create the output table header.
   147  	policies := []string{"ID|Enabled|Type|Target"}
   148  
   149  	// Sort the list of policies based on their target.
   150  	sortedPolicies := scalingPolicyStubList{policies: stubs}
   151  	sort.Sort(sortedPolicies)
   152  
   153  	// Iterate the policies and add to the output.
   154  	for _, policy := range sortedPolicies.policies {
   155  		policies = append(policies, fmt.Sprintf(
   156  			"%s|%v|%s|%s",
   157  			limit(policy.ID, uuidLength),
   158  			policy.Enabled,
   159  			policy.Type,
   160  			formatScalingPolicyTarget(policy.Target)))
   161  	}
   162  	return formatList(policies)
   163  }
   164  
   165  // scalingPolicyStubList is a wrapper around []*api.ScalingPolicyListStub that
   166  // list us sort the policies alphabetically based on their target.
   167  type scalingPolicyStubList struct {
   168  	policies []*api.ScalingPolicyListStub
   169  }
   170  
   171  // Len satisfies the Len function of the sort.Interface interface.
   172  func (s scalingPolicyStubList) Len() int { return len(s.policies) }
   173  
   174  // Swap satisfies the Swap function of the sort.Interface interface.
   175  func (s scalingPolicyStubList) Swap(i, j int) {
   176  	s.policies[i], s.policies[j] = s.policies[j], s.policies[i]
   177  }
   178  
   179  // Less satisfies the Less function of the sort.Interface interface.
   180  func (s scalingPolicyStubList) Less(i, j int) bool {
   181  
   182  	iTarget := formatScalingPolicyTarget(s.policies[i].Target)
   183  	jTarget := formatScalingPolicyTarget(s.policies[j].Target)
   184  
   185  	stringList := []string{iTarget, jTarget}
   186  	sort.Strings(stringList)
   187  
   188  	return stringList[0] == iTarget
   189  }