Moved code of commands to their main package

- add init code to reduce code duplication of connection setup
This commit is contained in:
Peter 2021-01-16 17:34:50 +01:00
parent af31b1166a
commit 2f0f3edfdf
Signed by: prskr
GPG key ID: C1DB5D2E8DB512F9
13 changed files with 75 additions and 103 deletions

View file

@ -7,7 +7,7 @@ before:
builds: builds:
- id: "inetmock" - id: "inetmock"
binary: inetmock binary: inetmock
main: ./cmd/inetmock/main.go main: ./cmd/inetmock/
ldflags: ldflags:
- -w -s - -w -s
env: env:
@ -19,7 +19,7 @@ builds:
- amd64 - amd64
- id: "imctl" - id: "imctl"
binary: imctl binary: imctl
main: ./cmd/imctl/main.go main: ./cmd/imctl/
ldflags: ldflags:
- -w -s - -w -s
goos: goos:
@ -65,7 +65,7 @@ release:
name: inetmock name: inetmock
dockers: dockers:
- binaries: - ids:
- inetmock - inetmock
- imctl - imctl
image_templates: image_templates:

View file

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"context" "context"
@ -43,13 +43,6 @@ func runAddFile(_ *cobra.Command, args []string) (err error) {
} }
func runRemoveFile(_ *cobra.Command, args []string) (err error) { func runRemoveFile(_ *cobra.Command, args []string) (err error) {
var conn *grpc.ClientConn
if conn, err = grpc.Dial(inetMockSocketPath, grpc.WithInsecure()); err != nil {
fmt.Printf("Failed to connecto INetMock socket: %v\n", err)
os.Exit(10)
}
auditClient := rpc.NewAuditClient(conn) auditClient := rpc.NewAuditClient(conn)
ctx, cancel := context.WithTimeout(appCtx, grpcTimeout) ctx, cancel := context.WithTimeout(appCtx, grpcTimeout)
defer cancel() defer cancel()

View file

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"encoding/json" "encoding/json"
@ -8,7 +8,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"gitlab.com/inetmock/inetmock/internal/rpc" "gitlab.com/inetmock/inetmock/internal/rpc"
"gitlab.com/inetmock/inetmock/pkg/audit" "gitlab.com/inetmock/inetmock/pkg/audit"
"google.golang.org/grpc"
) )
var ( var (
@ -27,13 +26,6 @@ var (
) )
func watchAuditEvents(_ *cobra.Command, _ []string) (err error) { func watchAuditEvents(_ *cobra.Command, _ []string) (err error) {
var conn *grpc.ClientConn
if conn, err = grpc.Dial(inetMockSocketPath, grpc.WithInsecure()); err != nil {
fmt.Printf("Failed to connecto INetMock socket: %v\n", err)
os.Exit(10)
}
auditClient := rpc.NewAuditClient(conn) auditClient := rpc.NewAuditClient(conn)
var watchClient rpc.Audit_WatchEventsClient var watchClient rpc.Audit_WatchEventsClient

View file

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"context" "context"
@ -10,12 +10,16 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"google.golang.org/grpc"
) )
var ( var (
cliCmd = &cobra.Command{ cliCmd = &cobra.Command{
Use: "", Use: "",
Short: "IMCTL is the CLI app to interact with an INetMock server", Short: "IMCTL is the CLI app to interact with an INetMock server",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
return initGRPCConnection()
},
} }
inetMockSocketPath string inetMockSocketPath string
@ -23,6 +27,7 @@ var (
grpcTimeout time.Duration grpcTimeout time.Duration
appCtx context.Context appCtx context.Context
appCancel context.CancelFunc appCancel context.CancelFunc
conn *grpc.ClientConn
) )
func init() { func init() {
@ -33,8 +38,7 @@ func init() {
cliCmd.AddCommand(endpointsCmd, handlerCmd, healthCmd, auditCmd) cliCmd.AddCommand(endpointsCmd, handlerCmd, healthCmd, auditCmd)
endpointsCmd.AddCommand(getEndpoints) endpointsCmd.AddCommand(getEndpoints)
handlerCmd.AddCommand(getHandlersCmd) handlerCmd.AddCommand(getHandlersCmd)
healthCmd.AddCommand(generalHealthCmd) healthCmd.AddCommand(generalHealthCmd, containerHealthCmd)
healthCmd.AddCommand(containerHealthCmd)
currentUser := "" currentUser := ""
if usr, err := user.Current(); err == nil { if usr, err := user.Current(); err == nil {
@ -50,25 +54,22 @@ func init() {
"set listener name - defaults to the current username, if the user cannot be determined a random UUID will be used", "set listener name - defaults to the current username, if the user cannot be determined a random UUID will be used",
) )
auditCmd.AddCommand(watchEventsCmd, addFileCmd, removeFileCmd) auditCmd.AddCommand(watchEventsCmd, addFileCmd, removeFileCmd)
appCtx, appCancel = initAppContext()
} }
func ExecuteClientCommand() error { func initGRPCConnection() (err error) {
defer appCancel() appCtx, appCancel = context.WithCancel(context.Background())
return cliCmd.Execute()
}
func initAppContext() (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())
signals := make(chan os.Signal, 1) signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() { go func() {
<-signals <-signals
cancel() appCancel()
}() }()
return ctx, cancel dialCtx, cancel := context.WithTimeout(appCtx, grpcTimeout)
conn, err = grpc.DialContext(dialCtx, inetMockSocketPath, grpc.WithInsecure())
cancel()
return
} }

View file

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"context" "context"
@ -8,7 +8,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"gitlab.com/inetmock/inetmock/internal/format" "gitlab.com/inetmock/inetmock/internal/format"
"gitlab.com/inetmock/inetmock/internal/rpc" "gitlab.com/inetmock/inetmock/internal/rpc"
"google.golang.org/grpc"
) )
var ( var (
@ -51,12 +50,6 @@ func fromEndpoints(eps []*rpc.Endpoint) (out []*printableEndpoint) {
} }
func runGetEndpoints(_ *cobra.Command, _ []string) (err error) { func runGetEndpoints(_ *cobra.Command, _ []string) (err error) {
var conn *grpc.ClientConn
if conn, err = grpc.Dial(inetMockSocketPath, grpc.WithInsecure()); err != nil {
fmt.Printf("Failed to connecto INetMock socket: %v\n", err)
os.Exit(10)
}
endpointsClient := rpc.NewEndpointsClient(conn) endpointsClient := rpc.NewEndpointsClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), grpcTimeout) ctx, cancel := context.WithTimeout(context.Background(), grpcTimeout)
defer cancel() defer cancel()

View file

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"context" "context"
@ -8,7 +8,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"gitlab.com/inetmock/inetmock/internal/format" "gitlab.com/inetmock/inetmock/internal/format"
"gitlab.com/inetmock/inetmock/internal/rpc" "gitlab.com/inetmock/inetmock/internal/rpc"
"google.golang.org/grpc"
) )
var ( var (
@ -39,15 +38,11 @@ func fromHandlers(hs []string) (handlers []*printableHandler) {
} }
func runGetHandlers(_ *cobra.Command, _ []string) { func runGetHandlers(_ *cobra.Command, _ []string) {
var err error
var conn *grpc.ClientConn
if conn, err = grpc.Dial(inetMockSocketPath, grpc.WithInsecure()); err != nil {
fmt.Printf("Failed to connecto INetMock socket: %v\n", err)
os.Exit(10)
}
handlersClient := rpc.NewHandlersClient(conn) handlersClient := rpc.NewHandlersClient(conn)
ctx, _ := context.WithTimeout(context.Background(), grpcTimeout)
ctx, cancel := context.WithTimeout(appCtx, grpcTimeout)
defer cancel()
var err error
var handlersResp *rpc.GetHandlersResponse var handlersResp *rpc.GetHandlersResponse
if handlersResp, err = handlersClient.GetHandlers(ctx, &rpc.GetHandlersRequest{}); err != nil { if handlersResp, err = handlersClient.GetHandlers(ctx, &rpc.GetHandlersRequest{}); err != nil {

View file

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"context" "context"
@ -8,7 +8,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"gitlab.com/inetmock/inetmock/internal/format" "gitlab.com/inetmock/inetmock/internal/format"
"gitlab.com/inetmock/inetmock/internal/rpc" "gitlab.com/inetmock/inetmock/internal/rpc"
"google.golang.org/grpc"
) )
var ( var (
@ -55,15 +54,10 @@ func fromComponentsHealth(componentsHealth map[string]*rpc.ComponentHealth) (com
} }
func getHealthResult() (healthResp *rpc.HealthResponse, err error) { func getHealthResult() (healthResp *rpc.HealthResponse, err error) {
var conn *grpc.ClientConn
if conn, err = grpc.Dial(inetMockSocketPath, grpc.WithInsecure()); err != nil {
return
}
var healthClient = rpc.NewHealthClient(conn) var healthClient = rpc.NewHealthClient(conn)
ctx, _ := context.WithTimeout(context.Background(), grpcTimeout) ctx, cancel := context.WithTimeout(context.Background(), grpcTimeout)
healthResp, err = healthClient.GetHealth(ctx, &rpc.HealthRequest{}) healthResp, err = healthClient.GetHealth(ctx, &rpc.HealthRequest{})
cancel()
return return
} }

View file

@ -1,9 +1,8 @@
package main package main
import "gitlab.com/inetmock/inetmock/internal/cmd"
func main() { func main() {
if err := cmd.ExecuteClientCommand(); err != nil { defer appCancel()
if err := cliCmd.Execute(); err != nil {
panic(err) panic(err)
} }
} }

View file

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"crypto/tls" "crypto/tls"

View file

@ -1,14 +1,47 @@
package main package main
import ( import (
"gitlab.com/inetmock/inetmock/internal/cmd" "fmt"
"os"
"gitlab.com/inetmock/inetmock/internal/app"
"gitlab.com/inetmock/inetmock/internal/endpoint/handler/dns/mock"
_ "gitlab.com/inetmock/inetmock/internal/endpoint/handler/dns/mock" _ "gitlab.com/inetmock/inetmock/internal/endpoint/handler/dns/mock"
_ "gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/mock" _ "gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/mock"
mock2 "gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/mock"
"gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/proxy"
_ "gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/proxy" _ "gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/proxy"
"gitlab.com/inetmock/inetmock/internal/endpoint/handler/metrics"
_ "gitlab.com/inetmock/inetmock/internal/endpoint/handler/metrics" _ "gitlab.com/inetmock/inetmock/internal/endpoint/handler/metrics"
"gitlab.com/inetmock/inetmock/internal/endpoint/handler/tls/interceptor"
_ "gitlab.com/inetmock/inetmock/internal/endpoint/handler/tls/interceptor" _ "gitlab.com/inetmock/inetmock/internal/endpoint/handler/tls/interceptor"
"go.uber.org/zap"
)
var (
server app.App
) )
func main() { func main() {
cmd.ExecuteServerCommand() logger, _ := zap.NewProduction()
defer func() {
if err := logger.Sync(); err != nil {
fmt.Println(err.Error())
}
}()
var err error
if server, err = app.NewApp(
mock2.AddHTTPMock,
mock.AddDNSMock,
interceptor.AddTLSInterceptor,
proxy.AddHTTPProxy,
metrics.AddMetricsExporter,
); err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
server.
WithCommands(serveCmd, generateCaCmd).
MustRun()
} }

View file

@ -1,4 +1,4 @@
package cmd package main
import ( import (
"strings" "strings"

View file

@ -1,34 +0,0 @@
package cmd
import (
"fmt"
"os"
"gitlab.com/inetmock/inetmock/internal/app"
"gitlab.com/inetmock/inetmock/internal/endpoint/handler/dns/mock"
mock2 "gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/mock"
"gitlab.com/inetmock/inetmock/internal/endpoint/handler/http/proxy"
"gitlab.com/inetmock/inetmock/internal/endpoint/handler/metrics"
"gitlab.com/inetmock/inetmock/internal/endpoint/handler/tls/interceptor"
)
var (
server app.App
)
func ExecuteServerCommand() {
var err error
if server, err = app.NewApp(
mock2.AddHTTPMock,
mock.AddDNSMock,
interceptor.AddTLSInterceptor,
proxy.AddHTTPProxy,
metrics.AddMetricsExporter,
); err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
server.
WithCommands(serveCmd, generateCaCmd).
MustRun()
}

View file

@ -12,8 +12,8 @@ const (
) )
var ( var (
defaultDistributeParallelization int
generatorIdx int64 = 1 generatorIdx int64 = 1
defaultDistributeParallelization = runtime.NumCPU() / 2
WithBufferSize = func(bufferSize int) EventStreamOption { WithBufferSize = func(bufferSize int) EventStreamOption {
return func(cfg *eventStreamCfg) { return func(cfg *eventStreamCfg) {
cfg.bufferSize = bufferSize cfg.bufferSize = bufferSize
@ -44,6 +44,12 @@ var (
} }
) )
func init() {
if defaultDistributeParallelization = runtime.NumCPU() / 2; defaultDistributeParallelization < 2 {
defaultDistributeParallelization = 2
}
}
type EventStreamOption func(cfg *eventStreamCfg) type EventStreamOption func(cfg *eventStreamCfg)
type eventStreamCfg struct { type eventStreamCfg struct {