|
| 1 | +package healthcheck |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "path" |
| 7 | + |
| 8 | + "github.com/cloudnative-pg/machinery/pkg/log" |
| 9 | + "github.com/spf13/cobra" |
| 10 | + "google.golang.org/grpc" |
| 11 | + "google.golang.org/grpc/credentials/insecure" |
| 12 | + "google.golang.org/grpc/health/grpc_health_v1" |
| 13 | + |
| 14 | + "github.com/cloudnative-pg/plugin-barman-cloud/internal/cnpgi/metadata" |
| 15 | +) |
| 16 | + |
| 17 | +// NewCmd returns the healthcheck command |
| 18 | +func NewCmd() *cobra.Command { |
| 19 | + cmd := &cobra.Command{ |
| 20 | + Use: "healthcheck", |
| 21 | + Short: "healthcheck commands", |
| 22 | + } |
| 23 | + |
| 24 | + cmd.AddCommand(unixHealthCheck()) |
| 25 | + |
| 26 | + return cmd |
| 27 | +} |
| 28 | + |
| 29 | +func unixHealthCheck() *cobra.Command { |
| 30 | + cmd := &cobra.Command{ |
| 31 | + Use: "unix", |
| 32 | + Short: "unix healthcheck", |
| 33 | + RunE: func(cmd *cobra.Command, _ []string) error { |
| 34 | + dialPath := fmt.Sprintf("unix://%s", path.Join("/plugins", metadata.PluginName)) |
| 35 | + cli, cliErr := grpc.NewClient(dialPath, grpc.WithTransportCredentials(insecure.NewCredentials())) |
| 36 | + if cliErr != nil { |
| 37 | + log.Error(cliErr, "error while building client") |
| 38 | + return cliErr |
| 39 | + } |
| 40 | + |
| 41 | + healthCli := grpc_health_v1.NewHealthClient(cli) |
| 42 | + res, healthErr := healthCli.Check( |
| 43 | + cmd.Context(), |
| 44 | + &grpc_health_v1.HealthCheckRequest{}, |
| 45 | + ) |
| 46 | + if healthErr != nil { |
| 47 | + log.Error(healthErr, "healthcheck call failed") |
| 48 | + return healthErr |
| 49 | + } |
| 50 | + |
| 51 | + log.Info("received status: %s", res.Status.String()) |
| 52 | + switch res.Status { |
| 53 | + case grpc_health_v1.HealthCheckResponse_SERVING: |
| 54 | + os.Exit(0) |
| 55 | + case grpc_health_v1.HealthCheckResponse_UNKNOWN: |
| 56 | + os.Exit(1) |
| 57 | + case grpc_health_v1.HealthCheckResponse_NOT_SERVING: |
| 58 | + os.Exit(2) |
| 59 | + default: |
| 60 | + os.Exit(125) |
| 61 | + } |
| 62 | + |
| 63 | + return nil |
| 64 | + }, |
| 65 | + } |
| 66 | + |
| 67 | + return cmd |
| 68 | +} |
0 commit comments