Skip to content

Commit

Permalink
chore: apply linters suggestions
Browse files Browse the repository at this point in the history
Signed-off-by: Francesco Canovai <francesco.canovai@enterprisedb.com>
  • Loading branch information
fcanovai committed Jul 1, 2024
1 parent 336abbf commit 2cfa9d7
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 33 deletions.
7 changes: 4 additions & 3 deletions pkg/logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,20 @@ func newLogger(debug bool) logr.Logger {
}

result := zapr.NewLogger(zapLog)

return result
}

// IntoContext injects the logger into the passed context, returning
// a context having the logger embedded. The logger can be recovered
// with FromContext
// with FromContext.
func IntoContext(ctx context.Context, logger logr.Logger) context.Context {
return logr.NewContext(ctx, logger)
}

// NewIntoContext injects a new logger into the passed context, returning
// a context having the logger embedded. The logger can be recovered
// with FromContext
// with FromContext.
func NewIntoContext(ctx context.Context, debug bool) context.Context {
logger := newLogger(debug)
return IntoContext(ctx, logger)
Expand All @@ -62,11 +63,11 @@ func NewIntoContext(ctx context.Context, debug bool) context.Context {
//
// This should probably have a means of panicking if a logger is not found
// during development.
//
func FromContext(ctx context.Context) logr.Logger {
logger, err := logr.FromContext(ctx)
if err != nil {
return newLogger(false)
}

return logger
}
33 changes: 17 additions & 16 deletions pkg/pluginhelper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ package pluginhelper

import (
"encoding/json"
"fmt"
"strconv"

apiv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1"
"github.com/cloudnative-pg/cnpg-i/pkg/operator"
jsonpatch "github.com/snorwin/jsonpatch"
"github.com/snorwin/jsonpatch"
corev1 "k8s.io/api/core/v1"
)

Expand All @@ -32,7 +33,7 @@ const (
)

// Data is an helper structure to be used by
// plugins wanting to enhance the CNPG validating webhooks
// plugins wanting to enhance the CNPG validating webhooks.
type Data struct {
// Parameters are the configuration parameters of this plugin
Parameters map[string]string
Expand All @@ -42,37 +43,37 @@ type Data struct {
pluginIndex int
}

// DataBuilder a fluent constructor for the Data struct
// DataBuilder a fluent constructor for the Data struct.
type DataBuilder struct {
pluginName string
clusterJSON []byte
podJSON []byte
}

// NewDataBuilder initializes a basic DataBuilder
// NewDataBuilder initializes a basic DataBuilder.
func NewDataBuilder(pluginName string, clusterJSON []byte) *DataBuilder {
d := DataBuilder{clusterJSON: clusterJSON, pluginName: pluginName}
d.clusterJSON = clusterJSON
return &d
}

// WithPod adds Pod data to the DataBuilder
// WithPod adds Pod data to the DataBuilder.
func (d *DataBuilder) WithPod(podJSON []byte) *DataBuilder {
d.podJSON = podJSON
return d
}

// Build returns the constructed Data object and any errors encountered
// Build returns the constructed Data object and any errors encountered.
func (d *DataBuilder) Build() (*Data, error) {
result := &Data{}

if err := json.Unmarshal(d.clusterJSON, &result.cluster); err != nil {
return nil, err
return nil, fmt.Errorf("error unmarshalling cluster JSON: %w", err)
}

if len(d.podJSON) > 0 {
if err := json.Unmarshal(d.podJSON, &result.pod); err != nil {
return nil, err
return nil, fmt.Errorf("error unmarshalling pod JSON: %w", err)
}
}

Expand All @@ -87,32 +88,32 @@ func (d *DataBuilder) Build() (*Data, error) {
return result, nil
}

// GetCluster gets the decoded cluster object
// GetCluster gets the decoded cluster object.
func (helper *Data) GetCluster() *apiv1.Cluster {
return &helper.cluster
}

// GetPod gets the decoded pod object
// GetPod gets the decoded pod object.
func (helper *Data) GetPod() *corev1.Pod {
return &helper.pod
}

// CreateClusterJSONPatch creates a JSON patch changing the cluster
// that was loaded into this helper into the
// that was loaded into this helper into the cluster.
func (helper *Data) CreateClusterJSONPatch(newCluster apiv1.Cluster) ([]byte, error) {
patch, err := jsonpatch.CreateJSONPatch(newCluster, helper.cluster)
return []byte(patch.String()), err
}

// CreatePodJSONPatch creates a JSON patch changing the cluster
// that was loaded into this helper into the
// that was loaded into this helper into the pod.
func (helper *Data) CreatePodJSONPatch(newPod corev1.Pod) ([]byte, error) {
patch, err := jsonpatch.CreateJSONPatch(newPod, helper.pod)
return []byte(patch.String()), err
}

// ValidationErrorForParameter creates a validation error for a certain plugin
// parameter
// parameter.
func (helper *Data) ValidationErrorForParameter(name, message string) *operator.ValidationError {
if helper.pluginIndex == -1 {
return &operator.ValidationError{
Expand All @@ -137,7 +138,7 @@ func (helper *Data) ValidationErrorForParameter(name, message string) *operator.
}
}

// InjectPluginVolume injects the plugin volume into a CNPG Pod
// InjectPluginVolume injects the plugin volume into a CNPG Pod.
func (*Data) InjectPluginVolume(pod *corev1.Pod) {
foundPluginVolume := false
for i := range pod.Spec.Volumes {
Expand Down Expand Up @@ -170,12 +171,12 @@ func (*Data) InjectPluginVolume(pod *corev1.Pod) {
}
}

// DecodeBackup decodes a JSON representation of a backup
// DecodeBackup decodes a JSON representation of a backup.
func (*Data) DecodeBackup(backupDefinition []byte) (*apiv1.Backup, error) {
var backup apiv1.Backup

if err := json.Unmarshal(backupDefinition, &backup); err != nil {
return nil, err
return nil, fmt.Errorf("error unmarshalling backup JSON: %w", err)
}

return &backup, nil
Expand Down
35 changes: 21 additions & 14 deletions pkg/pluginhelper/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,30 +19,31 @@ package pluginhelper
import (
"context"
"errors"
"fmt"
"net"
"os"
"os/signal"
"path"
"syscall"

"github.com/cloudnative-pg/cnpg-i/pkg/identity"
"github.com/go-logr/logr"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/grpc"
"github.com/go-logr/logr"

"github.com/cloudnative-pg/cnpg-i-machinery/pkg/logging"
)

const unixNetwork = "unix"

// ServerEnricher is the type of functions that can add register
// service implementations in a GRPC server
// service implementations in a GRPC server.
type ServerEnricher func(*grpc.Server) error

// CreateMainCmd creates a command to be used as the server side
// for the CNPG-I infrastructure
// for the CNPG-I infrastructure.
func CreateMainCmd(identityImpl identity.IdentityServer, enrichers ...ServerEnricher) *cobra.Command {
cmd := &cobra.Command{
Use: "plugin",
Expand Down Expand Up @@ -79,7 +80,7 @@ func CreateMainCmd(identityImpl identity.IdentityServer, enrichers ...ServerEnri
return cmd
}

// run starts listining for GRPC requests
// run starts listening for GRPC requests.
func run(ctx context.Context, identityImpl identity.IdentityServer, enrichers ...ServerEnricher) error {
logger := logging.FromContext(ctx)

Expand All @@ -88,14 +89,14 @@ func run(ctx context.Context, identityImpl identity.IdentityServer, enrichers ..
&identity.GetPluginMetadataRequest{})
if err != nil {
logger.Error(err, "Error while querying the identity service")
return err
return fmt.Errorf("error while querying the identity service: %w", err)
}

pluginPath := viper.GetString("plugin-path")
pluginName := identityResponse.Name
pluginDisplayName := identityResponse.DisplayName
pluginVersion := identityResponse.Version
socketName := path.Join(pluginPath, identityResponse.Name)
pluginName := identityResponse.GetName()
pluginDisplayName := identityResponse.GetDisplayName()
pluginVersion := identityResponse.GetVersion()
socketName := path.Join(pluginPath, identityResponse.GetName())

// Remove stale unix socket it still existent
if err := removeStaleSocket(ctx, socketName); err != nil {
Expand All @@ -110,7 +111,7 @@ func run(ctx context.Context, identityImpl identity.IdentityServer, enrichers ..
)
if err != nil {
logger.Error(err, "While starting server")
return err
return fmt.Errorf("cannot listen on the socket: %w", err)
}

// Handle quit-like signal
Expand Down Expand Up @@ -150,26 +151,31 @@ func run(ctx context.Context, identityImpl identity.IdentityServer, enrichers ..
return nil
}

// removeStaleSocket removes a stale unix domain socket
// removeStaleSocket removes a stale unix domain socket.
func removeStaleSocket(ctx context.Context, pluginPath string) error {
logger := logging.FromContext(ctx)
_, err := os.Stat(pluginPath)

switch {
case err == nil:
logger.Info("Removing stale socket", "pluginPath", pluginPath)
return os.Remove(pluginPath)
err := os.Remove(pluginPath)
if err != nil {
return fmt.Errorf("error while removing stale socket: %w", err)
}

return nil

case errors.Is(err, os.ErrNotExist):
return nil

default:
return err
return fmt.Errorf("error while checking for stale socket: %w", err)
}
}

// handleSignals makes sure that we close the listening socket
// when we receive a quit-like signal
// when we receive a quit-like signal.
func handleSignals(ctx context.Context, listener net.Listener) {
logger := logging.FromContext(ctx)

Expand Down Expand Up @@ -199,6 +205,7 @@ func panicRecoveryHandler(listener net.Listener) recovery.RecoveryHandlerFuncCon
}

os.Exit(1)

return nil
}
}

0 comments on commit 2cfa9d7

Please sign in to comment.