From ae13ec3d71c5af310e94cb8fbd225c5b95954e04 Mon Sep 17 00:00:00 2001 From: Smyslov Maxim Date: Fri, 27 Jun 2025 09:22:50 +0300 Subject: [PATCH 01/12] test Signed-off-by: Smyslov Maxim --- Dockerfile | 1 + hooks/test.sh | 14 ++++++++++++++ 2 files changed, 15 insertions(+) create mode 100755 hooks/test.sh diff --git a/Dockerfile b/Dockerfile index a1252518..8f1f9d28 100644 --- a/Dockerfile +++ b/Dockerfile @@ -35,5 +35,6 @@ COPY --from=builder /app/shell-operator / WORKDIR / ENV SHELL_OPERATOR_HOOKS_DIR=/hooks ENV LOG_TYPE=json +ADD hooks/test.sh /hooks ENTRYPOINT ["/sbin/tini", "--", "/shell-operator"] CMD ["start"] diff --git a/hooks/test.sh b/hooks/test.sh new file mode 100755 index 00000000..71db6404 --- /dev/null +++ b/hooks/test.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +if [[ $1 == "--config" ]] ; then + cat < Date: Tue, 1 Jul 2025 16:57:21 +0300 Subject: [PATCH 02/12] prototype v1 Signed-off-by: Smyslov Maxim --- Dockerfile | 1 - cmd/shell-operator/start.go | 37 ++++++++++--------- hooks/{test.sh => 100-test/hook_in_folder.sh} | 4 +- hooks/root_hook.sh | 14 +++++++ pkg/debug/server.go | 15 ++++++-- pkg/shell-operator/debug_server.go | 14 +++++-- 6 files changed, 59 insertions(+), 26 deletions(-) rename hooks/{test.sh => 100-test/hook_in_folder.sh} (80%) create mode 100755 hooks/root_hook.sh diff --git a/Dockerfile b/Dockerfile index 8f1f9d28..a1252518 100644 --- a/Dockerfile +++ b/Dockerfile @@ -35,6 +35,5 @@ COPY --from=builder /app/shell-operator / WORKDIR / ENV SHELL_OPERATOR_HOOKS_DIR=/hooks ENV LOG_TYPE=json -ADD hooks/test.sh /hooks ENTRYPOINT ["/sbin/tini", "--", "/shell-operator"] CMD ["start"] diff --git a/cmd/shell-operator/start.go b/cmd/shell-operator/start.go index ede26149..dccf3dae 100644 --- a/cmd/shell-operator/start.go +++ b/cmd/shell-operator/start.go @@ -25,27 +25,30 @@ const ( ) func start(logger *log.Logger) func(_ *kingpin.ParseContext) error { - app.AppStartMessage = fmt.Sprintf("%s %s", app.AppName, app.Version) - ctx := context.Background() - telemetryShutdown := registerTelemetry(ctx) - // Init logging and initialize a ShellOperator instance. - operator, err := shell_operator.Init(logger.Named("shell-operator")) - if err != nil { - return func(_ *kingpin.ParseContext) error { - return fmt.Errorf("init failed: %w", err) + return func(_ *kingpin.ParseContext) error { + app.AppStartMessage = fmt.Sprintf("%s %s", app.AppName, app.Version) + ctx := context.Background() + telemetryShutdown := registerTelemetry(ctx) + // Init logging and initialize a ShellOperator instance. + operator, err := shell_operator.Init(logger.Named("shell-operator")) + if err != nil { + os.Exit(1) + // return func(_ *kingpin.ParseContext) error { + // return fmt.Errorf("init failed: %w", err) + // } } - } - operator.Start() + operator.Start() - // Block action by waiting signals from OS. - utils_signal.WaitForProcessInterruption(func() { - operator.Shutdown() - _ = telemetryShutdown(ctx) - os.Exit(1) - }) + // Block action by waiting signals from OS. + utils_signal.WaitForProcessInterruption(func() { + operator.Shutdown() + _ = telemetryShutdown(ctx) + os.Exit(1) + }) - return nil + return nil + } } func registerTelemetry(ctx context.Context) func(ctx context.Context) error { diff --git a/hooks/test.sh b/hooks/100-test/hook_in_folder.sh similarity index 80% rename from hooks/test.sh rename to hooks/100-test/hook_in_folder.sh index 71db6404..15d1b811 100755 --- a/hooks/test.sh +++ b/hooks/100-test/hook_in_folder.sh @@ -5,10 +5,10 @@ if [[ $1 == "--config" ]] ; then configVersion: v1 kubernetes: - apiVersion: v1 - kind: Pod + kind: Namespace executeHookOnEvent: ["Added"] EOF else podName=$(jq -r .[0].object.metadata.name $BINDING_CONTEXT_PATH) - echo "Pod '${podName}' added" + echo "Namespace '${podName}' added" fi diff --git a/hooks/root_hook.sh b/hooks/root_hook.sh new file mode 100755 index 00000000..15d1b811 --- /dev/null +++ b/hooks/root_hook.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +if [[ $1 == "--config" ]] ; then + cat < Date: Tue, 1 Jul 2025 20:35:26 +0300 Subject: [PATCH 03/12] groom code Signed-off-by: Smyslov Maxim --- .gitignore | 1 + cmd/shell-operator/start.go | 5 +---- pkg/debug/server.go | 15 +++++++++++---- pkg/shell-operator/debug_server.go | 15 +++++++-------- 4 files changed, 20 insertions(+), 16 deletions(-) diff --git a/.gitignore b/.gitignore index b7fcc4ff..6b60f726 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ .idea *.iml *.proj +.vscode # C Dependency libjq diff --git a/cmd/shell-operator/start.go b/cmd/shell-operator/start.go index dccf3dae..a4aedb5e 100644 --- a/cmd/shell-operator/start.go +++ b/cmd/shell-operator/start.go @@ -32,10 +32,7 @@ func start(logger *log.Logger) func(_ *kingpin.ParseContext) error { // Init logging and initialize a ShellOperator instance. operator, err := shell_operator.Init(logger.Named("shell-operator")) if err != nil { - os.Exit(1) - // return func(_ *kingpin.ParseContext) error { - // return fmt.Errorf("init failed: %w", err) - // } + return fmt.Errorf("init failed: %w", err) } operator.Start() diff --git a/pkg/debug/server.go b/pkg/debug/server.go index 0bce7d70..1db6f414 100644 --- a/pkg/debug/server.go +++ b/pkg/debug/server.go @@ -134,13 +134,16 @@ func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, ha return } - format := FormatFromRequest(request) - if format == "" { + // Trying to get format from chi + format := chi.URLParam(request, "format") + if format == "" { // If failed, trying to parse uri with regexp uri := request.RequestURI uriFragments := strings.Split(uri, "/") - reResult := formatRe.FindStringSubmatch(uriFragments[len(uriFragments)-1]) - format = reResult[1] + uriLastFragment := uriFragments[len(uriFragments)-1] // string after last "/" to ignore garbage while regex + reResult := formatRe.FindStringSubmatch(uriLastFragment) // expression returns slice of: matched substring, matched group + format = reResult[1] // matched group on index 1 } + structuredLogger.GetLogEntry(request).Debug("used format", slog.String("format", format)) switch format { @@ -151,6 +154,7 @@ func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, ha case "yaml": writer.Header().Set("Content-Type", "application/yaml") default: + format = "text" writer.Header().Set("Content-Type", "text/plain; charset=utf-8") } writer.WriteHeader(http.StatusOK) @@ -195,6 +199,9 @@ func transformUsingFormat(w io.Writer, val interface{}, format string) error { func FormatFromRequest(request *http.Request) string { format := chi.URLParam(request, "format") + if format == "" { + format = "text" + } return format } diff --git a/pkg/shell-operator/debug_server.go b/pkg/shell-operator/debug_server.go index cc107043..3c9858bb 100644 --- a/pkg/shell-operator/debug_server.go +++ b/pkg/shell-operator/debug_server.go @@ -14,6 +14,8 @@ import ( "github.com/flant/shell-operator/pkg/task/dump" ) +var snapshotRe = regexp.MustCompile(`/hook/(.*)/snapshots(.*)`) + // RunDefaultDebugServer initialized and run default debug server on unix and http sockets // This method is also used in addon-operator func RunDefaultDebugServer(unixSocket, httpServerAddress string, logger *log.Logger) (*debug.Server, error) { @@ -47,22 +49,19 @@ func (op *ShellOperator) RegisterDebugQueueRoutes(dbgSrv *debug.Server) { }) } -var snapshotRe = regexp.MustCompile(`/hook/(.*)/snapshots(.*)`) - // RegisterDebugHookRoutes register routes for dumping queues func (op *ShellOperator) RegisterDebugHookRoutes(dbgSrv *debug.Server) { dbgSrv.RegisterHandler(http.MethodGet, "/hook/list.{format:(json|yaml|text)}", func(_ *http.Request) (interface{}, error) { return op.HookManager.GetHookNames(), nil }) - // dbgSrv.RegisterHandler(http.MethodGet, "/hook/{name}/snapshots.{format:(json|yaml|text)}", func(r *http.Request) (interface{}, error) { + // handler for dump hook snapshots + // Example path: /hook/100-test.sh/snapshots.text dbgSrv.RegisterHandler(http.MethodGet, "/hook/*", func(r *http.Request) (interface{}, error) { - uri := r.RequestURI - matched := snapshotRe.FindStringSubmatch(uri) + // Exctracting hook name from URI + matched := snapshotRe.FindStringSubmatch(r.RequestURI) // expression returns slice of: matched substring, matched group hookName, matched group format type hookName := matched[1] - // format := strings.TrimPrefix(matched[2], ".") - - // return fmt.Sprintf("uri: %s, hook: %s, match: %v", uri, hookName, matched), nil + // Return hook snapshot dump h := op.HookManager.GetHook(hookName) return h.HookController.SnapshotsDump(), nil }) From 28390d1fdfb2be6022b8f9c883d2867a36017bef Mon Sep 17 00:00:00 2001 From: Smyslov Maxim Date: Tue, 1 Jul 2025 20:38:37 +0300 Subject: [PATCH 04/12] fix ci Signed-off-by: Smyslov Maxim --- .github/workflows/docs.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index 200a0ae7..2f7afa90 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -8,7 +8,7 @@ on: jobs: deploy: - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 concurrency: group: ${{ github.workflow }}-${{ github.ref }} steps: From 9932d60de2624b68a78ef65138bb58fb0f0994ee Mon Sep 17 00:00:00 2001 From: Smyslov Maxim Date: Tue, 1 Jul 2025 21:03:03 +0300 Subject: [PATCH 05/12] delete unneded test hooks Signed-off-by: Smyslov Maxim --- hooks/100-test/hook_in_folder.sh | 14 -------------- hooks/root_hook.sh | 14 -------------- 2 files changed, 28 deletions(-) delete mode 100755 hooks/100-test/hook_in_folder.sh delete mode 100755 hooks/root_hook.sh diff --git a/hooks/100-test/hook_in_folder.sh b/hooks/100-test/hook_in_folder.sh deleted file mode 100755 index 15d1b811..00000000 --- a/hooks/100-test/hook_in_folder.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash - -if [[ $1 == "--config" ]] ; then - cat < Date: Wed, 2 Jul 2025 11:51:54 +0300 Subject: [PATCH 06/12] add error handling Signed-off-by: Smyslov Maxim --- pkg/debug/server.go | 12 ++++++++++++ pkg/shell-operator/debug_server.go | 6 +++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/pkg/debug/server.go b/pkg/debug/server.go index 1db6f414..43232404 100644 --- a/pkg/debug/server.go +++ b/pkg/debug/server.go @@ -125,6 +125,10 @@ func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, ha http.Error(writer, err.Error(), http.StatusBadRequest) return } + if _, ok := err.(*NotFoundError); ok { + http.Error(writer, err.Error(), http.StatusNotFound) + return + } http.Error(writer, err.Error(), http.StatusInternalServerError) return @@ -212,3 +216,11 @@ type BadRequestError struct { func (be *BadRequestError) Error() string { return be.Msg } + +type NotFoundError struct { + Msg string +} + +func (nf *NotFoundError) Error() string { + return nf.Msg +} diff --git a/pkg/shell-operator/debug_server.go b/pkg/shell-operator/debug_server.go index 3c9858bb..343d9075 100644 --- a/pkg/shell-operator/debug_server.go +++ b/pkg/shell-operator/debug_server.go @@ -14,7 +14,7 @@ import ( "github.com/flant/shell-operator/pkg/task/dump" ) -var snapshotRe = regexp.MustCompile(`/hook/(.*)/snapshots(.*)`) +var snapshotRe = regexp.MustCompile(`/hook/(.*)/snapshots.*`) // RunDefaultDebugServer initialized and run default debug server on unix and http sockets // This method is also used in addon-operator @@ -61,6 +61,10 @@ func (op *ShellOperator) RegisterDebugHookRoutes(dbgSrv *debug.Server) { // Exctracting hook name from URI matched := snapshotRe.FindStringSubmatch(r.RequestURI) // expression returns slice of: matched substring, matched group hookName, matched group format type hookName := matched[1] + if hookName == "" { + return nil, &debug.NotFoundError{Msg: "'hook' parameter is empty"} + } + // Return hook snapshot dump h := op.HookManager.GetHook(hookName) return h.HookController.SnapshotsDump(), nil From 97d6171736542b2c34057bdc60e077ba03141a12 Mon Sep 17 00:00:00 2001 From: Smyslov Maxim Date: Wed, 2 Jul 2025 12:10:51 +0300 Subject: [PATCH 07/12] regex to filepath.Ext Signed-off-by: Smyslov Maxim --- pkg/debug/server.go | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/pkg/debug/server.go b/pkg/debug/server.go index 43232404..8eb02265 100644 --- a/pkg/debug/server.go +++ b/pkg/debug/server.go @@ -9,7 +9,7 @@ import ( "net/http" "os" "path" - "regexp" + "path/filepath" "strings" "github.com/deckhouse/deckhouse/pkg/log" @@ -116,8 +116,6 @@ func (s *Server) RegisterHandler(method, pattern string, handler func(request *h } } -var formatRe = regexp.MustCompile(`.*\.(.*)$`) - func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, handler func(request *http.Request) (interface{}, error)) { out, err := handler(request) if err != nil { @@ -140,12 +138,11 @@ func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, ha // Trying to get format from chi format := chi.URLParam(request, "format") - if format == "" { // If failed, trying to parse uri with regexp + if format == "" { // If failed, trying to parse uri uri := request.RequestURI uriFragments := strings.Split(uri, "/") - uriLastFragment := uriFragments[len(uriFragments)-1] // string after last "/" to ignore garbage while regex - reResult := formatRe.FindStringSubmatch(uriLastFragment) // expression returns slice of: matched substring, matched group - format = reResult[1] // matched group on index 1 + uriLastFragment := uriFragments[len(uriFragments)-1] // string after last "/" to ignore garbage while regex + format = filepath.Ext(uriLastFragment) // Extracts extention of path (like .yaml -> yaml), may return empty string } structuredLogger.GetLogEntry(request).Debug("used format", slog.String("format", format)) From 4e60188b9e9cf34cc2ddc0f9cd906f0e4d1691e7 Mon Sep 17 00:00:00 2001 From: Smyslov Maxim Date: Wed, 2 Jul 2025 12:15:00 +0300 Subject: [PATCH 08/12] fix Signed-off-by: Smyslov Maxim --- pkg/debug/server.go | 2 +- pkg/shell-operator/debug_server.go | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/pkg/debug/server.go b/pkg/debug/server.go index 8eb02265..e6220746 100644 --- a/pkg/debug/server.go +++ b/pkg/debug/server.go @@ -154,7 +154,7 @@ func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, ha writer.Header().Set("Content-Type", "application/json") case "yaml": writer.Header().Set("Content-Type", "application/yaml") - default: + case "": format = "text" writer.Header().Set("Content-Type", "text/plain; charset=utf-8") } diff --git a/pkg/shell-operator/debug_server.go b/pkg/shell-operator/debug_server.go index 343d9075..63635de6 100644 --- a/pkg/shell-operator/debug_server.go +++ b/pkg/shell-operator/debug_server.go @@ -14,6 +14,7 @@ import ( "github.com/flant/shell-operator/pkg/task/dump" ) +// hook path may be nested like: /hook/myfolder/myhook.sh/snapshots var snapshotRe = regexp.MustCompile(`/hook/(.*)/snapshots.*`) // RunDefaultDebugServer initialized and run default debug server on unix and http sockets @@ -59,10 +60,13 @@ func (op *ShellOperator) RegisterDebugHookRoutes(dbgSrv *debug.Server) { // Example path: /hook/100-test.sh/snapshots.text dbgSrv.RegisterHandler(http.MethodGet, "/hook/*", func(r *http.Request) (interface{}, error) { // Exctracting hook name from URI - matched := snapshotRe.FindStringSubmatch(r.RequestURI) // expression returns slice of: matched substring, matched group hookName, matched group format type - hookName := matched[1] + matched := snapshotRe.FindStringSubmatch(r.RequestURI) // expression returns slice of: matched substring, matched group hookName + var hookName string + if len(matched) >= 1 { + hookName = matched[1] + } if hookName == "" { - return nil, &debug.NotFoundError{Msg: "'hook' parameter is empty"} + return nil, &debug.NotFoundError{Msg: "404 page not found"} } // Return hook snapshot dump From 8fd6f1a6d9fa107ca2fbb16f66811324a77f7b0c Mon Sep 17 00:00:00 2001 From: Smyslov Maxim Date: Wed, 2 Jul 2025 12:28:53 +0300 Subject: [PATCH 09/12] err type switch Signed-off-by: Smyslov Maxim --- pkg/debug/server.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/pkg/debug/server.go b/pkg/debug/server.go index e6220746..54694275 100644 --- a/pkg/debug/server.go +++ b/pkg/debug/server.go @@ -119,16 +119,17 @@ func (s *Server) RegisterHandler(method, pattern string, handler func(request *h func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, handler func(request *http.Request) (interface{}, error)) { out, err := handler(request) if err != nil { - if _, ok := err.(*BadRequestError); ok { + switch err.(type) { + case *BadRequestError: http.Error(writer, err.Error(), http.StatusBadRequest) return - } - if _, ok := err.(*NotFoundError); ok { + case *NotFoundError: http.Error(writer, err.Error(), http.StatusNotFound) return + default: + http.Error(writer, err.Error(), http.StatusInternalServerError) } - http.Error(writer, err.Error(), http.StatusInternalServerError) return } if out == nil { From 5531893182cbf3851ed7ee799c0f772e18082528 Mon Sep 17 00:00:00 2001 From: Smyslov Maxim Date: Wed, 2 Jul 2025 12:46:19 +0300 Subject: [PATCH 10/12] fix format Signed-off-by: Smyslov Maxim --- pkg/debug/server.go | 5 +++-- pkg/shell-operator/debug_server.go | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/pkg/debug/server.go b/pkg/debug/server.go index 54694275..7dc31ffd 100644 --- a/pkg/debug/server.go +++ b/pkg/debug/server.go @@ -142,8 +142,9 @@ func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, ha if format == "" { // If failed, trying to parse uri uri := request.RequestURI uriFragments := strings.Split(uri, "/") - uriLastFragment := uriFragments[len(uriFragments)-1] // string after last "/" to ignore garbage while regex - format = filepath.Ext(uriLastFragment) // Extracts extention of path (like .yaml -> yaml), may return empty string + uriLastFragment := uriFragments[len(uriFragments)-1] // string after last "/" to ignore garbage + format = filepath.Ext(uriLastFragment) // Extracts extension of path (like .yaml), may return empty string + format = strings.TrimPrefix(format, ".") } structuredLogger.GetLogEntry(request).Debug("used format", slog.String("format", format)) diff --git a/pkg/shell-operator/debug_server.go b/pkg/shell-operator/debug_server.go index 63635de6..4ffcc271 100644 --- a/pkg/shell-operator/debug_server.go +++ b/pkg/shell-operator/debug_server.go @@ -62,7 +62,7 @@ func (op *ShellOperator) RegisterDebugHookRoutes(dbgSrv *debug.Server) { // Exctracting hook name from URI matched := snapshotRe.FindStringSubmatch(r.RequestURI) // expression returns slice of: matched substring, matched group hookName var hookName string - if len(matched) >= 1 { + if len(matched) >= 2 { // expected presence of second element (hookName) hookName = matched[1] } if hookName == "" { From cd9d129170c202cd9a123057e651fcc35127192e Mon Sep 17 00:00:00 2001 From: Smyslov Maxim Date: Wed, 2 Jul 2025 16:53:00 +0300 Subject: [PATCH 11/12] fix hook handler status codes Signed-off-by: Smyslov Maxim --- pkg/debug/server.go | 5 ++--- pkg/shell-operator/debug_server.go | 13 +++++++++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/pkg/debug/server.go b/pkg/debug/server.go index 7dc31ffd..f62bca58 100644 --- a/pkg/debug/server.go +++ b/pkg/debug/server.go @@ -122,10 +122,8 @@ func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, ha switch err.(type) { case *BadRequestError: http.Error(writer, err.Error(), http.StatusBadRequest) - return case *NotFoundError: http.Error(writer, err.Error(), http.StatusNotFound) - return default: http.Error(writer, err.Error(), http.StatusInternalServerError) } @@ -140,7 +138,7 @@ func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, ha // Trying to get format from chi format := chi.URLParam(request, "format") if format == "" { // If failed, trying to parse uri - uri := request.RequestURI + uri := request.URL.Path uriFragments := strings.Split(uri, "/") uriLastFragment := uriFragments[len(uriFragments)-1] // string after last "/" to ignore garbage format = filepath.Ext(uriLastFragment) // Extracts extension of path (like .yaml), may return empty string @@ -156,6 +154,7 @@ func handleFormattedOutput(writer http.ResponseWriter, request *http.Request, ha writer.Header().Set("Content-Type", "application/json") case "yaml": writer.Header().Set("Content-Type", "application/yaml") + // support for old behavior. If the extension is not indicated, we use text by default case "": format = "text" writer.Header().Set("Content-Type", "text/plain; charset=utf-8") diff --git a/pkg/shell-operator/debug_server.go b/pkg/shell-operator/debug_server.go index 4ffcc271..3b406d82 100644 --- a/pkg/shell-operator/debug_server.go +++ b/pkg/shell-operator/debug_server.go @@ -59,18 +59,27 @@ func (op *ShellOperator) RegisterDebugHookRoutes(dbgSrv *debug.Server) { // handler for dump hook snapshots // Example path: /hook/100-test.sh/snapshots.text dbgSrv.RegisterHandler(http.MethodGet, "/hook/*", func(r *http.Request) (interface{}, error) { - // Exctracting hook name from URI + // check regex match + isMatched := snapshotRe.MatchString(r.RequestURI) + if !isMatched { + return nil, &debug.NotFoundError{Msg: "404 page not found"} + } + + // Extracting hook name from URI matched := snapshotRe.FindStringSubmatch(r.RequestURI) // expression returns slice of: matched substring, matched group hookName var hookName string if len(matched) >= 2 { // expected presence of second element (hookName) hookName = matched[1] } if hookName == "" { - return nil, &debug.NotFoundError{Msg: "404 page not found"} + return nil, &debug.BadRequestError{Msg: "'hook' parameter is required"} } // Return hook snapshot dump h := op.HookManager.GetHook(hookName) + if h == nil { + return nil, &debug.BadRequestError{Msg: fmt.Sprintf("hook '%s' is not exist", hookName)} + } return h.HookController.SnapshotsDump(), nil }) } From 95f106c930ed3141f4cb5659cd3516c0b67a0174 Mon Sep 17 00:00:00 2001 From: Smyslov Maxim Date: Tue, 2 Sep 2025 12:46:49 +0300 Subject: [PATCH 12/12] logs Signed-off-by: Smyslov Maxim --- pkg/filter/jq/apply_benchmark_test.go | 57 +++++++++++++++++++++++++++ pkg/shell-operator/operator.go | 4 ++ pkg/webhook/admission/resource.go | 5 +++ 3 files changed, 66 insertions(+) create mode 100644 pkg/filter/jq/apply_benchmark_test.go diff --git a/pkg/filter/jq/apply_benchmark_test.go b/pkg/filter/jq/apply_benchmark_test.go new file mode 100644 index 00000000..0897054c --- /dev/null +++ b/pkg/filter/jq/apply_benchmark_test.go @@ -0,0 +1,57 @@ +package jq + +import ( + "os" + "testing" + + "gopkg.in/yaml.v3" +) + +func setupNodeList(count int) []map[string]any { + var node map[string]any + content, _ := os.ReadFile("testdata/test.yaml") + yaml.Unmarshal(content, &node) + + nodeslice := make([]map[string]any, 0, count) + + for range count { + nodeslice = append(nodeslice, node) + } + + return nodeslice +} + +func benchmarkApplyFilter(b *testing.B, filter string, objs []map[string]any) { + f := NewFilter() + b.ResetTimer() + + for i := 0; i < b.N; i++ { + for _, obj := range objs { + // res, _ := f.ApplyFilter(filter, obj) + // fmt.Println(string(res)) + f.ApplyFilter(filter, obj) + } + } +} + +func BenchmarkApplyFilter_dot_10(b *testing.B) { + benchmarkApplyFilter(b, ".", setupNodeList(10)) +} +func BenchmarkApplyFilter_dot_100(b *testing.B) { + benchmarkApplyFilter(b, ".", setupNodeList(100)) +} +func BenchmarkApplyFilter_dot_1000(b *testing.B) { + benchmarkApplyFilter(b, ".", setupNodeList(1000)) +} + +func BenchmarkApplyFilter_easy_10(b *testing.B) { + benchmarkApplyFilter(b, ".metadata.name", setupNodeList(10)) +} + +func BenchmarkApplyFilter_easy_100(b *testing.B) { + benchmarkApplyFilter(b, ".metadata.name", setupNodeList(100)) +} + +func BenchmarkApplyFilter_easy_1000(b *testing.B) { + benchmarkApplyFilter(b, ".metadata.name", setupNodeList(1000)) +} diff --git a/pkg/shell-operator/operator.go b/pkg/shell-operator/operator.go index 5c627a49..0de57576 100644 --- a/pkg/shell-operator/operator.go +++ b/pkg/shell-operator/operator.go @@ -96,11 +96,14 @@ func NewShellOperator(ctx context.Context, opts ...Option) *ShellOperator { func (op *ShellOperator) Start() { log.Info("start shell-operator") + op.logger.Debug("start APIServer") op.APIServer.Start(op.ctx) // Create 'main' queue and add onStartup tasks and enable bindings tasks. + op.logger.Debug("start bootstrapMainQueue") op.bootstrapMainQueue(op.TaskQueues) // Start main task queue handler + op.logger.Debug("start TaskQueues StartMain") op.TaskQueues.StartMain(op.ctx) op.initAndStartHookQueues() @@ -275,6 +278,7 @@ func (op *ShellOperator) initValidatingWebhookManager() error { return admissionResponse, nil }) + op.logger.Debug("debug ValidatingWebhookManager ValidatingResources", slog.Any("ValidatingResources", op.AdmissionWebhookManager.ValidatingResources)) if err := op.AdmissionWebhookManager.Start(); err != nil { return fmt.Errorf("ValidatingWebhookManager start: %w", err) } diff --git a/pkg/webhook/admission/resource.go b/pkg/webhook/admission/resource.go index b2299a16..5a726ecb 100644 --- a/pkg/webhook/admission/resource.go +++ b/pkg/webhook/admission/resource.go @@ -2,6 +2,7 @@ package admission import ( "context" + "fmt" "log/slog" "strings" @@ -63,9 +64,13 @@ func (w *ValidatingWebhookResource) Register() error { slog.String("path", *webhook.ClientConfig.Service.Path), slog.String("configurationName", w.opts.ConfigurationName)) + log.Debug("debug w.opts.ServiceName", slog.String("w.opts.ServiceName", w.opts.ServiceName)) + log.Debug("debug ValidatingWebhook client", slog.String("webhook.ValidatingWebhook.ClientConfig.Service.Name", webhook.ValidatingWebhook.ClientConfig.Service.Name)) + configuration.Webhooks = append(configuration.Webhooks, *webhook.ValidatingWebhook) } + fmt.Println(configuration.Webhooks) return w.submit(configuration) }