...

Source file src/edge-infra.dev/cmd/edge/monitoring/alertman/cli/get.go

Documentation: edge-infra.dev/cmd/edge/monitoring/alertman/cli

     1  package cli
     2  
     3  import (
     4  	"context"
     5  	"flag"
     6  	"fmt"
     7  	"strings"
     8  
     9  	"github.com/peterbourgon/ff/v3/ffcli"
    10  
    11  	alertmgr "edge-infra.dev/pkg/lib/gcp/monitoring/alertmanager"
    12  )
    13  
    14  type getArgsT struct {
    15  	overwrite      bool
    16  	templateFormat bool
    17  	templatePath   string
    18  	prefix         string
    19  	name           string
    20  }
    21  
    22  var getArgs getArgsT
    23  var getFlagSet = newGetFlagSet(&getArgs)
    24  
    25  func newGetFlagSet(getArgs *getArgsT) *flag.FlagSet {
    26  	getf := newFlagSet("get")
    27  	getf.BoolVar(&getArgs.overwrite, "overwrite", false, "Forces the overwrite of existing alert template files in the destination folder. (optional)\nNOTE: If not specified, any new files to be created that are in conflict will be appended with a timestamp.")
    28  	getf.BoolVar(&getArgs.templateFormat, "all-fields", false, "Get all the fields of the running AlertPolicy (*.json). (optional)\nNOTE: If not specified, additional fields not required for the template are omitted.")
    29  	getf.StringVar(&getArgs.templatePath, "path", "", "Folder path to save the alert template files to.\nFiles will be written with the filename based on the display name filtered for unsupported characters and whitespace (e.g. <display_name>.json) (required)\nNOTE: Duplicate display names will be appended with a (Duplicate_Name_n) filename to prevent file conflicts.")
    30  	getf.StringVar(&getArgs.prefix, "prefix", "", "Custom prefix to append to the alert template file name (i.e. <prefix>_<alert_display_name>.json) (optional)")
    31  	getf.StringVar(&getArgs.name, "name", "", "Only get the alert with the specified name or display name. (optional)\nNOTE: All alerts with the same display name will be retrieved, and the template file name will be automatically incremented.")
    32  	return getf
    33  }
    34  
    35  var getCmd = &ffcli.Command{
    36  	Name:       "get",
    37  	ShortUsage: "get [flags]",
    38  	ShortHelp:  "Get and save alert policies as templates",
    39  	LongHelp: strings.TrimSpace(`
    40  Saves alert template files to a specified path from project alert configurations.
    41  `),
    42  	FlagSet: withGlobalFlags(getFlagSet),
    43  	Exec:    runGet,
    44  }
    45  
    46  func runGet(_ context.Context, args []string) error {
    47  	var err error
    48  
    49  	if len(args) > 0 {
    50  		Fatalf("too many non-flag arguments: %q", args)
    51  	}
    52  	if !checkGetFlags() {
    53  		Println()
    54  		return flag.ErrHelp
    55  	}
    56  
    57  	var filter string
    58  
    59  	// retrieve alert by name.
    60  	if len(getArgs.name) > 0 {
    61  		// https://cloud.google.com/monitoring/api/v3/sorting-and-filtering#sorting_and_filtering_basics
    62  		filter = fmt.Sprintf("display_name=\"%s\"", getArgs.name)
    63  	}
    64  
    65  	// retrieve all alerts. an empty filter means get everything.
    66  	if len(getArgs.name) == 0 {
    67  		filter = ""
    68  	}
    69  
    70  	templates, err := alertmgr.GetAlertPolicies(projectID, "", filter)
    71  	if err != nil && templates == nil {
    72  		return err
    73  	}
    74  
    75  	if len(templates) == 0 {
    76  		logger.Info("No alert policies were found")
    77  		return Errorf("No alert policies were found")
    78  	}
    79  	for _, temp := range templates {
    80  		if temp.UserLabels == nil {
    81  			temp.UserLabels = make(map[string]string)
    82  			temp.UserLabels["managed"] = "true"
    83  		} else {
    84  			temp.UserLabels["managed"] = "true"
    85  		}
    86  	}
    87  
    88  	// save alert configs to template file(s).
    89  	if err = alertmgr.CreateAlertTemplates(templates, tPath, getArgs.prefix, getArgs.overwrite, getArgs.templateFormat); err != nil {
    90  		return err
    91  	}
    92  	logger.WithValues("tPath", tPath, "projectID", projectID).Info("alert templates saved to project.\n")
    93  
    94  	return nil
    95  }
    96  
    97  // checkGetFlags validates the required get subcommand flags have been provided.
    98  func checkGetFlags() bool {
    99  	if len(projectID) == 0 {
   100  		logger.Error(nil, "Error: no value specified for [project] - a valid project-id is required")
   101  		return false
   102  	}
   103  
   104  	if len(getArgs.templatePath) == 0 {
   105  		logger.Error(nil, "Error: no value specified for [path] - a valid destination folder path is required")
   106  		return false
   107  	}
   108  
   109  	if !checkPath(getArgs.templatePath, true) {
   110  		logger.Error(nil, fmt.Sprintf("Error: invalid AlertPolicy [path] specified - %s\n", getArgs.templatePath))
   111  		return false
   112  	}
   113  
   114  	return true
   115  }
   116  

View as plain text