handler

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2023 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Command = cli.Command{
	Name:        "handler",
	Description: "Manage handlers",
	Usage:       "Manage handlers",
	Subcommands: []*cli.Command{
		&RegisterCommand,
		&ValidateCommand,
		&ListCommand,
		&DiagnosticCommand,
		&LogsCommand,
		&DeleteCommand,
	},
}
View Source
var DeleteCommand = cli.Command{
	Name:        "delete",
	Description: "Delete handlers",
	Usage:       "Delete handlers",
	Flags: []cli.Flag{
		&cli.StringFlag{Name: "id", Required: true},
	},
	Action: cli.ActionFunc(func(c *cli.Context) error {
		ctx := c.Context
		cfg, err := config.Load()
		if err != nil {
			return err
		}

		cf, err := client.FromConfig(ctx, cfg)
		if err != nil {
			return err
		}
		_, err = cf.AdminDeleteHandlerWithResponse(ctx, c.String("id"))
		if err != nil {
			return err
		}
		clio.Success("Deleted handler ", c.String("id"))

		return nil
	}),
}
View Source
var DiagnosticCommand = cli.Command{
	Name:        "diagnostic",
	Description: "List diagnostic logs for a handler",
	Usage:       "List diagnostic logs for a handler",
	Flags: []cli.Flag{
		&cli.StringFlag{Name: "id", Required: true},
	},
	Action: cli.ActionFunc(func(c *cli.Context) error {
		ctx := c.Context
		id := c.String("id")
		cfg, err := config.Load()
		if err != nil {
			return err
		}

		cf, err := client.FromConfig(ctx, cfg)
		if err != nil {
			return err
		}
		res, err := cf.AdminGetHandlerWithResponse(ctx, id)
		if err != nil {
			return err
		}

		health := "healthy"
		if !res.JSON200.Healthy {
			health = "unhealthy"
		}
		fmt.Println("Diagnostic Logs:")
		fmt.Printf("%s %s %s %s\n", res.JSON200.Id, res.JSON200.AwsAccount, res.JSON200.AwsRegion, health)

		table := tablewriter.NewWriter(os.Stdout)
		table.SetHeader([]string{
			"Level", "Message"})
		table.SetAutoWrapText(false)
		table.SetAutoFormatHeaders(true)
		table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
		table.SetAlignment(tablewriter.ALIGN_LEFT)
		table.SetCenterSeparator("")
		table.SetColumnSeparator("")
		table.SetRowSeparator("")
		table.SetHeaderLine(false)
		table.SetBorder(false)

		for _, d := range res.JSON200.Diagnostics {
			table.Append([]string{
				d.Message,
			})
		}
		table.Render()

		return nil
	}),
}
View Source
var GetCommand = cli.Command{
	Name:        "get",
	Description: "Get logs for a handler",
	Flags: []cli.Flag{
		&cli.StringFlag{Name: "id", Required: true},
		&cli.StringFlag{Name: "start", Usage: "Start time", Value: "-5m", Required: false},
		&cli.StringFlag{Name: "end", Usage: "End time", Value: "now", Required: false},
	},
	Action: func(c *cli.Context) error {

		ctx := c.Context
		cfg, err := cfaws.ConfigFromContextOrDefault(ctx)
		if err != nil {
			return err
		}

		logGroup := "/aws/lambda/" + c.String("id")
		start := c.String("start")
		end := c.String("end")
		clio.Info("Starting to get logs for Health check lambda, log group id: %s", logGroup)
		hasLogs := true
		cwClient := cloudwatchlogs.NewFromConfig(cfg)

		o, _ := cwClient.DescribeLogGroups(ctx, &cloudwatchlogs.DescribeLogGroupsInput{
			LogGroupNamePrefix: &logGroup,
		})
		if o != nil && len(o.LogGroups) == 1 {
			lo, err := cwClient.DescribeLogStreams(ctx, &cloudwatchlogs.DescribeLogStreamsInput{
				LogGroupName: o.LogGroups[0].LogGroupName,
				Limit:        aws.Int32(1),
			})
			_ = err
			if lo != nil && len(lo.LogStreams) != 0 {
				hasLogs = true
			}
		}
		if hasLogs {
			getEvents(GetEventsOpts{Group: logGroup, Start: start, End: end}, cfg.Region, c.String("filter"))
		} else {
			clio.Warnf("The handler may not have been invoked yet. Log group id: %s", logGroup)
		}

		return nil
	},
}
View Source
var ListCommand = cli.Command{
	Name:        "list",
	Aliases:     []string{"ls"},
	Description: "List handlers",
	Usage:       "List handlers",
	Action: cli.ActionFunc(func(c *cli.Context) error {
		ctx := c.Context
		cfg, err := config.Load()
		if err != nil {
			return err
		}

		cfApi, err := client.FromConfig(ctx, cfg)
		if err != nil {
			return err
		}
		res, err := cfApi.AdminListHandlersWithResponse(ctx)
		if err != nil {
			return err
		}

		table := tablewriter.NewWriter(os.Stdout)
		table.SetHeader([]string{"ID", "Account", "Region", "Health"})
		table.SetAutoWrapText(false)
		table.SetAutoFormatHeaders(true)
		table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
		table.SetAlignment(tablewriter.ALIGN_LEFT)
		table.SetCenterSeparator("")
		table.SetColumnSeparator("")
		table.SetRowSeparator("")
		table.SetHeaderLine(false)
		table.SetBorder(false)

		for _, d := range res.JSON200.Res {
			health := "healthy"
			if !d.Healthy {
				health = "unhealthy"
			}
			table.Append([]string{
				d.Id, d.AwsAccount, d.AwsRegion, health,
			})
		}
		table.Render()

		return nil
	}),
}
View Source
var LogsCommand = cli.Command{
	Name:        "logs",
	Description: "View log groups for a handler",
	Usage:       "View log groups for a handler",
	Subcommands: []*cli.Command{
		&WatchCommand,
		&GetCommand,
	},
}
View Source
var RegisterCommand = cli.Command{
	Name:        "register",
	Description: "Register a handler in Common Fate",
	Usage:       "Register a handler in Common Fate",
	Flags: []cli.Flag{
		&cli.StringFlag{Name: "id", Required: true},
		&cli.StringFlag{Name: "runtime", Required: true, Value: "aws-lambda"},
		&cli.StringFlag{Name: "aws-region", Required: true},
		&cli.StringFlag{Name: "aws-account", Required: true},
	},
	Action: func(c *cli.Context) error {

		ctx := c.Context

		reqBody := types.AdminRegisterHandlerJSONRequestBody{
			AwsAccount: c.String("aws-account"),
			AwsRegion:  c.String("aws-region"),
			Runtime:    c.String("runtime"),
			Id:         c.String("id"),
		}

		cfg, err := config.Load()
		if err != nil {
			return err
		}

		cf, err := client.FromConfig(ctx, cfg)
		if err != nil {
			return err
		}

		_, err = cf.AdminRegisterHandlerWithResponse(ctx, reqBody)
		if err != nil {
			return err
		}

		clio.Successf("Successfully registered handler '%s' with Common Fate", c.String("id"))

		return nil
	},
}
View Source
var ValidateCommand = cli.Command{
	Name:        "validate",
	Description: "Validate a handler by invoking the handler directly",
	Usage:       "Validate a handler",
	Flags: []cli.Flag{
		&cli.StringFlag{Name: "id", Required: true, Usage: "The ID of the handler, when deploying via CloudFormation this is the HandlerID parameter that you configured. e.g 'aws-sso'"},
		&cli.StringFlag{Name: "aws-region", Required: true},

		&cli.StringFlag{Name: "runtime", Required: true, Value: "aws-lambda"},
		&cli.StringFlag{Name: "cloudformation-stack-name", Usage: "If CloudFormation was used to deploy the provider, use this flag to check the status of the stack"},
	},
	Action: func(c *cli.Context) error {
		id := c.String("id")
		awsRegion := c.String("aws-region")

		if c.String("runtime") != "aws-lambda" {
			return errors.New("unsupported runtime. Supported runtimes are [aws-lambda]")
		}

		providerRuntime, err := handlerclient.NewLambdaRuntime(c.Context, id)
		if err != nil {
			return err
		}

		cfg, err := cfaws.ConfigFromContextOrDefault(c.Context)

		cfg.Region = awsRegion
		if err != nil {
			return err
		}
		if c.String("cloudformation-stack-name") != "" {
			cfnClient := cloudformation.NewFromConfig(cfg)
			stacks, err := cfnClient.DescribeStacks(c.Context, &cloudformation.DescribeStacksInput{
				StackName: aws.String(c.String("cloudformation-stack-name")),
			})
			if err != nil {
				return err
			}
			clio.Infof("cloudformation stack '%s' exists in '%s' and is in '%s' state", c.String("cloudformation-stack-name"), awsRegion, stacks.Stacks[0].StackStatus)
		}

		desc, err := providerRuntime.Describe(c.Context)
		if err != nil {
			return err
		}

		clio.Infof("Provider: %s/%s@%s\n", desc.Provider.Publisher, desc.Provider.Name, desc.Provider.Version)

		schemaBytes, err := json.Marshal(desc.Schema)
		if err != nil {
			return err
		}

		clio.Infof("Provider Schema:\n%s", string(schemaBytes))

		if len(desc.Diagnostics) > 0 {
			clio.Infow("Deployment Diagnostics", "logs", desc.Diagnostics)
		}

		if desc.Healthy {
			clio.Success("Deployment is healthy")

		} else {
			clio.Error("Deployment is unhealthy")
		}

		return nil
	},
}
View Source
var WatchCommand = cli.Command{
	Name:        "watch",
	Description: "Stream logs for a handler",
	Flags: []cli.Flag{
		&cli.StringFlag{Name: "id", Required: true},
	},
	Action: func(c *cli.Context) error {

		ctx := c.Context
		cfg, err := cfaws.ConfigFromContextOrDefault(ctx)
		if err != nil {
			return err
		}

		logGroup := "/aws/lambda/" + c.String("id")
		clio.Infof("Starting to watch logs for log group id: %s", logGroup)
		watchEvents(logGroup, cfg.Region, c.String("filter"))
		return nil
	},
}

Functions

This section is empty.

Types

type GetEventsOpts

type GetEventsOpts struct {
	Group string
	Start string
	End   string
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL