-
Notifications
You must be signed in to change notification settings - Fork 1.4k
CONTINT-5286 - add new action in remote config k8s actions #49331
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
gh-worker-dd-mergequeue-cf854d
merged 1 commit into
main
from
crayon/CONTINT-5286_kube_action_get_resource
Apr 24, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| // Unless explicitly stated otherwise all files in this repository are licensed | ||
| // under the Apache License Version 2.0. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
| // Copyright 2016-present Datadog, Inc. | ||
|
|
||
| //go:build kubeapiserver | ||
|
|
||
| package executors | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "net/url" | ||
| "strings" | ||
|
|
||
| "k8s.io/client-go/kubernetes" | ||
|
|
||
| "sigs.k8s.io/yaml" | ||
|
|
||
| "github.com/DataDog/datadog-agent/pkg/util/log" | ||
|
|
||
| kubeactions "github.com/DataDog/agent-payload/v5/kubeactions" | ||
| ) | ||
|
|
||
| const ( | ||
| maxResourceOutputSize = 4 * 1024 // 4KB | ||
| ) | ||
|
|
||
| type GetResourceExecutor struct { | ||
| clientset kubernetes.Interface | ||
| } | ||
|
|
||
| // Ensure interface compliance at compile time | ||
| var _ Executor = (*GetResourceExecutor)(nil) | ||
|
|
||
| var ( | ||
| // ErrUnsupportedFormat is returned when the requested output format is not supported | ||
| ErrUnsupportedFormat = errors.New("unsupported output format") | ||
| ) | ||
|
|
||
| // NewGetResourceExecutor creates a new GetResourceExecutor | ||
| func NewGetResourceExecutor(clientset kubernetes.Interface) *GetResourceExecutor { | ||
| return &GetResourceExecutor{ | ||
| clientset: clientset, | ||
| } | ||
| } | ||
|
|
||
| // Execute retrieves the specified Kubernetes resource and returns it as JSON string in the message field of ExecutionResult | ||
| func (e *GetResourceExecutor) Execute(ctx context.Context, action *kubeactions.KubeAction) ExecutionResult { | ||
| resource := action.Resource | ||
| namespace := strings.ToLower(resource.GetNamespace()) | ||
| name := strings.ToLower(resource.GetName()) | ||
|
frank-spano marked this conversation as resolved.
|
||
| apiVersion := strings.ToLower(resource.GetApiVersion()) | ||
| kind := strings.ToLower(resource.GetKind()) | ||
|
lavigne958 marked this conversation as resolved.
frank-spano marked this conversation as resolved.
|
||
|
|
||
| if apiVersion == "" { | ||
| return ExecutionResult{ | ||
| Status: StatusFailed, | ||
| Message: "apiVersion is required to get resource", | ||
| } | ||
| } | ||
|
|
||
| // prevent the executor from being used to get secrets for security reasons, even if the user has permissions to do so, we don't want to allow that | ||
| if strings.Contains(kind, "secret") { | ||
| return ExecutionResult{ | ||
| Status: StatusFailed, | ||
| Message: "getting secrets is not allowed for security reasons", | ||
| } | ||
| } | ||
|
|
||
| log.Infof("Getting resource %s/%s of type %s", namespace, name, resource.Kind) | ||
|
|
||
| // build the raw REST request to get the resource as unstructured JSON | ||
| var path string | ||
|
|
||
| // the api version for core resources does not contain a '/'. | ||
| // and the path for core resources is /api/.... | ||
| // as for all other resources the path is /apis/... | ||
| var apiPrefix string | ||
| if !strings.Contains(apiVersion, "/") { | ||
| apiPrefix = "/api" | ||
| } else { | ||
| apiPrefix = "/apis" | ||
| } | ||
|
|
||
| // resource.GetApiVersion() returns group/version, it will automagically handle adding the group prefix if needed | ||
| // or not adding it for core resources | ||
| if namespace == "" { | ||
| path, _ = url.JoinPath(apiPrefix, apiVersion, kind, name) | ||
| } else { | ||
| path, _ = url.JoinPath(apiPrefix, apiVersion, "namespaces", namespace, kind, name) | ||
| } | ||
|
|
||
| ctx, cancel := context.WithTimeout(ctx, defaultExecutorTimeout) | ||
| defer cancel() | ||
|
|
||
| log.Debugf("get_resource using path '%s'", path) | ||
| data, err := e.clientset.CoreV1().RESTClient().Get().AbsPath(path).Do(ctx).Raw() | ||
| if err != nil { | ||
| return ExecutionResult{ | ||
| Status: StatusFailed, | ||
| Message: fmt.Sprintf("failed to get resource: %v -- raw response body: %s", err, string(data)), | ||
| } | ||
| } | ||
|
|
||
| outputFormat := "json" | ||
| if output := action.GetGetResource_().GetOutputFormat(); output != "" { | ||
| outputFormat = strings.ToLower(output) | ||
| } | ||
|
|
||
| output, err := formatOutput(data, outputFormat) | ||
| if err != nil { | ||
| return ExecutionResult{ | ||
| Status: StatusFailed, | ||
| Message: fmt.Sprintf("failed to format output to %s: %v", outputFormat, err), | ||
| } | ||
| } | ||
|
|
||
| output = bytes.TrimSpace(output) | ||
| if len(output) > maxResourceOutputSize { | ||
| log.Warnf("output for resource %s/%s of type %s is too large (%d bytes), truncating to %d bytes", namespace, name, kind, len(output), maxResourceOutputSize) | ||
| output = output[:maxResourceOutputSize] | ||
| } | ||
|
|
||
| return ExecutionResult{ | ||
| Status: StatusSuccess, | ||
| Message: fmt.Sprintf("get resource %s/%s success", kind, name), | ||
| Payloads: map[string][]byte{ | ||
| "resource": []byte(output), | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| func formatOutput(data []byte, format string) ([]byte, error) { | ||
| switch format { | ||
| case "json": | ||
| return data, nil | ||
| case "yaml": | ||
| jsonData := data | ||
| yamlData, err := yaml.JSONToYAML(jsonData) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to convert resource JSON to YAML: %v", err) | ||
| } | ||
| return yamlData, nil | ||
| default: | ||
| return nil, ErrUnsupportedFormat | ||
| } | ||
| } | ||
79 changes: 79 additions & 0 deletions
79
pkg/clusteragent/kubeactions/executors/get_resource_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| // Unless explicitly stated otherwise all files in this repository are licensed | ||
| // under the Apache License Version 2.0. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
| // Copyright 2016-present Datadog, Inc. | ||
|
|
||
| //go:build kubeapiserver | ||
|
|
||
| package executors | ||
|
|
||
| import ( | ||
| "errors" | ||
| "testing" | ||
| ) | ||
|
|
||
| var testPodJSON = []byte(`{ | ||
| "apiVersion": "v1", | ||
| "kind": "Pod", | ||
| "metadata": { | ||
| "name": "test-pod", | ||
| "namespace": "default" | ||
| }, | ||
| "spec": { | ||
| "containers": [ | ||
| { | ||
| "name": "test-container", | ||
| "image": "busybox", | ||
| "command": ["sleep", "3600"] | ||
| } | ||
| ] | ||
| } | ||
| }`) | ||
|
|
||
| func TestOutputFormat(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| input []byte | ||
| outputFormat string | ||
| expectErr bool | ||
| }{ | ||
| { | ||
| name: "from json to json", | ||
| input: testPodJSON, | ||
| outputFormat: "json", | ||
| expectErr: false, | ||
| }, | ||
| { | ||
| name: "from json to yaml", | ||
| input: testPodJSON, | ||
| outputFormat: "yaml", | ||
| expectErr: false, | ||
| }, | ||
| { | ||
| name: "unsupported format", | ||
| input: testPodJSON, | ||
| outputFormat: "xml", | ||
| expectErr: true, | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| // test the output format conversion | ||
| _, err := formatOutput(tt.input, tt.outputFormat) | ||
|
|
||
| // we don't compare the output because the yaml output can have unordered fields. | ||
| // we only ensure it does not fail | ||
| if err != nil { | ||
| if !tt.expectErr { | ||
| t.Errorf("exccpected a result, unexpected error: %v", err) | ||
| } | ||
|
|
||
| // with unsuported format we expect an error | ||
| if !errors.Is(err, ErrUnsupportedFormat) { | ||
| t.Errorf("expected ErrUnsupportedFormat, got: %v", err) | ||
| } | ||
| } | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.